Applescript in Automator - Loops and Variables
Hi to everyone!
I'm trying to create an Automation with a Loop action in which workflow there is an Applescript Action too. What I need to do and I couldn't find anywhere on the net is how to make a variable increase in 1 each times it makes a loop. I will try to explain it again, in case it's not clear.
First Action
Applescript
N=1
Second Action
Loop
So each time it loops, the N variable increases 1 number. First loop, N=1, second loop N=2, third loop N=3 and so on.
Any ideas.
Thank you!
well, it's easy enough to wrap a one-shot applescript in a repeat loop, but...
the Get Text From Webpage action is not a script - it's a small cocoa plugin for automator. There's no direct way to get webpages from applescript. normally you use applescript to fetch them in Safari and then read the source from there. however, if you want to do it directly you can use the following:
set webpageText to do shell script "curl http://www.weppage.com"
All together it would look something like:
set webList to {"http://www.weppage1.com", "http://www.weppage2.com", "http://www.weppage3.com"}
repeat with thisURL in webList
set webpageText to do shell script "curl " & thisURL
--process webpageText
end repeat
Similar Messages
-
Automator - Loop through a text file and process data through a 3rd party software
Just stumbled on Automator the other day (I am a mac n00b) and would like to automate the processing of a text file, line-by-line, using a third party tool. I would like Automator to loop through the text file one line at a time, copy the string and keep as a variable. Next, place the variable data (copied string) into the text field of the 3rd party software for processing. Once the processing is complete, I would like Automator to fetch the next line/string for processing. I see items like "copy from clipboard" and "variables" within the menu but I am not finding much documentation on how to utilizle this tool. Just hear how potentially powerful it is.
The 3rd party software is not a brand name, just something made for me to process text. I may have to use mouse clicks or tabs + [return] to navigate with Automator. A term I heard on Bn Walldie's itunes video series was "scriptable software" for which I don't think this 3rd party app would be.
Kind regards,
jwGood news and bad news...
The good news is that it should be entirely possible to automate your workflow.
The bad news is that it will be a nightmare to implement via Automator, if it's even possible.
Automator is, essentially a pretty interface on top of AppleScript/Apple Events, and with the pretty interface comes a certain stranglehold on features. Knowing how to boil rice might make you a cook, but understanding flavor profiles and ingredient combinations can make you a chef, and it's the same with AppleScript and Automator. Automator's good at getting you from points A to B but if there are any bumps in the road (e.g. the application you're using isn't scriptable) then it falls apart.
What I'm getting at is that your requirements are pretty simple to implement in AppleScript because you can get 'under the hood' and do exactly what you want, as opposed to Automator's restricted interface.
The tricky part is that if no one else can see this app it's going to be hard to tell you what to do.
I can give you the basics on reading a file and iterating through the lines of text in it, and I can show you how to 'type' text in any given application, but it may be up to you to put the pieces together.
Here's one way of reading a file and working through each line of text:
-- ask the user for a file:
set theFile to (choose file)
-- read the file contents:
set theFileContents to (read file theFile)
-- break out the lines/paragraphs of text:
set theLines to paragraphs of theFileContents
-- now iterate through those lines, one by one:
repeat with eachLine in theLines
-- code to perform for eachLine goes here
end repeat
Once you have a line of text (eachLine in the above example) you can 'type' that into another application via something like:
tell application "AppName" to activate
tell application "System Events"
tell process "AppName"
keystroke eachLine
end tell
end tell
Here the AppleScript is activating the application and using System Events to emulate typing the contents of the eachLine variable into the process. Put this inside your repeat loop and you're almost there. -
How to hide rows and columns by AppleScript or Automator for printing
Hello,
I have to hide first empty rows (I do it by: organize - Column B is not empty)
then: By context-menu in Header of Column K: Hide column
and: By context-menu in Header of Column L: Hide column
How can I make this 3 Steps automatic with AppleScript or Automator or maybe by formula?
Thanks for any helpHere is an edited version which allow you to choose the custom template on the fly.
No need to edit a property in the script.
--[SCRIPT printtable(s)_choosecustom]
Enregistrer le script en tant que Script ou Application : printtable(s)_choosecustom.xxx
déplacer le fichier ainsi créé dans le dossier
<VolumeDeDémarrage>:Users:<votreCompte>:Library:Scripts:Applications:Numbers:
Il vous faudra peut-être créer le dossier Numbers et peut-être même le dossier Applications.
Sélectionner une partie de table, une table ou même plusieurs tables.
Aller au menu Scripts , choisir Numbers puis choisir “printtable(s)_choosecustom”
Le script crée un nouveau document depuis un modèle perso sélectionné,
puis applique « Colle les valeurs » au contenu du presse-papiers.
Il envoie enfin la commande d'impression.
--=====
L'aide du Finder explique:
L'Utilitaire AppleScript permet d'activer le Menu des scripts :
Ouvrez l'Utilitaire AppleScript situé dans le dossier Applications/AppleScript.
Cochez la case "Afficher le menu des scripts dans la barre de menus".
Sous 10.6.x,
aller dans le panneau "Général" du dialogue Préférences de l'Éditeur Applescript
puis cocher la case "Afficher le menu des scripts dans la barre des menus".
--=====
Save the script as a Script or an Application : printtable(s)_choosecustom.xxx
Move the newly created file into the folder:
<startup Volume>:Users:<yourAccount>:Library:Scripts:Applications:Numbers:
Maybe you would have to create the folder Numbers and even the folder Applications by yourself.
Select a subset of a table, a table or even several tables.
Go to the Scripts Menu, choose Numbers, then choose “printtable(s)_choosecustom”
The script create a new document based on the selected custom template,
then apply “Paste Values” to the clipboard's contents.
At last, it issue the print command.
--=====
The Finder's Help explains:
To make the Script menu appear:
Open the AppleScript utility located in Applications/AppleScript.
Select the "Show Script Menu in menu bar" checkbox.
Under 10.6.x,
go to the General panel of AppleScript Editor’s Preferences dialog box
and check the “Show Script menu in menu bar” option.
--=====
Yvan KOENIG (VALLAURIS, France)
2011/02/20
2011/03/16 -- replaced the Blank template by a custom one defined thru the property custom_template
2011/03/17 -- Let choose the custom template, no longer Paste but Paste Values.
--=====
property theApp : "Numbers"
--=====
on run
--my doyourduty()
run script doyourduty
end run
script doyourduty
--on doyourduty()
my activateGUIscripting()
Copy the selected items *)
my raccourci(theApp, "c", "c") (* cmd + c *)
Create a new document based upon Blank.template *)
set myNewDoc to my makeAnIworkDocFromCustom()
As it's a custom template, there is no default table to delete.
Delete the default table *)
tell application "Numbers" to tell document 1 to tell sheet 1 to delete table 1
my selectMenu("Numbers", 4, 8) (* Paste Values *)
my raccourci(theApp, "p", "c") (* cmd + p = Print *)
my raccourci(theApp, return, "") (* return = validate the Print command*)
--end doyourduty
end script
--=====
Creates a new iWork document from a custom template and returns its name.
example:
set myNewDoc to my makeAnIworkDocFromCustom()
on makeAnIworkDocFromCustom()
set nb_chiffres to 3 (*
2 = allow 99 templates
3 = allow 999 templates *)
Grab the localized names of the templates folders *)
tell application "Numbers"
set templates_loc to localized string "Templates"
-- set myTemplates_loc to localized string "My Templates"
end tell -- to application a
Define the path to the folder storing custom templates *)
--set chemindesmodeles to "" & (path to library folder from user domain) & "Application Support:iWork:Numbers:" & templates_loc & ":" & myTemplates_loc & ":"
set chemindesmodeles to "" & (path to library folder from user domain) & "Application Support:iWork:Numbers:" & templates_loc & ":"
Grab the list of every items stored in the folder *)
tell application "Finder"
set entire_contents to entire contents of folder chemindesmodeles
end tell
Build two lists. One contain the path to every custom templates.
The other contain the names of these templates and the names of subfolders *)
set indx to 1
set cheminde_mesmodeles to {}
set nomsde_mesmodeles to {}
set le_conteneur to ""
tell application "System Events"
repeat with i from 1 to count of entire_contents
set un_element to item i of entire_contents as text
try
if type identifier of disk item un_element is in {"com.apple.iwork.numbers.template", "com.apple.iwork.numbers.sfftemplate"} then
if name of container of disk item un_element is not le_conteneur then
set le_conteneur to name of container of disk item un_element
copy (text 1 thru nb_chiffres of "---") & space & le_conteneur to end of nomsde_mesmodeles
end if
copy un_element to end of cheminde_mesmodeles
copy text -nb_chiffres thru -1 of ("00" & indx) & space & name of disk item un_element to end of nomsde_mesmodeles
set indx to indx + 1
end if
end try
end repeat
end tell -- System Events
if my parleAnglais() then
set le_titre to "Numbers’s custom templates"
else
set le_titre to "Modèles personnalisés de Numbers"
end if
Choose the template to use.
If you select a subfolder name, the script beep and ask one more time *)
tell application (path to frontmost application as string)
repeat
set mon_choix to choose from list nomsde_mesmodeles with title le_titre
if mon_choix is false then error number -128
try
set mon_choix to text 1 thru nb_chiffres of (item 1 of mon_choix) as integer
exit repeat
on error
beep 1
end try
end repeat
end tell
tell application "Numbers"
set nb_doc to count of documents
open (item mon_choix of cheminde_mesmodeles)
repeat until (count of documents) > nb_doc
delay 0.1
end repeat
set doc_name to name of document 1
end tell -- the_App
return doc_name
end makeAnIworkDocFromCustom
--=====
on parleAnglais()
local z
try
tell application theApp to set z to localized string "Cancel"
on error
set z to "Cancel"
end try
return (z is not "Annuler")
end parleAnglais
--=====
on activateGUIscripting()
(* to be sure than GUI scripting will be active *)
tell application "System Events"
if not (UI elements enabled) then set (UI elements enabled) to true
end tell
end activateGUIscripting
--=====
==== Uses GUIscripting ====
This handler may be used to 'type' text, invisible characters if the third parameter is an empty string.
It may be used to 'type' keyboard raccourcis if the third parameter describe the required modifier keys.
I changed its name « shortcut » to « raccourci » to get rid of a name conflict in Smile.
on raccourci(a, t, d)
local k
tell application a to activate
tell application "System Events" to tell application process a
set frontmost to true
try
t * 1
if d is "" then
key code t
else if d is "c" then
key code t using {command down}
else if d is "a" then
key code t using {option down}
else if d is "k" then
key code t using {control down}
else if d is "s" then
key code t using {shift down}
else if d is in {"ac", "ca"} then
key code t using {command down, option down}
else if d is in {"as", "sa"} then
key code t using {shift down, option down}
else if d is in {"sc", "cs"} then
key code t using {command down, shift down}
else if d is in {"kc", "ck"} then
key code t using {command down, control down}
else if d is in {"ks", "sk"} then
key code t using {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
key code t using {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
key code t using {command down, shift down, option down}
end if
on error
repeat with k in t
if d is "" then
keystroke (k as text)
else if d is "c" then
keystroke (k as text) using {command down}
else if d is "a" then
keystroke k using {option down}
else if d is "k" then
keystroke (k as text) using {control down}
else if d is "s" then
keystroke k using {shift down}
else if d is in {"ac", "ca"} then
keystroke (k as text) using {command down, option down}
else if d is in {"as", "sa"} then
keystroke (k as text) using {shift down, option down}
else if d is in {"sc", "cs"} then
keystroke (k as text) using {command down, shift down}
else if d is in {"kc", "ck"} then
keystroke (k as text) using {command down, control down}
else if d is in {"ks", "sk"} then
keystroke (k as text) using {shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "k" then
keystroke (k as text) using {command down, shift down, control down}
else if (d contains "c") and (d contains "s") and d contains "a" then
keystroke (k as text) using {command down, shift down, option down}
end if
end repeat
end try
end tell
end raccourci
--=====
my selectMenu("Numbers",4, 8)
==== Uses GUIscripting ====
on selectMenu(theApp, mt, mi)
tell application theApp
activate
tell application "System Events" to tell process theApp to tell menu bar 1 to ¬
tell menu bar item mt to tell menu 1 to click menu item mi
end tell -- application theApp
end selectMenu
--=====
--[/SCRIPT]
Yvan KOENIG (VALLAURIS, France) jeudi 17 mars 2011 21:29:15 -
Difference between initialising variables inside a loop and outside it.
What is the difference between initialising a variable, say a String, inside a loop and outside it?
Are there performance differences, memory allocation issues etc? Or is there no difference at all?
For example:
1. Outside the loop
String s = "";
while (foo)
s = some variable;
2. Inside the loop
while(foo)
String s = some variable;.Hence, it definitely improves the performance of your code.That only depends on the code. Modern VM like Hotspot are very good at optimizing things.
for the in the loop thing.
Its true you need to create a new Object but memory doesnt need to be reallocated always because the VM knows the previiously declared Object has become available (it went out of scope)
Generaly: dont use the outside loop because you think it might help performance: always leave micro-optimizations for the VM.
It might be faster but its not a certantiy -
Problem with AppleScript inside automator app
Creating an Automator Application that I want to run by itself (hence application instead of workflow). The firs thing asks for a folder, then it goes to run the following applescript, followed by some more automator applications and another applescript. Everything works perfectly when i run it inside automator, but when I run it as a standalone app it fails on the first applescript. Here it is:
on run {input, parameters}
set aFolder to input
tell application "Finder"
set folderName to name of folder aFolder
end tell
set value of variable "SeasonNumber" of front workflow to "0" & ((characters -1 thru -1 of folderName) as string)
return input
end run
I'm thinking it has something to do with the fact that I am setting a value to an automator variable (SeasonNumber) but not sure. If so, I have attached the second applescript in case something needs to be fixed in both. Thanks in advance.
on run {input, parameters}
set whichFile to input
set epNum to 1
set sNumber to get value of variable "SeasonNumber" of front workflow
repeat with aFile in whichFile
if epNum < 10 then
set ifZero to "0"
else set ifZero to ""
end if
set textBox to "What is episode title for S" & (sNumber as string) & "E" & epNum & "?"
tell application "Finder"
set filename to name of aFile
set nameEnding to ((characters -4 thru -1 of filename) as string)
display dialog textBox default answer ""
set text_returned to text returned of result
set name of aFile to "S" & (sNumber as string) & "E" & (ifZero as string) & (epNum as string) & " - " & text_returned & nameEnding
end tell
set epNum to epNum + 1
end repeat
return input
end runAwesome. Figured since now it is just a ask for finder items and run applescript, might as well convert the whole thing to applescript and save as application in script editor. So the first thing is ask for finder items, which I have as:
set a set aFolder to (choose folder with prompt "Select Season Folder" default location "afp://DiskStation._afpovertcp._tcp.local/Entertainment/TV Shows") as text
But I keep getting an error saying that it can't make it into type alias. What is the correct way of changing the default location to this? It is a Folder called TV Shows that is on my NAS, connected through afp. Let me know as I have tried putting POSIX file, I have tried Network/DiskStation/Entertainment/TV Shows, among other things. DiskStation is the server and Entertainment is a partition. Thanks in advance. -
How to pass user input in automator to a variable?
I want to ceate a workflow/application to
-create a new folder eg Batch001 in directory B
-grab a group of folders in directory A
-and move them to Batch001
-create an archive of Batch001
-create a new set of empty folders in directory A
I thought I had this worked out, and planned to create a small applescript to grab a user input, then pass it to a variable. Figured if I do that at the beginning I can use the variable to create the Batch folder name, which I would enter manually. There will be a number of them, but not hundreds.
I have an applescript in automator to show a dialog, but ti does not seem to pass anything to the results. Even if I just use a simple dialog no results are passed. If I run it in actionscript editor it shows a result as expected.
on run {input, parameters}
--Display Dialog and Get Input
display dialog "Batch Number?" default answer "BatchXXX"
--Get Answer & Return Comment
set input to (text returned of result)
return input
end runI tried that, but when I run my workflow, it fails and I get an error message: The action “Rename Finder Items” encountered an error.
Here are a couple of screenshots of my workflow: -
Hello.
I would like to search for specific online сhеss games. Each game has a single adress. We are talking about millions of games. Obviously, it's far too long to index all the games. So I will set a limit and use the script at night. Conditions should be something like this:
For adress example.com/game=NumberA to example.com/game=NumberB
Search every web page containing SpecificWord
Store wanted web adresses somewhere (so I could see the games by myself during the day)
As you can see, I know nothing about Applescript and I don't know how to start, nor how the script can pick up adresses. I think it's possible and not difficult to code, just time consuming for the program to search through thousands of games.
Should I use AppleScript or Automator? Should the script open Safari (or Firefox if possible) or can it search without any browser? Is it possible to simultaneously search through multiple pages/adresses? Maybe I could write several scripts for different ranges of games? If so, how many pages can I open at once? For instance I could disable images in Firefox to load quicker. How much time does it need to search for one game? 1, 2, 3, 4, 5 seconds?
Any easy tutorials, examples of similar codes, advices, hints or tips are appreciated.Thanks for answering. Sorry that I was so unclear. My main problem was how to get urls and games id as variables. But then I thought there already should be programs doing web crawling. I have found Scrapy which use Python language.
(Maybe I should edit my question, add Scrapy and Python as tags instead of applescript and automator. Is it possible?)
I have Mac OS 10.6.8, Python 2.6.1. Scrapy needs at least Python 2.7 so I have downloaded the last version of Python (3.3). I think I can handle the programming in Scrapy thanks to their tutorial. The most difficult part should be... how to install Scrapy. Don't laugh at me.
I have entered "sudo easy_install Scrapy" in the terminal. But the terminal still uses Python 2.6.1. Python 3.3 is installed but I don't know how to clean update Python. If anyone knows, feel free...
When I write scrapy in the terminal, here is what I get:
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 4, in <module>
import pkg_resources
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg _resources.py", line 2556, in <module>
working_set.require(__requires__)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg _resources.py", line 620, in require
needed = self.resolve(parse_requirements(requirements))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg _resources.py", line 518, in resolve
raise DistributionNotFound(req) # XXX put more info here
pkg_resources.DistributionNotFound: lxml
It seems Scrapy also needs something called lxml. Right now I am trying to make Python 3.3 the default python version. Is there a web crawler GUI which already includes Python, Scrapy, lxml?
By default I also have Python 2.4 and 2.5. Does the system need them? I prefer not to delete system files but together all Python versions weigh 500 MB.
In regard to the real example URL: let's say instantchess.com. Here's a game URL: http://www.instantchess.com/?EXP=1&GPI=84094532
84094532 is the game id. Let's say I want to search every Reti openings (thus the page must contain the word "Reti") from id 84000000 to 85000000 and store games id in my computer. If I have understood correctly, I need to search through the source code of the pages.
Feel free to add any remarks, suggestions, ideas. -
Automator, AD, and moving folders.
I keep looking at Automator and it confuses me more every time. Is something like this possible?
I want Automator to parse through a folder full of student folders for the district I work at. It will take the name of the folder (which is the student's login name), ask Active Directory where that student's folder should be and if not on that server, it will mount the correct server and move the contents of the folder to the other server. Then move on to the next folder
This would be done in the summer after updating the Active Directory for the next school year. The idea being that it will copy the student's folder to the server at the next building they are at (They go from a kindergarten to a primary, to an intermediate, and end their sentence with us at a jr high). Currently we delete everyone's folder, but I thought it'd be nice to let them keep the same files their entire stay and with moving to full network home folders in the next couple years, it will copy their library and preferences as well.
Just wondering if this is in the scope of automator or should I look to something else?
ThanksNot in Automator.. It may be possible in AppleScript.
Automator doesn't work with loops or conditionals... It basically takes a bunch of files and processes them as a group. Everything that passes one action is sent to the next-it's not possible parse through them and selectively copy off to different places. -
Multiple Copies of Same Data in RTF - Looping using variable
We have a requirement, where an Invoice batch job will run
at night and pick up all the entire invoices, batch would contain invoices of
different customers.
Each customer will have DFF at site level informing number
of copies required to be printed.
Eg:
Customer ABC Invoice ABC111 No. of Copies -4
Customer PQR Invoice PQR222 No. of Copies -2
Customer XYZ Invoice XYZ3333 No. of Copies -1
I am trying to use following variable in the RTF, for the data to loop but it creates various problems
Grouping and Variables:
<?for-each@section:G_HEADER?>
<?for-each@section:xdoxslt:foreach_number($_XDOCTX,1,DFF,1)?> --- value coming in XML tag from DFF
<?for-each:/?>
The actual invoice tables and rtf
<?end for-each?>
Problems:
If I remove <?for-each:/?> tag, I am
getting the looping of data but the output file has no data from tags – only column
labels / headers appear ---- But looping happens
a.) With <?for-each:/?> tag,
sometimes the RTF works and looping happens along with data and something the RTF crashes with below error
oracle.xdo.XDOException:java.lang.reflect.InvocationTargetException
b.) When I try with a data containing just single invoice – looping and everything works as expected.
However, if I load data which has multiple invoices each having different value in DFF for looping, entire file only contains first invoice ---- Looping happens still but does not proceed to next group
Solutions:
Can someone please guide me to the solution?
Please recommend what would be the correct syntax, so that each invoice gets looped dynamically in the RTF.Here's the dataset I used and tried to replicate what you were trying to achieve:
<ROWSET>
<ROW>
<ITEM>A</ITEM>
<COUNT>3</COUNT>
</ROW>
<ROW>
<ITEM>B</ITEM>
<COUNT>5</COUNT>
</ROW>
</ROWSET>
Here's the code:
<?for-each@section:ROW?><?variable@incontext:G1;current()?>
<?for-each@section:xdoxslt:foreach_number($_XDOCTX,1,COUNT,1)?>
<?$G1/ITEM?>
<?end for-each?>
<?end for-each?>
So based on the count, there are 3 pages where A (from ITEM field) is printed and 5 pages where B is printed.
Hope this helps.
Bipuser -
Hi,
I'm a freshman in college and new to java. I am completely lost and really need help with a current assignment. Here are the instructions given by my teacher...
Building on provided code:
Loops and Arrays
Tracking Sales
Files Main.java and Sales.java contain a Java application that prompts for and reads in the sales for each of 5 salespeople in a company. Files Main.java and Sales.java can be found here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Main.java
and here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Sales.java It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify the program as follows:
1. (1 pts) Compute and print the average sale. (You can compute this directly from the total; no new loop is necessary.)
2. (2 pts) Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't necessarily need another loop for this; you can get it in the same loop where the values are read and the sum is computed.
3. (2 pts) Do the same for the minimum sale.
4. (6 pts) After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.
5. (2 pts) The salespeople are objecting to having an id of 0-no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array-just make the information for salesperson 1 reside in array location 0, and so on.
6. (8 pts) Instead of always reading in 5 sales amounts, allow the user to provide the number of sales people and then create an array that is just the right size. The program can then proceed as before. You should do this two ways:
1. at the beginning ask the user (via a prompt) for the number of sales people and then create the new array
2. you should also allow the user to input this as a program argument (which indicates a new Constructor and hence changes to both Main and Sales). You may want to see some notes.
7. (4 pts) Create javadocs and an object model for the lab
You should organize your code so that it is easily readable and provides appropriate methods for appropriate tasks. Generally, variables should have local (method) scope if not needed by multiple methods. If many methods need a variable, it should be an Instance Variable so you do not have to pass it around to methods.
You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this.
I'm not asking for someone to do this assignment for me...I'm just hoping there is someone out there patient and kind enough to maybe give me a step by step of what to do or how to get started, because I am completely lost from the beginning of #1 in the instructions.
Any help would be much appreciated! Thank you!
Message was edited by:
Scott_010
Message was edited by:
Scott_010First ask the person who gave this asignment as to why do you require two classes for this , you can have only the Sales.java class with main method in it . Anyways.
Let Main.java have a main method which instanciates a public class Sales and calls a method named say readVal() in Sales class.
In the readVal method of sales class define two arrays i.e ids and sales. Start prompting the user for inputting the id and sales and with user inputting values keep storing it in the respective arrays .. Limit this reading to just 5 i.e only 5 salesPerson.
Once both the arrays are populated, call another method of Sales class which will be used for all computations and output passing both the arrays.
In this new method say Compute() , read values from array and keep calculating total,average and whatever you want by adding steps in just this loop. You can do this in readval method too after reading the values but lets keep the calculation part seperate from input.
You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this. I think this is ur personal stuff , but if you want to use web page , you probably will require to use servlet to read values from the html form passed to the server. -
Please help. Thank you for your time and expertise.
Prerequisites: sql query needs to be a view. Real view is more than recursion. It computes location path, is used in JOINs and returns this path.
Problem: no matter what I tried, sql server does not produce 'index seek' when using variable but does with literal.
See full reproduction code below.
I expect that query SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID will seek UNIQUE index but it does not.
I tried these:
1. Changing UX and/or PK to be CLUSTERED.
2. query OPTION(RECOMPILE)
3. FORCESEEK on view
4. SQL Server 2012/2014
5. Wrap it into function and CROSS APPLY. On large outer number of rows this just dies, no solution
but to no avail. This smells like a bug in SQL Server. I am seeking your confirmation.
I am thinking it is a bug as variable value is high-cardinality, 1, and query is against unique key. This must produce single seek, depending if clustered or nonclustred index is unique
Thanks
Vladimir
use tempdb
BEGIN TRAN
-- setup definition
CREATE TABLE dbo.LocationHierarchy(
lcID int NOT NULL ,
lcHID hierarchyid NOT NULL,
lcCode nvarchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
lcHIDParent AS lcHID.GetAncestor(1) PERSISTED,
CONSTRAINT PK_LocationHierarchy_lcID PRIMARY KEY NONCLUSTERED (lcID ASC),
CONSTRAINT UX_LocationHierarchy_pltID_lcHID UNIQUE CLUSTERED (lcHID ASC)
-- add some data
INSERT INTO dbo.LocationHierarchy
VALUES
(1, '/', 'A')
,(2, '/1/', 'B')
,(3, '/1/1/', 'C')
,(4, '/1/1/1/', 'D')
--DROP VIEW dbo.vwLocationCodes
GO
CREATE VIEW dbo.vwLocationCodes
AS
WITH ru AS
SELECT
lh.lcID
,lh.lcCode
,lh.lcHID
,CAST('/' + lh.lcCode + '/' as varchar(8000)) as LocationPath
-- to support recursion
,lh.lcHIDParent
FROM dbo.LocationHierarchy lh
UNION ALL
SELECT
ru.lcID
,ru.lcCode
,ru.lcHID
,CAST('/' + lh.lcCode + ru.LocationPath as varchar(8000)) as LocationPath
,lh.lcHIDParent
FROM dbo.LocationHierarchy lh
JOIN ru ON ru.lcHIDParent = lh.lcHID
SELECT
lh.lcID
,lh.lcCode
,lh.LocationPath
,lh.lcHID
FROM ru lh
WHERE lh.lcHIDParent IS NULL
GO
-- get data via view
SELECT
CONCAT(SPACE(l.lcHID.GetLevel() * 4), lcCode) as LocationIndented
FROM dbo.vwLocationCodes l
ORDER BY lcHID
GO
SET SHOWPLAN_XML ON
GO
DECLARE @lcID int = 2
-- I believe this produces bad plan and is defect in SQL Server optimizer.
-- variable value cardinality is 1 and SQL Server should know that. Optiomal plan is to do index seek with key lookup.
-- This does not happen.
SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID -- bad plan
-- this is a plan I expect.
SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = 2 -- good plan
-- I reviewed these but I need a view here, can't be SP
-- http://sqlblogcasts.com/blogs/tonyrogerson/archive/2008/05/17/non-recursive-common-table-expressions-performance-sucks-1-cte-self-join-cte-sub-query-inline-expansion.aspx
-- http://social.msdn.microsoft.com/Forums/sqlserver/en-US/22d2d580-0ff8-4a9b-b0d0-e6a8345062df/issue-with-select-using-a-recursive-cte-and-parameterizing-the-query?forum=transactsql
GO
SET SHOWPLAN_XML OFF
GO
ROLLBACK
Vladimir MoldovanenkoHere is more... note that I am creating table Items and these can be in Locations.
I am trying LEFT JOIN and OUTER APLLY to 'bend' query into NESTED LOOP and SEEK. There has to be nested loop, 2 rows against 4. But SQL Server fails to generate optimal plan with SEEK. Even RECOMPILE does not help
use tempdb
BEGIN TRAN
-- setup definition
CREATE TABLE dbo.LocationHierarchy(
lcID int NOT NULL ,
lcHID hierarchyid NOT NULL,
lcCode nvarchar(25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
lcHIDParent AS lcHID.GetAncestor(1) PERSISTED,
CONSTRAINT PK_LocationHierarchy_lcID PRIMARY KEY NONCLUSTERED (lcID ASC),
CONSTRAINT UX_LocationHierarchy_pltID_lcHID UNIQUE CLUSTERED (lcHID ASC)
-- add some data
INSERT INTO dbo.LocationHierarchy
VALUES
(1, '/', 'A')
,(2, '/1/', 'B')
,(3, '/1/1/', 'C')
,(4, '/1/1/1/', 'D')
--DROP VIEW dbo.vwLocationCodes
GO
--DECLARE @Count int = 10;
--WITH L0 AS (SELECT N FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N (N))-- 10 rows
--,L1 AS (SELECT n1.N FROM L0 n1 CROSS JOIN L0 n2) -- 100 rows
--,L2 AS (SELECT n1.N FROM L1 n1 CROSS JOIN L1 n2) -- 10,000 rows
--,L3 AS (SELECT n1.N FROM L2 n1 CROSS JOIN L2 n2) -- 100,000,000 rows
--,x AS
-- SELECT TOP (ISNULL(@Count, 0))
-- ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as Number
-- FROM L3 n1
--SELECT Number as itmID, NTILE(4)OVER(ORDER BY Number) as lcID
--INTO dbo.Items
--FROM x
----ORDER BY n1.N
--ALTER TABLE dbo.Items ALTER COLUMN itmID INT NOT NULL
--ALTER TABLE dbo.Items ADD CONSTRAINT PK PRIMARY KEY CLUSTERED (itmID)
CREATE TABLE dbo.Items (itmID int NOT NULL PRIMARY KEY, lcID int NOT NULL)
INSERT INTO dbo.items
VALUES(1, 1)
,(2, 3)
GO
CREATE VIEW dbo.vwLocationCodes
AS
WITH ru AS
SELECT
lh.lcID
,lh.lcCode
,lh.lcHID
,CAST('/' + lh.lcCode + '/' as varchar(8000)) as LocationPath
-- to support recursion
,lh.lcHIDParent
FROM dbo.LocationHierarchy lh
UNION ALL
SELECT
ru.lcID
,ru.lcCode
,ru.lcHID
,CAST('/' + lh.lcCode + ru.LocationPath as varchar(8000)) as LocationPath
,lh.lcHIDParent
FROM dbo.LocationHierarchy lh
JOIN ru ON ru.lcHIDParent = lh.lcHID
SELECT
lh.lcID
,lh.lcCode
,lh.LocationPath
,lh.lcHID
FROM ru lh
WHERE lh.lcHIDParent IS NULL
GO
-- get data via view
SELECT
CONCAT(SPACE(l.lcHID.GetLevel() * 4), lcCode) as LocationIndented
FROM dbo.vwLocationCodes l
ORDER BY lcHID
GO
--SET SHOWPLAN_XML ON
GO
DECLARE @lcID int = 2
-- I believe this produces bad plan and is defect in SQL Server optimizer.
-- variable value cardinality is 1 and SQL Server should know that. Optiomal plan is to do index seek with key lookup.
-- This does not happen.
SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = @lcID-- OPTION(RECOMPILE) -- bad plan
-- this is a plan I expect.
SELECT lcCode FROM dbo.vwLocationCodes l WHERE l.lcID = 2 -- good plan
SELECT *
FROM dbo.Items itm
LEFT JOIN dbo.vwLocationCodes l ON l.lcID = itm.lcID
OPTION(RECOMPILE)
SELECT *
FROM dbo.Items itm
OUTER APPLY
SELECT *
FROM dbo.vwLocationCodes l
WHERE l.lcID = itm.lcID
) l
-- I reviewed these but I need a view here, can't be SP
-- http://sqlblogcasts.com/blogs/tonyrogerson/archive/2008/05/17/non-recursive-common-table-expressions-performance-sucks-1-cte-self-join-cte-sub-query-inline-expansion.aspx
-- http://social.msdn.microsoft.com/Forums/sqlserver/en-US/22d2d580-0ff8-4a9b-b0d0-e6a8345062df/issue-with-select-using-a-recursive-cte-and-parameterizing-the-query?forum=transactsql
GO
--SET SHOWPLAN_XML OFF
GO
ROLLBACK
Vladimir Moldovanenko -
Mounting a network share via Applescript or Automator causes errors in MS Office apps
If I connect a network share using an automated process, either using Applescript or Automator, though the share shows up on the Desktop and I can open it and view the various folders and files, MS Office apps including Powerpoint, Excel and Word are unable to open the files. Each gives a slightly different error message. In Excel, it looks like this:
In Word, it's:
In Powerpoint, it's:
BUT, if I connect to the server share manually (using Cmnd-K in Finder), all files and folders are properly accessible. I cannot see any differences between the shares connected by the two different means on the Desktop. They have the same name, are the same size, etc.; in short, everything about them seems identical. I even took screen shots of the Get Info page from one of them connected by the different methods:
"home" connected by Automator:
and connected manually:
Does anyone have any ideas as to why this is happening or how to fix it?I had the same issue. After upgrading kernel to 3.4.5 today the cifs share mounted with original fstab settings. I believe it was caused by this bug:
kernel changelog wrote: The double delimiter check that allows a comma in the password parsing code is
unconditional. We set "tmp_end" to the end of the string and we continue to
check for double delimiter. In the case where the password doesn't contain a
comma we end up setting tmp_end to NULL and eventually setting "options" to
"end". This results in the premature termination of the options string and hence
the values of UNCip and UNC are being set to NULL. This results in mount failure
with "Connecting to DFS root not implemented yet" error. -
Budget Report to show the fixed and variable split for Materials
Hello Gurus,
Could you tell me if there is a budget standards report that will show the fixed and variable split for Materials? Example: Labor, Equip., QC and Overheads?
I need it for the correctly rolled-up 'final material number' step. The report that does this now (without fixed and var split) is the Indented BOM Comparison (sret - cost mgmt-product costing - cost mgmt-customized reports - cost estimate comparison - costed multilevel compare rpt - Indented BOM Comparison).
Thanks,
Jeffersonone simple way is in your final itab declare a slno type i field
data : begin of itab occurs 0,
slno type i,
<other fields>
end of itab.
after filling the data in itab.
loop at itab.
itab-slno = sy-tabix.
modify itab.
endloop.
in fieldcatalog also you have to define that slno field as the first column.
but it will change its order if you are sorting the output or filtering the output.
regards
shiba dutta -
Need help with a java loop and word program
do you know any way to get a Scanner object to select a random string in a text file?
ok pretty much I have a text file that isa list of 5 letter words. I need to select one at random.
the only way I could think was to scan the file, get the entire nu of words, have Math.random choose a random nu then loop scanner.next() and have the loop condition run the Math.random amount of times
but... when I do that I CANT ACCESS THE WORD OUTSIDE THE STUPID LOOP grrr...
i'm annoyed lol
this is the loop code that selects the random word
int random = (int) Math.random() * numberOfWordsInFile + 1;
int chooseLoopCount = 0;
while (random >= chooseLoopCount)
String theWord = scan.next();
theWord = theWord.toLowerCase();
chooseLoopCount += 1;
see it's assigned properly to be the output of the scanner in all lower case letters, but outside the loop, the variable doesn't even exist
anyway any suggestions would be awesome. thxString theWord = null;
while (...)
// set theWord in the loop
// access to theWord is now available here, as it is in scope.
// bear in mind if your loop didn't get executed, theWord is still null -
What exactly is the diff between main window and variable window
what exactly is the diff between main window and variable window in SAP script?
hi,
MAIN WINDOW :- In a main window you display text and data, which can cover several pages (flow text). As soon as a main window is completely filled with text and data, the system continues displaying the text in the main window of the next page. It automatically triggers the page break.
You can define only have one window in a form as main window.
The main window must have the same width on each page, but can differ in height.
A page without main window must not call itself as next page, since this would trigger an endless loop. In such a case, the system automatically terminates after three pages.
VARIABLE WINDOW :- The contents of variable windows is processed again for each page, on which the window appears. The system outputs only as much text as fits into the window. Text exceeding the window size is truncated; the system does not trigger a page break. Unlike constant windows, the page windows declared as variable windows may have different sizes on different form pages.
As far as the processing of the window contents is concerned, the system currently treats constant and variable windows alike. The only difference is that constant windows have the same size throughout the form.
hope this will be useful.
If useful then reward points.
with regards,
Syed
Maybe you are looking for
-
[Error during Export] R3load exited with return code 11
Hi guys, While performing and Unicode Migration, during Export Phase, Migration Monitor returned the following error while exporting a package ERROR: 2014-06-01 10:57:44 com.sap.inst.migmon.LoadTask run Unloading of 'REGUC' export package is interrup
-
Can I retrieve data from my iPhone 4 hard drive without the SIM card?
Can I retreive data from my iPhone 4 hard drive without the sim?
-
Why can't one add artwork to music saved as a wave file
i can add scanned artwork to an entry in itunes only if it is saved as an AAC or MP3 file but when i try and save scanned artwork to a wave file, it doesn't afford me that choice.....any reason that would be?
-
FBL3N standard program to ZCOPY program issue
When I take a ZCOPY of standard program RFITEMGL of transaction code FBL3N and put break point over Function Module FI_ITEMS_DISPLAY and look into the table it_pos the material number and vendor numbers are not getting populated but without takin
-
Multi-choice parameters with "like" condition
Hi, I defined a parameter, multi-choice, using a "like" condition. It always works for the first value of the LOV and ignores the rest of the values chosen. Is there any way that the "like" condition can be used for more than one parameter value? In