text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Contents
In the last unit you built a search index that could respond to queries by going through each entry one at a time. The search index checked to see if the keyword matched the word you were looking for and then responding with a result.
However, with a large index and lots of queries, this method will be too slow. A typical search engine should respond in under a second and often much faster.
In this unit you will learn how to make your search index much faster.
The main goal for this unit is to develop an understanding of the cost of running programs. So far, you haven't worried about this and have been happy to write code that gives the correct result. Once you start to make programs bigger, make them do more things or run on larger inputs, you have to start thinking about the cost of running them. This question of what it costs to evaluate an execution is a very important, and it is a fundamental problem in computer science. Some people spend their whole careers working on this. It's called algorithm analysis.
You may not be aware of this but you've already written many algorithms. An algorithm is a procedure that always finishes and produces the correct result. A procedure is a well defined sequence of steps that it can be executed mechanically. We're mostly interested in procedures which can be executed by a computer, but the important part about what makes it a procedure is that the steps are precisely defined and require no thought to execute.
To be an algorithm, it has to always finish. You've already seen that it isn't an easy problem to determine if an algorithm always finishes. It isn't possible to answer that question in general, but it can be answered for many specific programs.
So, once you have an algorithm, you have well a defined sequence of steps that will always finish and produce the right results. This means you can reason about its cost.
The way computer scientists think about cost is quite different from how most people think about cost.
When you think about the cost of things, you know specific things such as the red car costs $25000 and the green car $10000 - the red car costs more than the green car. You just have to compare those costs. This is thinking in terms of very specific things with specific costs. It's different with algorithms. We don't usually have a specific execution in mind. The cost depends on the inputs.
Suppose algorithms Algo 1 and Algo 2 both solve the same problem.
You can't put a fixed price on them like with the cars. For some inputs, it might be the case that Algo 1 is cheaper than Algo 2, but for others, Algo 2 might be cheaper. You don't want to have to work this out for every input because then you might as well run it for every input. You want to be able to predict the cost for every input without having to run every input.
The primary way that cost is talked about in computer science is in terms of the size of the input. Usually, the size of the input is the main factor that determines the speed of the algorithm, that is, the cost in computing is measured in terms of how the time increases as the size of the input increases. Sometimes, other properties of the input matter, which will be mentioned later. Ultimately, cost always comes down to money. What costs money when algorithms are executed?
NOTE: So we want to know how cost(time,memory) depends on the input.
In summary, cost is talked about in terms of time and memory rather than money; although the actual implementation of these do convert to actual monetary costs. Time is often the most important aspect of cost, but memory is also another consideration.
Why do computer scientists focus on measuring how time scales with input size, instead of absolute time? (Check all correct answers.)
Throughout the entire history of computing, it's been the case that the computer you can buy in a year for the same amount of money will be faster than the computer you can buy today.
In this section, you'll see how you can check how long it takes for a piece of code to run. You may have seen people on the forums talking about bench marking code.
The procedure, time_execution, below, is a way to evaluate how long it takes for some code to execute. You could try to do this with a stopwatch but to be accurate, you'd have to run programs for a very long time. It's more accurate to use the built-in time.clock in the time library. An explanation of what is going on follows the code:
import time #this is a Python library def time_execution(code): start = time.clock() # start the clock result = eval(code) # evaluate any string as if it is a Python command run_time = time.clock() - start # find difference in start and end time return result, run_time # return the result of the code and time taken
The clock is started. The time it reads when it starts is somewhat arbitrary, but it doesn't matter because you're only interested in the time difference between it starting and stopping and not an absolute start and end time. After the clock is started, the code you want to evaluate is executed. This is done by the rather exciting method eval('<string>'). It allows you to run any code input as a string! You put in a string and it runs it as Python code. For example, eval('1 + 1') runs the code 1 + 1. After the code is executed, the clock is stopped and the difference between the start and stop times is calculated and stored as run_time. Finally, the procedure returns the result of the code in eval and its running time.
You can run the timing through the web interpreter, but it won't be accurate and there is a limit on how long your code is allowed to run there. If you have Python installed on your computer, you'll be able to run it on that. If you don't, then that's ok. Instructions will be available under the unit's Supplementary Information. You don't need to run it for yourself, but you should at least see it illustrated. The following outputs are all run in a Mac shell on Dave's desktop.
Recall that the input '1 + 1' to time_execution, shown in green in the image below, is sent as input to eval , which runs 1 + 1 as Python code.
The run time is written in scientific notation: 8.300000000005525e-05 which is sometimes also written as 8.300000000005525 x 10\^-5, or in Python code 8.300000000005525 * 10**-5. In decimal terms, this can be written as 0.00008300000000005525, or rounded to 0.000083. You can see where this comes from by looking at the -5 after the e. It tells you to move the decimal point 5 steps to the left like this:
The units are seconds, so this is only a fraction of a millisecond, that is, about 0.08 ms.
Trying the same instruction over and over, the result varies because other things are going on in the machine at the same time, but it's around the same value.
Instead, try larger numbers, the time is still very very small.
The actual processing time is even lower, because, for instance, starting and stopping the clock.
This doesn't tell you very much for short, fast executions, so next you'll see some longer ones.
In order to get a better idea of how timing works, define the procedure spin_loop:
def spin_loop(n): i = 0 while i < n: i = i + 1
This code will run for longer, and by picking the value n you can go through and loop any number of times. The image below shows spin_loop running 1000, 10000, 100000 and 1000000 times, returning a result that is the time it takes to run the loop that number of times.
It is important to notice that the time changes depending on the input - when you increase the input, the time (or the output) also increases accordingly.
First you'll see the time taken for running some code, and then there will be a quiz. This will show if you understand execution time well enough to make some predictions.
The code used to measure the time is the time_execution procedure from before which evaluates the time taken for the code passed in, and then a procedure spin_loop which just adds one to a variable as it loops through the numbers up to n.
import time def time_execution(code): start = time.clock() result = eval(code) # evaluate any string as if it is a python command run_time = time.clock() - start return result, run_time def spin_loop(n): i = 0 while i < n: i = i + 1
The results for execution times, in seconds, for spin_loop are given below. Note the [1] is there to just print out the running time rather than the result of evaluating spin_loop. The first result is for running the loop 1000 times, then 10000 followed by 100000. The next is a repeat of the 100000 iterations (runs) through the loop, but written in Python's power notation for 105;. The final time is the execution time for running through the loop 106;, which is one million times. All the execution times are given in seconds.
Given the execution times above, what is the expected execution time for spin_loop(10**9) (one billion) in seconds? You won't be able to guess the exact time, but the grader is looking for a multiple of 5.
The examples you've seen so far have shown the time taken to run short procedures. Next you'll see some test on longer code - the index code, which is important to the overall look up time of your search engine. In order to test this code, you'll first need to build a big index. You could do this by hand but it would take a very long time! The code to do it is as follows.
First an empty index called index is created, and a list, letters, of eight letter a's. Next, there is a while loop that adds an entry to the index each time it iterates. (Iterates means going through the loop - one iteration is one pass through the loop.) The while loop continues to add to the index until it is of the required length, size. The details as to what happens in loop are as follows.
word = make_string(letters)
The procedure make_string takes as its input letters and returns a single string of the entries contained in the list. This means that, for example, ['a','a','a','a','a','a','a','a'] becomes 'aaaaaaaa'. The code for this is:
def make_string(p): s="" for e in p: # for each element in the list p s = s + e # add it to string s return s add_to_index(index, word, 'fake')
This is the add_to_index code from before, and it adds an entry which looks like this:
['aaaaaaaa', ['fake']] to index. for i in range(len(letters) - 1, 0, -1):
Although you've seen range before, here it is used differently. If len(letters) is 8, then range(len(letters) - 1, 0, -1) becomes range(7, 0, -1),which is a list which counts down from 7 to one greater than 0 in steps of -1, that is, [7, 6, 5, 4, 3, 2, 1]. So, the for loop runs through the values of the list counting backwards from len(letter)-1 down to 1.
Discussion on Range
The for loop starts from the last letter in letters, and checks if it is a 'z'. If it is, it changes it to 'a', and goes back to the top of the loop for the next iteration, which will check one position closer to the beginning of the loop. It continues until it finds a letter which is not a 'z'.
Once it finds a letter which isn't a 'z', the line letters[i] = chr(ord(letters[i])+ 1) changes it to one letter later in the alphabet, 'a'→'b', 'b'→'c' and so on . (Precisely what chr and ord do will be explained later. ) After a letter has been changed, the for-loop stops and the code returns to the top of the while-loop .
During the first iteration of the while-loop, the for-loop it will change from: ['a','a','a,','a','a','a','a','a'] to ['a','a','a,','a','a','a','a','b'] and then break. The second time through, it will change from: ['a','a','a,','a','a','a','a','b'] to ['a','a','a,','a','a','a','a','c'] and break, and so on.
When it gets to: ['a','a','a,','a','a','a','a','z'], it will change it first to: ['a','a','a,','a','a','a','a','a'].
Then it will look at the last but one position, as it goes through the list backwards. It will change the 'a' in that position to 'b' which changes the list to: ['a','a','a,','a','a','a','b','a'], after which it breaks.
Finally, when the while loop has finished, the index of length size is returned.
The complete code to try this is reproduced below, so you can try it for yourself if you'd like.
def add_to_index(index,keyword,url): for entry in index: if entry[0] == keyword: entry[1].append(url) return index.append([keyword,[url]]) def make_string(p): s="" for e in p: s = s + e return s
To see what it does, you can look at some small values.
print make_big_index(3) # index with 3 keywords 'aaaaaaaa', ['fake', ['aaaaaaab', ['fake']], ['aaaaaaac', ['fake']]] print make_big_index(100) # index with 100 keywords 'aaaaaaaa', ['fake', ['aaaaaaab', ['fake']], ['aaaaaaac', ['fake']], ['aaaaaaad', ['fake']], ['aaaaaaae', ['fake']], ['aaaaaaaf', ['fake']], ... <snip> ... ['aaaaaadm', ['fake']], ['aaaaaadn', ['fake']], ['aaaaaado', ['fake']], ['aaaaaadp', ['fake']], ['aaaaaadq', ['fake']], ['aaaaaadr', ['fake']], ['aaaaaads', ['fake']], ['aaaaaadt', ['fake']], ['aaaaaadu', ['fake']], ['aaaaaadv', ['fake']]]
As you can see from the end of the list, the second to last letter has been changed as well as the last index.
To test the index, some larger indexes are needed. You'll see the results of tests run on one of length 10 000, and another of length 100 000. It takes over 5 minutes to construct the index of length 100 000. This doesn't matter as it is the lookup time that is important for your search engine.
To construct the smaller of the two indexes, you can use the line:
index10000 = make_big_index(10000)
The time to run this lookup on index10000 is checked several times, which you can see below. Note that the time varies, but is around the same value.
After constructing the larger index of length 100 000 using:
index1000000 = make_big_index(100000)
you can see the element at the last position using index1000000[99999], or the equivalent index1000000[-1], just like with strings.
print index1000000[99999] ['aaaafryd',['fake']] index100000[-1] ['aaaafryd',['fake']]
The timings for the longer index of length 100 000 are as follows:
If you compare these with the times for the index of length 10 000, you'll see that it takes approximately 10 times longer to do a lookup in the larger index than in the shorter index.
Timings vary for many reasons. One reason is that lots of other things run on the computer, which means that the program does not have total control over the processor. Another reason is that where things are in memory can take a longer or shorter time to retrieve. What matters is that the run time is roughly the same each time the test is run, and that it depends on the input size.
What is the largest size index that can do lookups in about one second?
Sample timings:
>>> time_execution('lookup(index10000, "udacity")') (None, 0.000968000000000302) >>> time_execution('lookup(index10000, "udacity")') (None, 0.000905999999863066) >>> time_execution('lookup(index100000, "udacity")') (None, 0.008590000000002652) >>> time_execution('lookup(index100000, "udacity")') (None, 0.008517999999998093)
Predict the lookup time for a particular keyword in an index created as given below. Be careful, this is a bit of a trick question.
What is the expected time to execute:
lookup(index10M, 'aaaaaaaa')
where index10M is an index created by
index10M = make_big_index(10000000)
Usually, when analysing programs it's the worst-case execution time that is important. The worst-case execution time is the time it takes for the case where the input for a given size takes the longest to run. For lookup, it's when the keyword is the last entry in the index, or not in the index at all. Looking at the code will give you a better understanding of why the time scales as it does, and the worse-case and the average case running times.
This is the code from the last unit.
def add_to_index(index,keyword,url): for entry in index: if entry[0] == keyword: entry[1].append(url) return # not found, add new keyword to index index.append([keyword,[url]]) def lookup(index, keyword): for entry in index: if entry[0] == keyword: return entry[1] return None
What lookup does is go through the list. For each entry, it checks if it is equal to the keyword. Below is the structure of the index.
The number of iterations through the loop depends on the index. The length of the index is the maximum number of times the code goes through the loop. If the keyword is found early, the loop finishes sooner.
The other thing that is relevant is how add_to_index constructs the list. It loops through all the entries to see if the keyword exists, and if it doesn't, it adds the new entry to the end of the list. The first addition is added to the beginning of the index and the last to the end. That is why 'aaaaaaaa' is the first entry in the index.
Which keyword will have the worst case running time for a given index? (Choose one or more answers.)
This is a fairly subjective question.
Is our lookup fast enough?
How can we make lookup faster? Why is it so slow?
It's slow because it has to go through the whole of the for loop
for entry in index: if ...
to find out if a keyword isn't there. This isn't how you use an index in real life. When you pick up a book, and look in the index, you don't start at A and work your way all the way through to Z to know if an entry isn't there. You go directly to where it should be. You can jump around the index because it is in sorted order. You know where the entry belongs because it is in alphabetic order. If it isn't where it belongs, it isn't in the index anywhere.
You could do something similar with the index in your code. If you had a sorted index, you could go directly to the entry you wanted. Sorting is an interesting problem, but it won't be covered in this course. Instead of having to keep the index in a specific order, you'll learn another way to know where to look for the entry you are interested in. This method will be a function, called a hash function. Given a keyword, the hash function will tell you where to look in the index. It will map the keyword to a number (this means it takes in a keyword and outputs a number) which is the position in the index where you should look for the keyword. This means you don't have to start at the beginning and look all the way through the index to find the keyword you are looking for.
NOTE: Hash function tells you where to look(which bucket to look in) to find the entry you are looking for.
There are lots of different ways to do this. A simple way would be to base it on the first letter in each keyword. It would be like the way an index in a book works. Each entry in the index will correspond to a letter and will contain all the keywords beginning with that letter.
This isn't the best way to do it. It will reduce the time it takes to search through all the keywords as you'll only need to search through the keywords beginning with that letter, but it won't speed it up that much. The best it could do is to speed up the look up by a factor of 26, as there are 26 buckets, so each list would be 26 times smaller if all the buckets were the same size. It wouldn't be that good for English, since there are many more words beginning with S or T than there are beginning with X or Q, so the buckets are very different sizes. If you have millions of keywords, it will be faster, but not fast enough. There are two problems to fix:
The table described is called a hash table. It's a very useful data structure. In fact, it is so useful that it's built into Python. There's a Python type (types are things like index and string) called the dictionary. It provides this functionality. At the end of this unit, you'll modify your search engine code to use the Python dictionary. However, before you learn about that, you'll learn to implement it yourself to make sure you understand how a hash table works.
My Notes: A Hash Table is a table with numbered bucket slots. Using a hash functions, an entry can be placed in a certain bucket by using the entry's keyword. The hash function maps a keyword to a number using the keyword's characters. That number is the bucket number in which that entry belongs in. It makes look up a lot faster....
Suppose we have b buckets and k keywords (k > b). Which of these properties should the hash function have? Recall that a hash function is a function which takes in a keyword and produces a number. That number gives the position in the table of the bucket where that input should be.
Next, define a hash function which will satisfy those properties. It will be called hash_string. It takes as its inputs a string and the number of buckets, b, and outputs a number between 0 and b-1.
What you will need, which has not been discussed yet, is a way to turn a string into a number. You may recall that there were two operators in the code to generate the big index, make_big_index, that were not explained. These were ord (for ordinal) and chr (for character). The operator ord turns a one-letter string into a number, and chr turns a number into a one-letter string.
ord(<one-letter string>) → Number chr(<Number>) → <one-letter string>
Examples:
print ord('a') 97 print ord('A') 65 print ord('B') 66 print ord('b') 98
Note that upper and lower case letters are mapped to different letters. Also note that the number for 'B' is higher than for 'A', and for 'b' it is higher than for 'a'.
A property of ord and chr is that they are inverses.((One function is the 'reverse' of the other)) This means that if you input a single letter string to ord and then input the answer to chr, you get back the original single letter. Similarly, if you input a number to chr and then input the answer to that into ord, you get back the original number (as long as that number is within a certain range.) This means that for any particular character, which we'll call alpha a, chr(ord(a)) → a. For example, in the code:
print chr(ord(u)) u print ord(chr(117)) 117
You can see below what happens if you enter a number which is too large.
print ord(chr(123456)) Traceback (most recent call last): File "C:\Users\Sarah\Documents\courses\python\testing.py", line 1, in <module> print ord(chr(123456)) ValueError: chr() arg not in range(256)
From the last line of the error message, ValueError: chr() arg not in range(256), you can see that chr() requires its input to be in the list of integers given by range(256), which is a list of all the integers from 0 to 255 inclusive.
The numbers given by ord are based on ASCII character encoding. What these numbers are doesn't matter for the purpose of making a hash table. All that is important is that they are different for each letter. You'll be able to use ord to turn characters into numbers. The limitation of ord is that it can only take one letter as input. If you try to input more, you'll get an error message. {{#!highlight python print ord('udacity') Traceback (most recent call last):
File "C:\Users\Sarah\Documents\courses\python\testing.py", line 2, in <module>
TypeError: ord() expected a character, but string of length 7 found }}} The last line tells you that you should just input a character, i.e. a single letter string, but instead you've input a string of length 7.
You now have a way to convert single character string to numbers which is ord. Next, you'll need a way to take care of the other property the hash function has to have which is to map the keywords to the range 0 to b-1.
The modulus operator (%) will be the tool used to change whatever values are calculated for strings into the range 0 to b-1. The modulus operator takes a number, divides it by the modulus and returns the remainder.
<''number''> % <''modulus''> → <''remainder''>
It's like clock arithmetic. The clock has <modulus> numbers on it. If you start counting from the top of a clock, and you count around <number> of steps, you arrive at the <remainder>. For example, if you want to work out 14 % 12, you can think about a clock with 12 numbers. If you count 14 steps, you end up at 2, that is, 14 % 12 → 2.
That's the same as the remainder when you divide 14 by 12. When you divide 14 by 12, you get a remainder of 2 since :
. 14 = 12 * 1 + 2
The remainder given by modulus is a number between 0 and <modulus> - 1. This is good news when we're looking for something for our hash function to give us values between 0 and b-1, where b is the number of buckets.
In terms of the code:
print 14 % 12 2
What is the value of each expression? Try to think of what the answer might be. You can also test it out in the Python interpreter.
a. 12 % 3 a. ord('a') % ord('a') Try to do this without working out what the ord of 'a' is. a. (ord('z') + 3) % ord('z')
Which of these expressions are always equivalent to x, where x is any integer between 0 and 10:
The hash function takes two inputs, the keyword and the number of buckets and outputs a number between zero and buckets minus one (b-1), which gives you the position where that string belongs.
You have seen that the function ord takes a one-letter string and maps that to a number.
And you have seen the modulus operator, which takes a number and a modulus and outputs the remainder that you get when you divide the number by the modulus.
You can use all of these to define a hash function. Here is an example of a bad hash function:
def bad_hash_string (keyword, buckets): return ord(keyword[0]) % buckets # output is the bucket based on the first letter of the keyword
Why is bad_hash_string a bad hash function?
Now you know that looking at just the first letter does not work very well; it does not use enough buckets, nor does it distribute the keys well. Here is how you can make a better hash function:
Begin with the same properties you had before, a function with two inputs, the keyword and the number of buckets. The output is the hash value in the range of zero to number of buckets minus 1.
The goal is for the keywords to be well distributed across the buckets and every time you hash the same keyword, you will get the same bucket to know quickly where to find it.
In order to make a more robust hash function, you are going to want to look at more than just one letter of the keyword. You want to look at all the letters of the keyword and based on all the letters you want to decide their bucket.
Recall that when you have a list of items you can use the for loop to go through the elements in the list:
p = [''"a", "b''', ...] for e in p: <''block''>
This is also the same for strings:
This gives you a way to go through all of the elements in a string. Also recall how you turned single letter strings into numbers with an modulo arithmetic, then you know enough to define a much better hash function.
Define a function, hash_string, that takes as its input a keyword (string) and a number of buckets, and outputs a number representing the bucket for that keyword. Do this in such a way that it depends on all the characters in the string, not just the first character. Since there are many ways to do this, here are some specifications:
Make the output of hash_string a function of all the characters. You can think about this in terms of modulo arithmetic:
The image shows a circle, which is the size of the number of buckets, and goes from zero to the number of buckets minus 1. For each character start at zero and go around the order of that character, ord(s[0]), distance around the circle. Then, keep going so that for each character you go some distance around the circle. The circle can be any size depending on the number of buckets, for example 27.
Which bucket will a and b land in?
hash_string('a', 12) = 1 # 11 will be the last bucket ord('a') = 97 # go around the circle eight times, b/c 97 is 12 * 8 + 1 hash_string('b', 12) = 2 ord('b') = 98
The size of the hash table matters as well as the string:
hash_string('a', 13) = 6 # this is because 97 = 13 * 7 + 6
What about multi-letter strings?
hash_string('au, 12') => 10 ord('a') = 97 ord('u') = 117 # add to 97 and modulo the sum, 214 to the number of buckets, 12, which equals 10 hash_string('udacity', 12) => 11
Now try the quiz!
Test your new hash function to make sure it does better than the bad hash function, using the same url from the example before.
def test_hash_function(func, keys, size): results = [0] * size #this makes a list where all elements refer to same thing(0) keys_used = [] for w in keys: if w not in keys_used: hv = func(w, size) results[hv] += 1 keys_used.append(w) return results words = get_page('').split() # initialize all the words from the page 'Adventures of Sherlock Holmes' counts = test_hash_function(bad_hash_string, words, 12) # obtain the counts for the old string print counts [725, 1509, 1066, 1622, 1764, 834, 1457, 2065, 1398, 750, 1045, 935] counts = test_hash_function(hash_string, words, 12) # find the distribution for the new function [1363, 1235, 1252, 1257, 1285, 1256, 1219, 1252, 1290, 1241, 1217, 1303]
Have a look at the distribution of the keywords into the buckets. Compare the first function, bad_hash_string, to the new function, hash_string:
NOTE: The hash function is not perfect. Depending on the keys and the number of buckets, it is still possible for all or most of the keywords to end up in a few buckets. It's still being studied....
Now try changing the number of buckets:
Building a good hash function is a very difficult problem. As your tables get larger it is very important to have an efficient hash function and while yours is not the most efficient, it is going to work for your purposes. Check out the website for more examples of how to build an even better hash function.
Assuming our hash function distributes keys perfectly evenly across the buckets, which of the following leaves the time to lookup a keyword essentially unchanged?
There may be more than one answer.
By now you should understand that the goal of a hash table is to map a keyword and a number of buckets using a hash_string function, to a particular bucket, which will contain all of the keywords that map to that location.
Now, try and write the code to do this! You can start with the index you wrote for the previous unit and try to figure out how to implement that with a hash table.
How is this going to change your data structure? Recall the data structure from the last class.
What data structure should we use to implement our hash table index?
[<word>, [<url>, ...](/wiki/%3Cword%3E%2C%20%5B%3Curl%3E%2C%20%E2%80%A6), ... ]
[<word>, [[<url>, ...], [<url>, ...](/wiki/%3Cword%3E%2C%20%5B%5B%3Curl%3E%2C%20%E2%80%A6%5D%2C%20%5B%3Curl%3E%2C%20%E2%80%A6), ...]
%5B%3Cword%3E%2C%20%5B%3Curl%3E%2C%20%E2%80%A6), [<word>, [<url>, ..., ...], ...]
[[<word>, <word>, ... ], [<url>, ...](/wiki/%5B%3Cword%3E%2C%20%3Cword%3E%2C%20%E2%80%A6%20%5D%2C%20%5B%3Curl%3E%2C%20%E2%80%A6), ... ]
The first thing you want to do to implement your hash table index, is figure out how to create an empty hash table. With a simple index, this was really easy, just make an empty list and as you add elements to the list, just add them to the empty list.
index = []
Unfortunately, this will not work for an empty hash table because you need to start with all the buckets. The initial value for the hash table needs to be a set of empty buckets so that you can do lookups right away. You also want to be able to add elements to your hash table.
If you just started with an empty list, then the first time you looked up a keyword it would say that keyword belongs in bucket 27, but since you don't have a bucket for that you would have to figure out how to create that bucket. It makes more sense to start by making an empty hash table be a list of buckets, where initially all the buckets are empty, ready and waiting for keywords to be dropped in them. So, what you need is code to create the empty hash table.
Define a procedure, make_hashtable, that takes as input a number, nbuckets, and outputs an empty hash table with nbuckets empty buckets.
Why does [[]] * nbuckets not work to produce our empty hash table?
NOTE: Because all the elements refer to the same empty list. So when you append, your changing the one object that all the elements refer to. It is possible to change what the list element is referring to by making the element equal to a new list. Then it will not refer to the same empty list.
Both operations you will perform on a hash table, i.e. lookup (read) and add (write), depending on first being able to find the right bucket:
Define a procedure, hashtable_get_bucket, that takes two inputs - a hash table and a keyword - and outputs the bucket where the keyword could occur. Note that the bucket returned by the procedure may not contain the searched for keyword in case the keyword is not present in the hash table:
hashtable_get_bucket(hashtable, keyword) # => list: bucket
Function hash_string, defined earlier, may prove useful:
hash_string(keyword, nbuckets) # => number: index of bucket
Note that there is a little mismatch between those two functions. The function hashtable_get_bucket takes hash table and the searched for keyword as its arguments, while the function hash_string takes the keyword and nbuckets, which is a number (size of the hash table).
The former function does not have any input like this, which means that you will need to determine the size of hash table yourself.
Hint: whole implementation of hashtable_get_bucket function might be done on a single line.
Define a procedure:
hashtable_add(htable, key, value)
that adds the key to the hash table (in the correct bucket). Create a new record in the hash table even if the given key already exists. Also note that records in the hash table are lists composed of two elements, where the first one is the key and the second one is the value associated with that key (i.e. key-value pairs):
[key, value]
Define a procedure:
hashtable_lookup(htable, key)
that takes two inputs, a hash table and a key (string), and outputs the value associated with that key. If the key is not in the table, output None.
Define a procedure:
hashtable_update(htable, key, vaue)
that updates the value associated with key. If key is already in the table, change the value to the new value. Otherwise add a new entry for the key and value.
You will perform both operations on a hash table, i.e. lookup (read) and add (write), depend on first being able to find the right bucket:
Now that you've built a hash table for yourself, you'll see an easier way to do it using the built-in Python type dictionary. It's an implementation of a hash table, and it's easier to use than defining your own hash table.
You've already seen two complex types in Python, string type and list type. The dictionary type is another. These three types have many things in common but other things are different.
To create a string, you have a sequence of characters inside quotes ' '. To create a list, you use square brackets [ ] and have a sequence of elements inside the square brackets, separated by commas. The elements can be of any type, unlike with a string which has to be made up of characters. The dictionary type is created using curly brackets { }, and consists of key:value pairs. The keys can be any immutable type, such as a string or a number, and the values can be of any type.
Recall a strings is immutable which means that once it is created, the characters can not be changed. A list is mutable, which means it can be changed once it's been created. A dictionary is also mutable and its key:value pairs are updated like in your update function for hash tables. In other words, if the key isn't in the list, it's created, and if it is, it's changed to the new value. The differences, and similarities between a string, list and dictionary are summarised below.
You can create a dictionary using { }. For the example below, the key:value pairs are the chemical elements along with their atomic numbers.
elements = { 'hydrogen': 1, 'helium': 2, 'carbon': 6 } print elements {'helium': 2, 'hydrogen': 1, 'carbon': 6}
Unlike with a list, when the elements are printed out, the key:value pairs can be in a different order from the order they were entered into the dictionary. When you made a hash table and put elements into it, you saw that the position of the elements in the table was not necessarily the same order as they were entered as it depended on the key and the hash function. You see the same thing with the dictionary as with your hash table as the dictionary is implemented like a hash table.
When you look up a chemical element in the dictionary, the value associated with that element is returned.
print elements['hydrogen'] 1 print elements['carbon'] 6
What do you think will happen when you try to lookup an element which is not in the list?
print elements['lithium'] Traceback (most recent call last): File "C:\Users\Sarah\Documents\courses\python\dummy.py", line 5, in <module> print elements['lithium'] KeyError: 'lithium'
You get a KeyError which tells you that "lithium" is not in the dictionary. Unlike in your lookup where you defined it to return None if the key is not there, you get an error if a key is not in a dictionary and you try to do a lookup on it.
To prevent this error, you can check if a key is in the dictionary using in, just like with lists. Just like for lists, it will return True if the key in in the list and False if it is not.
print 'lithium' in elements False
As a dictionary is mutable, it can be added to and changed. Using elements['lithium'] on the left hand side of an assignment does not cause an error even though "lithium" is not in the dictionary. Instead it adds the key:value pair "lithium":3 to the dictionary.
elements['lithium'] = 3 elements['nitrogen'] = 8 print elements {'helium': 2, 'lithium': 3, 'hydrogen': 1, 'nitrogen': 8, 'carbon': 6} print element['nitrogen'] 8
Although this gives the output expected, the atomic number of "nitrogen" is actually 7 and not 8, so it needs to be changed. As "nitrogen" is already in the dictionary, this time:
elements['nitrogen'] = 7
doesn't create a new key:value pair, but instead it updates the value associated with "nitrogen". To see that, you can see print the value:
print element['nitrogen'] 7
and the complete dictionary.
print elements {'helium': 2, 'lithium': 3, 'hydrogen': 1, 'nitrogen': 7, 'carbon': 6}
Define a dictionary, population, that provides information on the world's largest cities. The key is the name of a city (a string), and the associated value is its population in millions.
Shanghai 17.8 Istanbul 13.3 Karachi 13.0 Mumbai 12.5
If you don't happen to live in one of those cities, you might also like to add your hometown and its population or any other cities you might be interested in. If you define your dictionary correctly, you should be able to test it using print population['Mumbai'] for which you should get the output 12.5.
Now to return to the elements dictionary, but this time, to make it more interesting. The chemical element dictionary from earlier just contains elements and their atomic numbers.
elements = { 'hydrogen': 1, 'helium': 2, 'carbon': 6 } elements['lithium'] = 3 elements['nitrogen'] = 8 print elements['nitrogen'] elements['nitrogen'] = 7 print elements['nitrogen']
Values don't have to be numbers or strings. They can be anything you want. They can even be other dictionaries. The next example will have atomic symbols as keys with associated values which are dictionaries. First, an empty dictionary is created and then hydrogen, with key "H" and helium, with key "He" are added to it.
elements = {} elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794} elements['He'] = {'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True}
The code:
elements['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}
sets"H" as the key with associated value the dictionary {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}. This dictionary has three entries with the keys "name", "number" and "weight". For helium, "He" is the key and a dictionary containing the same keys as "H" but with an extra entry which has key "noble gas" and value True.
The dictionary of key:value pairs, atomic_symbol:{dictionary} is shown below.
print elements {'H': {'name': 'Hydrogen', 'weight': 1.00794, 'number': 1}, 'He': {'noble gas': True, 'name': 'Helium', 'weight': 4.002602, 'number': 2}}
To see the element hydrogen, look up its key which is 'H'.
print elements['H'] {'name': 'Hydrogen', 'weight': 1.00794, 'number': 1}
Note that the elements appear in a different order from the order they were input as elements['H'] is a dictionary.
To look up the name of the element with symbol H, use:
print elements['H']['name'] Hydrogen
where elements['H'] is itself a dictionary and "name" is one of its keys.
You could also lookup the weights of hydrogen and of helium, or check if helium is a noble gas.
print elements['H']['weight'] 1.00794 print elements['He']['weight'] 4.002602 print elements['He']['noble gas'] True
What happens if you try to check if hydrogen is a noble gas?
print elements['H']['noble gas'] Traceback (most recent call last): File "C:\Users\Sarah\Documents\courses\python\dummy.py", line 11, in <module> print elements['H']['noble gas'] KeyError: 'noble gas'
It's the same error as for the attempted lookup of lithium in the dictionary of elements which didn't include it. It tries to look up "noble gas" but it doesn't exist in the dictionary which is associated with the key "H".
Modifying the search engine code from the previous unit to use dictionary indexes instead of list indexes has the advantage of doing lookups in constant time rather than linear time.
Which of the procedures in your search engine do you need to change to make use of a dictionary index instead of a list index?
Code
def get_all_links(page): links = [] while True: url, endpos = get_next_target(page) if url: links.append(url) page = page[endpos:] else: break return links def crawl_web(seed): tocrawl = [seed] crawled = [] index = [] while tocrawl: page = tocrawl.pop() if page not in crawled: content = get_page(page) add_page_to_index(index, page, content) union(tocrawl, get_all_links(content)) crawled.append(page) return index def add_page_to_index(index, url, content): words = content.split() for word in words: add_to_index(index, word, url) def add_to_index(index, keyword, url): for entry in index: if entry[0] == keyword: entry[1].append(url) return # not found, add new keyword to index index.append([keyword, [url]]) def lookup(index, keyword): for entry in index: if entry[0] == keyword: return entry[1] return None
Change the lookup procedure to use a dictionary rather than a list index. This does not require any loop. Make sure an error is not raised if the keyword is not in the index; in that case, return None.
Congratulations! You have completed unit 5. You now have a search engine that can respond to queries quickly, no matter how large the index gets. You did so by replacing the list data structure with a hash table, which can respond to a query in a time that does not increase even if the index increases.
The problem of measuring cost, analyzing algorithms and designing algorithms that work well when the input size scales, is one of the most important and interesting problems in computer science.
Now, all you have left to do for your search engine is to figure out a way to find the best page for a given query instead of just finding all of the pages that have that keyword. This is what you will learn in unit 6. | https://www.udacity.com/wiki/cs101/unit-5-draft | CC-MAIN-2016-44 | refinedweb | 7,916 | 70.13 |
How shall I put it,
Are random functions (such as rand() or the ones boost offers) guaranteed to produce the same sequence of numbers on every machine, given that the function is seeded the same?
Thank you!
Printable View
How shall I put it,
Are random functions (such as rand() or the ones boost offers) guaranteed to produce the same sequence of numbers on every machine, given that the function is seeded the same?
Thank you!
That is very likely, yes, if not guaranteed.
Basically, they would compute mathematical formulas on the seed to get their "random" numbers.
Each implementation will give the same value for the same seed, I believe (so any VS2007 implementation should give the same values) -- or at least I'm not aware of any that differ, but it won't be the same from implementation to implementation.
This is just what I was hoping to find out.
Thank you!
So, to clarify:
As long as it is the same source code and seed, yes. However, bear in mind that in most cases, your C runtime is a shared library (.dll or .so depending on the OS). This means that your application does not contain the actual implementation of the random number generation.
You can (in most cases) make sure that the rand() or similar function is part of your application - this is called "static linking" - but there are drawbacks in the sense that you then get a much larger .exe, and any fixes to improve the C runtime that was compiled into your application will require a recompile - whilst the shared library build would automatically use the newer version if one is installed on the machine.
If you really want to ENSURE this behaviour, implementing your own random number generator (based on known good algorithms - do not attempt to write your OWN algorithm for a random number generator) is probably the safest option. And of course, if you ever want portability between different compilers, different OS's or different C runtime libraries, you will almost certainly have to do your own code.
For a small distribution base, you may simply do the "statically linked C runtime" and be done with it.
--
Mats
For where you need guaranteed same sequence across different implementations, I would just include a pseudo-random number generator in your code. Something like Mersenne Twister. The official site has a reference implementation, too, that is quite short and only requires <stdio>, and is under a liberal license..
I'd say to grab one of George Marsaglia's implementations of one of the simpler algorithms and never look back.
Soma
It's this simple -
Code:
#include "mt19937.ar.c"
int main() {
init_genrand(12345);
unsigned int random_number = genrand_int32();
}
In addition, it can only be done with hardware support (collecting truly random noise from the nature), since computers are deterministic by nature.In addition, it can only be done with hardware support (collecting truly random noise from the nature), since computers are deterministic by nature.Quote:
There are methods for producing truly random numbers, but they are non-trivial.
Well, software implimentations are never truly random, they are pseudo-random, and fully deterministic by nature. | http://cboard.cprogramming.com/cplusplus-programming/110796-question-about-random-repetition-printable-thread.html | CC-MAIN-2015-22 | refinedweb | 530 | 58.11 |
Now that you can
detect when the cheese and the bread collide, you need to make the
cheese "bounce" off the bat. Because the bread is horizontal, it makes
sense to bounce the cheese up and down the screen so that whenever the
cheese hits the bat, it reverses its movement in the Y direction. The
code to achieve this is very simple; you do the same thing with the YSpeed as you do when the cheese hits the top or bottom of the game region:
if (cheese.SpriteRectangle.Intersects(bread.SpriteRectangle))
{
cheese.YSpeed = cheese.YSpeed * -1;
}
This code can be placed at the end of the Update method to cause the cheese to bounce off the bat.
When you run the game,
you find that it works well, and you can guide the cheese around the
screen successfully. However, you make the mistake of letting your
younger brother have a go, and he’s soon complaining that there’s a bug
in your game. Sometimes the cheese gets "stuck" on the bread. You ask
him to show you what happens, and it turns out that he’s right. It seems
to happen when the bread is moving when it hits the cheese. The cheese
travels along the bread, vibrating up and down as it moves. After some
thought, you work out what’s causing the problem. Figure 3 shows what’s happening.
When the cheese
rectangle and the bread rectangle intersect, the program reverses the
direction of movement of the cheese. Normally, this means that the next
time the position of the cheese is updated, it moves away from the
bread, and the rectangles no longer intersect. However, if the cheese is
moving down and the bread is moving up when they collide, the cheese
goes so far "in" to the bread that, even after the cheese has been
updated, the bread and cheese rectangles still intersect. If this is the
case, the Update method reverses
the vertical direction of movement of the cheese, causing the cheese to
move back into the bread. This continues as the cheese moves along the
bread, following the path shown in Figure 12-3, until it finally escapes off the end. There are a number of ways you can solve this problem:
When
the cheese collides with the bread, the program could stop detecting
collisions for a while, giving the cheese a chance to move clear of the
bread. To implement this, you need to add a variable to count a certain
number of ticks after the collision and not allow collisions until after
that number of ticks.
The
program could move the cheese away from the bread after a collision so
that the two sprite rectangles no longer intersect at the next update.
To implement this, you need to know which direction the cheese is moving
so that you can move it appropriately.
You
could change the rules of the game and tell the player about this
special trick shot where a skillful player can send the cheese in a
particular direction by making it stick to the bat in this way. This
would require no additional programming at all.
The important thing to
remember is that because you own the game universe, including what you
say the game is supposed to do, you can change the rules to suit what
your program does. The Great Programmer doesn’t have this freedom;
usually she’s paid a large sum of money to create a solution that does
what the customer wants. However, quite a few games have turned out the
way they are because of the way the programmer made them work or because
of a bug that turned out to make the game more fun. In this case, you
decide to use the third approach and tell your younger brother that the
game is meant to work like that, and he has found a secret feature.
Your younger brother
is now very pleased with himself and with you. He is pleased with you
for making a game that rewards clever play and pleased with himself for
finding this new trick in the game. However, this doesn’t last long
because he soon comes back and tells you that he’s found a proper bug in
the game. He can make the cheese go right off the screen and not come
back. You ask him to show you, and sure enough, if he uses the bread to
chase the cheese right to the top of the screen, he can send the cheese
right off the screen. This is definitely a bug, and you can’t pass it
off as a feature.
One of the great things
about XNA Game Studio is that you can stop the game and take a look at
what’s happening. Once you’ve persuaded your younger brother to make the
problem happen, you can put a breakpoint into the program and stop it
so that you can look at the values of the variables. You can do this
even as the program is running, either on the Xbox, Zune or Windows PC
You can put a breakpoint in the Update
method by clicking next to the line at which you want it to stop. XNA
Game Studio indicates that a breakpoint has been set by highlighting the
line, as shown in Figure 4.
The
next time the program reaches this statement, it stops, and XNA Game
Studio enters debugging mode. You can then look at the values of the
variables to see what’s going wrong. When you take a look at the values in the cheese sprite, you find that
the X coordinate value is fine, but the Y coordinate is –50, which is very wrong. The cheese Y
coordinate should never get as low as this because the direction of the
cheese movement should reverse when it reaches an edge. You take
another look at the code that does this, and it looks sensible:
if (cheese.Y <= minDisplayY)
{
cheese.YSpeed = cheese.YSpeed * -1;
}
If the cheese Y
value becomes less than the minimum it’s allowed to have, the direction
of movement is reversed to bring it back onto the screen. The program
does this by multiplying the speed of the cheese by –1, which made
perfect sense when you wrote it. You take a look at the cheese YSpeed
and find that for the size of the screen you are using it has been
calculated as 4. This means that next time the cheese is updated, the Y position of the cheese will be changed to –46 (which is still much lower than it’s supposed to be). The result is that the same condition triggers again, reversing the direction of the YSpeed and sending the Y
position of the cheese back to –50. So the cheese remains forever off
the screen, dancing backward and forward just out of view. The problem
happens because the bread collision testing is performed after the
cheese has been made to bounce when it hits the edge of the screen, so
if the cheese repeatedly bounces off the bread when it’s on the edge of
the screen, it can be made to vanish like this.
There are a number of
ways you can fix this bug. You can stop the bread from going too close
to the edges so that it can’t harass the cheese like this, or you can
fix the bouncing problem of the cheese. You can’t really say that this
behavior is a feature, although you could create a completely different
game where the aim was to push all the objects off the screen, perhaps
something called "Herd the Cheese" or "Sweep the Table." However, you
decide to fix the problem.
The problem lies with
the use of multiplication by –1 to change the direction of movement. If
the next update brings the cheese back into the required range, then all
is well, but if by some mischance it doesn’t, you get the dancing
behavior that you’ve just uncovered.
The best way to fix this
is to set the direction of movement of the cheese explicitly to the one
in which you need it to go. Rather than bouncing, where you simply
reverse the sign of the speed value, you should say, "If the cheese Y
position is less than the limit, then make the movement positive so
that this always brings the cheese back onto the screen." Even if the
cheese Y position remains less
than the limit next time, the movement will still be correct and result
in the cheese heading in the right direction.
This turns out to be easy. You can use a method called Abs, which is provided by .NET. The Abs method is held in the Math
class and returns the absolute value or magnitude of a number. The
absolute value of a number is simply its value, if the number is zero or
positive, or the opposite of its value if the number is negative. For
example, the absolute value of –4 is 4. The Math class provides a number of static methods (which are always available) for use in your programs. The Math class is in the System namespace, so you can use it without having to add any using directives to your program. The code to deal with the Y position of the cheese ends up looking like this:
if (cheese.Y + cheese.SpriteRectangle.Height >= maxDisplayY)
{
cheese.YSpeed = Math.Abs(cheese.YSpeed) * -1;
}
if (cheese.Y <= minDisplayY)
{
cheese.YSpeed = Math.Abs(cheese.YSpeed) ;
}
If the cheese is too
high, you make it move downward. If the cheese is too low, you make it
move upward. Now there’s no way the cheese can get stuck off the screen.
Unfortunately
it is still possible to move the bat off the screen, To solve this, you
have to add code to limit the movement of the bread. | http://mscerts.programming4.us/windows_phone/microsoft%20xna%20game%20studio%203_0%20%20%20adding%20bread%20to%20your%20game%20(part%203)%20-%20strange%20bounce%20behavior,%20strange%20edge%20behavior.aspx | CC-MAIN-2016-22 | refinedweb | 1,664 | 74.63 |
A framework which provides hooks for easy testing of your Java code, as it's built. JUnit. Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit. JUnit. This assumes that you've read a bit about testing; I'm not going to lecture framework which provides hooks for easy testing of your Java code, as it's builtJUnit
Note: The examples from these slides can be found in ~kschmidt/public_html/CS265/Labs/Java/Junit
This assumes that you've read a bit about testing; I'm not going to lecture here
The heart of this is a test case, a class which contains tests
A test is a method that test methods that you've written
The framework is found in junit.jar
On the CS machines, currently, is located at /usr/share/java/junit.jar
Some version < 4.0 as of 8/06
Each test case is a class you provide that extends (inherits from) TestCase
Contains:
member data
special admin-type methods:
setUp() – run before each test
tearDown() – run after each test
suite() – (static), a method that, basically, lists the tests to be added to the framework
the tests
methods that take no arguments
often start with or contain the string "Test" (for older versions of the framework)
The files for these examples can be found in:
~kschmidt/public_html/CS265/Labs/Java/Junit
MoneyTest written to test class Money
import junit.framework.*;
public class MoneyTest extends TestCase
{
public MoneyTest( String name ) {
super( name );
}
...
}
Add some Money objects to use in our tests:
public class MoneyTest extends TestCase
{
public MoneyTest( String name ) {
super( name );
}
private Money m12CHF;
private Money m12CHF;
protected void setUp() {
m12CHF= new Money( 12, "CHF" );
m14CHF= new Money( 14, "CHF" );
}
...
}
When you implement a method, the test for that method should actually be written first
Add a corresponding "test" method to your TestCase class
Takes no arguments
returns void
use various Assert methods to access hooks into the framework (pass/fail, logging)
Static methods of the class Assert
All are overloaded to take an optional message (a String) as the first argument
assertTrue( boolean condition )
assertFalse( boolean condition )
assertEquals( expected, actual )
overloaded to take any primitives, or anything derived from Object
Note, if subtypes of Object, need to override equals()
assertNull( Object )
assertNotNull( Object )
assertSame( Object expected, Object actual)
Checks to see that expected and actual refer to the same object (so, of course, are equal)
assertNotSame( Object expected, Object actual)
fail()
Just dumps the testing, w/the optional msg
We need to provide Money.equals():
public boolean equals( Object anObject ){
if( anObject instanceof Money ) {
Money aMoney= (Money)anObject;
return
aMoney.currency().equals( currency() )
&& amount() == aMoney.amount();
}
return false;
}
Add to MoneyTest:
public void testEquals() {
Money expected = new Money( 12, "CHF" );
Assert.assertEquals( expected, m12CHF );
Assert.assertEquals( m12CHF, m12CHF );
Assert.assertNotSame( expected, m12CHF );
Assert.assertFalse( m12CHF.equals( m14CHF ));
Assert.assertFalse( expected.equals( m14CHF ));
}
Add to MoneyTest:
public void testAdd() {
Money expected= new Money( 26, "CHF" );
Money result= m12CHF.add( m14CHF );
Assert.assertEquals( expected, result );
expected = new Money( 1, "CHF" );
result = m12CHF.add( md13CHF );
Assert.assertEquals( expected, result );
result = md13CHF.add( m12CHF );
Assert.assertEquals( expected, result );
}
You've written some tests
They need to be identified to the testing framework
Override the suite() static method
Create a TestSuite object
Use its addTest() method to add tests you want to run
You can write a suite() method that uses reflection to add all of the testXXX() methods in the TestCase class to the Suite:
public static Test suite() {
return new TestSuite( MoneyTest.class );
}
As a sanity check, after writing a test or two, you might want to make a little main method for the TestCase class:
public static void main( String args[] ){
String[] caseName = { MoneyTest.class.getName() }; junit.textui.TestRunner.main( caseName );
}
This will set up and run the tests
Make sure you didn't make any errors in the testing framework
(Remember to add junit.jar to $CLASSPATH to run this from the command line)
Tests should be silent. Do not under any circumstances use System.out.println in any test method. Rather, use assertions.
Before you add a method to your production class, think about the pre-conditions and post-conditions for the method: what needs to be in place before the method can be called, and what is supposed to have happened after the method returns? Then, capture the pre-/post-conditions as initialization code and assertions in a unit test method: initialize the pre-conditions, call the method, assert the post-conditions. This accomplishes two things: first, it ensures that you understand what the method is supposed to do before you write it. Second, it provides a test for the method that is available as soon as the method is ready to test.
*See Java code, as it's builtHints (cont.)(from Prof. Noll at Santa Clara Univ.)
When you are tempted to put System.out.println in your production code, instead write a test method. This will help to clarify your design, and increase the coverage of your unit tests. It also prevents ``scroll blindness'', as the tests say nothing until a failure is detected.
Don't put System.out.println in your production code (see also above). If you want to do this to observe the behavior of your program, write a unit test to assert its behavior instead. If you need to print to stdout as part of the program's functionality, pass a PrintWriter or output stream to those methods that do printing. Then, you can easily create unit tests for those methods.
<target name='test' depends='compile'>
<junit>
<formatter type='plain'/>
<test name='MoneyTest'/>
</junit>
</target>
You can have Ant run these tests, as you write and compile each method
Add a target to build.xml
depends on the class and your TestCase being compiled
Might modify the classpath to include junit.jar
Have a jar action that describes the tests you want to run | http://www.slideserve.com/zoey/junit | CC-MAIN-2017-30 | refinedweb | 993 | 60.24 |
Android Dice Roller Source Code for Apps
An Android Dice Roller tutorial with source code for a basic dice roller app. OK it might not be a fancy 3D dice roller but it'll get you going. You can always upgrade your dice roller code later. Simply add the example source code to any app that requires a dice roll. Dice face images and a 3D dice icon image are provided, all the images and code are free to use and royalty free. The code here is for a six sided dice but can be adapted for larger dice or more than one dice. There are no restrictions placed upon the code or the dice face images (all the images are free as they are in the public domain).
By the way (BTW) I know that dice is the plural and means two or more die, but it is common to refer to one die as a dice so we will be doing that here.
(This Android dice roller tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)
The Dice Face Images and Sound
The code given in this article is for a common six sided dice. A dice is a cube, and each side of the cube (each face) has one of the numbers from one to six. Here six PNG images are used to show the dice roll result. Plus there is a 3D image shown for the dice roll. The same 3D image is used for the app icon. The dice images are from Open Clip Art Library user rg1024.
The sound of a dice roll is stored in shake_dice.mp3. It is by Mike Koenig and is from SoundBilble.com.
All the resources ready to add into a Android Studio project are available from this dice resources Zip file.
Android Studio Dice Roller Project
For this tutorial start a new Android Studio project. Here the Application name is Dice and an Empty Activity is used with other settings left at default values. Add the dice resources (from above) to the project by copying them to the res folder. Studio will update the Project explorer automatically (or use the Synchronize option).
Optionally change the app icon entries in the AndroidManifest.xml file to dice3d and dice3d_rounded.png, i.e.
android:icon="@drawable/dice3d" and
android:roundIcon="@mipmap/dice3d_rounded".
Android Dice Roller Project Layout
The screen for the dice roller is very simple. Just an
ImageView which when pressed the roll is performed. If using the basic starting empty screen then open the activity_main.xml layout file. Delete the Hello World! default
TextView (if present). From the widget Pallete, under Images, drag and drop an ImageView onto the layout and select dice3droll on the Resources chooser dialog. (Add the constraints if using a
ConstraintLayout.)
The layout source should be similar to the following:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns: <ImageView android: </android.support.constraint.ConstraintLayout>
Android Dice Roller Source Code
A Java
Random class (to generate the dice numbers) is declared along with an Android
SoundPool (to play the dice roll sound). To load the right picture for each roll a switch statement is used. Some feedback is provided to the user so that they can see that a new roll has occurred. An identical number can be rolled in succession. To provide the feedback a 3D dice image will be displayed. However, because the roll happens so fast (unlike a real dice) the 3D image would not be seen. Therefore a
Timer is used to provide a delay. This allows the UI to update. The Timer sends a
Handler message signal to a
Callback to perform the roll (the same method as described in the post Why Your TextView or Button Text Is Not Updating). Finally the roll value is used to update the UI.
Update: The creation of the SoundPool object has changed due to the deprecation of the constructor in Android API 21 and later. The code has been changed to allow for this, using a
SoundPool.Builder. To support pre-Lollipop Android versions a new class is added to the project called PreLollipopSoundPool. The code for this new class follows this MainActivity class:
package com.example.dice; import android.media.AudioAttributes; import android.media.SoundPool; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { ImageView dice_picture; //reference to dice picture Random rng=new Random(); //generate random numbers SoundPool dice_sound; //For dice sound playing int sound_id; //Used to control sound stream return by SoundPool Handler handler; //Post message to start roll Timer timer=new Timer(); //Used to implement feedback to user boolean rolling=false; //Is die rolling? @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Our function to initialise sound playing InitSound(); //Get a reference to image widget dice_picture = (ImageView) findViewById(R.id.imageView); dice_picture.setOnClickListener(new HandleClick()); //link handler to callback handler=new Handler(callback); } //User pressed dice, lets start private class HandleClick implements View.OnClickListener { public void onClick(View arg0) { if (!rolling) { rolling = true; //Show rolling image dice_picture.setImageResource(R.drawable.dice3droll); //Start rolling sound dice_sound.play(sound_id, 1.0f, 1.0f, 0, 0, 1.0f); //Pause to allow image to update timer.schedule(new Roll(), 400); } } } //New code to initialise sound playback void InitSound() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //Use the newer SoundPool.Builder //Set the audio attributes, SONIFICATION is for interaction events //uses builder pattern AudioAttributes aa = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build(); //default max streams is 1 //also uses builder pattern dice_sound= new SoundPool.Builder().setAudioAttributes(aa).build(); } else { //Running on device earlier than Lollipop //Use the older SoundPool constructor dice_sound=PreLollipopSoundPool.NewSoundPool(); } //Load the dice sound sound_id=dice_sound.load(this,R.raw.shake_dice,1); } //When pause completed message sent to callback class Roll extends TimerTask { public void run() { handler.sendEmptyMessage(0); } } //Receives message from timer to start dice roll Handler.Callback callback = new Handler.Callback() { public boolean handleMessage(Message msg) { //Get roll result //Remember nextInt returns 0 to 5 for argument of 6 //hence + 1 switch(rng.nextInt(6)+1) { case 1: dice_picture.setImageResource(R.drawable.one); break; case 2: dice_picture.setImageResource(R.drawable.two); break; case 3: dice_picture.setImageResource(R.drawable.three); break; case 4: dice_picture.setImageResource(R.drawable.four); break; case 5: dice_picture.setImageResource(R.drawable.five); break; case 6: dice_picture.setImageResource(R.drawable.six); break; default: } rolling=false; //user can press again return true; } }; //Clean up protected void onPause() { super.onPause(); dice_sound.pause(sound_id); } protected void onDestroy() { super.onDestroy(); timer.cancel(); } }
To support APIs pre Lollipop add a new class called PreLollipopSoundPool in the same folder as the MainActivity class. Creating it as a separate class supports Java lazy loading, ensuring the app works when the deprecated method is removed from Android.
package com.example.dice; import android.media.AudioManager; import android.media.SoundPool; /** * Created a pre Lollipop SoundPool */ final class PreLollipopSoundPool { @SuppressWarnings("deprecation") public static SoundPool NewSoundPool() { return new SoundPool(1, AudioManager.STREAM_MUSIC,0); } }
The Android dice roller source code is now ready to run, either in an AVD or an actual Android device.
The complete source code is available in android_dice_roller.zip or from the Android Example Projects page. The code can be seen running using Dice.apk, also available from the projects page.
See Also
- The dice images were from the Open Clip Art Library by rg1024.
- The dice roll sound is from the SoundBible.com.
- See the other Android Studio example projects to learn Android app programming.
Archived Comments
Phil said on 27/09/2014: Nice code. I’m hoping to write a more complex Roller, and this is very useful!
Cesar said on 18/07/2013: I don't get it. I have tried and tried, but I don't get it. Line
handler=new Handler(callback); shows me an error. callback execution doesn't enter
handleMessage(Message msg). If I initialize
new Handler(callback); in other ways the app crashes. Can you help me, please? Thanks a lot!
Tek Eye said, in reply to Cesar, on 18/07/2013: Hi, the Handler class used here is from android.os and not java.util.logging, Callback is from android.os as well, though you probably used the correct imports. To help I’ve added a zip file with all the source code to the Android Example Projects page as well as a link in this article. You can import the code from the Zip file into a new Android project and run it to see it working. Failing that there is an APK file on the same page to install onto a device to see the code working (link to APK in article as well). Note you may need to change your device settings temporarily to allow the APK to be installed, only install APKs from trusted sources.
Author:Daniel S. Fowler Published: Updated: | https://tekeye.uk/android/examples/android-dice-code | CC-MAIN-2018-39 | refinedweb | 1,562 | 59.9 |
In 1964 Abraham Kaplan said: “Give a small boy a hammer, and he will find that everything he encounters needs pounding”.
Another famous version of this is known as Maslow’s hammer, and it goes like this: “if all you have is a hammer, everything looks like a nail”.
This post is about how every time there’s a new tool, new approach or an old idea made new in software, it becomes like a hammer in a small boy’s hands. And it will be used to pound on everything.
Read on for a few examples:
IoC Containers
If you write code that conforms to the Dependency Inversion Principle then it means that your classes do not depend on other concrete classes, they depend on abstractions, for example:
public class MyClass { private readonly IDependency1 _dependency1; private readonly IDependency2 _dependency2; private readonly IDependency3 _dependency3; public MyClass(IDepdendency1 dependency1, IDependency2 dependency2, IDependency3 dependency3) { _dependency1 = dependency1; _dependency2 = dependency2; _dependency3 = dependency3; } //... }
Creating an instance of this class “by hand” is a pain, you have to instantiate all of it’s dependencies:
MyClass myClass = new MyClass(new Dependency1(...), new Dependency2(...), new Dependency3(...));
An IoC container solves this problem, when you ask it for
MyClass it will get you an instance of
MyClass with all its dependencies instantiated. To do this it only needs you to specify rules for how to instantiate
IDependency1,
IDependency2 and
IDependency3. For example in StructureMap for
IDependency1 it would be something like this:
For<IDependency>().Use<Dpendency1>();
The neat thing about this is that if
Dependency1 has dependencies of its own, the IoC container will resolve them for you.
This is the problem that IoC containers solve. It is intimately related to the Dependency Inversion Principle and constructor injection.
To tie all of this up frameworks provide some mechanism to create types that you can extend and plug in your favourite IoC container. For example in ASP.NET MVC there’s an interface you can implement named IDependencyResolver with a method named
GetService(Type type) that gets called when a
Controller needs to be created. An implementation of it looks something like this:
public object GetService(Type type){ return YourFavoriteIoCContainer.Resolve(type); }
Is this how IoC containers are used? No, what you frequently see instead is what is known as the service locator pattern. The above example usually looks like:
public class MyClass { private readonly IDependency1 _dependency1; private readonly IDependency2 _dependency2; private readonly IDependency3 _dependency3; public MyClass() { _dependency1 = IoCContainer.Resolve<IDependency1>(); _dependency2 = IoCContainer.Resolve<IDependency2>(); _dependency3 = IoCContainer.Resolve<IDependency3>() } //... }
Usually the calls to the IoC container are spread all over the place, not only in the constructor.
So what is the problem of doing this? First, that code depends on a particular IoC container, so if you want to share it with someone that is using another IoC container then tough luck.
Second, you need the IoC container to instantiate that type, it won’t work without it. This becomes glaringly obvious when you find a code base where the unit tests need an IoC container to run.
It seems that the reasoning for using IoC containers was: “it’s a new thing we should all use, you should never
new up things in your code, so replace them all with
IoCContainer.Resolve, problem solved”.
There are also other more creative uses of IoC containers. When they were the new big thing it was easy to find code that would use them in conditional statements. For example, imagine you need to create different word documents, and you decide which to create through an IoC container:
IDocumentCreator documentCreator; if (templateToUse == "Letter") { documentCreator = IoCContainer.Resolve<IDocumentCreator>("letterTemplate"); }else if (templateToUse == "Book"){ documentCreator = IoCContainer.Resolve<IDocumentCreator>("bookTemplate"); } documentCreator.CreateDocument(...);
Most IoC containers allow you to specify a “named mapping”, i.e. you can create a rule that says when
IType is requested with name “A” resolve with
TypeX, when requested with name “B” resolve with
TypeY.
IoC containers were not designed with this type of scenario in mind, so much so that the above approach has the serious limitation of requiring a new
if statement and a new IoC mapping every time a new template type is added.
Generics
In .Net generics where introduced in version 2.0 of the framework. Before generics were introduced every time you used a collection, for example a
List, you would add its elements as type
object and when you wanted to retrieve them you would have to cast them to their original type (or a base class of that type).
For example:
ArrayList numbers = new ArrayList(); numbers.Add(1); numbers.Add(2); int firstNumber = (int)numbers[0];
The example above also illustrates what happened with value types. They had to be “boxed” and “unboxed”, which crudely means that the value types would have to be converted to
object (boxed) and be allocated in the heap, and when they were retrieved they had to be converted back to their original value type (unboxed) and that process was slow and lead to more garbage collections.
Generics solved this problem, no more casting for your data-structures and no more boxing and unboxing of value types.
A creative use of generics that somehow became popular is their use “to define dependencies”. In .Net it is possible to define constraints on the generic type, for example:
public class MyClass<T> where T: new(), IType { //... }
The
where T: new(), IType means that type T needs to provide a parameterless constructor and implement
IType.
This allows someone to write in a method of
MyClass<T>:
public void SomeMethod() { T t = new T(); t.DoSomething(); //DoSomething is a method that interface IType defines }
Instead of this
IType could be passed as a parameter in
MyClass‘s constructor. There’s absolutely no advantages in doing this with generics.
A sure sign that this is happening is if you generic type does not have any method returning any generic parameter.
Code regions
Code regions were a mechanism to delimit code that was generated by a tool (usually a visual designer) and therefore should not be touched. Before .Net had partial classes, if you’d create a Windows Forms application and opened the main Form you’d see something like this:
#region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { //... } #endregion
And you would know that if you changed any of the code in the region you would lose it as soon as you made any changes in the designer.
Somehow regions become a popular way to organize code. Is your class too long? No problem just organize the code in different regions:
#region Helpers ... #endregion #region Managers ... #endregion ...
I purposely named the regions
Helpers and
Managers. Two names that have no place in object oriented programming unless you are writing an application about football or something that needs a helper (can’t remember of any).
Also, here’s an interesting article about the more general idea of “code folding” being a design error.
Partial classes
Partial classes are a more elegant way to deal with generated code. Instead of putting it all in a region on the same file that you have to edit, put the generated part in a different file and let the compiler deal with putting it all together.
There’s no good reason for using partial classes if one of the partials is not generated code, but somehow partial classes became a way to deal with classes that become too big.
I’ve seen much of this in ASP.NET MVC where when controllers become too big, they are split up in partials, where each partial has a descriptive name, for example:
File: BookController_Retrieve.cs public partial class BookController: Controller { //action methods related to retrieving books } File: BookController_Storing.cs public partial class BookController: Controller { //action methods related to saving books }
There’s no good reason for using partials like this. The tragedy is that some of the visual studio templates use partial classes this way, if you create a new ASP.NET MVC application and select Individual User Accounts, the project is initialised with a Startup.cs with several partials.
Unit testing
The idea behind creating unit tests, and having an automated way of testing your code in general, is that you can find problems with your code without having to test it manually.
For all of this to work the tests have to follow certain rules. For example, they have to be written in a way that their execution order does not change their outcome. A very common problem is to find code bases where the unit tests share state, so they might not run if you change the order they are executed in.
In unit testing you are supposed to execute some code and verify if your expectations about that code are verified. There’s even a popular pattern for writing unit tests named “Arrange Act Assert” where you write some code to setup the state you want to test, call a method, and verify the result of calling that method.
The verification part, for some reason, is very frequently neglected. The reason for that is that a test will pass if no exception is thrown and virtually all testing frameworks provide asserting mechanisms that when fail throw an exception, here’s an example:
[Test] public void SomeMethod_SomeStateToTest_ExpectedResult() { SomeClass c = new SomeClass(); c.DoSomething(); }
The only way this test will fail is if an exception is thrown.
Another, slightly more elaborate version of this, but nearly as useless, is to just check if the return value is not null, for example:
[Test] public void SomeMethod_SomeStateToTest_ExpectedResult() { SomeClass c = new SomeClass(); var result = c.DoSomething(); Assert.IsNotNull(result); }
There are also other more creative uses for unit tests. Because the tooling makes it easy to run the tests with a click of a button they are sometimes used to populate databases using ORMs, for example:
[Test] public void PopulateDatabase() { var c = new EntitiesContext(); c.Table.AddOrUpdate(...); c.Table.AddOrUpdate(...); c.Table.AddOrUpdate(...); }
Conclusion
I don’t really have an explanation for why this is so prevalent in the software industry, maybe it’s because it’s dominated by men and everybody knows that “real men don’t read the instructions”.
Maybe technology, because it evolves so quickly, is frequently learned by word of mouth, and this process becomes a little bit like that game of Chinese whispers where details are lost along the way.
How about you dear reader? Do you think this just happens in software, or do you think other areas have their own version of “The daily WTF”? Have you seen some creative use for some tool/technology that completely misses the point? Please share in the comments! | https://www.blinkingcaret.com/2016/05/ | CC-MAIN-2019-09 | refinedweb | 1,799 | 51.58 |
Important: Please read the Qt Code of Conduct -
Qlabel scrolling text
- sagar.vekariya last edited by
i have a problem in QLabel.
my string length is larger then QLabel length so when displaying that label only that part appears.
i have to make QLabel that show string animated just like a marquee in Html in QLabel boundary.
Keep in mind that moving UI elements tend to be rather distracting. Perhaps a tool tip / popup is a better solution to your problem. Anyway here is a simple marquee
@
import QtQuick 2.0
import QtQuick.Controls 1.0
Rectangle {
width: 360
height: 360
Rectangle {
id: marquee
width: 100
height: label.height
color: "white"
clip: true
border.color: "lightgray"
anchors.centerIn: parent
Label {
id: label
x: 2
text: "Hello I am a very long label"
property int scrollLength: (label.implicitWidth - marquee.width) + 4
SequentialAnimation on x {
loops: Animation.Infinite
NumberAnimation { to: -label.scrollLength ; duration: 2000 ; easing.type: Easing.OutSine}
PauseAnimation { duration: 1000 }
NumberAnimation { to: 2 ; duration: 2000 ; easing.type: Easing.OutSine}
PauseAnimation { duration: 1000 }
}
}
}
}
@ | https://forum.qt.io/topic/35334/qlabel-scrolling-text | CC-MAIN-2021-21 | refinedweb | 171 | 53.68 |
A few months ago, Hugh accepted a contract assignment to work on a Java project and, ever since starting, his day-to-day has felt a bit like the old game of Zork: a maze of twisty passages, all alike. So far as he can tell, a large part of the system was created by a chimpanzee (possibly orangutan) that received a treat whenever it pressed a giant button marked "Copy and Paste". One of the class files that Hugh has spent a bit of time working on has over 10,000 lines of code and at least one method that's over 2,500 lines long.
As Hugh navigated through the numerous methods like processEntry1, processEntry2, etc., he noticed an interesting pattern start to emerge.
ParentID = MathUtil.getInteger(0); // Yuck
The comment wasn't his, but certainly expressed his sentiment. The code seemed like an overly complex way of writing "ParentID = 0;" and utilized that MathUtil class that was also all over the place. Against his better judgment, Hugh dove in to the code of the MathUtil class.
public class MathUtil { ...snip... private static final int NUM_CACHED_INTEGERS = 256; private static Integer[] arrCachedIntegers; static { arrCachedIntegers = new Integer[NUM_CACHED_INTEGERS]; for (int i = 0; i < NUM_CACHED_INTEGERS; i++) { arrCachedIntegers[i] = new Integer(i); } } public static Integer getInteger(final int i) { return ((i >= 0) && (i < NUM_CACHED_INTEGERS)) ? arrCachedIntegers[i] : new Integer(i); } ...snip... }/
He had never quite seen anything like that before. The getInteger() method was retrieving a pre-built Integer from an array of what looks like a harebrained effort to save memory by not creating a new Integer.
Yuck, indeed. | http://thedailywtf.com/Articles/The-Integer-Cache.aspx | CC-MAIN-2014-35 | refinedweb | 267 | 60.24 |
Timeline
Sep 15, 2011:
- 11:10 PM Ticket #5491 (build GHC binaries against GMP 5) created by
- Currently the development and release binaries are built against the …
- 8:37 PM Ticket #4956 (threadDelay behavior 64-bit mac os x) closed by
- worksforme: No response from submitter, and worked for me.
- 5:17 PM Ticket #4923 (HEAD unregisterised build broken: unlit missing) closed by
- fixed: unreg builds of 7.2.1 work, so presumably this was fixed at some point.
- 4:22 PM Ticket #5490 (Core lint error after desugaring) created by
- I was investigating a "PAP object entered!" crash and found out that …
- 3:34 PM Ticket #4892 (panic building darcs) closed by
- invalid: No testcase, so closing.
- 3:29 PM Ticket #4853 (Invalid links on web page) closed by
- fixed: The doc links work now, and I've just removed the out-of-date buildbot …
- 3:18 PM Ticket #4475 (unreliable ghc on sparc) closed by
- wontfix: Not a tier 1 platform, so closing.
- 1:21 PM Ticket #4219 (sequence is not tail recursive, doesn't work with large inputs in strict ...) closed by
- wontfix: We don't have a general way to optimise this, so closing.
- 10:02 AM Records edited by
- Linked to previous discussion about local modules. (diff)
- 9:56 AM Records edited by
- removed problems with namespace part (diff)
- 9:50 AM Records edited by
- Typo: binging => binding (diff)
- 9:45 AM Records edited by
- Add missing word 'other' in "Are there any other approaches?" (diff)
- 9:40 AM Records edited by
- Added some problems I've experienced with record name clashes. (diff)
- 9:34 AM Ticket #5489 (Win7: Bootstrapping 7.3 from 7.2.1 using msys git 1.7.6 causes integer-gmp ...) created by
- Following the getting started instructions and the approximate suggested …
- 8:48 AM Ticket #5485 (Build failure on powerpc-linux at compiler/stgSyn/CoreToStg.lhs line 188) closed by
- fixed: OK now I claim it's fixed! Try now.
- 8:46 AM Records edited by
- (diff)
- 8:43 AM Records edited by
- (diff)
- 8:43 AM Records created by
-
- 6:45 AM Ticket #5488 (GHC-7.2.1 standalone failed to bootstrap ghc-HEAD on windows) created by
- AR_STAGE0 gets set to: …
- 6:43 AM RunTimeData edited by
- (diff)
- 1:40 AM Ticket #5487 (LLVM broken at -O0) closed by
- fixed: OK. nevermind, this isn't present in 7.2.1. It was in 7.0.3.
- 1:30 AM Ticket #5487 (LLVM broken at -O0) created by
- The LLVM Mangler doesn't seem to be getting run at -O0. So no compiles …
- 1:13 AM Ticket #5486 (LLVM can't compile HsOpenSSL) created by
- […] Also seems to be some mangler problems.
Sep 14, 2011:
- 11:56 PM Ticket #4194 (add no spaces allowed in new qualified operators to user guide) closed by
- fixed: NewQualifiedOperators was removed, so this ticket is now redundant.
- 4:23 PM Ticket #5478 (GHC panics when asked to derive Show for ByteArray#) closed by
- fixed: Thanks for finding this bug.
- 11:05 AM Ticket #5485 (Build failure on powerpc-linux at compiler/stgSyn/CoreToStg.lhs line 188) closed by
- fixed
- 8:13 AM Ticket #5485 (Build failure on powerpc-linux at compiler/stgSyn/CoreToStg.lhs line 188) created by
- Current GHC head fails to build on powerpc-linux: […] Resetting to …
- 7:15 AM KindFact edited by
- (diff)
- 12:07 AM SafeHaskell edited by
- (diff)
- 12:03 AM SafeHaskell edited by
- (diff)
Sep 13, 2011:
- 11:57 PM Ticket #4117 (GHC does not accept --srcdir) closed by
- wontfix: I don't think this will ever be a high priority for us, so I'm going to …
- 11:48 PM Ticket #4062 (Bad choice of loop breaker?) closed by
- invalid: No testcase, so closing
- 9:03 PM Ticket #3993 (allow implicit parameter bindings in patterns) closed by
- wontfix: This seems to have little support, so I'll close the ticket.
- 8:38 PM Ticket #3829 (GHC leaks memory when compiling many files) closed by
- worksforme: I had a look a --make's memory usage a while ago, but it seemed that the …
- 8:26 PM Ticket #3743 (type checker fails to infer an implicit parameter constraint in the ...) closed by
- fixed: This now works. I've added a test.
- 6:12 PM Ticket #3737 (inlining happens on foldl1 and does not happen on direct application of ...) closed by
- fixed: Hopefully fixed, and no response from submitter, so closing.
- 6:09 PM Ticket #3715 (GHC API no longer exports location information for error/warning messages) closed by
- fixed: The problem is fixed, so closing the ticket.
- 4:19 PM Ticket #3608 (Build the ghc-bin package in the standard way) closed by
- fixed: ghc-bin uses Cabal nowadays.
- 10:00 AM Ticket #5465 (deepseq missing NFData instances for (->), Data.Fixed and Data.Version) closed by
- fixed: Pushed.
Sep 12, 2011:
- 2:32 PM Ticket #5484 (HEAD build fails with ghc-7.2.1) created by
- Buidling HEAD with ghc-7.2.1 as bootstrapping compiler fails with a …
- 1:56 PM KindFact edited by
- (diff)
- 1:54 PM KindFact edited by
- (diff)
- 12:59 PM KindFact edited by
- (diff)
- 9:57 AM Ticket #5483 (Eta-reduced term has wrongly inferred monomorphic type) closed by
- invalid: * Why rowtotals' is monomorphic: …
- 9:46 AM Ticket #1799 (Retain export-list order in ModIface, use it in :browse) closed by
- fixed: The order is now stable, so closing. We may in the future use info from …
- 9:45 AM Ticket #3507 (In TH, allow e.g. (type T) rather than ''T) closed by
- wontfix: No support for this, so closing as wontfix.
- 9:35 AM Ticket #5483 (Eta-reduced term has wrongly inferred monomorphic type) created by
- Hi, When creating a file with the following two definitions: […] And …
Sep 11, 2011:
- 6:13 PM Ticket #2897 (HsFFI.h is not in the default include path for hsc2hs) closed by
- fixed: I'm going to declare this fixed by: […]
- 5:46 PM Ticket #5481 (Associated type defaults + MultiParamTypeClasses error) closed by
- fixed
- 5:43 PM Ticket #2911 (Error messages have the wrong qualified names) closed by
- wontfix: I'm going to close this as not worth fixing. After all, errors are already …
- 5:40 PM Ticket #5482 (isSymbolicLink doesn't work) closed by
- worksforme: I suspect you're using getFileStatus rather than …
- 5:24 PM Ticket #5482 (isSymbolicLink doesn't work) created by
- This function from System.Posix.Files (unix-2.5.0.0) always returns False …
- 4:50 PM Ticket #2281 (properFraction implemented with modf primitive?) closed by
- wontfix: I'm going to close this ticket, but I suggest that if anyone is interested …
- 2:46 PM Ticket #5353 (Cabal bug building haddock, alex, happy, etc) closed by
- fixed: Fixed by […] in Cabal HEAD, and Duncan says he'll make a new stable …
- 2:14 PM Ticket #5481 (Associated type defaults + MultiParamTypeClasses error) created by
- If I try this with GHC HEAD as of yesterday: […] I get this error: …
- 1:49 PM Ticket #5477 (Missing space in Windows cmd.exe invocation breaks shell command ...) closed by
- fixed: Applied, thanks: […]
- 1:30 PM Ticket #5450 (copy-pasto in IntMap docs) closed by
- fixed: Thanks, fixed. Also improved the documentation of fromListWith.
- 10:55 AM Ticket #5479 (The impossible happened!) closed by
- duplicate: Thanks for the report. I'll close this ticket as it's a duplicate of …
- 10:19 AM Ticket #5480 (Ghc 7.2.1 does not build anymore on NetBSD) created by
- While ghc 7.0.4 builds fine, changes between 7.0.4 and 7.2.1 breaks the …
- 7:22 AM Ticket #5479 (The impossible happened!) created by
- Running my haskell script gives me the following error: eliza.hs: …
Sep 10, 2011:
- 3:55 PM Ticket #5299 (ghc.exe: panic! (the 'impossible' happened)) closed by
- worksforme: No response from submitter.
- 3:54 PM Ticket #5271 (Compilation speed regression) closed by
- worksforme: If you still think there's a problem, please reopen and include some way …
- 3:52 PM Ticket #5212 (waitForProcess: does not exist (No child processes)) closed by
- worksforme: No response from submitter.
- 3:48 PM Ticket #5048 (Wrong SrcSpan on AbsBinds) closed by
- fixed: No response from submitter, so assuming it's fixed.
- 3:45 PM Ticket #4987 (darcs: internal error: stg_ap_v_ret (GHC version 7.0.1 for ...) closed by
- wontfix: No testcase, so closing.
- 3:43 PM Ticket #4805 (segfault in Data.HashTable, triggered by long Agda runs) closed by
- invalid: Please reopen if you have a way to reproduce this.
- 3:42 PM Ticket #4473 (GHC --make switch does not set file timestamp correctly) closed by
- fixed: No response from submitter, so closing.
- 3:27 PM Ticket #813 (-optc-O2 used by default in GhcRtsHcOpts while building 6.5, leading make ...) closed by
- fixed: No response, so let's assume it's fixed.
- 3:25 PM Ticket #68 (Warnings for unitialized fields) closed by
- wontfix: There doesn't seem to be a consensus that anything should be done, so I'm …
- 12:51 PM Ticket #5478 (GHC panics when asked to derive Show for ByteArray#) created by
- The following Haskell […] caused GHC to panic with […]
- 5:11 AM Ticket #5477 (Missing space in Windows cmd.exe invocation breaks shell command ...) created by
- Consider this code example: […] When compiled and run on Wine, using …
Note: See TracTimeline for information about the timeline view. | https://ghc.haskell.org/trac/ghc/timeline?from=2011-09-15T01%3A46%3A29-0700&wiki=on&ticket=on&milestone=on | CC-MAIN-2014-15 | refinedweb | 1,568 | 61.06 |
Hi ive made a program that does 3 things.
1. lets you enter 2 words to form one word ( red + cat = redcat ).
2. opens a separate txt file.
3. checks what you entered is the same as one of the words in the separate txt file.
here is my code:
#include <iostream> #include <fstream> using namespace std; class animals { public: string name; }; int main(){ string x; string y; string z; cout<<"firstword"<<endl; cin>>x; cout<<"secondword"<<endl; cin>>y; z=x+y; cout<<z<<endl; animals array[10]; ifstream infile; infile.open("C:\\animals.txt"); while(infile.peek()!=EOF){ infile >>array[0].name; } infile.close(); if(z==array[0].name) cout<<"correct"<<endl; else cout<<"wrong"<<endl; cout<<array[0].name; system("pause"); return 0; }
what it does however, is only checks for the array 0 ( so in this case only one word out of three ).
how would i go about changing or fixing it to make it check so that ANY of the three words that matches up with what the user types down is correct.(not just the array 0 word).
here is the txt file
redcat bluedog greenbird
as you can see the user must match a colour with the animal to be correct. however the only code that reads out to be correct is at current, the green bird. I know doing array 0 is wrong but i dont know how to fix it.
any help is greatly appreciated. | https://www.daniweb.com/programming/software-development/threads/420151/match-what-you-enter-to-a-separate-txt-file | CC-MAIN-2017-04 | refinedweb | 244 | 73.17 |
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. An array is a collection of similar data types. An array is a container object that holds values of a homogenous type.
Arrays are also known as static/fixed data structure because the size of an array must be specified at the time of its declaration. Once defined, the size of an array is fixed and cannot increase to accommodate more elements.
An array could be either primitive or object/reference type. Arrays get memory in heap area. Array in java is index-based, the first element of the array is stored at the 0 index.
Arrays also follow declarations and assignments like any other variable.
Declaration: Both of the declarations are valid, the first one most preferred one
dataType[] variableName;
dataType variableName[];
Actual Examples :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
Assignment:
//creates an empty array named arrayA of integer type whose size is 5.
int[] arrayA = new int[5];
or
//creates an array named arrayB whose elements are given.
int[] arrayB = {3,33,32,29,9};
There are two types of arrays present in java
A one-dimensional array is, essentially, a list of like-typed variables.
Below Images shows how the values are stored in 1D arrays in java
In the above image, we can access the values using a single index, and storing the values in arrays is also done using a single index. One dimensional array will have only one index.
For example, If I want to access the element at 2nd index than I can write code like
arrayA[2] and it will fetch the value to store a value we might need to use like
arrayA[2] = 10 The values will be updated if any values are existing, or set if no value is present.
Multi-dimensional arrays hold the values in table format, and values will be aligned like rows and columns
To access any element present in the arrays we need to provide row number and column numbers, both starts from 0.
If we consider the above array as arrayM, then to access the value 90, we need to provide the rows and columns like
arrayM[2][3]
Multi-dimensional arrays will be helpful when we are handling matrix kind of data.
We can assign elements to each index position in an array ranging from 0 to N-1, where N is the size of the array. In our case, the index numbers will range from 0 to 4 in the below example as the size is 5.
public class ArrayExample { public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; arrayA[2] = 12; arrayA[3] = 99; System.out.println(arrayA[4]); } }
The above program will store 20 and 33 in the 0th and 1st index position respectively in the array numbers. By default, all the positions from 0 to 4 have default value 0 stored.
Elements of an array can also be assigned at the same time when declaring the array. The format for doing so is as follows:
public class ArrayExample { public static void main(String[] args) { int arrayB[]={2,6,9,4,8}; System.out.println(arrayB[2]); } }
In the above example, the size of the array is automatically decided by the number of elements passed
After storing elements in an array, we may require to retrieve those elements at some point to time for calculations or in an expression for evaluation. This can be done again with the help of index number.
Not only just accessing elements, we can also perfom some operations using the elements like below.
public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; arrayA[2] = 12; arrayA[3] = 99; System.out.println("Value at 3rd index " +arrayA[3]); System.out.println("sum of index 1 and 2 " +arrayA[1] + arrayA[2]); arrayA[4] = arrayA[0] * arrayA[2]; System.out.println("Value at 4th index " +arrayA[3]); }
We can get the size of an array using length property present in arrays. This is useful when we have not declared array with size, I mean when the array is formed using other means.
Size of the array is about number of cells allocated in memory, so it does not care about how many cells have user given values.
public class ArrayExample { public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; System.out.println("Size of the array :" +arrayA.length); } }
We can fetch all the values from an array rather than fetching the elements one by one. We can use for-loop and enhanced-for loop for this purpose.
Fetching elements using for Loop : We need to get the size of an array to iterate over the array, we can get the size using length property. we would be using the loop variable for iterating through the index of the array
public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; for (int i = 0; i < arrayA.length; i++) { System.out.println(arrayA[i]); } }
You can zeros because we have not assigned any values for index 2,3,4
enhanced for-loop / for-each loop: We can use for-each loop to iterate over the array without using any loop variables or without using the size of an array. for-each loop internally verifies whether it has reached to end of array or not on each iteration.
public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; for (int item : arrayA) { System.out.println(item); } }
Compiler throws
public static void main(String[] args) { int[] arrayA = new int[5]; arrayA[0] = 20; arrayA[1] = 33; // max index is 4 System.out.println("Value at 7th index :" +arrayA[7]); }
Jagged arrays in java are arrays containing arrays of different length.
Jagged array is an array of arrays (multi-dimensional array) such that members of the second dimensions can be of different sizes, i.e., we can create 2-D arrays but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Jagged arrays are also known as Ragged arrays in Java.
We can create Jagged arrays like other arrays. If the elements of the array are known to us, we can declare and initialize the array in one step like below :
int[][] myArray = {{12},{32,12,38},{14,6},{3}};
Here, we have created one Jagged array of four elements. Each element is an array of integers. First element is {12} second element is {32, 12, 38}, third element is {14, 6}, and the fourth element is {3}.
In the above case, we know the elements of the array. So, it becomes easier for us to create the array. We need to declare the jagged array and initialize later if we do not know the elements which are going to be present.
public static void main(String args[])
{ int[][] myArray = new int[3][]; myArray[0] = new int[]{1,2,3,4}; myArray[1] = new int[]{5,6}; myArray[2] = new int[]{7}; }(" "); } }
Array without having any name is called Anonymous Array..
class AnonymousArray { static void print(int a[]) { for (int i = 0; i < a.length; ++i) System.out.print(a[i] + " "); } static void print(int a[][]) { for (int i = 0; i < a.length; ++i) { for (int j = 0; j < a[i].length; ++j) System.out.println(a[i][j] + " "); } } public static void main(String...s) { //1d anonymous array print(new int[] {10, 20, 30, 40 }); System.out.println("n"); //2d anonymous array print(new int[][] {{10, 20}, {30, 40}, {50, 60} }); } }
Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.
String[] names = {"Alex", "Brian", "Charles", "David"}; // Use arr.clone() method - Recommended String[] cloneOfNames = names.clone(); for (String string : cloneOfNames) { System.out.println(string); }
System class
arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions.
For example
System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.
String[] names = {"Alex", "Brian", "Charles", "David"};
// Use Arrays.copyOf() method - Most readable String[] copyOfNames = Arrays.copyOf(names, names.length); for (String string : copyOfNames) { System.out.println(string); }
If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like
System.arraycopy() but it’s also not confusing and easy to use.
String[] names = {"Alex", "Brian", "Charles", "David"}; //Using System.arraycopy() method - Equally efficient but less readable String[] copyOfNames2 = new String[names.length]; System.arraycopy(names, 0, copyOfNames2, 0, copyOfNames2.length); for (String string : copyOfNames2) { System.out.println(string); }
If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.
String[] names = {"Alex", "Brian", "Charles", "David"}; //used names.length to get last number String[] copyRanges = Arrays.copyOfRange(names, 0, names.length); for (String string : copyRanges) { System.out.println(string); }
Just like any other variables we can also accept and return arrays from methods.
public class ArrayExample { public static void main(String args[]) { int arr[] = {1, 2, 7, 5, 4}; // passing array to method m1 sumArray(arr); createArray(5, 3); } //methods accepts array public static void sumArray(int[] arr) { // getting sum of array values int sum = 0; for (int i = 0; i < arr.length; i++) sum+=arr[i]; System.out.println("sum of array values : " + sum); } //method return array public static int[] createArray(int elementValue, int numberOfElements) { // getting sum of array values int[] newArray = new int[numberOfElements]; for (int i = 0; i < numberOfElements; i++) { newArray[i] = elementValue; } return newArray; } }
Sometimes you may need to find the minimum or maximum value in a Java array. Java does not have any built-in functions for finding minimum and maximum value, so I will show you how to code that yourself.
// Method for getting the minimum value
public static int getMinimum(int[] inputArray){ int minValue = inputArray[0]; for(int i=1;i<inputArray.length;i++){ if(inputArray[i] < minValue){ minValue = inputArray[i]; } } return minValue;
}
// Method for getting the maximum value
public static int getMaximum(int[] inputArray){ int maxValue = inputArray[0]; for(int i=1;i < inputArray.length;i++){ if(inputArray[i] > maxValue){ maxValue = inputArray[i]; } } return maxValue; }
You can convert an Java array of primitive types to a String using the toString() method present in
public class ArrayExample { public static void main(String args[]) { int arr[] = {1, 2, 7, 5, 4}; for(int i=0; i < arr.length; i++){ arr[i] = 10 - i; } System.out.println("Using Arrays.toString() : " +Arrays.toString(arr)); System.out.println("Using toString() from Object class : " +arr.toString()); } } | https://chercher.tech/java-programming/arrays-java | CC-MAIN-2020-10 | refinedweb | 1,862 | 54.52 |
[C++] Function Returning
16 February 2013
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ======================================================= COPYRIGHT (c) 2013, Naveen Venkat | All Rights Reserved ======================================================= THERE ARE SOME MUST READ GIVEN AT THE END OF THE PROGRAM. PLEASE DO READ THEM. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #include<iostream.h> #include<string.h> //FOR strlen() function #include<stdio.h> //FOR gets() function int func(char a[], int stringlength, char k) { for (int i=0; i<stringlength; i++) { if (a[i]==k) { return(1); //It returns 'true', and ends** the function there itself, so the further statements do not execute //**return brings the control out of the function, equal to termination (end) of a function } } return(0); //If it did not end the function by returning 'true', this statement will return 'false' } void main() { char a[40]; char m; int st; //a=string, m=charecter, st= string length cout << "ENTER YOUR STRING: "; gets(a); //As, if we write cin, it will end after the first space. So "being human" will be taken as "being" only! cout << "ENTER THE CHARECTER TO CHECK: "; cin >> m; //For a single charecter, cin is no problem. If we try to input "abc" here, it will take only "a". st = strlen(a); //For the end point of the loop which will compare charecter by charecter in the function. if (func(a,st,m)) //Here, if the function returns 1, then it will be if(1), [if(true)], which is true so it will display "String has m in it". { cout << "The string has " << m << " in it."; } else //If, the function returns 0, it will become if(0), [if(false)], which means execute the else statement. { cout << "The string does not have " << m << " in it."; } } /* MUST READ: ----------------------- RETURNING OF A FUNCTION ----------------------- ALWAYS REMEMBER THAT THE FUNCTION ENDS ITS RUNNING (EXECUTION) AS SOON AS YOU WRITE return STATEMENT [in a non-void function] A return STATEMENT GIVES THE VALUE TO THE STATEMENT IN WHICH THE FUNCTION IS CALLED. For eg, int square(int a) { int b = a*a; return(a); } OR [BOTH DO THE SAME JOB] int square(int b) { return (b*b); } will make the value of square(2) as 4. So, cout << square(2); will display 4 on the screen. -------------------------------- true and false during comparison -------------------------------- 1) value 0 => FALSE any other value => is TRUE. So even if you return(10) or return (-285) from the function, it will be considered true. 2) Expression A --> if(func(a,st,m)) Expression B --> if(func(a,st,m)==1) both the expressions (exp.) are same. As, if the function returns a true value (1), then exp. A becomes if(1) and exp. B becomes if(1==1). Now == is a comparison operator. If both are equal it makes the expression TRUE, ie. 1 (by default, 1 is taken as true). So, exp. B also becomes if(1). If the function returns a false value (0), then exp. A becomes if(0), and exp. B becomes if(0==1). Since, == will only make the expression 1 if both the sides are equal, so if(0==1) becomes if(0), which is same as exp. A */
Trackbacks for this entry [ Trackback URL ]) | http://www.dreamincode.net/forums/blog/2051/entry-4390-c-function-returning/ | CC-MAIN-2017-17 | refinedweb | 514 | 81.22 |
Let's assume that you need to calculate the square root of a number for one of your programs. There is no existing square root function in Python. You could write one, but there have been a lot of people before you in the exact same position. Guess what? One of them already created a function and stored it in a module!
What are modules in Python?
A module is like a code library: a file containing a set of functions, classes, and variables you want to include in your application.
For instance, if you're working on a geometry application, you may need some:
Classes:
A square with its side's length as attribute.
A triangle with the length of its three sides as attributes.
A circle defined by its radius.
Etc.
Variables:
PI: constant, useful to calculate circle area, etc.
Phi: constant, represents the golden ratio.
Functions:
Area with calculations dependent upon an object (square, triangle, etc.).
Angles which calculate angles of a triangle based on the length of its sides.
Etc.
You could write/define all these in your notebook, or you could store them in a Python file, and then import them in your notebook, which is called a module!
Use the
import keyword to import the geometry module:
import geometry
Now you can use your functions, classes, etc. in your notebook:
sq = geometry.square(4)tri = geometry.triangle(3, 6, 5)print(geometry.pi) # -> 3.14159265359geometry.area(sq) # -> 16
All of the functions, variables, classes, etc. included in the geometry module can be used with
moduleName.function() or
moduleName.class(). If you don't want to write
geometry every time you want to use a geometry function, you have two options:
from geometry import * # -> we can use area() or access pi directly# OR :import geometry as geo # we can now use geo.are() or geo.pi
You can also import a specific function from a module and use it like any other Python native function (print, len, etc.):
from geometry import piprint(pi) # -> 3.14159265359
When one module isn't enough: the packages
A package is a collection of Python modules. While a module is a single Python file, a package is a directory containing an additional
__init__.py file. This distinguishes it from a directory that contains a number of scripts.
For instance, you could have stored your geometry in three different files:
One for the classes: classes.py
One for the variable: variables.py
One for the functions: function.py
In this case, you would have the following directory:
You have to use the
. operator to access a module after importing the whole package:
import geometry # import all the geometry packageprint(geometry.variables.pi) # -> 3.1415...sq = geometry.classes.square(4)geometry.function.area(sq) # -> 16
Or you can import a module from a package:
import geometry.variables as var # import only what is available in variables.pyprint(var.pi) # -> 3.1415...
NumPy: the first glimpse of scientific computing
Let's try this with
numpy, a well-known package containing a lot of scientific tools! To import the NumPy package, you could write
import numpy, but it's easier to write:
import numpy as np
Now that you've imported the NumPy module, what about the square root function? It's the
sqrt function of NumPy:
np.sqrt(16) # -> 4.0
But NumPy is providing a particular new object: the array. An array is similar to a list, or a mathematical matrix, and includes a lot of useful methods! Let's see an example of what is possible with arrays:
To go deeper with Python packages
These are just a few examples of what NumPy does! If you want to go deeper into packages, below are some other frequently used ones:
math: contains a lot of mathematical functions/variables. A lot of these are also included in NumPy.
matplotliband
seaborn: used for data visualization.
pandas: to import and process your data into Python.
sklearn: simple and efficient tools for data mining and data analysis.
scipy: used for scientific computing.
Summary
In this chapter, you learned the basics of modules that provide useful functions:
A module is a file consisting of Python code which can define functions, classes, and variables.
You can use any module in Python through the
importkey.
To use a module's function, classes, etc., use the
.notation:
module.function()
A package is a collection of Python modules.
A Python array is a NumPy's object, similar to a list, but with far more available methods. | https://openclassrooms.com/fr/courses/2304731-learn-python-basics-for-data-analysis/6009081-more-functions-with-modules-and-packages | CC-MAIN-2022-27 | refinedweb | 755 | 57.57 |
C# System.IO.FileInfo Class
The System.IO.FileInfo class is quite similar to the System.IO.File class in that, they are used for the same purpose…
Reading data from a text file is almost similar to writing data to it. You create a FileStream pointing to the file to be read. But instead of passing the stream to a StreamWriter class, we used the StreamReader class which contains methods for reading data from a file. The following program demonstrates reading of a file. The program will use the text file created in the previous lesson as the source file.
using System; using System.IO; using System.Text; using System.Collections.Generic; namespace ReadingFromFile { class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } class Program { static void Main() { List<Person> persons = new List<Person>(); try { FileStream fs = new FileStream("sample.txt", FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fs); while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] fields = line.Split('#'); Person newPerson = new Person(); newPerson.FirstName = fields[0]; newPerson.LastName = fields[1]; newPerson.Age = Convert.ToInt32(fields[2]); persons.Add(newPerson); } } catch (IOException ex) { Console.WriteLine(ex.Message); } //Show each person's details foreach (Person p in persons) { Console.WriteLine("Name: {0} {1}\nAge: {2}", p.FirstName, p.LastName, p.Age); } } } }
Figure 1
Name: John Smith Age: 21 Name: Mike Roberts Age: 31 Name: Garry Mathews Age: 27
We created a class called Person(line 8-13) to store each person’s data that is retrieved from the file. We also created a List of Personobjects(line 19) the will hold all the person’s data and makes it easier for us to output them. We will be opening and reading a text file so in lines 23-24, we created a FileStream object with the location of the file to be read, a FileMode value of Open (which means to open the file), and a FileAccess value of Read (which only allows reading of the file).
We created a StreamReader object(line 25) and passed the created stream to its constructor. The StreamReader object will be responsible for reading data to the file. We then enter a while loop in line 27 and we test if the stream position has not yet reached the end by using the EndOfStream property of the StreamReader class. Inside the loop, we used the ReadLine() method of the StreamReader class which reads the whole line starting from where the stream position is located. The position is then moved to the next line.
The whole line is then stored in a string (line 29). We used the Split() method in line 30 and passed the character ‘#’ to separate the fields and distribute them to separate elements of the string array. Remember last lesson that we added the ‘#’ character as the delimiter, now you see the reason why we did that. A new Person object was created and each element of the fields array was assigned to the respective properties of the created Person object. The Person object is then added to the persons List. When the end of the file is reached, the loop exits and proceeds to the displaying of each person. | https://compitionpoint.com/file-read/ | CC-MAIN-2020-05 | refinedweb | 539 | 65.22 |
While preparing the release of ArangoDB 2.7, some improvements were made for the PHP driver for ArangoDB.
The 2.7 version of the PHP driver now supports the AQL query results cache. The cache can be turned on or off globally, or be set to demand mode. The demand mode will allow controlling caching on a per-AQL-query basis.
Additionally, the HTTP transport layer in the PHP driver was improved. Some internal string handling methods were optimized so that the transport part becomes cheaper. All driver operations that communicate with the ArangoDB server will benefit from this.
For a demonstration of the improvements, here is a script that creates 100,000 documents in a local ArangoDB database via the PHP driver. As we’re interested in assessing the HTTP layer improvements, the script intentionally issues 100,000 HTTP requests instead of using the specialized
import method provided by the driver.
The script code can be found here.
The baseline for the improvements is the (non-optimized) 2.6 version of the PHP driver. Here are the results for issuing 100,000 requests with the 2.6 driver (script was run twice to see if there are variations in execution time):
plain execution times with 2.6 driver
Running it with the 2.7 version of the PHP driver now shows the improvements. Execution time for the same script goes down from 54 seconds to 42 seconds:
plain execution times with 2.7 driver
The PHP version used here was:
PHP version details
Following are the results from a different machine, this time using PHP 5.6:
execution times with 2.6 driver
plain execution times with 2.7 driver
The PHP version details for this machine were:
The actual improvements depend on many factors, so your exact mileage may vary. The improvements may not be noticable for applications that issue only a few requests with the driver, but they will be significant when performing lots of requests, as in the above examples. | https://www.arangodb.com/2015/09/arangodb-php-driver-improvements-2-7/ | CC-MAIN-2019-51 | refinedweb | 334 | 65.93 |
SCROLL_SENSITIVE result set can't see the data inserted.955481 Jan 8, 2015 1:19 PM
hi all ,
I am trying to display all the latest data available in the table through SCROLL_SENSITIVE and UPDATABLE result set after inserting a new record in the table.
But the result set obtained after executing the query initially is not able to see the newly inserted record in the table and hence same result is getting printed out in both the cases.
Can u explain me what's happening in this case ?? And how can i get the updated record also without executing the statement query twice to get the latest result set.
My full code is given below.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Misc3 {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
int empid;
String lname;
String fname;
int deptno;
int mngrid;
con = JDBCUtil.getOracleConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "select employee_id , last_name , first_name , department_number , manager_id from employees ";
rs = stmt.executeQuery(query);
System.out.println("Before inserting the new record....."););
}
System.out.println("Going to insert the new record.....");
rs.moveToInsertRow();
rs.updateInt(1, 10);
rs.updateString(2, "Clark");
rs.updateString(3, "John");
rs.updateInt(4, 2);
rs.updateInt(5, 2);
rs.insertRow();
System.out.println("New record inserted successfully.....");
System.out.println("After inserting the new record.....");
rs.beforeFirst(););
}
} catch (SQLException ex) {
System.out.println("error code : " + ex.getErrorCode());
System.out.println("error message : " + ex.getMessage());
} finally {
JDBCUtil.cleanUp(con, stmt);
}
}
}
*** JDBCUtil Class ****
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCUtil {
public static Connection getOracleConnection(){
Connection con = null;
try{
// Load the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Establish Connection
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","ex","ex");
}catch(Exception ex){
ex.printStackTrace();
}
return con;
}
public static void cleanUp (Connection con , Statement stmt){
// Release the resource
try{
if(con != null){
con.close();
}
if(stmt != null){
stmt.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Edited by: user12848632 on Aug 13, 2012 2:06 PM
1. Re: SCROLL_SENSITIVE result set can't see the data inserted.rp0428 Aug 13, 2012 4:50 PM (in response to 955481)>
Can u explain me what's happening in this case ?? And how can i get the updated record also without executing the statement query twice to get the latest result set.
>
Sure - but you could have answered your own question if you had read the doc link I gave you in your other thread and next time you post code use \
tags on the lines before and after the code - see the FAQ for info 17076 : Invalid operation for read only resultset {quote} •Internal INSERT operations are never visible, regardless of the result set type. {quote} See •Seeing Database Changes Made Internally and Externally in the JDBC Dev doc I pointed you to Did you notice the words 'never visible'? You won't see them as part of the result set unless you requery.
2. Re: SCROLL_SENSITIVE result set can't see the data inserted.dsurber Sep 7, 2012 6:28 PM (in response to rp0428)What rp0428 wrote..
3. Re: SCROLL_SENSITIVE result set can't see the data inserted.rp0428 Sep 7, 2012 8:03 PM (in response to dsurber)Why are you addressing those comments to me instead of to OP?
>.
>
I assume you are referring to the Note at the end of the link I provided OP
>.
>
I wouldn't call that 'faking it'. It's a client-side implementation rather that server-side if that's what you mean. As the note you need to be careful to use scroll-sensitive sets carefully.
A large part of the issue with using server-side methodology with Oracle is maintaining the read consistency that Oracle is famous for and that other databases don't provide. Part of that read consistency is related to what I (and the doc) told OP about why new inserts were not visible. Table 17-1 'Visibility of Internal and External Changes for Oracle JDBC summarizes some of the issues and shows why internal/external INSERTs cannot be seen and why even external DELETEs cannot be seen.
Scroll-sensitive result sets certainly aren't designed to be used for extensive back-and-forth scrolling through large numbers of records.
4. Re: SCROLL_SENSITIVE result set can't see the data inserted.DrClap Sep 8, 2012 12:33 AM (in response to rp0428)
rp0428 wrote:I'm curious what they are designed for, then. I've never encountered a situation where I thought they might be useful. (Of course that doesn't mean they are useless, it just means I don't get around enough.)
Scroll-sensitive result sets certainly aren't designed to be used for extensive back-and-forth scrolling through large numbers of records.
5. Re: SCROLL_SENSITIVE result set can't see the data inserted.rp0428 Sep 8, 2012 10:13 AM (in response to DrClap)>
I'm curious what they are designed for, then.
>
The best example is a data browser in a GUI (sql developer, toad, etc). A data grid is displayed that shows a 'window' of rows. The underlying query will 'fetch' a number of rows (based on fetchsize) and display a subset in the 'window'.
The issue is how to get the data needed when the user scrolls down (forward) or up.
Forward-only isn't a problem; that just uses the normal 'fetch' to get the next set of rows if a new fetch is needed. The original cursor is still open and fetch operations just return records as normal. Oracle's read consistency is maintained to allow the query to only fetch records that the user's transaction should see based on the isolation level. That is easily done using the SCN that is part of the data blocks and the UNDO segment that allows old versions of data to be reconstructed even if there have been multiple committed updates or deletes.
The problem is reverse scrolling - retrieving records that had previously been retrieved. Oracle rows in a table or query have no inherent order. Rows in a table are like balls in a basket; there is no 'first' row. You have to use an ORDER BY to ensure that you get the order you want.
So if the fetch size is the standard 10 rows and the last fetch was for rows 1001 - 1010 how do you now fetch rows 991 - 1000? Rerun the query and then spin through it throwing away rows until you reach row 991 and then fetch those 10 rows.
Now if the user wants to scroll backward again you rerun the query again throwing away rows until you reach the ones you want.
That is very expensive. You can often get by with it in a GUI when the user takes several seconds to look at the data grid anyway.
Recent versions of Oracle support RESULT SET CACHING and if that is enabled then Oracle can just use the cache to get previous records. But as the doc showed for JDBC if the refreshRow function is used (even under the covers) then the result set needs to include commited updates to rows that were in the result set to begin with.
Oracle now also supports client-side caching and this makes things even faster. But the larger the result set the bigger the problem with memory and storage.
6. Re: SCROLL_SENSITIVE result set can't see the data inserted.dsurber Sep 10, 2012 8:50 AM (in response to rp0428)Oracle JDBC has supported client side scrolling for at least ten years. The JDBC spec includes (optional) support for scrollable read-only result sets. Since the server has no support for this the JDBC driver has had client side support since the feature was added to the JDBC spec. As you say though, it can be memory intensive.
The use case you describe, supporting a scrolling list in a GUI is perfect for scrolling insensitive. While there are use cases for scrolling updateable or scrolling sensitive, because of the overhead required by the client side support, I don't think they are very useful with Oracle. They work if you don't mind paying the cost, but in general, I wouldn't use them. Scrolling sensitive reads every row in the result (except for the first fetch block) twice, at least. It executes <number of rows> / <fetch size> + 1 queries at least to view the whole result set. If you start scrolling around the number goes up. | https://community.oracle.com/thread/2428898?tstart=75 | CC-MAIN-2015-27 | refinedweb | 1,448 | 65.52 |
Hide Forgot
An issue was discovered in the XFS filesystem in fs/xfs/libxfs/xfs_attr_leaf.c in the Linux kernel. A NULL pointer dereference may occur for a corrupted xfs image after xfs_da_shrink_inode() is called with a NULL bp. This can lead to a system crash and a denial of service.
References:
An upstream patch:
Created kernel tracking bugs for this issue:
Affects: fedora-all [bug 1597772]
Notes:
While the flaw reproducer works when run as a privileged user (the "root"), this requires a mount of a certain filesystem image. An unprivileged attacker cannot do this even from a user+mount namespace:
$ unshare -U -r -m
# mount -t xfs-2019:0831
This issue has been addressed in the following products:
Red Hat Enterprise Linux 7
Via RHSA-2019:2029
This issue has been addressed in the following products:
Red Hat Enterprise Linux 7
Via RHSA-2019:2043 | https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2018-13094 | CC-MAIN-2019-39 | refinedweb | 147 | 57.1 |
Blue_Chi | Flash CS5 | ActionScript 3.0 | Beginner
Using the Geolocation Sensor in Flash Using AS3
This tutorial will teach you how to use the Geolocation Sensor in a Flash movie your mobile device to retrieve the geographical position of the user. This feature is only compatible with Flash Lite 4, Adobe AIR Mobile, and the iPhone. The most basic function of geolocation is to retrieve the latitude and longitude positions of the user, so that you can locate the user on a map. The sensor could also be used to retrieve additional details such as the speed at which the user is moving. This is a beginner AS3 tutorial that will only require you to know the basics of AS3 Variables and Event Handling.
Starting Off
This tutorial can be followed as a Flash Lite 4 project, an Adobe AIR project, and an iPhone project. We are going to create a Flash Lite 4 project because it is easier to test the device in Device Central using this format as AIR Mobile and iPhone applications cannot be tested in Device Central at the time of writing this tutorial. Our tutorial will simply retrieve the geolocation data and display them on the screen inside a text field.
Start up Flash CS5 and go through
do not need any graphical elements on the screen as we can create our text field by using AS3
later. Just right-click the only frame you have on the timeline and select
the
We are going to begin our code, the first step is importing the classes needed to use the geolocation sensor - the Geolocation Class and the GeolocationEvent Class:
import flash.sensors.Geolocation; import flash.events.GeolocationEvent;
New>Flash Lite 4
to create a new Flash Lite 4 movie. We
to open up
Actions Panel
.
We can now use geolocation capabilities in our project, but before we do that we need to detect whether the device that will run the movie supports geolocation - as you should not not all mobile phones have GPS features. It is necessary to make sure that you can have an alternative option or a warning message if the user's device doesn't support geolocation or if the user has disabled geolocation access to your application. We can check for geolocation support
by using the
isSupported()
method of the Geolocation Class:
if (Geolocation.isSupported){
}
You can learn more about the AS3
Conditional by reviewing our tutorial on this topic.
The method above will return the value
we put between the curly brackets of the conditional will only then be executed. Our first action to carry out once we have verified that geolocation is support is to create an instance of our geolocation class. In order to use any ActionScript Class we have to create an instance of it and then play around with that instance of the class. To create an instance of the
class we use the
if geolocation is supported and therefore whatever
keyword. We are going to call our instance
var my_geo:Geolocation = new Geolocation();
You can learn more about AS3 Variables and Classes by reviewing our tutorial on this topic.
The geolocation class sends updates on the status of the location repeatedly, we have to register the geolocation update event and retrieve the data we need from an event listener function that we will have that as its specific task. import flash.sensors.Geolocation; import flash.events.GeolocationEvent;
var my_geo:Geolocation = new Geolocation(); my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);
You can learn more about AS3 Event Handling by reviewing our tutorial on this topic.
We now need to create a text field which will display our location coordinates. We can do that easily by using the TextField Class, once created we will make the textfield wrap the text properly in case the longitude values are long and then display the empty text field on the
screen by using the Display List method
DisplayChild()
:
var my_txt:TextField = new TextField(); my_txt.wordWrap=true; addChild(my_txt);
You can learn more about AS3 TextField Class and AS3 Display List by reviewing our tutorials on these topics.
It is now time to create the function that will retrieve our geolocation details. We can define this function outside the conditional as it will only be triggered if called by the event listener. The
function will set the value of the text field by using the
and
properties of
GeolocationEvent
instance:
function onGeoUpdate(e:GeolocationEvent):void{
my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;
We are set, this is everything you need to use the Geolocation Sensor on your mobile device,
you can test your movie by going through
Device Central and play your movie, you might have to set the Test Device in Device Central so that you are using a Flash Lite 4 device:
Control>Test>In Device Central
. This should launch
Now you access the Geolocation Panel on the right-side of the window (or by going
through
values for the
value here and then click on appear inside the emulator.
Window>Flash>Geolocation
latitude
longitude
if you can't see it). Inside this panel you can manually put which you want your mobile to emulate. You can put any
. Once you do that you should see your values
Send to Device
Our use is obviously basic, but it shows you how to retrieve the location data.
Update Frequency
In a real world application your location would change as you move around, the frequency at which Flash will be updated about changes in your location can be configured by using
depend on the default values of your device which vary from one device to another. This method can be used directly on an instance of the Geolocation Class and accepts a value in milliseconds this way:
setRequestedUpdateInterval()
method. If you do not use this method the updates will
my_geo.setRequestedUpdateInterval(50);
function onGeoUpdate(e:GeolocationEvent):void{ my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;
You should be careful about setting very short intervals for your geolocation sensor as that will rapidly consume the battery of your device. You should always unregister your event after you are done retrieving the data that you need as well.
Additional Values
In addition to the latitude and longitude values which we have used in our example above you can also retrieve the following pieces of information:
—The altitude value.
—The angle in respect to north in which the user is heading.
—The speed in meters per second.
—The vertical accuracy.
horizontalAccuracy
—The horizontal accuracy.
These values would only be helpful to someone creating an advanced location based application such as a navigation system. This concludes our tutorial, you can try integrating geolocation with a Google Maps application to show the location on a map. You should note however that the Google Maps application does not work in iPhone Flash Applications as it requires loading code at runtime. If you have any questions feel free to post them at the Republic of Code Forum. - End of Tutorial
By Blue_Chi | Flash CS3 | Intermediate
Pages 1, 2, 3, 4, 5
Creating a Flash Lite Game - Tutorial player -. The game we will create is a very basic arcade game, the player merely collects the objects before they reach the ground. If he fails to collect three objects then the game ends. Our game will use very simple ActionScript concepts such as variables and conditionals. You really do not need to know much else.
To play the game on your phone, unzip this file and send it to your phone. You can alternatively play the game on your computer if you have the standalone player installed.
What's Behind the Code?
As previously stated, our game uses very basic ActionScript concepts, as each of the objects fall, the value of their location on the _y axis increases, we run a conditional that checks if the player coincides with any of the fallen objects at the same position, if it is that is the case, the player gains an extra score point. Another conditional checks if the object reached the ground, if it does, the player loses one life. It is that easy!
Game Structure
Our game will require five frames only, they are as follows:
1. Game Start The user will see a screen that says start game, he has to press a button to start playing.
2.
Initialization All objects and variables required for the game will be created in this frame. This code needs to
be executed once only and that is why it is separated from the rest of the code that will have to be repeatedly executed.
3. Game Execution Loop This frame will have the actual code to run the game, it will control the movement of the objects during gameplay and will continuously run throughout the game.
4. Game Loop 2 This frame has the simple task of making the previous frame loop. It does not have any other task or code.
5. Game Over The player is transferred to this screen when he consumes all his lives. This screen will show him his final score and will also give him the option to play again.
This is the basic structure for creating a game on any platform. Making a game in Flash is easier to understand because you can separate the code of each of these sections in different physical frames. We will go through them one by one, but first we will create the basic layer structure to organise the content in each of our frames.
Starting Off - Layer Structure
Create a new Flash Lite movie, you can use Adobe Device Central, or alternatively create a regular Flash file and change the ActionScript version from the Publish settings. Set the
specific type of content as labelled.
We will now create keyframes in each of these layers in accordance with the 5
Frames structure illustrated above. Start off with the
Create
layer.
separate
keyframes
in it.
Now for the
The
layer, we need a keyframe in
layer on the other hand needs a keyframe in each of
We are going to have only across all the five frames.
one keyframe
in our
Background
layer, make that frame span
Our timeline is now ready. We will start working on each of the frames in turn:
Frame 1: Game Start - Page 2
Frame 2: Initialization - Page 3
Frames 3 and 4: Game Execution Loop and Game Loop 2 - Page 4
Frame 5: Game Over - Page 5
You are now set to start making the game, the Game Start Frame is naturally next. We will create in this section the Game Start Frame. This frame will stop the game from playing instantly and will contain the title text and the button to make the game start when the player presses the 'Enter' button. In order to follow this tutorial, you will have to download this file that contains the graphics for our game.
'Game Start' Frame
We will start working from the bottom layer going up. Starting with the background, select
it. If the image is not automatically aligned at the right place, you have to make sure it does by
doing that manually. Once you do that,
throughout the game so we don't have to make any changes to it.
layer, then import (
File>Import>Import To Stage
) the
background.gif
image to
this layer. The same background will be displayed
For the main content in this frame we are going to have text that says
colour, and font size you wish for this. You can also add any graphics for a logo or anything of that sort in this frame. Make sure that you have your text type set to Static (Check the Properties Inspector), if you use any other text type you will have to embed the characters before hand to make the text visible at run-time.
Start Game
Main Content
layer and then use the
Text Tool
to create such text, you can use any font,
Even though no physical button will be required as the navigation is going to be through the phone keypad, Flash Lite 1 can only register key presses through a button symbol, so we will
have to create one. Select the
the stage - our button should not be seen. Now use the
then press
We will keep using an instance of this object each time we want to register keypad presses.
layer and use the
. Name it
to draw a little circle above
to select this circle and
to convert it to a
Button Symbol
We will start putting some Actions now.
the following code in the Actions Panel. This code will be assigned directly onto the button. on (keyPress "<Enter>"){ play();
Right-click
our button, select
, and then paste
The code is self-explanatory, if the button "Enter" is pressed, the movie will be played. Of course, the movie by default should be playing, but we do not want to it to do that, so we will
make it stop. To do this, first close the Actions panel,
the first frame and select
. Paste the following code:
stop();
Just noticed something annoying about Flash CS3, if you want to assign a script to a certain frame, you will have to do the following: (1) select the layer of that contains the frame, (2) click on a faraway empty frame in the same layer - for example, frame 10 in our case, (3) now right- click the frame that you want to assign (frame 1 in our case) and select Actions. It doesn't make sense, but that's how it works.
An essential command to set at the first frame along with the
switches the player to fullscreen mode. Add the following code below the that:
method is one that
command to do
fscommand2("fullscreen", true);
We are done with our Game Start Frame, here is a summary of what we did:
1. Added the background to the
2. Added the title text to the
3. Added the button to the
4. Assigned to the
layer and assigned the
method to the button.
fullscreen
the movie and started the
mode.
I hope that you found this section easy. We will now move to the Initialization Frame next. In this stage we will create the Game Initialization Frame, the code in this frame runs only once to create all the objects we need for the game, it also creates the starting values for variables in the game such as the game score and the number of lives the player has. We will start with the different types of content we have from the bottom up, the background is already
game. Assuming that you have already unzipped the file given in the previous page. Import the
included player.swf movie into your library (
File>Import>Import to Library
second frame
). Open
) and drag an instance of your player onto the
of our
Contents layer
later position using ActionScript. We have to convert this graphic to a Movie Clip Symbol to do
. The location of the player object on stage does not matter because we will it
that though. So select it, and then press
, set the type to
to convert it to a Symbol. Assign the name
Registration Point
, and then change the
to the
as indicated in the image below.
Registration Point: Setting the registration point to the left makes it easier to position the object in our game. When you set the _x position to Zero this means that the left side of the object would be at the point Zero and not the center of the object ilke what happens with default settings. This makes things so much easier, especially as player's width equals exactly the 1/3 of the stage's width, so the three positions that it has to be at are 0, 1/3, and 2/3 of the width of the stage.
Before we forget, you have to also assign the
using the
Properties Inspector
to this movie clip
Our game is going to have three targets falling at the same time, we will create these three targets using ActionScript, but we need to have the source template for the target from which
we will duplicate our additional copies. You will have to import the
zip file you downloaded earlier, go through
open the library (
position this object somewhere above the stage because we do not need to see it during run
time.
symbol
to do just that, then
target.swf
file included in the
Main Contents
) and drag a copy of it onto the
), set the
layer. You have to
. Click
registration point
corner,
to it.
and then assign the
instance name
Adding the Score and number of Lives display
The player needs to see the number of points he scored and how many lives he has remaining. We will do that by creating the text labels and then a couple of dynamic text fields to show the
actual numbers. Start off by using the
to write two texts that say
score
lives
,
make sure that the text type of each of these texts is
(check the
).
We will now create the dynamic texts that will actually display the numbers for each of these
variables. Make sure that no text is selected, pick the
. Now draw a text field next to score, set the font
to
Text Tool,
access the
Properties
Inspector
_sans
and set the text type to
, font size to
, and align the text to the
. You will now have to assign
variable name
to it to display that variable when it is created.
Create another field next to the text that says
assign the
, use the same properties as above and
to it. You should end up with a screen similar to the one below.
We used the system font _sans to avoid embedding any characters as would usually be required when using a Dynamic text field.
That completes all the visual content of this frame, we will skip the
are no navigation commands in this frame. We will move to the Actions now.
ActionScript
layer because there
layer,
right-click
and select
. (Might need to use
the trick mentioned in the previous page regarding Frame selection for ActionScript). Paste the code below to initialize the game assets. The code is pretty simple. The first two lines are the basic variables which we are using, the score (starts at zero) and the lives (player has three lives). we are setting the _x and _y properties of the player_mc object, and then duplicating the target_mc three times, the actual target_mc will not be used again. Each of the new targets will be set at their position horizontally, and will be placed at a random position above the screen before falling, I used a random value here to make sure that they don't all fall together making it hard for the player to catch all three objects at the same instance. //Essential Variables
score=0;
lives=3;
//Positions the player on the stage. player_mc x=0; player_mc y=280;
//Creates 3 targets by duplicating the one on stage duplicateMovieClip("target_mc","target1_mc",1);
duplicateMovieClip("target_mc","target2_mc",2);
duplicateMovieClip("target_mc","target3_mc",3);
//Positions the new targets above the stage ready to play target1_mc x=0;
target1_mc y=-random(40);
target2_mc x=80; target2_mc y=-random(40);
target3_mc x=160; target3_mc y=-random(40);
We would like our targets to fall at different speeds, so we will assign a different speed property
to each of these targets. The
have to assign it now. The initial speed will be a random number between 0 and 10. If the speed
to whatever speed
is actually zero, the targets will not move, so we will be adding the number
we get. We could have used code was changed this way:
//Essential Variables
property will be used when the game actually runs, but we
instead of
, but playing at speed
is way too boring. The
//Positions the new targets above the stage ready to play target1_mc x=0; target1_mc y=-random(40);
target1_mc.speed=random(10)+4;
target2_mc.speed=random(10)+4;
target3_mc.speed=random(10)+4;
We need to create a variable to store the location of the player on the stage and to check for it at the time the objects fall, we can recall the position at run time, but checking for a number like that can be messy, to have a nicer and a more understandable code we are going to create a
property called
center), or position
to tell us if the player is at position
(the left), position
(the
(the right). At the start, the player is as the left (_x=0), so his position is 1.
This will make much more sense by the end of the next frame.
//Positions the player on the stage. player_mc x=0;
player_mc y=280;
player_mc.myPosition=1;
//Creates 3 targets by duplicating the one on stage
duplicateMovieClip("target_mc","target1_mc",1);
Initialization is now done. In this stage, we did the following:
1. Added the
Added the
object to the
2. Added the
3.
4. Assigned the
displays in the
to create the essential
5. Assigned the
to position the
6. Assigned the
to duplicate the
7. Assigned the
to position and configure these new targets.
Glad you have made it to this frame, the main Game Execution loop Frame is next. The Game Execution loop Frame holds the code that runs the game, controls the objects, counts the score and takes away lives when you fail to catch the object. Our frame will also configure the controls for moving the player on the screen, we will start with this last part first. We have already created and aligned all our visual objects in our previous frame so we can move straight into the stage to create the button that captures key presses and then code the game loop.
Creating the Game Controls
We need to create the button to hold the control code,
sure that it placed somewhere above the stage so that it is not visible during the game.
layer, open up
) and drag an instance of the
symbol we created earlier, make
this instance of the button on the stage and select
. We are going to
use two buttons only to control the player, we are going to use a very simple conditional to
move the player and change the value of its currently is. on (keyPress "<Left>"){ if (player_mc.myPosition != 1){ player_mc.myPosition--; player_mc x-=80;
myPosition
variable depending on where it
on (keyPress "<Right>"){ if (player_mc.myPosition != 3){ player_mc.myPosition++; player_mc x+=80;
The code is simple, as long as the position of the player is not
the left key button moves it to the left by
not
player movie clip is exactly
(absolute left), then pressing
pixels, and as long as the position of the player is
(absolute right), then pressing the
key button moves it to the right by
pixels. The
pixels in width, which is also exactly
of the width of the
stage, so moving it by
I find using the
positions when making my conditionals, although those would work the same if you use the exact values. We will also be using this variable later on below to check if the targets are caught.
Coding the Game loop
pixels to the left or the right is a whole step to the left or the right.
property easier because I do not have to think about the actual
We have to assign our biggest chunk of code to
frame and open the
as we go through. Most of our code will be duplicated three times, each for one of the targets.
Our first task is to make our objects fall down, we do that by increasing the
of the
layer. Select that
panel. We are going to do this in segments, I will explain each one
property of each
target, we will add to them the value of the
object has a different
//Commands the targets to move downwards.
property we set in the previous frame. Each
value, so they should be falling at different speeds.
target1_mc
y
+= target1_mc.speed;
target2_mc
+= target2_mc.speed;
target3_mc
+= target3_mc.speed;
The next task is to configure what happens when the balls reach the ground without being
caught. We know that the height of the stage is
the target has fallen down. If that is true, then the player loses a life, and then the ball is thrown
up to a random place above the stage (that's the new
a random value between zero and the current score (plus 4 to avoid zero speed). This makes the game become faster as you score more. You paste the following below the first segment:
//The targets fall down. if (target1_mc y>320){ lives--;
target1_mc.speed= random(score)+4;
pixels, so if the
property exceeds that
is set as
is negative), and the
=-random(40);
if (target2_mc y>320){
lives--;
target2_mc.speed= random(score)+4;
if (target3_mc y>320){
target3_mc.speed= random(score)+4;
Now what happens if our targets are actually caught? First, each target will be caught under a
different condition, each will have to have its
the targets is satisfied, the players gains one extra score point, and then the target is thrown up at a random position with random speed to start again. //The targets are caught.
if (target1_mc score++;
property lower than
has to be at the corresponding position as the target.
object, and
for
for the object on the
absolute right
. If the capture condition for any of
y>250
and player_mc.myPosition == 1 ){
if (target2_mc
and player_mc.myPosition == 2 ){
score++;
if (target3_mc
and player_mc.myPosition == 3 ){
Our final task is to check for Game Over, if the number of lives reaches zero, then we have to remove all of our targets from the stage and then go to and stop at the Game Over Frame -
ie
//Game Over if (lives == 0){
removeMovieClip("target1_mc");
removeMovieClip("target2_mc");
removeMovieClip("target3_mc");
gotoAndStop(5);
We only need to remove objects we created dynamically via ActionScript as those will not be removed when you leave the frame that contains them. The player movie clip does not have to be removed because it is an actual object on the stage and it will not be visible once we leave the frame that contains it.
The loop 2 (Frame 4)
That completes our game engine, but if you noticed, this was all just one frame and to make it
loop we will add this code to the
//Plays the previous frame
gotoAndPlay(3);
Our Game loop is done, here is what we did here:
in the
1. Added a button to the
2. Assigned the
3. Assigned the
layer and configured the key controls.
to make the targets move.
to determine what happens when the targets reach the ground.
to determine what happens when the targets are captured.
to determine what happens when all the lives are consumed.
loop with
. (Game Execution loop).
The very last frame, Game Over Frame, is next. The player will be directed to the Game Over Frame if he loses all his lives. The Game Over screen will display the final score achieved and will give the player the option to play the game once more. This means that we will have to put some static text, dynamic text to display the score, and a button to make key commands to restart the game. We will do these from the bottom up.
Adding Text
Select the
part of the stage and then write
the image below. You will have to make sure that the type of both of these texts is
PLAY AGAIN?
to write
YOUR SCORE IS
at the upper
at the lower section of the stage as illustrated in
(check
Displaying the Score
To display the actual score on the screen, we need to use a
that nothing on stage is selected, select the
Inspector
and assign the
Dynamic Text Field
. Make sure
, and then access the
to be able to draw such a text field. Now
draw a big rectangular field between the two lines of text you have on stage. While your text
field is still selected, set the size to
the variable name
, the font to
the text, and then assign
Adding Key Controls
To register the key command for the game to be played again would require us to create a
button the same way we did for the previous commands. Select the
somewhere above the stage. Now right-click this button and select
) and drag a copy of the
myButton
symbol we created previously. Put it
panel. Type this code to make the game play once again when pressing
button. The code is self-explanatory. Frame
is the Intialization Frame which sets
all the variables and objects required to start the game, the game will follow from there automatically. on (keyPress "<Enter>"){
gotoAndPlay(2);
We are done! In this final stage you did the following:
1. Added the Game Over text to the
3. Added a button to the game.
display text field to the
layer and configured the key controls to go back and play the
We are done. You can now test your movie or export it to try it on your mobile device.
The game we created here is a very basic one, I added a couple more features to make this game richer, you can download it to get an idea on how you expand your game.
I hope you found this tutorial helpful. Feel free to post the Oman3D Forum if you have any questions.
- End of. | https://ru.scribd.com/document/403455829/Geolocalization-with-Flash-and-a-simple-game-fo-iPhone | CC-MAIN-2020-50 | refinedweb | 4,974 | 69.21 |
only ever be, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, getc, print, printf, read, readdir, rewinddir, seek, seekdir, select, syscall, sysread,, last, next,and
-Xis based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write or execute the file. Also note that, for the superuser,
-r,
-R,
-wand
-Walways return 1, and
-xand
-Xreturn ... } odd
Returns the absolute value of its argument.
- accept NEWSOCKET,GENERICSOCKET
Accepts an incoming socket connect, just as the accept(2) system call does. Returns the packed address if it succeeded, FALSE otherwise. See example in "Sockets: Client/Server Communication" in perlipc.
- alarm SECONDS
Arranges to have a SIGALRM delivered to this process after the specified number of seconds have elapsed. , you may use Perl's syscall() interface to access setitimer(2) if your system supports it, or else see "select()" below. It is not advised to intermix alarm() and sleep() calls.
- atan2 Y,X.
- bless REF,CLASSNAME
-
- bless REF.
- caller EXPR
-
- caller
Returns the context of the current subroutine call. In a scalar context, returns TRUE if there is a caller, that is, if we're in a subroutine or eval() or require(), and FALSEargs) = caller($i);
Furthermore, when called from within the DB package, caller returns more detailed information: it sets the list variable @DB::args to be the arguments with which. Returns the number of files successfully changed.
$cnt = chmod 0755, 'foo', 'bar'; chmod 0755, @executables;
- chomp VARIABLE
-
- chomp LIST
-
- chomp
This is a slightly safer version of chop (see below). It removes any line ending that corresponds to the current value of
$/(also known as $INPUT_RECORD_SEPARATOR in the
Englishmodule). It returns the number of characters removed.: "; chop($user = <STDIN>); print "Files: " chop($pattern = <STDIN>); ($login,$pass,$uid,$gid) = getpwnam($user) or die "$user not in passwd file"; @ary = <$
Returns the character represented by that NUMBER in the character set. For example,
chr(65)is "A" in ASCII.
- chroot FILENAME. complete,
Closes a directory opened by opendir().
-).
- cos EXPR
Returns the cosine of EXPR (expressed in radians). If EXPR is omitted takes cosine ASSOC_ARRAY
[This function has been superseded by the untie() function.]
Breaks the binding between a DBM file and an associative array.
- dbmopen ASSOC,DBNAME,MODE
[This function has been superseded by the tie() function.]
This binds a dbm(3), ndbm(3), sdbm(3), gdbm(), or Berkeley DB file to an associative array. ASSOC is the name of the associative array. only supports.
- defined EXPR. For example, if you say
only use defined() when you're questioning the integrity of what you're trying to do. At other times, a simple comparison to 0 or "" is what you want.
- delete EXPR};
- die LIST
Outside of() and warn().
- do BLOCK
Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by a loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.)
-" in perlvar).');
- each ASSOC_ARRAYin Perl, because the input operators return undef when they run out of data.
-, or a return statement may be used, just as with subroutines...
- exec LIST
The exec() function executes a system command AND NEVER RETURNS. Use the system() function if you want it to return.
If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp(3) with the arguments in LIST. If there is only one scalar argument, the argument is checked for shell metacharacters. If there are any, the entire argument is passed to
/bin/sh -cfor multi-valued list, even if there is only a single scalar in the list.) Example:
$shell = '/bin/csh'; exec $shell '-sh'; # pretend it's a login shell
or, more directly,
exec {'/bin/csh'} '-sh'; # pretend it's a login shell
- exists EXPR}) { ... }
- exit EXPR
Evaluates EXPR and exits immediately with that value. (Actually, it calls any defined
ENDroutines first, but the
ENDroutines may not abort the exit. Likewise any object destructors that need to be called are called before exit.) Example:
$ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/;
See also die(). If EXPR is omitted, exits with 0 status.
- exp EXPR.
- flock FILEHANDLE,OPERATION.
- fork
Does a fork(2) system call. Returns the child pid to the parent process and 0 to the child process, or
undefif the fork is unsuccessful. Note: unflushed buffers remain unflushed in both processes, which means you may need to set
$|($AUTOFLUSH in English) or call the autoflush() FileHandle method to avoid duplicate output. perlipc for more examples of forking and reaping moribund children.
- format
Declare a picture format, since an "
@" character may be taken to mean the beginning of an array name. formline() always returns TRUE. See perlform for other examples.
- getc FILEHANDLE
-
- getc
Returns the next character from the input file attached to FILEHANDLE, or a null string at end of file. to whether $BSD_STYLE should be set is left as an exercise to the reader.
See also the
Term::ReadKeymodule from your nearest CPAN site; details on CPAN can be found on "CPAN" in perlmod
- getlogin
Returns the current login from /etc/utmp, if any. If null, use getpwuid().
$login = getlogin || (getpwuid($<))[0] || a list undefined if there is an error.
- glob EXPR
Returns the value of EXPR with filename expansions such as a shell would do. This is the internal function implementing the <*.*> operator, except it's easier to use.
- gmtime EXPR
Converts a time as returned by the time function to a 9-element array with the time localized for the standard Greenwich timezone. Typically used as follows:
(
-
- goto EXPR
-
-, since $_ is a reference into the list value, it can be used to modify the elements of the array. While this is useful and supported, it can cause bizarre results if the LIST is not a named array.
- hex EXPR
Interprets EXPR as a hex string and returns the corresponding decimal value. (To convert strings that might start with 0 or 0x see oct().) If EXPR is omitted, uses $_.
- import
There is no built
Returns the integer portion of EXPR. If EXPR is omitted, uses $_.
- ioctl FILEHANDLE,FUNCTION,SCALAR
Implements the ioctl(2) function. You'll probably have to say
require "ioctl.ph"; # probably in /usr/local/lib/perl/ioctl.ph
first, but it's non-trivial.)
Joins the separate strings of LIST or ARRAY into a single string with fields separated by the value of EXPR, and returns the string. Example:
$_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
See "split" in perlfunc.
- keys ASSOC_ARRAY
Returns a normal array consisting of all the keys of the named associative array. (In a scalar context, returns the number of keys.) ... }
- lc EXPR
Returns an lowercased version of EXPR. This is the internal function implementing the \L escape in double-quoted strings. Should respect any POSIX setlocale() settings.
- lcfirst EXPR
Returns the value of EXPR with the first character lowercased. This is the internal function implementing the \l escape in double-quoted strings. Should respect any POSIX setlocale() settings.
- otherwise. See example in "Sockets: Client/Server Communication" in perlipc.
- local EXPR.
- log EXPR
Returns logarithm (base e) of EXPR. If EXPR is omitted, returns log of $_.
- lstat FILEHANDLE
-
- lstat EXPR
Does the same thing as the stat() function, but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal stat() is done.
-($_)} = $_; }
- parens..
- no Module LIST
See the "use" function, which "no" is the opposite of.
- oct EXPR>;
Returns the numeric ascii value of the first character of EXPR. If EXPR is omitted, uses $_.
-. i A signed integer value. I An unsigned integer value. l A signed long value. L An unsigned long value. n A short in "network" order. N A long in "network" order. dynamic variables--including those you've used local() on--but not lexical variables" in perlipc for examples of such things.
- pop ARRAY().
- pos SCALAR
Returns the offset of where the last
m//gsearch left off for the variable in question. May be modified to change that offset.
- parens";
- printf FILEHANDLE LIST
-
- printf LIST
Equivalent to a "print FILEHANDLE sprintf(LIST)". The first argument of the list will be interpreted as the printf format.
- prototype FUNCTION
Returns the prototype of a function as a string (or
undefif the function has no prototype). FUNCTION is a reference to the the function whose prototype you want to retrieve.
-x/STRING/
-
- qw/STRING/
Generalized quotes. See perlop.
- quotemeta EXPR
Returns the value of EXPR with with all regular expression metacharacters backslashed. This is the internal function implementing the \Q escape in double-quoted strings.
- rand EXPR
-
- rand.)
- read FILEHANDLE,SCALAR,LENGTH,OFFSET
-
- read FILEHANDLE,SCALAR,LENGTH;
- readlink EXPR
Returns the value of a symbolic link, if symbolic links are implemented. If not, gives a fatal error. If there is some system error, returns the undefined value and sets
$!(errno). If EXPR is omitted, uses $_.
- recv SOCKET,SCALAR,LEN,FLAGS
Receives a message on a socket. Attempts to receive LENGTH bytes of data into variable SCALAR from the specified SOCKET filehandle. Actually does a C recvfrom(), so that it can returns; }
- ref EXPR
Returns a TRUE value if EXPR is a reference, FALSE otherwise. an associative array.\n"; } if (!ref ($r) { print "r is not a reference at all.\n"; }
- rename OLDNAME,NEWNAME
Changes the name of a file. Returns 1 for success, 0 otherwise. Will not work across filesystem boundaries.
- word, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace. 'X'; # reset all X variables reset 'a-z'; # reset lower case variables reset; # just reset ?? searches
Resetting "A-Z" is not recommended since you'll wipe out your ARGV and ENV arrays. Only resets package variables--lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See "my".
- return LIST
Returns from a subroutine or eval with the value specified. (Note that in the absence of a return a subroutine or eval() will automatically return the value of the last expression evaluated.)
- reverse LIST
-
Deletes the directory specified by FILENAME if.
- seek FILEHANDLE,POSITION,WHENCE);
- select RBITS,WBITS,EBITS,TIMEOUT.
-,FLAGS
Calls the System V IPC function semget. Returns the semaphore id, or the undefined value if there is an error.
-. See "UDP: Message Passing" in perlipc for examples.
- setpgrp PID,PGRP.
- if @ARGV array in the main program, otherwise.
-.
- shutdown SOCKET,HOW
Shuts down a socket connection in the manner indicated by HOW, which has the same interpretation as in the system call of the same name.
- sin EXPR
Returns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of $_.
- sleep EXPR
-
- sleep
Causes the script to sleep for EXPR seconds, or forever if no EXPR. May be interrupted by sending the process a SIGALRM. Returns the number of seconds actually slept. You probably cannot mix alarm() and sleep() calls, since.
- socket SOCKET,DOMAIN,TYPE,PROTOCOL
Opens a socket of the specified kind and attaches it to filehandle SOCKET. DOMAIN, TYPE and PROTOCOL are specified the same as for the system call of the same name. You should "use Socket;" first to get the proper definitions imported. See the example.
- sort SUBNAME LIST
-
- sort BLOCK LIST
-
- sort LIST
Sorts the LIST and returns the sorted list value. Nonexistent values of arrays are stripped out. If SUBNAME or BLOCK is omitted, sorts, in which case the value provides the name of the; # this sorts the %age associative arrays by value # instead of key using an inline;
- splice ARRAY,OFFSET,LENGTH,LIST
-
- following.
- sqrt EXPR
Return the square root of EXPR. If EXPR is omitted, returns square root of $_.
- srand EXPR
Sets the random number seed for the
randoperator..
- stat FILEHANDLE
-
- stat EXPR LEN is negative, leaves that many characters off,.
-". This is NOT what you want to use to capture the output from a command, for that you should merely use backticks, as described in "`STRING`" in perlop.
- syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
-
- syswrite FILEHANDLE,SCALAR,LENGTH.
- array values an associative array should have the following methods:
TIEHASH classname, LIST
Unlike dbmopen(), the tie() function will not use or require a module for you--you need to do that explicitly yourself. See DB_File or the Config module for interesting tie() implementations.
- tied VARIABLE
Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the tie() call which array giving the user and system times, in seconds, for this process and the children of this process.
($user,$system,$cuser,$csystem) = times;
- tr///
The translation operator. See perlop.
- truncate FILEHANDLE,LENGTH
-
- truncate EXPR,LENGTH
Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Produces a fatal error if truncate isn't implemented on your system.
- uc EXPR
Returns an uppercased version of EXPR. This is the internal function implementing the \U escape in double-quoted strings. Should respect any POSIX setlocale() settings.
- ucfirst EXPR
Returns the value of EXPR with the first character uppercased. This is the internal function implementing the \u escape in double-quoted strings. Should respect any POSIX setlocale() settings.
- umask EXPR
-
- umask
Sets the umask for the process and returns the old one. If EXPR is omitted, merely returns current umask.
- undef EXPR
-
- undef;
- a list word. which you don't want your namespace altered, explicitly supply an empty list:
use Module ();
That is exactly equivalent to
BEGIN { require Module; }
If the VERSION argument is present between Module and LIST, then the
usewill fail if the
$VERSIONvariable in package Module is less);
These pseudomodules';. Example of a "touch" command:
#!/usr/bin/perl $now = time; utime $now, $now, @ARGV;
- values ASSOC_ARRAY().
- vec EXPR,OFFSET,BITS are needed to give the expression the correct precedence as in
vec($image, $max_x * $x + $y, 8) = 3;
Vectors created with vec() can also be manipulated with the logical operators |, & and ^, which will assume a bit vector operation is desired when both operands are strings.
To transform a bit vector into a string or array of 0's and 1's, use these:
$bits = unpack("b*", $vector); @bits = split(//, unpack("b*", $vector));
If you know the exact length in bits, it can be
use POSIX " executing subroutine is looking for a list value. Returns FALSE if the context is looking for a scalar.
return wantarray ? () : undef;
- warn LIST
Produces a message on STDERR just like die(), but doesn't exit or on an exception.
. See perlop. | https://metacpan.org/pod/release/KRISHPL/pod2texi-0.1/perlfunc.pod | CC-MAIN-2020-24 | refinedweb | 2,474 | 57.98 |
While you can read and write CSV files in Python using the built-in
open() function, or the dedicated csv module - you can also use Pandas.
In this article, you will see how to use Python's Pandas library to read and write CSV files.
What is a CSV File?
Let's quickly recap what a CSV file is - nothing more than a simple text file, following a few formatting conventions. However, it is the most common, simple, and easiest method to store tabular data. This format arranges tables by following a specific structure divided into rows and columns. It is these rows and columns that contain your data.
A new line terminates each row to start the next row. Similarly, a delimiter, usually a comma, separates columns within each row.
For example, we might have a table that looks |
If we were to convert it into the CSV format, it'd look
Although the name (Comma-Separated Values) inherently uses a comma as the delimiter, you can use other delimiters (separators) as well, such as the semicolon (
;). Each row of the table is a new line of the CSV file and it's a very compact and concise way to represent tabular data.
Now, let's take a look at the
read_csv() function.
Reading and Writing CSV Files using Pandas
Pandas is a very powerful and popular framework for data analysis and manipulation. One of the most striking features of Pandas is its ability to read and write various types of files including CSV and Excel. You can effectively and easily manipulate CSV files in Pandas using functions like
read_csv() and
to_csv().
Installing Pandas
We have to install Pandas before using it. Let's use
pip:
$ pip install pandas
Reading CSV Files with read_csv()
Let's import the Titanic Dataset, which can be obtained on GitHub:
import pandas as pd titanic_data = pd.read_csv('titanic.csv')
Pandas will search for this file in the directory of the script, naturally, and we just supply the filepath to the file we'd like to parse as the one and only required argument of this method.
Let's take a look at the
head() of this dataset to make sure it's imported correctly:
titanic_data.head()
This
Alternatively, you can also read CSV files from online resources, such as GitHub, simply by passing in the URL of the resource to the
read_csv() function. Let's read this same CSV file from the GitHub repository, without downloading it to our local machine first:
import pandas as pd titanic_data = pd.read_csv(r'') print(titanic_data.head())
This also [5 rows x 12 columns]
Customizing Headers
By default, the
read_csv() method uses the first row of the CSV file as the column headers. Sometimes, these headers might have odd names, and you might want to use your own headers. You can set headers either after reading the file, simply by assigning the
columns field of the
DataFrame instance another list, or you can set the headers while reading the CSV in the first place.
Let's define a list of column names, and use those names instead of the ones from the CSV file:
import pandas as pd col_names = ['Id', 'Survived', 'Passenger Class', 'Full Name', 'Gender', 'Age', 'SibSp', 'Parch', 'Ticket Number', 'Price', 'Cabin', 'Station'] titanic_data = pd.read_csv(r'E:\Datasets\titanic.csv', names=col_names) print(titanic_data.head())
Let's run this code:
Id Survived Passenger Class ... Price Cabin Station 0 PassengerId Survived Pclass ... Fare Cabin Embarked 1 1 0 3 ... 7.25 NaN S 2 2 1 1 ... 71.2833 C85 C 3 3 1 3 ... 7.925 NaN S 4 4 1 1 ... 53.1 C123 S
Hmm, now we've got our custom headers, but the first row of the CSV file, which was originally used to set the column names is also included in the
DataFrame. We'll want to skip this line, since it no longer holds any value for us.
Skipping Rows While Reading CSV
Let's address this issue by using the
skiprows argument:
import pandas as pd col_names = ['Id', 'Survived', 'Passenger Class', 'Full Name', 'Gender', 'Age', 'SibSp', 'Parch', 'Ticket Number', 'Price', 'Cabin', 'Station'] titanic_data = pd.read_csv(r'E:\Datasets\titanic.csv', names=col_names, skiprows=[0]) print(titanic_data.head())
Now, let's run this code:
Id Survived Passenger Class ... Price Cabin Station 0 1 0 3 ... 7.2500 NaN S 1 2 1 1 ... 71.2833 C85 C 2 3 1 3 ... 7.9250 NaN S 3 4 1 1 ... 53.1000 C123 S 4 5 0 3 ... 8.0500 NaN S
Works like a charm! The
skiprows argument accepts a list of rows you'd like to skip. You can skip, for example,
0, 4, 7 if you'd like as well:
titanic_data = pd.read_csv(r'E:\Datasets\titanic.csv', names=col_names, skiprows=[0, 4, 7]) print(titanic_data.head(10))
This would result in a
DataFrame that doesn't have some of the rows we've seen before:
Id Survived Passenger Class ... Price Cabin Station 0 1 0 3 ... 7.2500 NaN S 1 2 1 1 ... 71.2833 C85 C 2 3 1 3 ... 7.9250 NaN S 3 5 0 3 ... 8.0500 NaN S 4 6 0 3 ... 8.4583 NaN Q 5 8 0 3 ... 21.0750 NaN S 6 9 1 3 ... 11.1333 NaN S 7 10 1 2 ... 30.0708 NaN C 8 11 1 3 ... 16.7000 G6 S 9 12 1 1 ... 26.5500 C103 S
Keep in mind that skipping rows happens before the
DataFrame is fully formed, so you won't be missing any indices of the
DataFrame itself, though, in this case, you can see that the
Id field (imported from the CSV file) is missing IDs
4 and
7.
Removing Headers
You can also decide to remove the header completely, which would result in a
DataFrame that simply has
0...n header columns, by setting the
header argument to
None:
titanic_data = pd.read_csv(r'E:\Datasets\titanic.csv', header=None, skiprows=[0])
You'll also want to skip the first row here, since if you don't, the values from the first row will be actually be included in the first row:
0 1 2 3 4 ... 7 8 9 0 1 0 3 Braund, Mr. Owen Harris male ... 0 A/5 21171 7.2500 1 2 1 1 Cumings, Mrs. John Bradley (Florence Briggs Th... female ... 0 PC 17599 71.2833 2 3 1 3 Heikkinen, Miss. Laina female ... 0 STON/O2. 3101282 7.9250 3 4 1 1 Futrelle, Mrs. Jacques Heath (Lily May Peel) female ... 0 113803 53.1000 4 5 0 3 Allen, Mr. William Henry male ... 0 373450 8.0500
Specifying Delimiters
As stated earlier, you'll eventually probably encounter a CSV file that doesn't actually use commas to separate data. In such cases, you can use the
sep argument to specify other delimiters:
titanic_data = pd.read_csv(r'E:\Datasets\titanic.csv', sep=';')
Writing CSV Files with to_csv()
Again,
DataFrames are tabular. Turning a
DataFrame into a CSV file is as simple as turning a CSV file into a
DataFrame - we call the
write_csv() function on the
DataFrame instance.
When writing a
DataFrame to a CSV file, you can also change the column names, using the
columns argument, or specify a delimiter via the
sep argument. If you don't specify either of these, you'll end up with a standard Comma-Separated Value file.
Let's play around with this:
import pandas as pd cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida']], columns=['City', 'State']) cities.to_csv('cities.csv')
Here, we've made a simple
DataFrame with two cities and their respective states. Then, we've gone ahead and saved that data into a CSV file using
to_csv() and providing the filename.
This results in a new file in the working directory of the script you're running, which contains:
,City,State 0,Sacramento,California 1,Miami,Florida
Though, this isn't really well-formatted. We've still got the indices from the
DataFrame, which also puts a weird missing spot before the column names. If we re-imported this CSV back into a
DataFrame, it'd be a mess:
df = pd.read_csv('cities.csv') print(df)
This results in:
Unnamed: 0 City State 0 0 Sacramento California 1 1 Miami Florida
The indices from the
DataFrame ended up becoming a new column, which is now
Unnamed.
When saving the file, let's make sure to drop the index of the
DataFrame:
import pandas as pd cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida']], columns=['City', 'State']) cities.to_csv('cities.csv', index=False)
Now, this results in a file that contains:
City,State Sacramento,California Miami,Florida
Works like a charm! If we re-import it and print the contents, the
DataFrame is constructed well:
df = pd.read_csv('cities.csv') print(df)
This results in:
City State 0 Sacramento California 1 Miami Florida
Customizing Headers
Let's change the column headers from the default ones:
import pandas as pd cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida']], columns=['City', 'State']) new_column_names = ['City_Name', 'State_Name'] cities.to_csv('cities.csv', index=False, header=new_column_names)
We've made a
new_header list, that contains different values for our columns. Then, using the
header argument, we've set these instead of the original column names. This generates a
cities.csv with these contents:
City_Name,State_Name Sacramento,California Miami,Florida Washington DC,Unknown
Customizing Delimiter
Let's change the delimiter from the default (
,) value to a new one:
import pandas as pd cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida']], columns=['City', 'State']) cities.to_csv('cities.csv', index=False, sep=';')
This results in a
cities.csv file that contains:
City;State Sacramento;California Miami;Florida
Handling Missing Values
Sometimes,
DataFrames have missing values that we've left as
NaN or
NA. In such cases, you might want to format these when you write them out into a CSV file. You can use the
na_rep argument and set the value to be put instead of a missing value:
import pandas as pd cities = pd.DataFrame([['Sacramento', 'California'], ['Miami', 'Florida'], ['Washington DC', pd.NA]], columns=['City', 'State']) cities.to_csv('cities.csv', index=False, na_rep='Unknown')
Here, we've got two valid city-state pairs, but
Washington DC is missing its state. If we run this code, it'll result in a
cities.csv with the following contents:
City,State Sacramento,California Miami,Florida Washington DC,Unknown
Conclusion
The article shows how to read and write CSV files using Python's Pandas library. To read a CSV file, the
read_csv() method of the Pandas library is used. You can also pass custom header names while reading CSV files via the
names attribute of the
read_csv() method. Finally, to write a CSV file using Pandas, you first have to create a Pandas DataFrame object and then call
to_csv method on the DataFrame. | https://stackabuse.com/reading-and-writing-csv-files-in-python-with-pandas/ | CC-MAIN-2021-17 | refinedweb | 1,817 | 65.12 |
Hello everyone!! I am in my second year of college and am majoring in computer science, however, my computer programming beginner class is the first programming I have ever done in my life and I would love if anybody could comment on this homework assignment I have! I've done most of it but there are still pieces missing. Here are the instructions:
Write a program: MidtermStat.java, to output (on screen) the average, lowest, and highest grades in the midterm exam (if there is multiple highest and lowest, just output one of them). The midterm grades are previously stored in a text file named "midterm_grade.txt". You may assume there are exactly 30 grades in the file.
Code Java:
import java.io.*; import java.util.*; public class MidtermStat { public static void main(String[] ags) throws IOexception { Scanner in = new Scanner(new FileReader("midterm_grade.txt")); int number; int lowest = 36.0; int highest = 100.0; double average; System.out.println("Numbers on file midterm_grade.txt: "); while (in.hasNextInt()) { number = in.nextInt(); System.out.println("The lowest grade is: "); System.out.print("The highest grade is: "); } System.out.println(); in.close(); } }
//I'm supposed to be using count-controlled loop or event controlled loop in this
//along with if-else statements
//the file called "midterm_grade.txt" is a seperate file composed of approximately 30 grades
//the lowest grade is 36.0 and the highest is obviously 100.0 | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/5589-programming-beginner-printingthethread.html | CC-MAIN-2018-09 | refinedweb | 237 | 60.51 |
We have a use case where we want to extract many non-consecutive rows from a
DataSet, so we thought we would create a union selection in a
DataSpace to use in the subsequent
DataSet::read() call. However, when the rows were non-consecutive, the construction of the union was extremely slow - in fact, slower than the actual reading of the data from file! The C++ code below provides a simple standalone example:
#include "H5Cpp.h" #include <vector> #include <iostream> #include <algorithm> #include <ctime> int main (int argc, const char** argv) { if (argc!=4) { std::cout << argv[0] << " [FILE] [DATASET] [CONSEC]" << std::endl; return 1; } const char* fname=argv[1]; const char* dname=argv[2]; const bool consec= submatrices. const size_t NR=10000, NC=100; hsize_t h5_start[2], h5_count[2]; h5_start[0]=0; h5_start[1]=0; h5_count[0]=1; h5_count[1]=NC; { hspace.selectNone(); clock_t start=std::clock(); size_t counter=0; for (size_t i=0; i<NR; ++i) { counter += (consec ? 1 : 2); // non-consecutive. h5_start[0]=counter; hspace.selectHyperslab(H5S_SELECT_OR, h5_count, h5_start); } clock_t end=std::clock(); std::cout << "Elapsed for union: " << double(end - start)/CLOCKS_PER_SEC << std::endl; } std::vector<double> storage(NR * NC); h5_count[0]=NR; H5::DataSpace outspace(2, h5_count); outspace.selectAll(); { clock_t start=std::clock(); hdata.read(storage.data(), H5::PredType::NATIVE_DOUBLE, outspace, hspace); clock_t end=std::clock(); std::cout << "Elapsed for read: " << double(end - start)/CLOCKS_PER_SEC << std::endl; } double total = std::accumulate(storage.begin(), storage.end(), 0.0); std::cout << "Total is: " << total << std::endl; return 0; }
I should point out that the above example takes every second row for the sake of simplicity; our actual use case does not have such a predictable structure, so we can’t use
stride in
selectHyperslab.
We ran this on a HDF5 file containing a gene expression matrix for about 30000 genes (columns) and 1 million cells (rows), which can be obtained from. Compiled against the HDF5 library (version 1.10.3), I get:
$ ./HDF5UnionTester ~/.ExperimentHub/1040 counts 1 # consecutive Elapsed for union: 0.002197 Elapsed for read: 0.023256 Total is: 198451 $ ./HDF5UnionTester ~/.ExperimentHub/1040 counts 0 # non-consecutive Elapsed for union: 4.7186 Elapsed for read: 0.227834 Total is: 190563
The longer read I can understand, as it involves twice as many chunks (though I am surprised it’s 10 times longer rather than just 2-fold); however, the time taken by the union is very unexpected. At this rate, it seems faster to just call
DataSet::read() multiple times instead of using a single call with a union… which seems to defeat the purpose of having this union capability in the first place. | https://forum.hdfgroup.org/t/union-of-non-consecutive-hyperslabs-is-very-slow/5062 | CC-MAIN-2018-51 | refinedweb | 437 | 55.13 |
In SharePoint 2010 Microsoft provided a version of the managed code CSOM for developers of .NET applications. This library has been rebuilt for SharePoint 2013 and is provided as part of the SharePoint installation. As in the 2010 release, it is provided as part of a redistributable package for developers to include in their applications.
It is made up of the following .NET assemblies:
Later in this chapter you learn about which parts of the CSOM are in what DLL and namespace, but the naming of the DLLs should also give you a few hints.
You can install the DLLs on any computer by downloading the SharePoint Client Components SDK available at:.
Additionally you can find them in the following location on a machine with SharePoint installed, as shown in Figure 9-1:
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI
After you have added references to these DLLs from your .NET application such as a Windows Forms application or console application, you can add a ...
No credit card required | https://www.oreilly.com/library/view/beginning-sharepoint-2013/9781118654873/xhtml/sec47.html | CC-MAIN-2019-18 | refinedweb | 172 | 52.8 |
*Edited to remove the "Advanced" tag
This post has been edited by pbl: 05 March 2009 - 08:45 PM
Posted 05 March 2009 - 06:56 PM
This post has been edited by pbl: 05 March 2009 - 08:45 PM
Posted 05 March 2009 - 07:01 PM
jnartey, on 5 Mar, 2009 - 05:56 PM, said:
Posted 05 March 2009 - 07:12 PM
Posted 05 March 2009 - 07:19 PM
jnartey, on 5 Mar, 2009 - 06:12 PM, said:
Posted 05 March 2009 - 07:32 PM
Posted 06 March 2009 - 11:44 AM
public class InteractiveTableModelListener implements TableModelListener { public void tableChanged(TableModelEvent evt) { if (evt.getType() == TableModelEvent.UPDATE) { int row = evt.getFirstRow(); System.out.println("Updated row:"+" "+row); jTable1.setRowSelectionInterval(row, row); } } } [CODE] If you print updated row, it does not include the last cell unless you hit enter in the last cell or navigate away from it using the arrow. I also use getRowCount() to loop through the rows as indicated in the code below: [CODE] public static void fillCodeList(){ JTable table = GLPanel.jTable1; int rowcount = table.getModel().getRowCount(); for(int i = 0;i<rowcount;i++){ String tablecode = (String)table.getModel().getValueAt(i, 0); if((tablecode != null)&&(!(tablecode.equalsIgnoreCase("")))){ gtrans.add(new GLCode(tablecode)); }
Posted 06 March 2009 - 02:16 PM
JTable jTable1 = new JTable(); jTable1.putClientProperty("terminateEditonfocusLost", Boolean.TRUE); | http://www.dreamincode.net/forums/topic/90885-how-to-read-the-last-cell-of-a-one-column-jtable/ | CC-MAIN-2017-51 | refinedweb | 220 | 51.18 |
Inject scripts, stylesheets and more into templates and htmls, with support for namespaces
Inject scripts, stylesheets and more into templates and htmls, with support for namespaces.
npm install --save-dev gulp-multinject
The example below will scan all the
.html and
.jade files and will inject the provided scripts and styles.
var gulp = ;var gulpMultinject = ;gulp;
For
.html files it will inject between the tags:
<!--INJECT:adminNamespace--><!--END INJECT-->
For
.jade files it will inject between the tags:
//INJECT:adminNamespace//END INJECT
**At the moment only
.html and
.jade files are supported by default, but you can override the
templates using the
templateMap option (or submitting a PR) **
Create a new gulp-multinject transform stream.
injectList:
Array. A list of URLs or files to inject.
namespace:
String. The namespace to use for the inject tags.
Options:
Object|undefined. An object containing the following
templateMap: A map used for resolving the tag and templates to use for the injection. For an example of a template map look into the default template map
base:
String. Defaults to
"". The base directory for the injected files. It will be removed from the provided path before the injection
urlPrefix:
String. Defaults to
"/". A string to prepend to the injected file url.
relative:
Boolean. Defaults to
false. If true the injected path will be relative to the file it is injected into.
defaultExtension:
String. Defaults to
null. Sometimes if you are injecting some URLs, for example from a CDN, they don't contain an extension, in this case gulp-multinject will use this options to resolve the proper template to use for the injection. | https://www.npmjs.com/package/gulp-multinject | CC-MAIN-2017-09 | refinedweb | 268 | 66.13 |
Read a File Line by Line in C++
- Use
std::getline()Function to Read a File Line by Line
- Use C Library
getline()Function to Read a File Line by Line
This article will introduces how to read a file line by line in C++.
Use
std::getline() Function to Read a File Line by Line
The
getline() function is the preferred way of reading a file line by line in C++. The function reads characters from the input stream until the delimiter char is encountered and then stores them in a string. The delimiter is passed as the third optional parameter, and by default, it’s assumed to be a new line character
\n.
Since the
getline method returns a nonzero value if the data can be read from the stream, we can put it as a
while loop condition to continue retrieving lines from a file until the end of it is reached. Note that it’s good practice to verify if the input stream has an associated file with the
is_open method.
#include <iostream> #include <fstream> #include <vector> using std::cout; using std::cerr; using std::endl; using std::string; using std::ifstream; using std::vector; int main() { string filename("input.txt"); vector<string> lines; string line; ifstream input_file(filename); if (!input_file.is_open()) { cerr << "Could not open the file - '" << filename << "'" << endl; return EXIT_FAILURE; } while (getline(input_file, line)){ lines.push_back(line); } for (const auto &i : lines) cout << i << endl; input_file.close(); return EXIT_SUCCESS; }
Use C Library
getline() Function to Read a File Line by Line
The
getline function can be used similarly to loop through the file line by line and store extracted lines in a character string variable. The main difference is that we should open a file stream using the
fopen function, which returns the
FILE* object, later to be passed as the third parameter.
Notice that
getline function stores at
char pointer, which is set to
nullptr. This is valid because the function itself allocates the memory dynamically for retrieved characters. Thus, the
char pointer should be explicitly freed by a programmer, even if the
getline call failed.
Also, it’s important to set the second parameter of type
size_t to 0 before calling the function. You can see the detailed manual of the
getline function here.
#include <iostream> #include <vector> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; int main() { string filename("input.txt"); vector<string> lines; char* c_line = nullptr; size_t len = 0; FILE* input_file = fopen(filename.c_str(), "r"); if (input_file == nullptr) return EXIT_FAILURE; while ((getline(&c_line, &len, input_file)) != -1) { lines.push_back(line.assign(c_line)); } for (const auto &i : lines) { cout << i; } cout << endl; fclose(input_file); free(c_line); return EXIT_SUCCESS; } | https://www.delftstack.com/howto/cpp/how-to-read-a-file-line-by-line-cpp/ | CC-MAIN-2021-25 | refinedweb | 453 | 59.94 |
[cc'ing back to lkml]
On Wed, Sep 08, 2004 at 05:05:51PM -0500, Steve Lord wrote:
>
> I wonder what the effect of /proc/sys/vm/swappiness
> and /proc/sys/vm/vfs_cache_pressure is on these situations.
Hi Steve.
I very much doubt vm_swappiness will have any effect on this - it
just determines whether to throw away page cache pages or swap out
mapped pages - it won't affect the dentry cache size. The best
it can do is allow us to swap out more pages so the dentry cache
can grow larger....
Looking at vfs_cache_pressure (documented in Documentation/
filesystems/proc.txt), it is used to make the number of unused
inodes and dentries used by the system appear to be smaller or
larger to the slab shrinker function:
661 static int shrink_dcache_memory(int nr, unsigned int gfp_mask)
662 {
663 if (nr) {
664 if (!(gfp_mask & __GFP_FS))
665 return -1;
666 prune_dcache(nr);
667 }
668 return (dentry_stat.nr_unused / 100) * sysctl_vfs_cache_pressure;
669 }
and hence the shrinker will tend to remove more or less dentries or
inodes when the cache is asked to be shrunk. It will have no real
effect if the unused dentry list is small (i.e. we're actively
growing the dentry cache) which seems to be the case here.
FWIW, it appears to me that the real problem is that shrink_dcache_memory()
does not shrink the active dentry cache down - I think it needs to do more
than just free up unused dentries. I'm not saying this is an easy thing
to do (I don't know if it's even possible), but IMO if we allow the dentry
cache to grow without bound or without a method to shrink the active
tree we will hit this problem a lot more often as filesystems grow larger.
For those that know this code well, it looks like there's a bug
in the above code - the shrinker calls into this function first with
nr = 0 to determine how much it can reclaim from the slab.
If the dentry_stat.nr_unused is less than 100, then we'll return 0
due to integer division (99/100 = 0), and the shrinker calculations
will see this as a slab that does not need shrinking because:
185 list_for_each_entry(shrinker, &shrinker_list, list) {
186 unsigned long long delta;
187
188 delta = (4 * scanned) / shrinker->seeks;
189 delta *= (*shrinker->shrinker)(0, gfp_mask);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
190 do_div(delta, lru_pages + 1);
191 shrinker->nr += delta;
192 if (shrinker->nr < 0)
193 shrinker->nr = LONG_MAX; /* It wrapped! */
194
195 if (shrinker->nr <= SHRINK_BATCH)
196 continue;
because we returned zero and therefore delta becomes zero and
shrinker->nr never gets larger than SHRINK_BATCH.
Hence in low memory conditions when you've already reaped most of
the unused dentries, you can't free up the last 99 unused dentries.
Maybe this is intentional (anyone?) because there isn't very much to
free up in this case, but some memory freed is better than none when
you have nothing at all left.
Cheers,
Dave.
--
Dave Chinner
R&D Software Engineer
SGI Australian Software Group | http://oss.sgi.com/archives/xfs/2004-09/msg00391.html | CC-MAIN-2013-48 | refinedweb | 509 | 63.22 |
- Author:
- robmadole
- Posted:
- November 12, 2010
- Language:
- Python
- Version:
- 1.2
- Score:
- 0 (after 0 ratings)
Testing low-level functionality sometimes requires a WSGIRequest object. An example of this is testing template tags.
This will monkey-patch the test Client object to return WSGIRequest objects
Normal Django behavior:
>>> client.get('/') <HttpResponse >
With this code, get the request object:
>>> client.request_from.get('/') <WSGIRequest >
Installation:
For this to work, you simply need to import the contents of this file.
If you name this file
clientrequestpatch.py, do this inside your Django tests.
from django.test.testcases import TestCase from myproject.test import clientrequestpatch. | http://www.djangosnippets.org/snippets/2259/ | CC-MAIN-2022-33 | refinedweb | 101 | 53.78 |
Introduction:.
First open Visual Studio and create new website after that right click on your website and add new folder and give name as JS and insert script files in folder you should get it from attached folder same way add another new folder and give name as CSS and insert required css files in folder you should get it from attached folder. After that write the following code in your aspx page
If you observe above code in header section I added some of script files and css files by using those files we have a chance to show popup messages when validation fails using JQuery in asp.net. Here one thing we need to remember that is if we want add validation for particular control then we need to add css class CssClass="validate[required]" to that particular control.
Now add the following namespaces in code behind
After that add following codes in code behind
After run your application and check the output.
Demo
Download sample code attached .
To know more about this JQuery plugin check these sites position-absolute.com and JQuery tooltip demo page position-relative.net
117 comments :
Thanks....
Present am looking for this..
Nice
Hi,
I was wondering if u could tell me how to use this within a content page.. When I use the form tag inside a content page it throws the following exception "System.Web.HttpException: A page can have only one server-side Form tag".
Is there any way to work around this?
Thankyou. .
I used it this is a great tools but i find it hard to fix certain thing, Like it validation triggers for MasterPage design for any button on the master page on content page.
How can we get around that.
Second i had integrated same validation with 3 Ajax Modal popups in one page as requirement was such in such scenario sometimes button doesnt fire and other similar issue. Anyway Just was to thank you who have put some real good article which are worth using
Hello sir, how can i attach my CSS with textbox and dropdown ? as u i have seen u used input type and radio kind of the tags for it..
*actually i need diff. css for textbox and dropdown.
will wait for ur reply...
Hi,
I want to ask you one simple question. I have checked it. It only works with button whose type=submit. How we can use it with type=button. I have checked it but it doesn't work.
@Zaheer..
If you observe above post in that i used asp control with type=button not type=submit please check it once it's working fine.
How we can set causevalidation="false" property of this button.. Using these validations
In my form 2 buttons are there one is submit and another one is cancel. when user press cancel button that time also validation has come so how to solve this?
Thanks for this! It does work as advertised; however, it does not seem to pass a validation check even though the form seems to work.
Also, In my scenario my form resides on a masterpage and that seems to break it. I have looked around and so far this is the best post I have seen in a hundred, but it doesn't cover this. Any help would be GREATLY apprecieated! Thanks!
This works great, best example I have seen and I REALLY looked! However, as soon as I try to use this in scenario where my form resides on a masterpage, and your provided table resides on the childpage it breaks it. The table renders fine, but the validation fails; actually running alert($("#form1").validationEngine('validate')); returns false even without altering your code. Any help you could give me would be MUCH appreciated! Thanks again!
how to validate dropdownlist if i will bind dropdownlist dynamically
How to validate on Button click, if I click on button I would like to show alert as Failed if validation fails and Success if Validation Success.. How can I do this
To show javascript validation message when click on button check this post
I am not finding any attachments for css and JQuery... could you please provide me CSS and JQuery...
@Sriniva.....
Everything is there in folder check it once......
hai suresh.i have one doubt
when i click the submit button validation required is coming but it will execute on server and form get post backed
abinash::--
hai suresh.i have one doubt
when i click the submit button validation required is coming but when i click the cancel button again validation is required
abinash::--
hai suresh.i have one doubt
when i click the submit button validation required is coming but when i click the cancel button again validation is required
in master page this jquery will not work any possible to work with master page
very nice client side validation by Jquery with ASP.NET.
by Bhupesh Kumar xpert infotech
How to Use It In Content Page without Form Tag
Hi Suresh,
This article looks good. where i can find the attached folder?
...Das
@Das...
In post i added DownLoad Sample Code Attached please check it and download it
Thank you Suresh,
Nice post.... Keep Posting.
...Das
How can I auto refresh web page if user skip or enter invalid data into textbox and after this validation must be visible to user
Its is not working with master page. how do I use it with masterpage
What is the of equals in JQuery From Validation??
"equals": {
"regex": "none",
"alertText": "* Fields do not match"
},
How can I use it?? It is for compare between two textBox????
Hi Suresh,
How can I set rules when I use from validation...like datetime range, compare password etc...
Please reply............
Where are you assigning the error message like "*Invalid URL"
this example not working in master page scenario ..
hi sir ,
please provide the code for validating
radio button list & check box list & list view
hi sir ,
How to validate
radio button list & check box list & list view..
very urgent please,.............
Hi suresh,
How can i show the validation message one by one in button click.
Thanks in advance.
sir i used your code..it worked for me thanks..but sir there is a prblm m having to button on my form btnSubmit and btnreset..on clicking submit its proper but when i m clicking on reset tnen also validation occurs i want the validation to fire only on submit button clientclick pls help thanks in advance...
sir i got the solution to avoid validation on reset button..i just set usesubmitbehaviour of resetbutton "false" and added type=reset on reset button..now its working fine for me on submit validation occurs and on reset all history is cleared..thanks sir your article is awesome.....but pls help me for fileupload control i want to restrict file size(only 2mb file allowed) how to do this...
@Raj...
Check this article to restrict file upload size
hi
as i see in previous question you have not answered how to use this code in masterpage- scenario . can you explain this as it is not working in this scenario.
if you want to use it in master page you need to use the same code and place the script files in master page also then it will work for you.
I am using js files references in master page but still its not working for me.
I am using js refrences in master page and
script type="text/javascript"
jQuery(document).ready(function()
{
jQuery("#form1").validationEngine();
});
/script
this code am also using in master page still i am unable to call validations.
Please check your form id whether is it form1 or not. Here in jQuery("#form1").validationEngine(); statement i am using form id value.
sir m using your validation code m having two radio buttons (eg: for sale and for rent ) and i want to the user to select atleast one option how to validate that using this plugin m not getting it..pls help
@manish kumar hey manish remove the form tag from master page and add form tag on every page inside master and give id "form1" to very page and paste the jquery function
jQuery(document).ready(function () {
jQuery("#form1").validationEngine();
});
on top of every page it will work for you...for me it worked..
Suresh sir... you are inspiration.
love u for all these demos and code.
makes life so easy
Hi sir i am use this code by using master page ,
and i am add script child as well as master page also but it is not working.
give me one reply how it will done by using master page?
Hi Chetan I did the same thing and it was not working.
To work around after running your application just view the source of the page from the browser and check id of form what it is coming. Use that form id in your code and it will work perfectly.
Usually it is aspnetform
nice post
On using this jquery files(jquery.validationEngine,jquery.validationEngine-en,jquery-1.6.min) from the above sample code getting problems in screen, sliding menu which uses older version of jquery-min. Kindly guide me to overcome from this problem
Hi
How to disable validation for Clear Button
Hi sir
dropdown validation is not working sir.. what to do sir......
Hi, it is a great work
However for me it is working in firefox but not in IE (9). Any idea what to do to run it in IE?
Your are genius.Hats off.
Hi Suresh,
If i am validating the email field and the textbox has not any value then how can i only show the required field validation message.
Currently it's showing required field message as well as the url validation messgae at a time.
if any user enter any string in email textbox then only the url validation will get fired.
Looking forward for your earliest response.
Thanks in advance.
vb cv
WOW superb nice article suresh,keep rocking
Hi Suresh !
How can i validate div instead of form?
Because my web page contains lot of buttons.If i click any the button validation occurs..
Thank you..
good
how to use your JQuery form validations example in asp.net with masterpage ? please send me one example of this . in my e-mail id
my id is hard.ghodasara@gmail.com
hello suresh sir this code very helpful for me
but in example message is display once than if we fill value in text box than give tab that time it is hide but i want to hide at the filling time of text box
to do this type validation what i want to do
Plz help me
hi suresh i want to do same validation for submit
it showing validation message as weel as postback to the server
You Gave answer at September 18, 2012 at 9:58 PM,
if you want to use it in master page you need to use the same code and place the script files in master page also then it will work for you.
But it is not working
Please help me
I have a master page and has a form Id . That's why in all project FormId is not use anywhere . Then how i used it.
Hii..
I am solved the qurrries related to master page..
Plz used following code..
When .net renders it changes the Form id so instead of using:
jQuery("#form1").validationEngine();
Please use:
jQuery("form").validationEngine();
Happy coding...
Any help for checkboxlist Validation....
Hi, Suresh
This validation is not properly working with master page. click event is fire but validation not not fire.
Thank you very much....suresh & Anonymous I done it properly in master page form.
Hi Suresh...
It's really amazing article you have post.
i want to use this validtation js using custom message instead of static message as you have defined in js.
will it be possible to do that ?
Great jquery validation
by unitedwebsoft
How i use for radiobuttonlist and Checkbuttonlist button?
Dev
Accept only alphabets in First Name and Last Name and only numbers in Contact Number field(Additional field)?
How i use for radiobuttonlist and Checkbuttonlist button?
using this validation engine
Thanks&Regards
Maddeswar K.
can u please suggest me how we can compare two text boxes
(i.e password textbox and confirm password textbox
hiii suresh i just want to add new field that is password compare...how i can compare two fields password and re password using this above style ......plz update
very good ......u have done a great job.Thank u so much at Allied Packers
Hi Friends,
those people are facing the issue of Jquery validation fail while using Master Page. they search the form id in source page after running the project. In Source Page whatever Form ID is being made, Copy the Form ID and Paste inside the jquery document.get ready function in master page or any page which uses master page. after giving the right Form ID to the Jquery validationEngine() function, the Jquery velidation will start working. If still you face same problem. you can send me request mail at my EmailID i.e jatinrana1988@gmail.com, i will send you test solution.
How can I use validation engine on button instead of type=submit ?
How do i use for radio buttonlist and Checkbutton list button?
hi great tutorial
i tried with master page from the form name generated in asp.net but it did not work..suggestions please
can u please upload one new projects after adding the user request again, we realy appricate ur work. visit. suffian ahmed
nice but ..how can i use with cancel button plzz reply....
I have tried with master pages inside modal popups but validations shuffle like popup goes and validation messages remains still.
Suresh Sir, I've created a master page. And in Content Page there is a jQuery function(according to u article) which is using form id(form1). The problem is that form/form ID is in Master Page.That'swhy this jQuery function is not working in Content Page. Pls help me by giving a hint/solution.
Sir i want use compare password between two textbox
using jquery function in asp.net c# plz help me.
Dear Sir,
i also want to compare 'password' and 'ConfirmPassword'.
How to achieve this?
How can I use validation for "Date"
hi suresh
It is very nice work but it is not working in Content pages, how I can achieve as on Content page
Plz help...
hey awesome article .....
this is very helpful for me....
hi suresh
i have 2 buttons in form "Submit" and "Cancel". i want validation process when click the submit button. but it works when click cancel button also. how can solve it. plz help
Hi Suresh
How can i add css class to text box/Drop down list if i add CssClass="validate[required]"?
Hi..suresh.
My browser is unable to find the validationEngine() method and showing the error.Please tell me how i can find this method.
how to use on master page i check all above ie like form id and all but is not working
thanks
thanku sir u r doing a good job for fresher....
ur code is properly executed...can u tell me if we want only character value aloow within textbox
Advance Thanks
Thanku Suresh:-) ??
Hi Suresh, this validation is not working in Responsive html ....:( plz help me
how can i change the position of validation popup box?
Sir This is not working For Master page And i given table inside the Form its showing error
Its error Showing like "A page can have only one server-side Form tag." how can i solve this please help me"
my mail id
yogeeshsp@gmail.com
I have a login form on my master page and another one is on content page. I mention the form tag on master page . but when I run my project , the login form of master page also effects by clicking the button on content page. I tried but not solved. What I need to do..?
how can i compare two password textbox using this equals format? ??
I have used this code it can be work. but it cant be work in pages which have master page. Any one know how to used it in pages which have master page?
Hi Suresh. Well done.
Code is working Great.
I m using your jQuery validation in my web application.
i've two dropdown list. One is for min and second is for max.
first dropdown list's value should be less than the value of second
dropdown list. Can you write code it?
Please Sir delete first and second index in country drop down list...
Sir I m using Master-Content page simple reg. form with gridview edit delete button and its working fine when clicking on submit button, but clicking on delete button its again asking for validations.
Please help me out. I m googling for solutions from 2-3 days cause i liked this kind of validations.
I have used this code it can be work. but it cant be work in pages which have master page. Any one know how to used it in pages which have master page?
Please help me..... please
Hi
Awesome article
How can i pass regex or min,max(datatype range) values from css class.
like: class="Validate[some regex here]"
class=Validate[min,max]
Hi Suresh,
I am using choosen.js for dropdown and thus facing the validation issue.
Also validation is not working for checkboxlist.
Please suggest me how to validate the above mentioned two of the controls.
Looking for your earliest response.
hello sir,
How to Use It In Content Page without Form Tag
its very useful ...............
Thanks Bro its Working...............
Thanks Suresh...I am exactly looking for it...But when I use jquery-2.1.3 instead of jquery-1.6 its not work...
Hi suresh, Your articles are really worth,
Have big query in when we are using master page so id of control of content page would be something like "ContentPlaceHolder1_txtfnm" so validation is based on id of control and is gonna check the id which is only txtfnm so my question is how to fix or how validation checks the id=ContentPlaceHolder1_txtfnm,
Let me clear you that i have server controls used in master page as well so form tag is required at master page only....
Thanks in advance | https://www.aspdotnet-suresh.com/2012/01/jquery-beautiful-popup-form-validations.html | CC-MAIN-2019-22 | refinedweb | 3,110 | 74.39 |
PySpark - SparkContext
SparkContext is the entry point to any spark functionality. When we run any Spark application, a driver program starts, which has the main function and your SparkContext gets initiated here. The driver program then runs the operations inside the executors on worker nodes.
SparkContext uses Py4J to launch a JVM and creates a JavaSparkContext. By default, PySpark has SparkContext available as ‘sc’, so creating a new SparkContext won't work.
The following code block has the details of a PySpark class and the parameters, which'> )
Parameters
Following are the parameters of a SparkContext.
Master − It is the URL of the cluster it connects to.
appName − Name of your job.
sparkHome − Spark installation directory.
pyFiles − The .zip or .py files to send to the cluster and add to the PYTHONPATH.
Environment − Worker nodes environment variables.
batchSize − The number of Python objects represented as a single Java object. Set 1 to disable batching, 0 to automatically choose the batch size based on object sizes, or -1 to use an unlimited batch size.
Serializer − RDD serializer.
Conf − An object of L{SparkConf} to set all the Spark properties.
Gateway − Use an existing gateway and JVM, otherwise initializing a new JVM.
JSC − The JavaSparkContext instance.
profiler_cls − A class of custom Profiler used to do profiling (the default is pyspark.profiler.BasicProfiler).
Among the above parameters, master and appname are mostly used. The first two lines of any PySpark program looks as shown below −
from pyspark import SparkContext sc = SparkContext("local", "First App")
SparkContext Example – PySpark Shell
Now that you know enough about SparkContext, let us run a simple example on PySpark shell. In this example, we will be counting the number of lines with character 'a' or 'b' in the README.md file. So, let us say if there are 5 lines in a file and 3 lines have the character 'a', then the output will be → Line with a: 3. Same will be done for character ‘b’.
Note − We are not creating any SparkContext object in the following example because by default, Spark automatically creates the SparkContext object named sc, when PySpark shell starts. In case you try to create another SparkContext object, you will get the following error – "ValueError: Cannot run multiple SparkContexts at once".
<<< logFile = "" <<< logData = sc.textFile(logFile).cache() <<< numAs = logData.filter(lambda s: 'a' in s).count() <<< numBs = logData.filter(lambda s: 'b' in s).count() <<< print "Lines with a: %i, lines with b: %i" % (numAs, numBs) Lines with a: 62, lines with b: 30
SparkContext Example - Python Program
Let us run the same example using a Python program. Create a Python file called firstapp.py and enter the following code in that file.
----------------------------------------firstapp.py--------------------------------------- from pyspark import SparkContext logFile = "" sc = SparkContext("local", "first app") logData = sc.textFile(logFile).cache() numAs = logData.filter(lambda s: 'a' in s).count() numBs = logData.filter(lambda s: 'b' in s).count() print "Lines with a: %i, lines with b: %i" % (numAs, numBs) ----------------------------------------firstapp.py---------------------------------------
Then we will execute the following command in the terminal to run this Python file. We will get the same output as above.
$SPARK_HOME/bin/spark-submit firstapp.py Output: Lines with a: 62, lines with b: 30 | https://www.tutorialspoint.com/pyspark/pyspark_sparkcontext.htm | CC-MAIN-2019-04 | refinedweb | 533 | 59.4 |
IRC log of xproc on 2007-01-11
Timestamps are in UTC.
15:28:37 [RRSAgent]
RRSAgent has joined #xproc
15:28:37 [RRSAgent]
logging to
15:48:41 [rlopes]
rlopes has joined #xproc
15:56:19 [PGrosso]
PGrosso has joined #xproc
15:57:41 [Alessandro]
Alessandro has joined #xproc
15:58:25 [ht]
Meeting: XProc telcon
15:58:32 [ht]
Chair: Henry S. Thompson (pro tem)
15:58:43 [ht]
Scribe: Henry S. Thompson
15:58:48 [ht]
ScribeNick: ht
15:59:02 [ht]
Agenda:
15:59:27 [ht]
zakim, please call ht-781
15:59:27 [Zakim]
ok, ht; the call is being made
15:59:28 [Zakim]
XML_PMWG()11:00AM has now started
15:59:28 [Zakim]
+Ht
15:59:47 [Zakim]
+??P24
15:59:48 [Zakim]
-??P24
15:59:49 [Zakim]
+??P24
16:00:28 [richard]
richard has joined #xproc
16:00:35 [Zakim]
-??P24
16:00:37 [Zakim]
+[ArborText]
16:00:38 [Zakim]
+Alessandro_Vernet
16:00:39 [Zakim]
-Alessandro_Vernet
16:00:41 [Zakim]
+Alessandro_Vernet
16:00:56 [Zakim]
+??P24
16:00:58 [richard]
zakim, ? is richard
16:00:58 [Zakim]
+richard; got it
16:01:39 [Zakim]
+??P26
16:01:48 [rlopes]
Zakim, ?? is me
16:01:48 [Zakim]
+rlopes; got it
16:01:59 [AndrewF]
AndrewF has joined #xproc
16:02:48 [Zakim]
+??P22
16:02:51 [AndrewF]
zakim, ? is AndrewF
16:03:04 [Zakim]
+AndrewF; got it
16:03:16 [Zakim]
+MoZ
16:04:36 [ht]
16:04:40 [MoZ]
MoZ has changed the topic to:
16:05:08 [ht]
HST: We will take 2.2 ahead of 2.1
16:05:28 [ht]
HST: Regrets from NDW
16:05:39 [ht]
16:05:52 [ht]
HST: Last week's minutes. . .
16:06:11 [ht]
... Approved.
16:06:22 [ht]
HST: Next meeting: 18 January
16:06:44 [ht]
... Regrets from Paul Grosso, Norm Walsh and Richard Tobin
16:07:28 [ht]
... Probably regrets from Mohammed
16:07:40 [MoZ]
s/Mohammed/Mohamed/
16:08:19 [ht]
Topic: Components list
16:08:37 [ht]
16:08:48 [ht]
HST: The most recent draft
16:09:14 [ht]
... Micro-operations components
16:11:32 [ht]
... Consider 3.1 Rename
16:11:42 [ht]
RT: Can the 'name' parameter be an XPath as well?
16:12:10 [ht]
HST: Makes sense, but causes the 90% case to have to be quoted twice. . .
16:12:28 [ht]
RT: We could have two distinct parameters, one for constant and one for XPath
16:13:03 [ht]
select='foo' name='bar'
16:13:41 [ht]
RT: or //foo
16:13:47 [ht]
HST: Match or select?
16:14:25 [ht]
... I guess the argument for select is that otherwise you lose the full generality of XPath
16:15:15 [ht]
MZ: Description says attribute, element or pi -- how do you do pi?
16:15:29 [ht]
RT: select='processing-instruction(foo)'
16:16:24 [ht]
HST: Happy with the design of this one?
16:16:57 [ht]
RT: Make this have deletion functionality, or have a separate component?
16:17:18 [ht]
HST: Prefer a separate component
16:17:22 [ht]
MZ: Me too
16:18:04 [ht]
HST: I assume, for the record, that to rename an attribute you say:
16:18:21 [ht]
... select='//*/@foo' name='bar'
16:18:34 [ht]
... name = '@bar'
16:19:01 [ht]
s/name =/NOT name =/
16:19:25 [ht]
RT: There's an overall question about namespace bindings
16:19:48 [ht]
... I presume the XPath finds namespace bindings in the pipeline document
16:20:18 [ht]
... What about the name -- is it a QName and do the default namespace rules apply?
16:20:33 [ht]
HST: Yes it's a QName, and yes they apply
16:21:23 [ht]
RT: I'd say they _don't_ apply, because that would make the 90% case for renaming attributes a problem if there was a default namespace binding in effect
16:23:19 [ht]
AV: I think in XSLT where QNames are used, the default binding doesn't apply, for example in nameing functions
16:23:27 [ht]
... so we can and should do the same here
16:25:28 [ht]
HST: I'm sorry to lose strong typing -- this proposal would mean we can't use xs:QName
16:25:43 [ht]
... Perhaps we should add a namespace parameter
16:26:22 [ht]
RT: Or allow either a name parameter or both local-name and (optional namespace-name) parameters
16:26:29 [ht]
AV: Let's take this to the mailing list
16:27:13 [ht]
HST: OK, agreed -- we like this component, but need to settle this outstanding issue of default NS wrt the 'name' parameter
16:27:30 [ht]
HST: Moving on to 3.2, Wrap
16:28:08 [ht]
... wraps the document element
16:28:14 [ht]
RT: Doesn't seem to useful
16:28:33 [ht]
HST: Agree, I'd like to see a 'select' parameter here as well -- I use that version all the time
16:28:54 [ht]
... A similar operation in other pipeline languages?
16:29:51 [ht]
... What about a 'select' parameter?
16:30:12 [ht]
RT: Yes, but what about recursive operation?
16:30:36 [ht]
HST: Yes, because you can defeat that with a more specialised XPath
16:31:40 [ht]
... although it's not easy to do
16:31:57 [ht]
RT: Yes it is, just write //foo[not(ancestor::foo)]
16:32:16 [ht]
HST: Same issue wrt what the 'name' parameter is arises
16:32:35 [ht]
... should be probably be settled in the same way
16:33:12 [ht]
HST: One more thing to consider -- a 'groupBy' attribute name or XPath parameter
16:34:14 [ht]
... select='//foo' name='bar' groupBy='@fam'
16:34:40 [ht]
... then input of <foo fam='1'/><foo fame='1'/><foo fam='2'/>
16:34:48 [ht]
would give two bars, not three
16:34:58 [ht]
s/fame/fam/
16:35:38 [ht]
RT: What about intervening elements, text, whitespace
16:35:51 [ht]
... and what about matching text?
16:36:02 [ht]
HST: I say it can match text, which I find very useful
16:36:19 [ht]
... select='//foo/text()' name='bar'
16:36:34 [ht]
... turns <foo>text</foo> into <foo><bar>text</bar></foo>
16:37:18 [ht]
RT: That (text) seems reasonable, but the groupBy would need to be carefully specified wrt what's allowed in between
16:37:31 [ht]
... what about comments, etc.
16:37:56 [ht]
HST: Agreed, more care on that front is needed, and email is the right place to do that
16:38:27 [ht]
... I think I here consensus that we want this, but definitely _with_ a select attribute added
16:38:39 [ht]
s/here consensus/hear consensus/
16:39:15 [ht]
RT: What about 'Unwrap' ?
16:39:37 [ht]
HST: Right, we've had suggestions to add Delete and Unwrap operations, we should come to those
16:40:42 [ht]
HST: 3.3 Insert, which takes a whole document and plugs it in just under the document element
16:41:09 [ht]
... typo, should say that it takes the document from the 'insertion' port . . .
16:42:30 [ht]
... Again, I want an XPath to select the parent of the insertion
16:42:55 [ht]
... Useful e.g. for putting a doc inside a soap wrapper
16:43:17 [ht]
RT: That's not fully general, is it -- you can't get it between arbitrary siblings that way
16:43:38 [Alessandro]
16:43:46 [ht]
AV: XForms have an 'insert' action, that we should look at to get an idea, perhaps
16:44:03 [ht]
... Perhaps the different attributes they have would help
16:45:05 [ht]
HST: Seems to be consensus to have this, with some extensions, at least a 'select' XPath, and probably some more articulation in the area of 'at-start' to get full(er) control of where the insertion happens under the selected parent
16:45:44 [ht]
HST: Looking at the final one, 3.4 set-attributes
16:46:07 [ht]
RT: I _think_ this just copies attributes from doc elt to doc elt
16:47:10 [ht]
RT: Going back to the Insert one, what about multiple matches?
16:47:38 [ht]
HST: Yes, needs to be decided -- my version says "first match" is where the insertion happens, multiple (or none) are not an error
16:47:51 [ht]
... But we should resolve this after email discussion as well
16:50:03 [ht]
HST: Back to set-attributes -- it's more like copy-attributes, and needs _two_ XPaths, I think -- this suggests Insert could be generalised to CopyChildren with another XPath selecting what to copy in the Insertion document
16:50:41 [ht]
RT: We could combine the two and have a Copy component -- use .../* or .../@* to copy/insert children or attributes respectively
16:51:22 [ht]
HST: I'd like the SOAP insertion case to continue to be simple, but I think that could be accomplished with some sensible defaults
16:52:15 [ht]
... For instance, if both XPaths default to '/', you get Alex's original Insert, and if you default the first and use '/*/@*' you get his set-attributes. . .
16:53:10 [ht]
... Sounds to me like these two both need some more thought, but there's definitely _somethign_ here we want.
16:53:45 [ht]
HST: Can we sketch the two additions we've suggested: Delete and Unwrap
16:54:17 [ht]
... Seems to me Delete just needs a 'select' XPath -- any tricky problems?
16:54:49 [ht]
... Recursion isn't an issue, because you delete the whole matching subtree. . .
16:55:25 [ht]
HST: Unwrap is very similar, but only matching elements makes sense
16:55:55 [ht]
... It's an error to match the doc. elt if it has more than one child or text children, etc.
16:57:35 [Zakim]
-PGrosso
16:57:36 [Zakim]
-rlopes
16:57:36 [Zakim]
-richard
16:57:38 [Zakim]
-Ht
16:57:39 [Zakim]
-AndrewF
16:57:40 [Zakim]
-Alessandro_Vernet
16:57:41 [Zakim]
XML_PMWG()11:00AM has ended
16:57:42 [Zakim]
Attendees were Ht, Alessandro_Vernet, PGrosso, richard, rlopes, AndrewF, MoZ
16:57:52 [AndrewF]
quit
16:58:47 [ht]
HST: We _will_ turn to the question of choose/when next week, but I think the best thing to do is go ahead and officially engage with the defaulting issue at this point, so we can take advantage of the useful thread on this topic which started in December
16:59:08 [ht]
... Please pick up this topic in email and get some discussion started before next time
16:59:13 [ht]
... Adjourned
16:59:21 [ht]
zakim, bye
16:59:21 [Zakim]
Zakim has left #xproc
16:59:30 [ht]
RRSAgent, make logs world-visible
16:59:36 [ht]
RRSAgent, draft minutes
16:59:36 [RRSAgent]
I have made the request to generate
ht
17:03:01 [PGrosso]
PGrosso has left #xproc | http://www.w3.org/2007/01/11-xproc-irc | CC-MAIN-2014-52 | refinedweb | 1,846 | 67.79 |
i have completed the circuit but it still not running ? find the images.
1) To spin the motor on breadboard circuit, does adruino uno really required, without adruino uno is it possible to complete circuit on breadboard using atmega?
2) is it necessary to use 2 battery for the circuit on breadboard to spin motor using atmega? in the rc mini helicopter the circuit contains only 1 rechargable battery, so why the circuit on breadboard require 2 battery and require adruino uno ?
here is the code for microcontroller atmega32
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
DDRC = 0x0F;
while(1)
{
PORTC = 0b00000101;
_delay_ms(100);
PORTC = 0b00001010;
Can anyone send me the images of circuit connections for l293d with atmega32 without adruino on breadboard ?
i am not using adruino in the connections to drive motors.
i have created the simple circuit using breadboard to blink led every 5 sec using microcontroller.
it works well and the led flashes out for 5 sec.
i want to use motor in the circuit.
but if i place the motor in place of led,the motor does not spin.
is the enough current not passing from microcontroller to motor or i have to use additional components like transistor/mosfets etc.
however if i connect the motor to 1.5 v cell battery separately,it spins well.
Can you help me what could be the reason the motor is not spinning ? | http://letsmakerobots.com/user/18815/pages/all | CC-MAIN-2014-49 | refinedweb | 239 | 66.33 |
propdb 0.1.2
Property Bag Style Database
Description
The propbd package is a simple database module.; therefore, the property item values must be able to be seriailized by the json module.
Property bag name and location form the path where the bag is saved. If no location is set then the current working directory is used.).
Installation
pip install propdb
Basic Usage
from propdb import propbag as bag from propdb import propbag as item bag1 = bag('bag1', autosave = True) import propbag from propdb import propitem
Create a new property bag
propbag('name', 'location', autosave = True).
# adds a property item with the value set to None propbag.add('item1') # by list of name/value pairs propbag.add(('item1', 1, 'item2', 2, ...)) # by dictionary propbag.add({'item1':1, 'item2':2, ...}) # by list or propitems propbag.add((propitem, propitem, ...)) # by propitem propbag.add(propitem)
Adding property items with the + and += operators can be done in the same exact way as the add method (e.g. propbag + propitem, etc). The only difference is that there is no return value when adding by operator.
For example:
propbag + 'item1' propbag += (.
# by list of name/value pairs propbag.set(('item1', 1, 'item2', 2, ...)) # by dictionary propbag.set({'item1':1, 'item2':2, ...}) # by list or propitems propbag.set((propitem, propitem, ...)) # by propitem propbag.set(propitem)
Updating property items with the [] operator can be done by indexing the property bag with the name of the property item and passing in a new value or a property item.
For example:
propbag['item1'] = value propbag. ('item1', propitem)).
# drops one property by name propbag.drop('item1') # drops one property item by name propbag.drop(propitem) # by list of names propbag.drop(('item1', 'item2', 'item3', ...)) # by list of propitems propbag.drop((propitem, propitem, ...))
Dropping property items with the - and -= operators can be done in the same exact way as the drop method (e.g. propbag - propitem, etc). The only difference is that there is no return value when dropping by operator.
For example:
propbag - 'item1' # drops one property item by name propbag -= ('item1', 'item2', 'item3', ...) # via list of names
- Downloads (All Versions):
- 12 downloads in the last day
- 136 downloads in the last week
- 592 downloads in the last month
- Author: Dax Wilson
- License: GNU-GPL
- Package Index Owner: daxwilson
- DOAP record: propdb-0.1.2.xml | https://pypi.python.org/pypi/propdb/0.1.2 | CC-MAIN-2014-15 | refinedweb | 385 | 60.61 |
Comparing Interfaces and Abstract Classes
When you create an interface, you are creating a set of one or more method definitions that you must write in each class that implements that interface. There is no default method code generated: you must include it yourself. The advantage of interfaces is that they provide a way for a class to appear to be part of two classes: one inheritance hierarchy and one from the interface. If you leave an interface method out of a class that is supposed to implement that interface, the compiler will generate an error.
When you create an abstract class, you are creating a base class that might have one or more complete, working methods, but at least one that is left unimplemented, and declared abstract. You can't instantiate an abstract class, but must derive classes from it that do contain implementations of the abstract methods. If all the methods of an abstract class are unimplemented in the base class, it is essentially the same as an interface, but with the restriction that you can't make a class inherit from it as well as from another class hierarchy as you could with an interface. The purpose of abstract classes is to provide a base class definition for how a
set of derived classes will work, and then allow the programmer to fill these implementations in differently in the various derived classes.
Another related approach is to create base classes with empty methods. These guarantee that all the derived classes will compile, but that the default action for each event is to do nothing at all. Here is a Shape class like that:
public class NullShape {
protected int height, width;
protected int xpos, ypos;
protected Pen bPen;
//-----
public Shape(int x, int y, int h, int w) {
width = w;
height = h;
xpos = x;
ypos = y;
bPen = new Pen(Color.Black );
}
public void draw(Graphics g){}
public virtual float getArea() {
return height * width;
Note that the draw method is now an empty method. Derived classes will compile without error, but they won't do anything much. And there will be no hint what method you are supposed to override, as you would get from using an abstract class.
Shashi Ray
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/kb/385-comparing-interfaces-and-abstract-classes.aspx | CC-MAIN-2017-39 | refinedweb | 387 | 54.26 |
rrt-core:
rrt-play:
rrt-plugin:
Currently in release process: 2.2.1
artie] rest-refactoring-test (rrt)[DEPRECATED | replacement
Often you have to refactor or fix REST services which are not covered by extensive automated test and are hard to test at all. But you want to make sure that these services haven't changed their behaviour after you have done your changes.
This library gives you the tools to test your services fast and simple. You only describe the data you need and how the request is built and let the library do the work. See this small example:
import com.github.pheymann.rrt._ // GET /rest/hello/:name?age: Int val config = newConfig("my-test", ServiceConfig("refactored-rest.com", 8080), ServiceConfig("old-rest.com", 8081)) .withRepetitions(100) .withIgnoreJsonKeys(List("service-tracking-id")) val testCase = for { userNames <- genStaticData("Luke", "Anakin", "Yoda") ages <- genInts(Some(900)) result <- testGet { _ => // selects randomly one name out of the static list val uri = s"/rest/hello/${userNames()}" // adds a query parameter `age` with a random `Int` between 0 and 900 val params = Params().add("age", ages) uri |+| params } } yield result assert(checkAndLog(testCase.runSeq(config)))
Output:
[GET] start my-test [####################] 100% test case my-test succeeded succeeded tries: 100 failed tries 0
Here, we create a test for a GET endpoint
/rest/hello/:name which is currently provided by the refactored REST service on
refactored-rest.com and the old version on
old-rest.com. The library will create a request with random
name and
age and send it to both services. It will then remove the
"service-tracing-id" key with value from the response Json and compare the responses and log possible differences. This step is repeated 100 times as configured.
Besides the random generation or selection of values you are also able to load data from a database, e.g. if you need existing user ids.
For more information have a look into the Wiki.
Get The LibrariesGet The Libraries
You can get the core library by adding the following dependency:
libraryDependencies += "com.github.pheymann" %% "rrt-core" % "2.1.x" % Test
Furthermore you can add a Play dependency which adds the ability to read Play database configs.
libraryDependencies += "com.github.pheymann" %% "rrt-play" % "2.1.x" % Test
Both libs are built for Scala 2.11.x.
SBT PluginSBT Plugin
If you want to have a
rrt task and don't want to manually define all modules you need you can use the SBT plugin. It is built for SBT version 0.13.x and can be used by adding the following line to your
plugins.sbt file:
addSbtPlugin("com.github.pheymann" % "rrt-plugin" % "2.1.x")
With that you can add the dependencies as follows:
import com.github.pheymann.rrt.plugin._ libraryDependencies ++= Seq( rrtCore % RestRefactoringTest, rrtPlay % RestRefactoringTest )
And run your refactoring tests with the following task:
rrt:test. As this task extends
Test you also have access to all sub-tasks.
DependeciesDependecies
This library is build with:
- Free Mondas provided by cats to build the library api
- the http client by akka-http for the REST calls
- the db api from scalike-jdbc for the database interactions
ExamplesExamples
In this early phase you can only find some running examples in the integration tests. You can also have a look into the Wiki. | https://index.scala-lang.org/pheymann/rest-refactoring-test/rrt-core/0.2.0-RC?target=_2.11 | CC-MAIN-2020-05 | refinedweb | 554 | 57.37 |
A lan-wide EventEmitter2 implementation supporting complete decentralization, auto-discovery and request-response emulation.
littlehook is a lan-wide, distributed EventEmitter2 implementation supporting complete decentralization, auto-discovery & request-response emulation, powered by MDNS.
Inspired by Hook.io and Tinyhook, littlehook provides lightweight, namespaced and fully-decentralized eventing in a "pure p2p" fashion. Littlehook is a distributed implementation of EventEmitter2.
Each hook uses MDNS in a store-sub fashion to discover its peers, monitor their subscriptions and publish his own subscriptions. NsSocket and EventEmitter2 are used to push events to the appropriate listener hooks. Each hook is free to fail without compromising the rest of its peers or the network (no meshes, no trees). Request-response emulation is provided.
Pre-alpha and don't even think about using this in production - otherwise working pretty well.
This is an updated version of the original package, one of my very first coding experiments with Node.js. I decided to clean it up a bit, improve it in some areas and put it back online after the original, unmaintained version that I thought I had removed long ago from both NPM and GitHub surprisingly sparked some interest around Jan 2013.
At the moment, I'm not maintaining and/or improving this package. Should it keep gathering attention, though, I'll think about a serious makeover.
I've updated the module as requested.
EHOSTUNREACHerror
NSSocket
Seems to be working ok on MacOS X Yosemite 10.10.1 and an up-to-date Arch Linux. It often does not behave well with IPv6 - I suggest using IPv4.
When updating the module and/or switching to/from node, io.js and other npm-compatible engines, do the following:
$ npm cache clean$ cd /path/to/littlehook$ rm -rf node_modules$ npm install
Hook
var Hook = require('littlehook'); var a = new Hook({ name: 'a', port: 9999 }); var b = new Hook({ name: 'b', port: 9998 }); // Matches events of type 'event::type' sent by // any hook in the same MDNS area a.on(['*', 'event', 'type'], function(data) { console.log('data: ' + data); console.log('sender: ' + this.event[0]); }); // This does the same as the above w/ events // specified as strings instead of arrays a.on('*::event::type', function(data) { console.log('data: ' + data); console.log('sender: ' + this.event.split('::')[0]); }); // When hook 'a' comes online, emits event of // type 'event::type' - the resulting event will // be namespaced as 'b::event::type' b.on(['a', 'up'], function() { b.emit(['event', 'type'], { some: 'data' }); }); a.start(); b.start();
Each hook is an EventEmitter2 instance, see the relative API specs.
Events are namespaced as in Tinyhook and Hook.io.
var hook = new Hook({name: 'johnny', port: 9999}); hook.emit('hello'); // Event emitted: ['johnny', 'hello']
The delimiter used is always '::' (see EventEmitter2's specs):
'hookName::event::type' <-> ['hookName', 'event', 'type']
Each hook emits the following events:
['hookName', 'up'] -> Hook 'hookName' came up ['hookName', 'down'] -> Hook 'hookName' went down ['hookName', 'update'] -> Hook 'hookName' updated its subscriptions
$ npm test | https://www.npmjs.com/package/littlehook | CC-MAIN-2015-27 | refinedweb | 490 | 57.98 |
我们知道,Linux每个文件的详细属性都存储在一个stat结构中,可以用stat命令查看文件的详细属性,例如文件大小,修改时间,所属用户,文件权限等。 */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ };
在stat结构中,st_mode字段表示了文件的模式相关属性。下图是关于该字段的详细描述,可以发现st_mode通过一个8进制数字存储文件模式:
- 后三位分布表示了文件读、写、执行的权限以及文件的掩码mask信息
- 第4位表示文件的粘着位,设置用户组编号,设置用户编号信息
- 其他位表示了文件的类型信息(管道,设备,文件夹,普通文件等)
下面一段代码将对setuid的使用作出简单说明。父进程通过fork创建一个子进程,然后父进程和子进程将分别打印设置用户ID,最后父进程将会尝试创建一个新的文件。
#include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char *argv[]) { int fd; pid_t pid; if ((pid = fork()) < 0) { fprintf(stderr, "fork error\n"); exit(1); } else if (pid == 0) { printf("child real user id: %d\n", getuid()); printf("child effective user id: %d\n", geteuid()); } else { sleep(1); printf("parrent real user id: %d\n", getuid()); printf("parrent effective user id: %d\n", geteuid()); exit(0); } if ((fd = open(argv[1], O_CREAT | O_RDWR)) < 0) { fprintf(stderr, "open error\n"); fprintf(stderr, "error: %s\n", strerror(errno)); } close(fd); return 0; }
编译并执行程序,结果如下:
roo@roose:~$ ls -l a.out -rwxrwxr-x 1 roo roo 9174 Jan 29 17:17 a.out* roo@roose:~$ ./a.out /usr/local/testfile child real user id: 1000 child effective user id: 1000 parrent real user id: 1000 parrent effective user id: 1000 open error error: Permission denied
根据打印的信息,可以发现
- 父进程和子进程的实际用户ID和有效用户ID都是1000,即为普通用户
- 尝试创建文件/usr/local/testfile时,程序提示权限错误,说明执行用户权限为普通用户
下面修改a.out的属性,设置文件拥有者为root用户,添加setuid
roo@roose:$ sudo chown root:root a.out roo@roose:$ sudo chmod 4775 a.out roo@roose:$ ls -l a.out -rwsrwxr-x 1 root root 9174 Jan 29 17:17 a.out
然后重新执行程序
roo@roose:~$ ./a.out /usr/local/testfile child real user id: 1000 child effective user id: 0 parrent real user id: 1000 parrent effective user id: 0
根据打印的信息,可以发现:
- 进程的实际用户编号(uid)为执行用户的用户编号1000,即为普通用户
- 进程的有效用户编号(euid)是文件所属用户的用户编号0,即为root用户
- 子进程也集成了父进程的实际用户编号和有效用户编号
- 父进程成功创建了/usr/local/testfile文件,说明程序是以root权限执行的
尝试执行设置了setuid的shell脚本,创建脚本文件test.sh内容如下:
#!/bin/bash sleep 10 touch /usr/local/testfile
roo@roose:~$ sudo chown root:root test.sh roo@roose:~$ sudo chmod 4775 test.sh roo@roose:~$ ./test.sh & [1] 54280 roo@roose:~$ ps -eo uid,euid,command | grep test.sh 1000 1000 /bin/bash ./test.sh 1000 1000 grep --color=auto test.sh roo@roose:~$ touch: cannot touch ‘/usr/local/testfile’: Permission denied
同样对test.sh赋予相关权限并执行,结果却和上面C生成的可执行文件不太一样:
- 程序的实际用户编号(uid)和有效用户编号(euid)都是1000,即为普通用户;
- 程序也没有权限创建/usr/local/testfile,即添加的设置用户编号没有效果。
为什么已经设置了setuid却没有效果呢?通过查找相关资料,发现出现该问题的原因是:
出于安全问题,Linux会忽略任何编译器文件的设置用户位。
详细说明如下(博主太懒,有空再翻译)
Linux ignores the setuid¹ bit on all interpreted executables (i.e. executables starting with a #! line). The comp.unix.questions FAQ explains the security problems with setuid shell scripts. These problems are of two kinds: shebang-related and shell-related; I go into more details below.If you don't care about security and want to allow setuid scripts, under Linux, you'll need to patch the kernel. As of 3.x kernels, I think you need to add a call to install_exec_creds in the load_script function, before the call to open_exec, but I haven't tested.
Setuid shebang
There is a race condition inherent to the way shebang (#!) is typically implemented:
The kernel opens the executable, and finds that it starts with #!.
The kernel closes the executable and opens the interpreter instead.
The kernel inserts the path to the script to the argument list (as argv[1]), and executes the interpreter..
One way to secure this implementation would be for the kernel to lock the script file until the interpreter has opened it (note that this must prevent not only unlinking or overwriting the file, but also renaming any directory in the path). But unix systems tend to shy away from mandatory locks, and symbolic links would make a correct lock feature especially difficult and invasive. I don't think anyone does it this way.
A few unix systems (mainly OpenBSD, NetBSD and Mac OS X, all of which require a kernel setting to be enabled) implement secure setuid shebang using an additional feature: the path /dev/fd/N refers to the file already opened on file descriptor N (so opening /dev/fd/N is roughly equivalent to dup(N)). Many unix systems (including Linux) have /dev/fd but not setuid scripts.
The kernel opens the executable, and finds that it starts with #!. Let's say the file descriptor for the executable is 3.
The kernel opens the interpreter.
The kernel inserts /dev/fd/3 the argument list (as argv[1]), and executes the interpreter.
Sven Mascheck's shebang page has a lot of information on shebang across unices, including setuid support.
Setuid interpretersLet's assume you've managed to make your program run as root, either because your OS supports setuid shebang or because you've used a native binary wrapper (such as sudo). Have you opened a security hole? Maybe. The issue here is not about interpreted vs compiled programs. The issue is whether your runtime system behaves safely if executed with privileges.
Any dynamically linked native binary executable is in a way interpreted by the dynamic loader (e.g. /lib/ld.so), which loads the dynamic libraries required by the program. On many unices, you can configure the search path for dynamic libraries through the environment (LD_LIBRARY_PATH is a common name for the environment variable), and even load additional libraries into all executed binaries (LD_PRELOAD). The invoker of the program can execute arbitrary code in that program's context by placing a specially-crafted libc.so in $LD_LIBRARY_PATH (amongst other tactics). All sane systems ignore the LD_* variables in setuid executables.
In shells such as sh, csh and derivatives, environment variables automatically become shell parameters. Through parameters such as PATH, IFS, and many more, the invoker of the script has many opportunities to execute arbitrary code in the shell scripts's context. Some shells set these variables to sane defaults if they detect that the script has been invoked with privileges, but I don't know that there is any particular implementation that I would trust.
Most runtime environments (whether native, bytecode or interpreted) have similar features. Few take special precautions in setuid executables, though the ones that run native code often don't do anything fancier than dynamic linking (which does take precautions).
Perl is a notable exception. It explicitly supports setuid scripts in a secure way. In fact, your script can run setuid even if your OS ignored the setuid bit on scripts. This is because perl ships with a setuid root helper that performs the necessary checks and reinvokes the interpreter on the desired scripts with the desired privileges. This is explained in the perlsec manual. It used to be that setuid perl scripts needed #!/usr/bin/suidperl -wT instead of #!/usr/bin/perl -wT, but on most modern systems, #!/usr/bin/perl -wT is sufficient.
Note that using a native binary wrapper does nothing in itself to prevent these problems. In fact, it can make the situation worse, because it might prevent your runtime environment from detecting that it is invoked with privileges and bypassing its runtime configurability.
A native binary wrapper can make a shell script safe if the wrapper sanitizes the environment. The script must take care not to make too many assumptions (e.g. about the current directory) but this goes. You can use sudo for this provided that it's set up to sanitize the environment. Blacklisting variables is error-prone, so always whitelist. With sudo, make sure that the env_reset option is turned on, that setenv is off, and that env_file and env_keep only contain innocuous variables.
TL,DR:
Setuid shebang is insecure but usually ignored.
If you run a program with privileges (either through sudo or setuid), write native code or perl, or start the program with a wrapper that sanitizes the environment (such as sudo with the env_reset option). | https://my.oschina.net/u/1049845/blog/611490 | CC-MAIN-2018-47 | refinedweb | 1,274 | 56.86 |
AWS CDK package that empties an S3 bucket upon resource deletion.
Project description
AWS Empty Bucket
A custom S3 bucket with an ability to completely delete itself (even if it contains files within). S3 (Amazon Web Services Simple Storage Service).
Assumptions
This library project assumes the following:
- You have knowledge in AWS (Amazon Web Services).
- You have knowledge in AWS CloudFormation and AWS S3.
- You are managing your infrastructure with AWS CDK.
- You are writing AWS CDK templates with a python language.
Install
The project is built and uploaded to PyPi. Install it by using pip.
pip install aws-empty-bucket
Or directly install it through source.
./build.sh -ic
Description
Natively S3 buckets can not be deleted if they contain files. If you were to delete a bucket through CloudFormation, you would get a similar error message:
The bucket you tried to delete is not empty (Service: Amazon S3; Status Code: 409; Error Code: BucketNotEmpty; Request ID: <some-id>; S3 Extended Request ID: <some-other-id>)
This gets especially annoying if a developer is spinning up and tearing down the infrastructure many times a day. Wouldn't it be awesome if S3 buckets could just be simply deleted in any case?
With this project you can create S3 buckets that can be deleted even if they
contain filed inside. A project exposes a class
EmptyS3Bucket which can
be used exactly the same as a class
Bucket provided by AWS CDK. Next time
you delete your stack, you will not see that error message again.
Examples
To create an S3 Bucket that can be easily deleted create an
EmptyS3Bucket
instance in your stack. An example is given below:
from aws_cdk import core, aws_s3 from aws_empty_bucket.empty_s3_bucket import EmptyS3Bucket class MainStack(core.Stack): def __init__(self, scope: core.App) -> None: super().__init__( scope=scope, id='MyCoolStack' ) self.empty_bucket = EmptyS3Bucket( self, 'MyCoolBucketThatCanBeDeleted', access_control=aws_s3.BucketAccessControl.PRIVATE, bucket_name='mybucket', )
To delete inner S3 Bucket files, a custom resource with a lambda function as
as a backend is created too.
EmptyS3Bucket exposes two properties:
backend and
custom_resource. If you need to access them use the following:
from aws_empty_bucket.empty_s3_bucket import EmptyS3Bucket empty_bucket = EmptyS3Bucket(...) function = empty_bucket.backend resource = empty_bucket.custom_resource
Release history
2.0.1
Do not use singleton lambdas since we are using roles for specific buckets.
2.0.0
Make a custom S3 bucket with inner-file deletion capabilities.
1.0.0
Initial project. Not tested. No extensive readme.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/aws-empty-bucket/2.0.1/ | CC-MAIN-2022-33 | refinedweb | 429 | 59.9 |
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
C++17 Filesystem
Although C++ is an old programming language, its Standard Library misses a few basic things. Features that Java or .NET had for years were/are not available in STL. With C++17 there’s a nice improvement: for example, we now have the standard filesystem!
Traversing a path, even recursively is so simple now!
Maybe I was a bit harsh in the first paragraph. Although the Standard Library lacks some important features, you could always use Boost with its thousands of sub-libraries and do the work. The C++ Committee and the Community decided that the Boost libraries are so important that some of the systems were merged into the Standard. For example smart pointers (although improved with the move semantics in C++11), regular expressions, and much more.
The similar story happened with the filesystem. Let’s try to understand what’s inside.
This playground is adapted from my blog: Bartek's coding blog: C++17 in details: Filesystem:
Filesystem Overview
I think the Committee made a right choice with this feature. The filesystem library is nothing new, as it's modeled directly over Boost filesystem, which is available since 2003 (with the version 1.30). There are only a little differences, plus some wording changes. Not to mention, all of this is also based on POSIX.
Thanks to this approach it's easy to port the code. Moreover, there's a good chance a lot of developers are already familiar with the library. (Hmmm... so why I am not that dev? :))
The library is located in the
<filesystem> header. It uses namespace
std::filesystem.
The final paper is P0218R0: Adopt the File System TS for C++17 but there are also others like P0317R1: Directory Entry Caching, PDF: P0430R2–File system library on non-POSIX-like operating systems, P0492R2... All in all, you can find the final spec in the C++17 draft: the "filesystem" section, 30.10.
We have three/four core parts:
- The
pathobject
directory_entry
- Directory iterators
- Plus many supportive functions
- getting information about the path
- files manipulation: copy, move, create, symlinks
- last write time
- permissions
- space/filesize
- ...
Compiler/Library support
Depending on the version of your compiler you might need to use
std::experimental::filesystem namespace.
- GCC: You have to specify
-lstdc++fswhen you want filesystem. Implemented in
<experimental/filesystem>.
- Clang should be ready with Clang 5.0
-
- Visual Studio: In VS 2017 (2017.2) you still have to use
std::experimentalnamespace, it uses TS implementation.
- See the reference link and also C++17 Features In Visual Studio 2017 Version 15.3 Preview.
- Hopefully by the end of the year VS 2017 will fully implement C++17 (and STL)
Examples
All the examples can be found on my Github: github.com/fenbf/articles/cpp17.
I've used Visual Studio 2017 Update 2.
Working with the Path object
The core part of the library is the
path object. Just pass it a string of the path, and then you have access to lots of useful functions.
For example, let's examine a path:
namespace fs = std::experimental:";
Here's an output for a file path like
"C:\Windows\system.ini":
exists() = 1 root_name() = C: root_path() = C:\ relative_path() = Windows\system.ini parent_path() = C:\Windows filename() = system.ini stem() = system extension() = .ini
What's great about the above code?
It's so simple to use! But there's more cool stuff:
For example, if you want to iterate over all the elements of the path just write:
int i = 0; for (const auto& part : pathToShow) cout << "path part: " << i++ << " = " << part << "\n";
The output:
path part: 0 = C: path part: 1 = \ path part: 2 = Windows path part: 3 = system.ini
We have several things here:
- the path object is implicitly convertible to
std::wstringor
std::string. So you can just pass a path object into any of the file stream functions.
- you can initialize it from a string, const char*, etc. Also, there's support for
string_view, so if you have that object around there's no need to convert it to
stringbefore passing to
path. PDF: WG21 P0392
pathhas
begin()and
end()(so it's a kind of a collection!) that allows iterating over every part.
What about composing a path?
We have two options: using append or operator
/=, or operator
+=.
- append - adds a path with a directory separator.
- concat - only adds the 'string' without any separator.
For example:
fs::path p1("C:\\temp"); p1 /= "user"; p1 /= "data"; cout << p1 << "\n"; fs::path p2("C:\\temp\\"); p2 += "user"; p2 += "data"; cout << p2 << "\n";
output:
C:\temp\user\data C:\temp\userdata
Play with the code:
What can we do more?
Let's find a file size (using
file_size):
uintmax_t ComputeFileSize(const fs::path& pathToCheck) { if (fs::exists(pathToCheck) && fs::is_regular_file(pathToCheck)) { auto err = std::error_code{}; auto filesize = fs::file_size(pathToCheck, err); if (filesize != static_cast<uintmax_t>(-1)) return filesize; } return static_cast<uintmax_t>(-1); }
Or, how to find the last modified time for a file:
auto timeEntry = fs::last_write_time(entry); time_t cftime = chrono::system_clock::to_time_t(timeEntry); cout << std::asctime(std::localtime(&cftime));
Isn't that nice? :)
As an additional information, most of the functions that work on a
path have two versions:
- One that throws:
filesystem_error
- Another with
error_code(system specific)
Let's now take a bit more advanced example: how to traverse the directory tree and show its contents?
Traversing a path
We can traverse a path using two available iterators:
directory_iterator
recursive_directory_iterator- iterates recursively, but the order of the visited files/dirs is unspecified, each directory entry is visited only once.
In both iterators the directories
. and
.. are skipped.
Ok... show me the code:
void DisplayDirTree(const fs::path& pathToShow, int level) { if (fs::exists(pathToShow) && fs::is_directory(pathToShow)) { auto lead = std::string(level * 3, ' '); for (const auto& entry : fs::directory_iterator(pathToShow)) { auto filename = entry.path().filename(); if (fs::is_directory(entry.status())) { cout << lead << "[+] " << filename << "\n"; DisplayDirTree(entry, level + 1); cout << "\n"; } else if (fs::is_regular_file(entry.status())) DisplayFileInfo(entry, lead, filename); else cout << lead << " [?]" << filename << "\n"; } } }
The above example uses not a recursive iterator but does the recursion on its own. This is because I'd like to present the files in a nice, tree style order.
We can also start with the root call:
void DisplayDirectoryTree(const fs::path& pathToShow) { DisplayDirectoryTree(pathToShow, 0); }
The core part is:
for (auto const & entry : fs::directory_iterator(pathToShow))
The code iterates over
entries, each entry contains a path object plus some additional data used during the iteration.
Not bad, right?
You can play with the sample here:
Of course there's more stuff you can do with the library:
- Create files, move, copy, etc.
- Work on symbolic links, hard links
- Check and set file flags
- Count disk space usage, stats
Today I wanted to give you a general glimpse over the library. As you can see there are more potential topics for the future.
More resources
You might want to read:
- Chapter 7, "Working with Files and Streams" - of Modern C++ Programming Cookbook.
- examples like: Working with filesystem paths, Creating, copying, and deleting files and directories, Removing content from a file, Checking the properties of an existing file or directory, searching.
- The whole Chapter 10 ""Filesystem" from "C++17 STL Cookbook"
- examples: path normalizer, Implementing a grep-like text search tool, Implementing an automatic file renamer, Implementing a disk usage counter, statistics about file types,Implementing a tool that reduces folder size by substituting duplicates with symlinks
- C++17- std::byte and std::filesystem - ModernesCpp.com
- How similar are Boost filesystem and the standard C++ filesystem libraries? - Stack Overflow
Summary
I think the filesystem library is an excellent part of the C++ Standard Library. A lot of time I had to use various API to do the same tasks on different platforms. Now, I'll be able to just use one API that will work for probably 99.9% cases.
The feature is based on Boost, so not only a lot of developers are familiar with the code/concepts, but also it's proven to work in many existing projects.
And look at my samples: isn't traversing a directory and working with paths so simple now? I am happy to see that everting can be achieved using
std:: prefix and not some strange API :)
Call To action
If you want to read more about C++17 just visit my blog and start reading :) | https://tech.io/playgrounds/5659/c17-filesystem | CC-MAIN-2018-17 | refinedweb | 1,418 | 55.24 |
This structure describes a single particle. More...
#include "ParticleEngineMS.hpp"
This structure describes a single particle.
Age of the particle, in seconds.
The list of all render materials possibly used with this particle.
Auxiliary particle data.
?? REMOVE (MatSys respects ambient light color already) ?? The RGBA color with which this particles texture is modulated.
Pointer to the function that moves this particle through time.
Origin of the particle in Cafu world coordinates.
Billboard radius in world coords.
The particles RenderMaterial ID.
Rotation angle of the billboard in the "screen plane". A value of 256 corresponds to 360 degrees.
Length of the Y-axis relative to the X-axis, e.g. for sparks, flashes etc.
Velocity vector of the particle. | https://api.cafu.de/c++/structParticleMST.html | CC-MAIN-2018-51 | refinedweb | 118 | 55.81 |
I saw that the data of this problem mentioned in Luogu was especially water, so I wrote a very water approach.
Title: P1078 [NOIP2012 popularization group] cultural tour - New Ecology of computer science education in Luogu (luogu.com.cn)
Topic background
This problem is wrong. It was later proved that there is no reliable practice of polynomial complexity. The test data is very watery, and various metaphysical practices can pass (such as reverse scanning), which does not mean that the algorithm is correct. Therefore, the title and data are for reference only.
Title Description
There is a messenger who wants to travel around countries. Every time he goes to a country, he can learn a culture, but he is unwilling to learn any culture more than once (that is, if he learns a culture, he can't reach other countries with this culture). Different countries may have the same culture. Countries with different cultures have different views on other cultures. Some cultures will exclude foreign cultures (that is, if he learns a certain culture, he cannot reach other countries that exclude this culture).
Given the geographical relationship between countries, the culture of each country, the views of each culture on other cultures, as well as the starting point and end point of the envoy's tour (local culture will also be learned at the starting point and end point), the road distance between countries, try to find out the minimum distance to go from the starting point to the end.
Input format
The first line is five integers N. K, m, s, TN, K, m, s, t are separated by a space between every two integers, representing the number of countries in turn (country numbers are 11 to NN), number of cultural species (Cultural number is 11 to KK), number of roads, and number of starting and ending points (guaranteed) SS Not equal to TT);
The second line is NN integers, and every two integers are separated by a space, where the second line is ii number C_iCi, indicating that the culture of country ii is C_iCi.
Next KK line, KK integers in each line, separated by a space between each two integers, record the second line The j-th number of rows is a_{ij}aij,a_{ij}= 1aij=1 Express culture ii exclusion of foreign cultures JJ (ii) When equal to JJ, it means to exclude outsiders of the same culture), a_{ij}= 0aij=0 Indicates no exclusion (note ii) exclude jj There is no guarantee that JJ will also exclude ii).
Next MM Rows, three integers per row u. V, Du, V, D, every two integers are separated by a space, indicating the country uu and country vv has a two-way road with a distance of dd (ensure that uu is not equal to vv, there may be multiple roads between two countries).
Output format
An integer representing the minimum distance that the messenger needs to travel from the starting country to the ending country (if there is no solution, output - 1 − 1).
Input and output samples
Enter #1
2 2 1 1 2 1 2 0 1 1 0 1 2 10
Output #1
-1
Enter #2
2 2 1 1 2 1 2 0 1 0 0 1 2 10
Output #2
10
Description / tips
Input / output example description 11
Because to the country twenty-two It must pass through country 11, while the civilization of country 22 excludes countries eleven Civilization, so it is impossible to reach the country 22.
Input / output example description 22
Route 11 -> twenty-two
[data range]
For 100% data, there are 2 ≤ N ≤ 1002 ≤ N ≤ 100
1≤K≤1001≤K≤100
1≤M≤N^21≤M≤N2
1≤k_i≤K1≤ki≤K
1≤u, v≤N1≤u,v≤N
1≤d≤1000,S≠T,1≤S,T≤N1≤d≤1000,S=T,1≤S,T≤N
Question 4 of NOIP 2012 popularization group
Solution: since the data is very watery, let's try explosive search:
Idea: for each node to go, judge whether there is a node in conflict with him or a node that has been to.
Because the size of each edge is greater than 1, it is obvious that the answer is definitely not the smallest if you walk around the ring.
Do not use a stack to store every node. Remember to backtrack.
code:
#include <bits/stdc++.h> using namespace std; struct node { int f,t,val,nex; }rt[10010]; int head[10010],cnt,vis[1010][1010],qaq[10010]; int be,ed,a,b,c,lo[10010]; int bec; void add(int x,int y,int z) { cnt ++; rt[cnt].f = x; rt[cnt].t = y; rt[cnt].val = z; rt[cnt].nex = head[x]; head[x] = cnt; } int sta[1010]; int ans = 0x3f3f3f3f; void dfs(int x,int num,int co) { if(clock() - bec > 999900) { if(ans == 0x3f3f3f3f) cout<<-1; else cout<<ans; exit(0); } if(x == ed){ ans = min(ans,co); } else { for(int i = head[x];i;i = rt[i].nex) { bool faq = 1; for(int j = 1;j <= num;j ++) { if(qaq[rt[i].t]) faq = 0; if(vis[lo[rt[i].t]][lo[sta[j]]] || lo[rt[i].t] == lo[sta[j]]) faq = 0; } if(faq) { qaq[rt[i].t] = 1; sta[num + 1] = rt[i].t; dfs(rt[i].t,num + 1,co + rt[i].val); qaq[rt[i].t] = 0; } } } } int main() { bec = clock(); cin>>a>>c>>b>>be>>ed; for(int i = 1;i <= a;i ++) { cin>>lo[i]; } int x,y; for(int i = 1;i <= c;i ++) { for(int j = 1;j <= c;j ++) { cin>>x; vis[i][j] = x; } } int z; for(int i = 1;i <= b;i ++) { cin>>x>>y>>z; add(x,y,z); add(y,x,z); } qaq[be] = 1; sta[1] = be; dfs(be,1,0); if(ans == 0x3f3f3f3f) cout<<-1; else cout<<ans; return 0; } /* 10 5 18 1 7 4 2 5 3 2 2 1 2 3 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 656 2 4 989 2 1 947 3 2 731 4 10 830 4 8 688 5 6 573 5 3 492 6 10 700 6 3 854 8 7 839 8 7 461 10 9 885 10 9 960 4 7 4 3 4 8 2 3 4 1 2 5 */
Because the complexity of explosive search is certainly unacceptable, you can output it when you want to timeout. Anyway, the data is very water. [doge][doge][doge]. | https://programmer.help/blogs/noip-2012-cultural-tour.html | CC-MAIN-2021-49 | refinedweb | 1,108 | 62.21 |
Ticket #2982 (closed Feature Requests: fixed)
Required Arguments
Description
If I have a list of 10 parameters, and all are required,
I end up with a giant block of these:
if(!vm.count("input"))
{
std::cout << "Input was not set." << std::endl; exit(-1);
}
It would be nice to do something like: desc.add_options()
("input", po::value<std::string>(&InputFile?)->required(), "Set input file.")
That will perform that check automatically.
Attachments
Change History
Changed 8 years ago by s.ochsenknecht@…
- Attachment patch_ticket2982.diff added
comment:1 Changed 8 years ago by s.ochsenknecht@…
I find it useful, so I added a patch which implements the required() flag as described. It throws an exception from parsing if a required option isn't present.
This is my test case:
#include <boost/program_options.hpp> #include <string> #include <iostream> using namespace boost::program_options; using namespace std; int main(int argc, char *argv[]) { options_description opts; opts.add_options() ("cfgfile,c", value<std::string>()->required(), "the configfile") ("fritz,f", value<std::string>()->default_value("/other/file"), "the output file") ; variables_map vm; try { store(parse_command_line(argc, argv, opts), vm); notify(vm); } catch (required_option& e) { // new exception type cout << "required option: " << e.what() << endl; return -1; } catch (...) { cout << "other exception: " << endl; return -1; } }
Does it make sense? Is it useful?
I'm not a Boost maintainer, so I won't change the state of this ticket :-).
Thanks
comment:3 Changed 8 years ago by vladimir_prus
Sascha, I am not sure if the location of the check is right. I'd suspect that user wants the option to be always specified, but does not necessary care where it comes from. Maybe, a check inside 'notify' would be better?
comment:4 Changed 8 years ago by s.ochsenknecht@…
I was also not very sure if this is right place. Since I'm still not very familiar with the internals of this library. I just cam to that place by tracing with the debugger ...
I'm going to check your proposal with 'notify' within the next days. Keep you informed. Thanks for reviewing.
comment:5 Changed 8 years ago by s.ochsenknecht@…
I just checked if it is possible to place the check in notify(), but there is one problem. The notify function just gets the variables_map parameter and not the options_description's which have the information about required options.
I have following solutions in mind:
1) in store() we store any required options with an empty value (if not occur) in the variables_map. In notify we then check for empty() and throw exception if empty() and required(). Any side effects? My preferred solution.
2) we pass options_description's to notify() to be able to perform the cross check, but this breaks the interface (or we overload notify, but then its up to the user to choose the correct notify() ... :-(
3) we store a reference/pointer to options_description's in variables_map. :-(
...
Please comment. Thanks
Changed 8 years ago by s.ochsenknecht@…
- Attachment patch_ticket2982_2.diff added
patch
Changed 8 years ago by s.ochsenknecht@…
- Attachment required.cpp added
testcase
comment:6 Changed 8 years ago by s.ochsenknecht@…
I implemented option (1), see patch_ticket2982_2.diff and the attached testcase required.cpp.
store() now adds empty variable_value's to the variable_map. I also override the count() method of the underlying std::map in that way that the empty variable_values are not counted.
Hm, this can have some side effects when operator[] is used: const variable_value& operator[](const std::string& name) const
But I think the user has to check for !empty() anyhow ..!?
comment:7 follow-up: ↓ 8 Changed 8 years ago by vladimir_prus
Sascha,
thanks for the patch. I am out of time for today, but will review it as soon as possible.
Thanks, Volodya
comment:8 in reply to: ↑ 7 Changed 8 years ago by Sascha Ochsenknecht <s.ochsenknecht@…>
Replying to vladimir_prus:
Sascha,
thanks for the patch. I am out of time for today, but will review it as soon as possible.
Probably storing the required options together with the parsed options in the same map isn't a good idea. Maybe a new member variable (in variables_map) containing the required options would be better. I'll modify the patch again within the next days.
Thanks, Sascha
comment:9 Changed 7 years ago by s_ochsenknecht
- Owner changed from vladimir_prus to s_ochsenknecht
- Status changed from new to assigned
- Milestone changed from Boost 1.39.0 to Boost 1.42.0
comment:10 Changed 7 years ago by s_ochsenknecht
- Status changed from assigned to closed
- Resolution set to fixed
comment:11 Changed 7 years ago by anonymous
I modified the attached patch in that way that required options are stored as an additional member in variables_map. The check if all required options occur is done in notify().
Cheers, Sascha
comment:12 Changed 9 months ago by ihorfg@…
How to use the required flag for arguments that could be set from both argument list and configuration file? Parsing command line in such a case throws an exception while the missing required arguments can exist in configuration file. | https://svn.boost.org/trac/boost/ticket/2982 | CC-MAIN-2017-22 | refinedweb | 840 | 67.25 |
UP2 board with Windows 10 ioT as replacement for Raspberry Pi 3 B
I intend to replace my Raspberry Pi 3B UWP-applications running on Win10 iot Core with your UP2 board.
Before I do this, I want to know if this will be possible without any problems.
I use the GPIO/I2C interface of the Raspberry Pi with C++ and C#. As interface to the hardware I use the following namespace Windows.Devices.Gpio, Windows.Devices.I2c, Windows.Devices.Pwm in my UWP apps
Does the board run stable under win10 iot in conjunction with the GPIO interface?
Can I use the GPIO interface of the board in the same way as if it were a Raspberry Pi or do I need to adapt my existing code?
What about the graphics support of the board under Win10 ioT Core?
Is the grafic features fully supported under win 10 iot.
Best regards
WIlli Schneider
Dear Wllli,
Graphics support and feature in IoT Core is nothing different to the rest of windows and we used the same driver in IoT Core and Windows 10.
Currently GPIO/PWM is not support windows API yet, so you need adapt your existing code a lot.
We've planned to support windows API in Up framework in the future.
Hi
Im currently looking into a new platform for our next generation controller.
I can read fromt his post that GPIO/PWM isnt supported when using the UP board with Windows 10 IoT!.
Is there any information what is supported and what isn't supported on the UP board with Windows 10 IOT?
Thomas
That doesn't sound so bad.
PWM can also be implemented using I2C and an external device.
I have several applications running on Win10 iot.
One of them streams an rtsp-stream from an IP camera to the screen of a Raspi. The application uses ffmpeg under Win10 iot for streaming and decoding/encoding the hevc/h264 stream.
Since Win1o iot with a Raspi 3B only allows software rendering, hardware graphics support would be more than helpful.
I have one more question.
The application can be run as a UWP implementation on Windows 10 (64 bit) as well as on Windows 10 iot.
Under Windows 10 (64bit), which board equipment I would have to choose at least, so that the application can run well.
Which board equipment would be necessary under Windows 10 iot? Can you recommend me a 7 inch screen, which runs with the UP2 board under Win10 iot.
Best regards
Willi Schneider
@tjoAG
Currently we can support GPIO/I2C/PWM through Up framework in windows 10 and windows IoT | https://forum.up-community.org/discussion/4169/up2-board-with-windows-10-iot-as-replacement-for-raspberry-pi-3-b | CC-MAIN-2021-25 | refinedweb | 440 | 71.95 |
Introduction to Fluent API in C#
In object orientation programming, fluent APIs are just like any other APIs but they provide a more human redable code. Consider a scenario where we want to build an object called Car and assign some properties to it.
Var Car = new Car(); Car.Name = "Tesla Model S"; Car.Type = "Electric"; Car.Color = "Blue";
Arguablly the above code is still readable. If we are to translate the above code to plain english, it would be, “Create a car with the name Tesla Model S, which is type of electric with blue color”.
The fluent APIs will provide the ability to write code which looks some what close to the translated englist phrase.
So the code would look like the following if this car is created with a fluent API.
var Car = new Car() .WithName("Tesla Model S") .WithType("Electric") .WithColor("Blue");
Isn’t that a more clear way to build the car object. Isn’t that Neat?
So let’s see the implementaion of the fluent car builder which will build cars for us.
public class Car{ public string Name {get; set;} public string Type {get; set;} public string Color {get; set;} public Car WithName(string Name){ this.Name = Name; return this; } public Car WithType(string Type){ this.Type = Type; return this; } public Car WithColor(string Color){ this.Color = Color; return this; } }
The key thing to notice here is that we are returning ‘this’ in all the methods. This allows us to chain the method calls one after the other making the code redable and fun to write.
Another imporant advantage of fluent style API is, they are self discoverable. Meaning that they are easy to learn than normal APIs.
Even C# team realized the convenience of fluent style API’s and used them to implemented API like LINQ. Consider the following example.
var Results = items.Where(e => e.Approved) .OrderBy(e => e.ProductionDate) .Select(e => e.Name) .FirstOrDefault();
Even though fluent APIs are neat, they wont be appicable for all the situations. As programmers we have a tendency to apply the new thing we learn in all the places. Honestly I tried to apply fluent API in several situations when I got to know about them. But in some instances they just dont work. But there are best fit certain scenarios where fluent APIs excel as well. So use them wisely! | http://raathigesh.com/Introduction-to-Fluent-API-in-C/ | CC-MAIN-2018-26 | refinedweb | 397 | 75.71 |
On Thu, Aug 05, 2010 at 09:38:07PM +0200, Bruno Haible wrote: > Joerg Sonnenberger wrote: > > > So, I don't understand how you see a "conflict". > > > > The conflicting declarations are a result of the default namespace > > containing _NETBSD_SOURCE if no (other) standard compliance macro is > > set. > > Still, I don't see how you can get a conflict with <stdlib.h> if the test > code does not include <stdlib.h>, and your report is very vague. The problem is that people copy this. Both the version in the documentation and in the macro. Defining the prototype manually might be good enough for the configure test, but it is a lot worse than using a potential compiler builtin. As such, the use of the correct system header should be strongly encouraged. At least the documentation doesn't. With the prototype change, at least the most obvious fallout doesn't appear. Joerg | https://lists.gnu.org/archive/html/bug-autoconf/2010-08/msg00046.html | CC-MAIN-2019-35 | refinedweb | 149 | 66.94 |
This article is about a classic challenge that is often given in Python coding interviews. There are several different approaches you could take, but the aim is to come up with a solution which has “reasonable” time complexity – i.e. given a large input it will complete within seconds rather than hours…
Given an unsorted list of integers, find a pair which add up to a given value. Identify the indices of the values which sum to the target. These indices must be distinct (i.e. you can’t use a value in the same position twice).
For example:
the input
[1, 2, 3], 4
should give the output
(0, 2)
Why not have a go at coding a solution yourself?
In order to focus your mind on the desired outcome for this problem, it is a very good idea to write some basic tests, or at least to consider a specific example and to be clear about what you expect the output to be.
Testing is a big topic and we won’t go into much detail here, but to give you a head-start, I will provide some very basic tests in the form of Python
assert statements. If you are new to assert statements, they)).
With that in mind, here’s some a function stub and a few tests to get you started:
# 2-Sum Interview Problem def two_sum_problem(arr, target): pass assert two_sum_problem([1, 2, 3], 4) == (0, 2) assert two_sum_problem([1234, 5678, 9012], 14690) == (1, 2) assert two_sum_problem([2, 2, 3], 4) in [(0, 1), (1, 0)] assert two_sum_problem([2, 2], 4) in [(0, 1), (1, 0)] assert two_sum_problem([8, 7, 2, 5, 3, 1], 10) in [(0, 2), (2, 0), (1, 4), (4, 1)]
The reason some of these assertions have multiple possible values is that we have not defined the order in which the function will test candidate pairs so we need to account for more than one possible solution, including when both candidates happen to have the same value (they can’t have the same index by the problem definition).
Python Programming Two Sum Interview Problem – Naive Approach
The way you decide to tackle this problem will depend on your level of experience. One approach is to iterate through the list, and for each item, to compare it with all the remaining items in the list.
Although this approach is very inefficient, due to the number of comparisons involved (it has
O(n^2) time complexity), it is still worth implementing it as doing so will give you the opportunity to fully understand the task and get a feel for what is needed.
Here’s a stub and some tests for the naive approach. Have a go for yourself before looking at my solution.
def two_sum_problem_brute_force(arr, target): pass assert two_sum_brute_force([1, 2, 3], 4) == (0, 2) assert two_sum_brute_force([1234, 5678, 9012], 14690) == (1, 2) assert two_sum_brute_force([2, 2, 3], 4) in [(0, 1), (1, 0)] assert two_sum_brute_force([2, 2], 4) in [(0, 1), (1, 0)] assert two_sum_brute_force([8, 7, 2, 5, 3, 1], 10) in [(0, 2), (2, 0), (1, 4), (4, 1)]
# Two Sum Interview Problem # Brute force approach def two_sum_brute_force(arr, target): length = len(arr) for i in range(length - 1): for j in range(1, length): # print(i, j) if arr[i] + arr[j] == target: return i, j return None
You should keep you assertion statements, and if the code runs with no errors you can be fairly confident your solution is correct, although you may well want to write some more test, including checking of edge cases.
An Improved Solution for the 2-Sum Interview Problem using Binary Search
The goal of an interviewer when asking this question may well be to get a sense of your general approach to problem solving, but also to see if are aware of the “big” problem with the naive approach (its radical inefficiency for any large input), and how well you can apply your knowledge of algorithms to come up with a more efficient solution.
One approach that might impress your interviewer is to go down the road of sorting the input first, and see where that takes you. Sorting is a relatively inexpensive operation provided a good algorithm is used, so if we can improve on those nested
for loops by doing so, then we should.
It turns out that this provides a neat solution to the two sum problem: we can sort our data, and then use the Binary Search Algorithm to find the complement of the current value to solve the problem.
For example, if the current value as we loop through our input is
11, and the target value is 20, we use binary search to find the value
9 in the input. If it is there, we are done. We do need to be careful though that we exclude the current value from the search as the problem requires that we can’t use the same input item twice to form our sum.
The code for this improved solution is below:
# Binary Search Solution to Two Sum Interview Problem def binary_search(lst, target): low = 0 high = len(lst) - 1 while low <= high: mid = (low + high) // 2 if lst[mid] == target: return mid elif lst[mid] > target: high = mid - 1 else: low = mid + 1 return None def two_sum_binary_search(arr, total): length = len(arr) arr = sorted(arr) for i in range(length): complement = total - arr[i] complement_idx = binary_search(arr, complement) # print(f"comliment: {complement} idx: {complement_idx}") if complement_idx is not None: # Found solution! if complement_idx != i: return (i, complement_idx) return None assert two_sum_binary_search([2, 2], 4) in [(0, 1), (1, 0)] print(two_sum_binary_search([8, 7, 2, 5, 3, 1], 10)) # Sorted!! assert two_sum_binary_search([8, 7, 2, 5, 3, 1], 10) in [(2, 4), (4, 2), (1, 5), (5, 1)]
A couple of assertions are provided with this solution. Note that with this version, tests need to be based on the sorted array.
Hash Table Solution for Python Two Sum Interview Problem
The approach that is most likely to impress your interviewer is to use a hash table. In Python this generally just means using a dictionary. The basic idea is that we loop through our input looking up the compliment of the current value (
target - current_value) in a hash table. If it is found, we are done. Otherwise, we store the values in the hash table along with the indices where those values were found.
Key observation: the hash table stores
value: indexpairs, with the current input value as the key and the index as the entry for that key.
Here is the code listing for a hash table based solution to the Two Sum interview problem in Python. As hash tables are generally very efficient data structures for performing lookups, this solution is very time-efficient (basically
O(n) time complexity).
Depending on your level of experience, you may want to try to implement the solution for yourself, so I’ll hide my code – you can reveal it by clicking show solution below. Here’s a stub and some tests to get you started.
def two_sum_hash_table(arr, total): pass assert two_sum_hash_table([1, 2, 3], 4) in [(0, 2), (2, 0)] assert two_sum_hash_table([1234, 5678, 9012], 14690) in [(1, 2), (2, 1)] assert two_sum_hash_table([2, 2, 3], 4) in [(0, 1), (1, 0)] assert two_sum_hash_table([2, 2], 4) in [(0, 1), (1, 0)] assert two_sum_hash_table([8, 7, 2, 5, 3, 1], 10) in [(0, 2), (2, 0), (1, 4), (4, 1)]
def two_sum_hash_table(arr, total): hash_table = dict() for i in range(len(arr)): complement = total - arr[i] if complement in hash_table: return (i, hash_table[complement]) else: hash_table[arr[i]] = i return None assert two_sum_hash_table([1, 2, 3], 4) in [(0, 2), (2, 0)] assert two_sum_hash_table([1234, 5678, 9012], 14690) in [(1, 2), (2, 1)] assert two_sum_hash_table([2, 2, 3], 4) in [(0, 1), (1, 0)] # order! assert two_sum_hash_table([2, 2], 4) in [(0, 1), (1, 0)] assert two_sum_hash_table([8, 7, 2, 5, 3, 1], 10) in [(0, 2), (2, 0), (1, 4), (4, 1)]
We have covered three approaches to the Two Sum interview problem using Python in this article. I hope you found it helpful. Let me know in the comments if you did.
Happy computing! | https://compucademy.net/python-programming-two-sum-interview-problem/ | CC-MAIN-2022-27 | refinedweb | 1,380 | 56.73 |
In Tensorflow: The Confusing Parts (1), I described the abstractions underlying Tensorflow at a high level in an intuitive manner. In this follow-up post, I dig more deeply, and examine how these abstractions are actually implemented. Understanding these implementation details isn’t necessarily essential to writing and using Tensorflow, but it allows us to inspect and debug computational graphs.
Inspecting Graphs
The computational graph is not just a nebulous, immaterial abstraction; it is a computational object that exists, and can be inspected. Complicated graphs are difficult to debug if we are representing them entirely in our heads, but inspecting and debugging the actual graph object makes thigs much easier.
To access the graph object, use
tf.get_default_graph(), which returns a pointer to the global default graph object:
Code:
import tensorflow as tf g = tf.get_default_graph() print g
Output:
<tensorflow.python.framework.ops.Graph object at 0x1144ffd90>
This object has the potential to tell us everything we need to know about the computational graph we have constructed. But only if we know how to use it! First, let’s take a step back and dive a bit deeper into something I glossed over in the first part: the difference between edges and nodes.
The mathematical definition of a graph includes both edges and nodes. A Tensorflow graph is no exception: it has
tf.Operation objects (nodes) and
tf.Tensor objects (edges). An operation results in a single tensor (edge) as an output, so it’s fine to conflate the two in most cases; that’s what I did in TFTCP1. But in terms of the actual Python objects that make up the graph, they are programmatically distinct.
When we create a new node, there are actually three things happening under the hood:
- We gather up all the
tf.Tensorobjects corresponding to the incoming edges for our new node
- We create a new node, which is a
tf.Operationobject
- We create one or more new outgoing edges, which are
tf.Tensorobjects, and return pointers to them
There are three primary ways that we can inspect the graph to understand how these pieces fit together:
- List All Nodes:
tf.Graph.get_operations()returns all operations in the graph
- Inspecting Nodes:
tf.Operation.inputsand
tf.Operation.outputseach return a list of
tf.Tensorobjects, which correspond to the incoming edges and outgoing edges, respectively
- Inspecting Edges:
tf.Tensor.opreturns a single
tf.Operationfor which this tensor is the output, and
tf.Tensor.consumers()returns a list of all
tf.Operationsfor which this tensor is used as an input.
Here’s an example of these in action:
Code
import tensorflow as tf a = tf.constant(2, name='a') b = tf.constant(3, name='b') c = a + b print "Our tf.Tensor objects:" print a print b print c print a_op = a.op b_op = b.op c_op = c.op print "Our tf.Operation objects, printed in compressed form:" print a_op.__repr__() print b_op.__repr__() print c_op.__repr__() print print "The default behavior of printing a tf.Operation object is to pretty-print:" print c_op print "Inspect consumers for each tensor:" print a.consumers() print b.consumers() print c.consumers() print print "Inspect input tensors for each op:" # it's in a weird format, tensorflow.python.framework.ops._InputList, so we need to convert to list() to inspect print list(a_op.inputs) print list(b_op.inputs) print list(c_op.inputs) print print "Inspect input tensors for each op:" print a_op.outputs print b_op.outputs print c_op.outputs print print "The list of all nodes (tf.Operations) in the graph:" g = tf.get_default_graph() ops_list = g.get_operations() print ops_list print print "The list of all edges (tf.Tensors) in the graph, by way of list comprehension:" tensors_list = [tensor for op in ops_list for tensor in op.outputs] print tensors_list print print "Note that these are the same pointers we can find by referring to our various graph elements directly:" print ops_list[0] == a_op, tensors_list[0] == a
Output
Our tf.Tensor objects: Tensor("a:0", shape=(), dtype=int32) Tensor("b:0", shape=(), dtype=int32) Tensor("add:0", shape=(), dtype=int32) Our tf.Operation objects, printed in compressed form: <tf.Operation 'a' type=Const> <tf.Operation 'b' type=Const> <tf.Operation 'add' type=Add> The default behavior of printing a tf.Operation object is to pretty-print: name: "add" op: "Add" input: "a" input: "b" attr { key: "T" value { type: DT_INT32 } } Inspect consumers for each tensor: [<tf.Operation 'add' type=Add>] [<tf.Operation 'add' type=Add>] [] Inspect input tensors for each op: [] [] [<tf.Tensor 'a:0' shape=() dtype=int32>, <tf.Tensor 'b:0' shape=() dtype=int32>] Inspect input tensors for each op: [<tf.Tensor 'a:0' shape=() dtype=int32>] [<tf.Tensor 'b:0' shape=() dtype=int32>] [<tf.Tensor 'add:0' shape=() dtype=int32>] The list of all nodes (tf.Operations) in the graph: [<tf.Operation 'a' type=Const>, <tf.Operation 'b' type=Const>, <tf.Operation 'add' type=Add>] The list of all edges (tf.Tensors) in the graph, by way of list comprehension: [<tf.Tensor 'a:0' shape=() dtype=int32>, <tf.Tensor 'b:0' shape=() dtype=int32>, <tf.Tensor 'add:0' shape=() dtype=int32>] Note that these are the same pointers we can find by referring to our various graph elements directly: True True
There are a couple of funky things that we have to do to make everything nice to look at, but once you get used to them, inspecting the graph becomes second nature.
Of course, no discussion of graphs would be complete without taking a look at
tf.Variable objects too:
Code
import tensorflow as tf a = tf.constant(2, name='a') b = tf.get_variable('b', [], dtype=tf.int32) c = a + b g = tf.get_default_graph() ops_list = g.get_operations() print print "tf.Variable objects are really a bundle of four operations (and their corresponding tensors):" print b print ops_list print print "Two of these are accessed via their tf.Operations,", print "the core", b.op.__repr__(), "and the initializer", b.initializer.__repr__() print "The other two are accessed via their tf.Tensors,", print "the initial-value", b.initial_value, "and the current-value", b.value() print print "A tf.Variable core-op takes no inputs, and outputs a tensor of type *_ref:" print b.op.__repr__() print list(b.op.inputs), b.op.outputs print print "A tf.Variable current-value is the output of a \"/read\" operation, which converts from *_ref to a tensor with a concrete data-type." print "Other ops use the concrete node as their input:" print b.value() print b.value().op.__repr__() print list(c.op.inputs)
Output
tf.Variable objects are really a bundle of four operations (and their corresponding tensors): <tf.Variable 'b:0' shape=() dtype=int32_ref> [<tf.Operation 'a' type=Const>, <tf.Operation 'b/Initializer/zeros' type=Const>, <tf.Operation 'b' type=VariableV2>, <tf.Operation 'b/Assign' type=Assign>, <tf.Operation 'b/read' type=Identity>, <tf.Operation 'add' type=Add>] Two of these are accessed via their tf.Operations, the core <tf.Operation 'b' type=VariableV2> and the initializer <tf.Operation 'b/Assign' type=Assign> The other two are accessed via their tf.Tensors, the initial-value Tensor("b/Initializer/zeros:0", shape=(), dtype=int32) and the current-value Tensor("b/read:0", shape=(), dtype=int32) A tf.Variable core-op takes no inputs, and outputs a tensor of type *_ref: <tf.Operation 'b' type=VariableV2> [] [<tf.Tensor 'b:0' shape=() dtype=int32_ref>] A tf.Variable current-value is the output of a "/read" operation, which converts from *_ref to a tensor with a concrete data-type. Other ops use the concrete node as their input: Tensor("b/read:0", shape=(), dtype=int32) <tf.Operation 'b/read' type=Identity> [<tf.Tensor 'a:0' shape=() dtype=int32>, <tf.Tensor 'b/read:0' shape=() dtype=int32>]
So a
tf.Variable adds (at least) four ops, but most of the details can be happily abstracted away by the
tf.Variable interface. In general, you can just assume that a
tf.Variable will be the thing you want it to be in any given circumstance. For example, if you want to assign a value to a variable, it will resolve to the core-op; if you want to use the variable in a computation, it will resolve to the current-value-op; etc.
Take some time to play around with inspecting simple Tensorflow graphs in a Colab or interpreter - it will pay off in time saved debugging later! | https://jacobbuckman.com/2018-08-05-graph-inspection/ | CC-MAIN-2022-21 | refinedweb | 1,402 | 53.27 |
Created on 2019-05-02 00:40 by rhettinger, last changed 2019-05-26 19:14 by rhettinger. This issue is now closed.
Follow the lead of the dataclasses module and allow lru_cache() to be used as a straight decorator rather than as a function that returns a decorator. Both of these would now be supported:
@lru_cache
def f(x):
...
@lru_cache(maxsize=256)
def f(x):
...
I do not like mixing decorators and decorator fabrics. But this can of worms has already been open by dataclasses. The question is whether we want to extend this design to the rest of the stdlib. lru_cache() resisted this change for a long time.
The 90% use case with dataclasses is satisfied with just "@dataclass", and perhaps the target user there is less sophisticated.
But the main difference between @dataclass and @lru_cache is that all of the parameters to @dataclass are keyword-only. Which I did because they are mostly all booleans, and "@dataclass(True, False, True)" isn't very helpful.
That's not the case with @lru_cache. Whether that makes a difference for this issue in particular, I'm not sure.
I agree that this violates "only one way to do it". But I haven't seen anyone use "@dataclass()", and I've also never seen anyone be confused by the fact that once you want parameters, you change to using parens. For the dataclass case, I think that working both ways has been helpful.
I'm generally ok with such APIs. It seems needless to require
@lru_cache()
def f(): ...
when a simple decorator would suffice. I think I might decide otherwise in cases where almost all usages require arguments, but if the no-arguments case is common (and there is no ambiguity in the arguments), then I prefer not requiring parentheses.
At Pycon today, I mostly got all positive feedback on this. Apparently py.test already follows this pattern. Another developer said they found the () to be distracting and would welcome not having to use them.
FWIW, I've followed this pattern (one function is both decorator and factory) in my own code for quite a while. I've never found it confusing nor has anyone else (that I'm aware) that has used those decorators.
One reason I've done decorators this way is because the empty parentheses are a visual distraction to readers. They also imply to readers that more is going on than really is. So I'm in favor of Raymond's plan.
As to the issue of positional vs. keyword arguments, keyword arguments make the implementation easier in some cases. Otherwise I haven't seen positional arguments cause much of a problem.
To clarify, I am not opposing this feature. I had doubts because if the memory does not betray me similar propositions for lru_cache or other decorator fabrics were rejected in past. But times change.
I am +1 to this. Making it easier for the case of decorator factories that are called with all the defaults is a very common pattern in the wild. There are even known idioms for how to reduce the indentation of the naive approach (returning partials of the factory). In particular for lru_cache, my experience is that every time I teach this feature, people are confused initially about the '()' at the end of the call.
New changeset b821868e6d909f4805499db519ebc2cdc01cf611 by Raymond Hettinger in branch 'master':
bpo-36772 Allow lru_cache to be used as decorator without making a function call (GH-13048) | https://bugs.python.org/issue36772 | CC-MAIN-2020-45 | refinedweb | 579 | 65.93 |
rehello,
On 18.04.08, Andreas Matthias wrote:
> cl = path.path(path.moveto(-a,-a),
> path.lineto(a,-a),
> path.lineto(a,a),
> path.lineto(-a,a),
> path.closepath())
>
> # protected area
> cl.append(path.arcn(0,0,2,360,0))
Try instead
c1 += path.circle(0, 0, 2).reversed()
The offending line was the connection between the endpoint of the
first part of the path (after closepath) and the beginning of the
"arcn". Note that arcn is a strange pathelement which adds the
necessary lineto.
My replacement implies that a moveto is used instead.
Michael
--
Michael Schindler
Laboratoire de Physico-Chimie Théorique.
ESPCI. 10 rue Vauquelin, 75231 Paris cedex 05, France.
Tel: +33 (0)1 40 79 45 97 Fax: +33 (0)1 40 79 47 31
http:
Hello,
I tried to protect an area from being painted over. So I constructed
a clipping path out of two parts. The first part spans the whole
drawing picture (the rectangle in the following example), the
second part spans only the small protected area (arcn in the following
example).
from pyx import *
c = canvas.canvas()
# drawing area
a = 5
cl = path.path(path.moveto(-a,-a),
path.lineto(a,-a),
path.lineto(a,a),
path.lineto(-a,a),
path.closepath())
# protected area
cl.append(path.arcn(0,0,2,360,0))
#c.stroke(cl) # <-- clipping path
c.insert(canvas.clip(cl))
c.stroke(path.line(-2,3,2,-3),[style.linewidth(1)])
c.writeEPSfile("foo")
The thick line is clipped as intended, but the thin line shouldn't
exist at all. I know that the clipping path is chosen unfortunately,
because the connection line between the rectangle and the circle
crosses the circle. But it is very complex to prevent this crossing
if the protected area may have an arbitrary shape and is provided by
some other user and not me.
What's the recommended way to this kind of clipping? How to get
rid of the small line?
Ciao
Andreas
Thank you, Jörg!
using the dodata() method did the trick. The workaround using eps and
then eps2eps did also help, but produced files of approx. 10x the
original size.
Thanks a lot, I appreciate the help.
Benedikt
Am Donnerstag, den 17.04.2008, 13:26 +0200 schrieb Joerg Lehmann:
> Hi Benedikt,
>
> On 17.04.08, Benedikt Koenig wrote:
> > I am using 3d graphs for some illustrations. The linked file
> > 'example.pdf' shows the typical stuff I need for my publication. The pdf
> > looks good to me in Acrobat Reader, and I can't see anything wrong with
> > it.
>
> > However, when I print the graph I get the result shown in the linked
> > file 'printout.pdf' (printed using cups-pdf, but same result when I
> > hardcopy to laserjet). Seems there is a rectangular box around the
> > graph, which can not be seen in the original pdf, and that covers the
> > axes and labels. Also, using xpdf doesn´t show the 3d part of the graph
> > at all.
>
> I just tried to print it on a Nashuatec printer and it works. On the
> other hand, I'm not too surprised that there are problems with the
> shading implementation of some, especially older drivers.
>
> Anyway, what I would try is to let PyX generate an EPS file and then
> check whether that works. If yes, fine, convert the file into a PDF and
> keep fingers crossed. If not, try to use eps2eps and continue. I know
> that's a mess but in urgent cases, I always do something along these
> lines.
>
> In the specific case, you could also try to plot the surface first, i.e.
> before the rest of the graph. Just call the dodata() method of the graph
> after the plot() call. See
>
>
>
> for an example. I am optimistic that this fixes the problem...
>
> HTH,
>
> Jörg
>
Hi,
Am Freitag 18 April 2008 05:13 schrieb Brendon Higgins:
> Thus my question: how can I change the ordering of the key without
> changing the order in which the data is plotted? Is this even possible?
> (Please tell me it is, somehow. I'm not afraid of digging into PyX code
> if I have to. ;-) )
I'm not sure if this is the most elegant way in PyX, but the following
seems to work.
from pyx import *
g = graph.graphxy(width=8)
a = g.plot(graph.data.function("y(x)=sin(x)/x", min=-15, max=15),
[graph.style.line([color.cmyk.Red, style.linestyle.dashed])])
b = g.plot(graph.data.function("y(x)=sin(x)/x", min=-15, max=15),
[graph.style.line([color.cmyk.Black, style.linestyle.solid])])
g.doplot(b)
g.doplot(a)
g.writeEPSfile("function")
Greetings,
Stefan Schenk
Hello,
I'm relatively new to PyX, so forgive me if this has been addressed before,
however my searches through the manual, examples, FAQ, and lists were
fruitless.
Is there a way to specify the plot drawing order independent of the ordering
of the entries in the generated key?
Here's my situation: I build a plot that has lines (theory calculations) and
symbols (experimental data) with error bars on the symbols, for two different
sets of data (two different "configurations" of the experiment), on the same
graph. First, I'd like the symbols to be drawn overtop of the lines, but on
the key, the experimental symbols to be present before the theory lines. I'd
also like one configuration to appear before the other in the key, but also
for its symbols/lines to be plotted on top of the other pair.
As far as I can see, the current status is that key entries appear in the
order reverse of that of the most "forward" plot; i.e. first drawn plot gets
first place in the key, last drawn plot (overdrawing all other plots) gets
last place in the key. This is (in reality not quite) the exact opposite of
the order that I'd like.
Thus my question: how can I change the ordering of the key without changing
the order in which the data is plotted? Is this even possible? (Please tell
me it is, somehow. I'm not afraid of digging into PyX code if I have
to. ;-) )
For the record, I aim to patch PyXPlot to support this, if it turns out to be
possible.
Peace,
Brendon | https://sourceforge.net/p/pyx/mailman/pyx-user/?viewmonth=200804&viewday=18 | CC-MAIN-2018-09 | refinedweb | 1,051 | 75.4 |
Puffer — YARAI (Yet Another Rails Admin Interface)
Puffer was created to help a project owner or moderators view and edit all the project's data models.
It's compatible with Rails 3.1 only.
Discussion and help
xmpp:puffer@conference.jabber.org
Key features
- Full Ruby on Rails integration. Puffer has no configuration files, but a DSL to define administration interfaces. This DSL follows the Rails conventions.
- Flexibility. Puffer designed to provide much flexibility as possible, so you can create your own extensions without any design issues.
- Internationalization. Surely, enjoy the native Rails i18n subsystem.
- Puffer supports different ORMs or ODMs through the
orm_adaptergem. Currently, we can work with ActiveRecord and Mongoid.
Installation.
You can install puffer as a gem:
gem install puffer
Or in Gemfile:
gem "puffer"
Introduction.
Let's assume this is the data structure of your application:
create_table "users", :force => true do |t| t.string "email" t.string "password" t.datetime "created_at" t.datetime "updated_at" end create_table "posts", :force => true do |t| t.integer "user_id" t.string "title" t.text "body" t.datetime "created_at" t.datetime "updated_at" end
And let's also assume your models look like this:
class User < ActiveRecord::Base has_many :posts validates_presence_of :email, :password validates_length_of :password, :minimum => 6 end class Profile < ActiveRecord::Base belongs_to :user validates_presence_of :name, :surname end
First, let's generate the Puffer controllers:
rails g puffer:controller User
and
rails g puffer:controller Post
This will generate the following code:
class Admin::PostsController < Puffer::Base setup do group :posts end index do field :id field :user_id field :title field :body field :created_at field :updated_at end form do field :id field :user_id field :title field :body field :created_at field :updated_at end end
Puffer's DSL creates all the actions you need. Next step is routing.
namespace :admin do resources :users do resources :posts end resources :posts end
Let me explain this feature. Puffer tracks all the nested resources. For instance, according to our routing definitions, we can access only specified posts of our user:
/admin/users/1/post
Routing nesting implies the admin resources nesting.
Advanced usage
Puffer can work in different namespaces:
rails g puffer:controller moderator/posts
And we'll get posts controller for moderators:
class Moderator::PostsController < Puffer::Base before_filter :require_moderator setup do destroy false group :posting end index do field :user_id field :title field :body end form do field :user_id field :title field :body field :created_at field :updated_at end end
As you can see, moderators can't destroy posts. The moderator's post controller is placed in the Posting tab of the admin interface.
Finally, don't forget about routing:
namespace :moderator do resources :posts end
Have a nice day and let Puffer rock for you.
Thanks to Dmitry Ustalov for the name of Puffer along with the Clearance integration. | http://www.rubydoc.info/gems/puffer/frames | CC-MAIN-2017-26 | refinedweb | 462 | 56.55 |
Class names with first letter Uppercase and internal uppercase to separate compound words.
Function members of classes follow the same rule.
Example:
Public Variable members has the first letter lowercase and internal uppercase to separate compound words.
Example:
Private Variable members has an underscore as first char and the first letter lowercase and internal uppercase to separate compound words.
Example:
Point3f { private: ScalarType _v[3]; }
Class Template Arguments all capitalized and with names remembering where they have been defined.
Class TypeDefs used for templated Class arguments or for shortness are just like Class Names, but ending with “Type”, “Iterator”, “Pointer”, or “Container”.
Example:
typedef typename VertexType::CoordType CoordType; typedef typename VertContainer::iterator VertexIterator;
Header filenames and folders always fully lower case. Compound names are separated by '_'.
Example:
#include<vcg/space/point3.h>;
Each include file must begin with the standard legal disclamier/license intestation and report in the first line of history the $LOG$ cvs string.
The following automatically generated history can be, from time to time, compressed and shortened to save space.
Each file of the library has to include all the files that it requires. A include file should rely on the files included by its own include files. Example: in vcg/space/box3.h:
#include<vcg/math/base.h>; // not necessary because included by point3.h #include<vcg/space/point3.h>;
In Class definitions place all the prototypes all together before the inline or templated implementations.
Tabs are equivalent to two spaces.
There are no strict rules for the placement of '{' or indenting.
All basic classes (point3, box3 ecc) must have null constructors. Non null constructors can be added in debug versions.
Implicit casting is disallowed. Write a member Import function for casting from different integral types and a static.
Construct to build an object from different a integral type.
Example:
Point3f pf(1.0f,0.0f,0.0f); Point3d pd=Point3f::Construct(pf); pf.Import(pd);
All the classes, algorithms and functions MUST be documented using Doxygen. Please add a short intro before each class explaining design choices and for non trivial classes give some short usage example. For complex classes try to group similar members under categories. Non trivial algorithms should refer the paper/book where they are explained. Namespaces and files should be also documented trying to explain how the file/namespace partitioning works. | http://vcglib.net/VCG_01Library_01Coding_01Guide.html | CC-MAIN-2020-50 | refinedweb | 391 | 50.53 |
Hide Forgot
Description of problem:
The pod keeps crash looping, restarting for a while, then crashing. I restarted an hour ago and it has restart 27 times. Prior to that I saw that it restarted 1178 times!
OOMKiller killed the pod. So I increased the pod max memory limit from 500Mi to 1Gi (via the operator deployment). The system seems to like this for now. But why would this pod need so much memory? Metrics is showing that it is pegged at 1Gi as well so I'm not sure that OOM won't get it at some point.
The pod is crashing again even at 1Gi! Here are the events:
#oc4 get events
LAST SEEN TYPE REASON OBJECT MESSAGE
58s Normal Pulled pod/cloud-credential-operator-768d9c6f46-fw758 Container image "quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:ba803653c4af0089feca91b065d1d96ad4660ae061cf40793894d24585891f3c" already present on machine
58s Warning Failed pod/cloud-credential-operator-768d9c6f46-fw758 Error: container create failed: container_linux.go:329: creating new parent process caused "container_linux.go:1762: running lstat on namespace path \"/proc/47771/ns/ipc\" caused \"lstat /proc/47771/ns/ipc: no such file or directory\""
1s Warning BackOff pod/cloud-credential-operator-768d9c6f46-fw758 Back-off restarting failed containe
The original container was OOMKilled.
Version-Release number of selected component (if applicable):
4.1.z
How reproducible:
Happens consistently. It runs for a while before crashing again.
Steps to Reproduce:
1.
2.
3.
Actual results:
Expected results:
Additional info:
The deployment/pod originally had the new limits (150Mi/500Mi Limit) on it - so the patch was applied to the operator deployment before I did anything. I increased the hard limit on the deployment to 1Gi and it has been running since with 0 restarts. Any idea why this operator needs so much memory?
How many namespaces and secrets are in this cluster?
oc get secrets -A | wc -l
oc get namespaces -A | wc -l
We have seen this in both situations thus the removal of the memory limit.
The operator watches both resource types so we can react immediately if credentials are deleted or namespaces created which need credentials. The kube client code caches everything being watched, and thus if you have thousands of one of these resources it can cause excessive memory usage. We saw this in one cluster where an operator had gone rogue and there were 30k secrets created.
jrmini:aws jrigsbee$ oc4 get namespaces -A | wc -l
96
jrmini:aws jrigsbee$ oc4 get secrets -A | wc -l
27265
Wow! That's a lot of secrets.
Looks like namespace openshift-cluster-node-tuning-operator, secret name = tuned-dockercfg-XXXXX is the culprit:
oc4 get secrets -A -n openshift-cluster-node-tuning-operator | wc -l
27268
Looks like the root of your problem is, if it's ok I'm going to close this as a duplicate as we have already shipped a fix for CCO to remove memory limits and avoid this if possible.
That fix will not affect clusters on upgrade because the CVO does not reconcile memory limits, so any existing cluster hitting this should be able to remove the memory limits from the cloud credential operator deployment by hand.
*** This bug has been marked as a duplicate of bug 1723569 *** | https://bugzilla.redhat.com/show_bug.cgi?id=1734606 | CC-MAIN-2021-10 | refinedweb | 542 | 55.13 |
BN_copy,
BN_dup,
BN_with_flags—
#include <openssl/bn.h>
BIGNUM *
BN_copy(BIGNUM *to,
const BIGNUM *from);
BIGNUM *
BN_dup(const BIGNUM *from);
void
BN_with_flags(BIGNUM *dest,
const BIGNUM *b, int flags);
BN_copy() copies from to to.
BN_dup() creates a new
BIGNUM containing the value
from.
BN_with_flags() creates a
temporary shallow copy of b in
dest. It places significant restrictions on the copied
data. Applications that do not adhere to these restrictions may encounter
unexpected side effects or crashes. For that reason, use of this macro is
discouraged.
Any flags provided in flags will be set in
dest in addition to any flags already set in
b. For example, this can:
BN_copy() returns to on success or
NULLon error.
BN_dup() returns the new BIGNUM or
NULLon error. The error codes can be obtained by ERR_get_error(3).
BN_copy() and
BN_dup() first appeared in SSLeay 0.5.1 and have been available since OpenBSD 2.4.
BN_with_flags() first appeared in OpenSSL
0.9.7h and 0.9.8a and has been available since OpenBSD
4.0. | https://man.openbsd.org/BN_copy.3 | CC-MAIN-2019-30 | refinedweb | 170 | 78.45 |
NAME
pmap_change_wiring - change physical wiring for a map or virtual address pair
SYNOPSIS
#include <sys/param.h> #include <vm/vm.h> #include <vm/pmap.h> void pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired);
DESCRIPTION
The pmap_change_wiring() function changes the wiring attribute for the page at virtual address va in the physical map pmap. A wired page gets its name from being “wired” into the system page tables so that it will not be paged out. The mapping must already exist in the pmap. If wired is TRUE, the map’s wired page count will be incremented; if FALSE, it will be decremented. It is typically called by the vm_fault_unwire() function.
SEE ALSO
pmap(9)
AUTHORS
This manual page was written by Bruce M Simpson 〈bms@spc.org〉. | http://manpages.ubuntu.com/manpages/lucid/man9/pmap_change_wiring.9freebsd.html | CC-MAIN-2015-27 | refinedweb | 127 | 75.3 |
How to use "UI. Custom Structure view component for file type." Follow Dmitry Kashin Created December 17, 2004 13:15 Is it in OpenAPI already?TIA,Dmitry
Dmitry,
The API to Project, Structure & Hierarchy view is right under
development. It should appear pretty soon.
Hello,
I think a useful feature would be to allow associating file types by
other means than file extensions. For example, determining the correct
editor via the file's DTD, namespace, or even content.
Of course, this is not mainstream, but would prove useful for cases
where the file name/extension is not readily known (e.g. Commons Jelly,
Maven POMs, Apache Forrest, etc).
I assume it is not possible right now (from what I saw in the OpenAPI
interfaces) - but would it be possible to incorporate such capabilities
into future versions of IntelliJ?
10x,
Arik. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/206800925-How-to-use-UI-Custom-Structure-view-component-for-file-type- | CC-MAIN-2019-30 | refinedweb | 140 | 57.87 |
FSTAB(5) BSD Reference Manual FSTAB(5)
fstab - static information about the filesystems
#include <fstab.h> '#' character are comments and are ignored. The order of records in fstab is important be- cause fsck(8), mount(8), and umount. For filesystems of type ffs, the special file name is the block special file name, and not the character special file name. If a program needs the character special file name, the program must create it by appending an "r" after the last "/" in the special file name. The second field, fs_file, describes the mount point for the filesystem. For swap partitions, this field should be specified as "none". The third field, fs_vfstype, describes the type of the filesystem. The system currently supports twelve types of filesystems: adosfs An AmigaDOS filesystem. cd9660 An ISO9660 CD-ROM filesystem. fdesc An implementation of /dev/fd. ffs A local UNIX filesystem. ext2fs A local Linux compatible ext2fs filesystem. kernfs Various and sundry kernel statistics. mfs A local memory-based UNIX filesystem. msdos An MS-DOS FAT filesystem. nfs A Sun Microsystems compatible Network File System. procfs A local filesystem containing process information. swap A disk partition to be used for swapping. union A translucent filesystem. The fourth field, fs_mntops, describes the mount options associated with the filesystem. It is formatted as a comma separated list of options. It contains at least the type of mount (see fs_type below) plus any addi- tional options appropriate to the filesystem type. The option "auto" can be used in the "noauto" form to cause a file system not to be mounted automatically (with mount -A or mount -a, or at system boot time). quo- ta).
/etc/fstab
Here is a sample /etc/fstab file: /dev/sd0a / ffs rw 1 1 /dev/sd0e /var ffs rw,nodev,nosuid 1 2 #/dev/sd0f /tmp ffs rw,nodev,nosuid 1 2 /dev/sd0b /sd1b none swap sw 0 0 /dev/cd0a /cdrom cd9660 ro,noauto 0 0 server:/export/ports /usr/ports nfs rw,nodev,nosuid,tcp,soft,intr 0 0
quota(1), getfsent(3), fsck(8), mount(8), quotacheck(8), quotaon(8), umount(8)
The fstab file format appeared in 4.0BSD. MirOS BSD #10-current June. | http://www.mirbsd.org/htman/sparc/man5/fstab.htm | CC-MAIN-2014-10 | refinedweb | 366 | 58.69 |
This action might not be possible to undo. Are you sure you want to continue?
Tools & Languages: Objective-C
2009-10-19 .Mac is a registered service mark of Apple Inc. Apple, the Apple logo, Bonjour, Cocoa, Instruments,. Times is a registered trademark of Heidelberger Druckmaschinen AG, available from Linotype Library GmbH. 18 Polymorphism 18 Dynamic Binding 19 Dynamic Method Resolution 20 Dot Syntax 20 Classes 23 Inheritance 24 Class Types 27 Class Objects 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. . 2009-10-19 | © 2009 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. .
Mid. Classes. . and Messaging 13 Figure 1-1 Figure 1-2 Figure 1-3 Listing 1-1 Listing 1-2 Listing 1-3 Some Drawing Program Classes 24 Rectangle Instance Variables 25 Inheritance hierarchy for NSCell 30 Accessing properties using the dot syntax 20 Accessing properties using bracket syntax 21 Implementation of the initialize method 32 Chapter 2 Defining a Class 35 Figure 2-1 Figure 2-2 The scope of instance variables 41 High.Figures and Listings Chapter 1 Objects. direct method implementations 2009-10-19 | © 2009 Apple Inc. All Rights Reserved.
FIGURES AND LISTINGS Chapter 13 Remote Messaging 105 Figure 13-1 Figure 13-2 Remote Messages 106 Round-Trip Message 107 Chapter 14 Using C++ With Objective-C 111 Listing 14-1 Using C++ and Objective-C instances as instance variables 111 8 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. .
one of the first object-oriented programming languages. Important: This document describes the version of the Objective-C language released in Mac OS X v10. Objective-C is designed to give C full object-oriented programming capabilities. However.INTRODUCTION Introduction to The Objective-C Programming Language The Objective-C language is a simple computer language designed to enable sophisticated object-oriented programming.0. 9 . The runtime environment is described in a separate document. and to do so in a simple and straightforward way. it assumes some prior acquaintance with that language. the Mac OS X Objective-C application frameworks—collectively known as Cocoa..4 and earlier). Its additions to C are mostly based on Smalltalk. The two main development tools you use are Xcode and Interface Builder. read Object Oriented Programming and the Objective-C Programming Language 1. All Rights Reserved. It concentrates on the Objective-C extensions to C. described in Xcode Workspace Guide and Interface Builder respectively.6. Objective-C Runtime Programming Guide. not on the C language itself. and provides a foundation for learning about the second component. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language.0 of the Objective-C language (available in in Mac OS X v10. Most object-oriented development environments consist of several parts: ■ ■ ■ ■ An object-oriented programming language A library of objects A suite of development tools A runtime environment This document is about the first component of the development environment—the programming language. It fully describes the Objective-C language. You can start to learn more about Cocoa by reading Getting Started with Cocoa. which introduces the associative references feature (see “Associative References” (page 83)). Object-oriented programming in Objective-C is sufficiently different from procedural programming in ANSI C that you won’t be hampered if you’re not an experienced C programmer. it doesn’t have to be an extensive acquaintance. To learn about version 1. Who Should Read This Document 2009-10-19 | © 2009 Apple Inc. Because this isn’t a document about C.
Similarly. the syntax: @interfaceClassName(CategoryName) means that @interface and the two parentheses are required. Objective-C syntax is a superset of GNU C/C++ syntax. but that you can choose the class name and category name.m.mm.c. The appendix contains reference material that might be useful for understanding the language: ■ “Language Summary” (page 117) lists and briefly comments on all of the Objective-C extensions to the C language.. Computer voice denotes words or characters that are to be taken literally (typed as they appear). For example. Classes. the compiler recognizes C++ files that use Objective-C by the extension . and other programming elements. . just as it recognizes files containing only standard C syntax by filename extension . Conventions Where this document discusses functions. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “Objects. Italic denotes words that represent something else or can be varied. methods. C++ and Objective-C source code. The following chapters cover all the features Objective-C adds to standard C. All Rights Reserved. Other issues when using Objective-C with C++ are covered in “Using C++ With Objective-C” (page 111). 10 Organization of This Document 2009-10-19 | © 2009 Apple Inc. The compiler recognizes Objective-C source files by the filename extension . it makes special use of computer voice and italic fonts. and the Objective-C compiler works for C.INTRODUCTION Introduction to The Objective-C Programming Language Organization of This Document This document is divided into several chapters and one appendix.
ellipsis points indicates the parts. See Also If you have never used object-oriented programming to create applications before. Runtime Objective-C Runtime Programming Guide describes aspects of the Objective-C runtime and how you can use it. that have been omitted: . you can add classes or methods. Objective-C Runtime Reference describes the data structures and functions of the Objective-C runtime support library. Your programs can use these interfaces to interact with the Objective-C runtime system.) Memory Management Programming Guide for Cocoa describes the reference counting system used by Cocoa. often substantial parts. Object-Oriented Programming with Objective-C is designed to help you become familiar with object-oriented development from the perspective of an Objective-C developer. (Not available on iPhone—you cannot access this document through the iPhone Dev Center. or obtain a list of all class definitions for loaded classes. You should also consider reading it if you have used other object-oriented development environments such as C++ and Java. Memory Management Objective-C supports two environments for memory management: automatic garbage collection and reference counting: ■ Garbage Collection Programming Guide describes the garbage collection system used by Cocoa. since those have many different expectations and conventions from Objective-C. It spells out some of the implications of object-oriented design and gives you a flavor of what writing an object-oriented program is really like. ■ See Also 2009-10-19 | © 2009 Apple Inc.(void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder].INTRODUCTION Introduction to The Objective-C Programming Language Where example code is shown. Objective-C Release Notes describes some of the changes in the Objective-C runtime in the latest release of Mac OS X. .. All Rights Reserved. For example. 11 .. } The conventions used in the reference appendix are described in that appendix. you should read Object-Oriented Programming with Objective-C.
. All Rights Reserved.INTRODUCTION Introduction to The Objective-C Programming Language 12 See Also 2009-10-19 | © 2009 Apple Inc.
and so forth.CHAPTER 1 Objects. fill status. Objects As the name implies. rectangles. Runtime 2009-10-19 | © 2009 Apple Inc. if you are writing a drawing program that allows a user to create images composed of lines. This means that the language requires not just a compiler. you don’t need to interact with the runtime directly. and a line pattern that should be used to display the rectangle. It also introduces the Objective-C runtime. In Objective-C. Typically. bit-mapped images. 13 . and line pattern. the data they affect are its instance variables. however. The runtime system acts as a kind of operating system for the Objective-C language. you might create classes for many of the basic shapes that a user can manipulate. an object bundles a data structure (instance variables) and a group of procedures (methods) into a self-contained programming unit. and messaging as used and implemented by the Objective-C language. A Rectangle class would have methods to set an instance’s position. these operations are known as the object’s methods. All Rights Reserved. text. Other instance variables could define the rectangle’s color. color. but also a runtime system to execute the compiled code. though. circles. might have instance variables that identify the position of the rectangle within the drawing along with its width and its height. object-oriented programs are built around objects. you should typically ensure that you dispose of objects that are no longer needed. it’s what makes the language work. Object Basics An object associates data with the particular operations that can use or affect that data. To understand more about the functionality it offers. Whenever possible. classes. In essence. whether or not it is to be filled. A Rectangle object. size. Classes. Runtime The Objective-C language defers as many decisions as it can from compile time and link time to runtime. and Messaging This chapter describes the fundamentals of objects. In a program. An object associates data with the particular operations that can use or affect that data. along with a method that causes the instance to display itself. see Objective-C Runtime Programming Guide. for instance. it dynamically performs operations such as creating objects and determining what method to invoke. Objective-C provides a data type to identify an object variable without specifying a particular class of the object—this allows for dynamic typing. For example.
a program needs to find more specific information about the objects it contains—what the object’s instance variables are. each object has to be able to supply it at runtime.) id is defined as pointer to an object data structure: typedef struct objc_object { Class isa.) The keyword nil is defined as a null object. except that it is an object. Just as a C function protects its local variables. 14 Objects 2009-10-19 | © 2009 Apple Inc. Dynamic Typing The id type is completely nonrestrictive. nil. an object sees only the methods that were designed for it.CHAPTER 1 Objects. All Rights Reserved. (It can be used for both instances of a class and class objects themselves. But objects aren’t all the same.” Like a C function or an array. see “The Scope of Instance Variables” (page 40)). id replaces int as the default data type. (For strictly C constructs. it can’t mistakenly perform methods intended for other types of objects. such as function return values. For the object-oriented constructs of Objective-C. This is the general type for any kind of object regardless of class. there has to be a method to supply the information. a Rectangle would have methods that reveal its size and its position. All objects thus have an isa variable that tells them of what class they are an instance. are of type id.h. For example. generally. regardless of their instance variables or methods. int remains the default type. . object identifiers are a distinct data type: id. Terminology: Since the Class type is itself defined as a pointer: typedef struct objc_class *Class. A Rectangle won’t have the same methods or instance variables as an object that represents a bit-mapped image. it yields no information about an object. All objects. id anObject. and so on. the isa variable is frequently referred to as the “isa pointer. and Messaging In Objective-C. For others to find out something about an object. Moreover. an object is therefore identified by its address. At some point. hiding them from the rest of the program. id In Objective-C. an id with a value of 0. and the other basic types of Objective-C are defined in the header file objc/objc. an object’s instance variables are internal to the object. } *id. such as method return values. what methods it can perform. Since the id type designator can’t supply this information to the compiler. id. an object hides both its instance variables and its method implementations. By itself. Classes. you get access to an object’s state only through the object’s methods (you can specify whether subclasses or other objects can access instance variables directly by using scope directives.
(To learn more about the runtime. In Objective-C. The compiler records information about class definitions in data structures for the runtime system to use. Every Rectangle object would be able to tell the runtime system that it is a Rectangle. Every Circle can say that it is a Circle. discussed later. It is also important to ensure that you do not deallocate objects while they’re still being used. Objects with the same behavior (methods) and the same kinds of data (instance variables) are members of the same class. It’s also possible to give the compiler information about the class of an object by statically typing it in source code using the class name. or discover the name of its superclass.CHAPTER 1 Objects. you can. It also discusses the “visibility” of an object’s instance variables. (Not available on iPhone—you cannot access this document through the iPhone Dev Center. Objective-C offers two environments for memory management that allow you to meet these goals: ■ Reference counting. including how you can nest message expressions. the runtime system can find the exact class that an object belongs to. message expressions are enclosed in brackets: Object Messaging 2009-10-19 | © 2009 Apple Inc. you send it a message telling it to apply a method. Reference counting is described in Memory Management Programming Guide for Cocoa. The isa variable also enables objects to perform introspection—to find out about themselves (or other objects).) Dynamic typing in Objective-C serves as the foundation for dynamic binding. All Rights Reserved. Message Syntax To get an object to do something. The functions of the runtime system use isa. for example. it is important to ensure that objects are deallocated when they are no longer needed—otherwise your application’s memory footprint becomes larger than necessary. see Objective-C Runtime Programming Guide. determine whether an object implements a particular method. where you are ultimately responsible for determining the lifetime of objects. Classes. and the class name can serve as a type name. ■ Garbage collection. Classes are particular kinds of objects. Object classes are discussed in more detail under “Classes” (page 23). where you pass responsibility for determining the lifetime of objects to an automatic “collector. just by asking the object. Whenever it needs to. Objects are thus dynamically typed at runtime.) Object Messaging This section explains the syntax of sending messages. to find this information at runtime. Using the runtime system. Memory Management In an Objective-C program. 15 .” Garbage collection is described in Garbage Collection Programming Guide. See “Class Types” (page 27) and “Enabling Static Behavior” (page 91). and the concepts of polymorphism and dynamic binding. and Messaging The isa instance variable identifies the object’s class—what kind of object it is.
0. the second argument is effectively unlabeled and it is difficult to determine the kind or purpose of the method’s arguments. This particular method does not interleave the method name with the arguments and. 50. and an argument follows the colon. but does not include anything else. Classes.CHAPTER 1 Objects. or “arguments. method names should interleave the name with the arguments such that the method's name naturally describes the arguments expected by the method. In source code. Methods can also take parameters. the message is simply the name of a method and any arguments that are passed to it. // This is a good example of multiple arguments 16 Object Messaging 2009-10-19 | © 2009 Apple Inc. as shown in this example: [myRectangle setWidth:20. The method name in a message serves to “select” a method implementation. the runtime system selects the appropriate method from the receiver’s repertoire and invokes it.0].0].0): [myRectangle setOrigin:30.” as is normal for any line of code in C. this message tells the myRectangle object to perform its display method. Instead. For this reason. and Messaging [receiver message] The receiver is an object. When a message is sent. method names in messages are often referred to as selectors. a keyword ends with a colon. This construct is called a keyword. A selector name includes all keywords. All Rights Reserved.0 y: 50.” A message with a single argument affixes a colon (:) to the selector name and puts the argument right after the colon. and the message tells it what to do. . The imaginary message below tells the myRectangle object to set its origin to the coordinates (30. the method is named setOrigin::. For example. // This is a bad example of multiple arguments Since the colons are part of the method name. The message is followed by a “. For example. It has two colons as it takes two arguments.0 :50. the Rectangle class could instead implement a setOriginX:y: method that makes the purpose of its two arguments clear: [myRectangle setOriginX: 30.0]. which causes the rectangle to display itself: [myRectangle display]. thus. including colons. such as return type or parameter types.
memberThree].) operator that offers a compact and convenient syntax for invoking an object’s accessor methods. Object Messaging 2009-10-19 | © 2009 Apple Inc. The value returned from a message to nil may also be valid: ■ If the method returns an object. a float. a long double. BOOL isFilled. 17 . NeatMode=SuperNeat. the imaginary makeGroup: method is passed one required argument (group) and three that are optional: [receiver makeGroup:group. This is not the case with Objective-C. can be in a different order. a double. Extra arguments are separated by commas after the end of the method name. memberTwo. memberOne. can have default values. “Named arguments” and “keyword arguments” often carry the implication that the arguments to a method can vary at runtime. Here. Classes. b. All Rights Reserved. or a long long. Note that a variable and a method can have the same name. This is different from the named or keyword arguments available in a language like Python: def func(a. then a message sent to nil returns 0. One message expression can be nested inside another. This is typically used in conjunction with the declared properties feature (see “Declared Properties” (page 67)).CHAPTER 1 Objects. and Messaging Important: The sub-parts of the method name—of the selector—are not optional. can possibly have additional named arguments. the commas aren’t considered part of the name. Objective-C also provides a dot (. and is described in “Dot Syntax” (page 20). (Unlike colons. any integer scalar of size less than or equal to sizeof(void*). an Objective-C method declaration is simply a C function that prepends two additional arguments (see Messaging in the Objective-C Runtime Programming Guide). Like standard C functions. Thing=DefaultThing): pass where Thing (and NeatMode) might be omitted or might have different values when called. though they’re somewhat rare. For all intents and purposes. then mother is sent to nil and the method returns nil. Methods that take a variable number of arguments are also possible. If aPerson’s spouse is nil. or NO if it’s drawn in outline form only. isFilled = [myRectangle isFilled]. methods can return values. The following example sets the variable isFilled to YES if myRectangle is drawn as a solid rectangle. for example: Person *motherInLaw = [[aPerson spouse] mother]. the color of one rectangle is set to the color of another: [myRectangle setPrimaryColor:[otherRect primaryColor]]. it is valid to send a message to nil—it simply has no effect at runtime. ■ If the method returns any pointer type. Sending Messages to nil In Objective-C.) In the following example. then a message sent to nil returns 0 (nil). There are several patterns in Cocoa that take advantage of this fact. nor can their order be varied.
messages behave differently than function calls. any pointer type. a message to nil also is valid. any pointer type. a message sent to nil returns nil. A method has automatic access only to the receiver’s instance variables. or any vector type) the return value is undefined. // this is valid if ([anObjectMaybeNil methodThatReturnsADouble] == 0. Polymorphism As the examples above illustrate.. All Rights Reserved. On Mac OS X v10. it must send a message to the object asking it to reveal the contents of the variable. But. void. Messages are sent to receivers much as letters are delivered to your home. Message arguments bring information from the outside to the receiver. yet it can find the primary color for otherRect and return it. It also supports the way object-oriented programmers think about objects and messages. if it does. See “Defining a Class” (page 35) for more information on referring to instance variables. Classes.CHAPTER 1 Objects. or any integer scalar of size less than or equal to sizeof(void*). then a message sent to nil returns 0. the primaryColor method illustrated above takes no arguments. This convention simplifies Objective-C source code. You don’t need to pass them to the method as arguments.4 and earlier. You should therefore not rely on the return value of messages sent to nil unless the method’s return type is an object. as long as the message returns an object. If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined. For example.. If the message sent to nil returns anything other than the aforementioned value types (for example.5. messages in Objective-C appear in the same syntactic positions as function calls in standard C.0 for every field in the data structure. if it returns any struct type. as defined by the Mac OS X ABI Function Call Guide to be returned in registers. 18 Object Messaging 2009-10-19 | © 2009 Apple Inc. or any integer scalar of size less than or equal to sizeof(void*). without having to declare them as arguments. id anObjectMaybeNil = nil. because methods “belong to” an object. } Note: The behavior of sending messages to nil changed slightly with Mac OS X v10. and Messaging ■ If the method returns a struct. ■ The following code fragment illustrates valid use of sending a message to nil. they don’t need to bring the receiver to itself. The primaryColor and isFilled methods shown above are used for just this purpose.0) { // implementation continues. . any floating-point type. Every method assumes the receiver and its instance variables. If it requires information about a variable stored in another object. The Receiver’s Instance Variables A method has automatic access to the receiving object’s instance variables. Other struct data types will not be filled with zeros.
The message goes to whatever object controls the current selection. A Circle and a Rectangle would respond differently to identical instructions to track the cursor. An object that displays text would react to a copy message differently from an object that displays scanned images.) This dynamic binding of methods to messages works hand-in-hand with polymorphism to give object-oriented programming much of its flexibility and power. receivers can be decided “on the fly” and can be made dependent on external factors such as user actions. Together with dynamic binding. without you having to choose at the time you write the code what kinds of objects they might be. This means that two objects can respond differently to the same message. This is information the receiver is able to reveal at runtime when it receives a message (dynamic typing). a program can achieve a variety of results. see Messaging in the Objective-C Runtime Programming Guide. The precise method that a message invokes depends on the receiver. but a message and a receiving object aren’t united until the program is running and the message is sent. plays a significant role in the design of object-oriented programs. the exact method that’s invoked to respond to a message can only be determined at runtime. and passes it a pointer to the receiver’s instance variables. When a message is sent. Copy. It can’t confuse them with methods defined for other kinds of object. An object that represents a set of shapes would respond differently from a Rectangle. each kind of object sent a display message could display itself in a unique way. but by varying just the object that receives the message. for example. an object can be operated on by only those methods that were defined for it. Each application can invent its own objects that respond in their own way to copy messages. If you write code that sends a display message to an id variable. Since each object can have its own version of a method. a runtime messaging routine looks at the receiver and at the method named in the message. Object Messaging 2009-10-19 | © 2009 Apple Inc. “calls” the method. it doesn’t even have to enumerate the possibilities. it would have to know what kind of object the receiver is—what class it belongs to. They might even be objects that will be developed later. by other programmers working on other projects. Since messages don’t select methods (methods aren’t bound to messages) until runtime. This can be done as the program runs. even if another object has a method with the same name. For the compiler to find the right method implementation for a message. This is discussed in the section Messaging in the Objective-C Runtime Programming Guide. The selection of a method implementation happens at runtime. The code that sends the message doesn’t have to be concerned with them. not by varying the message itself. When executing code based upon the Application Kit. For example. It locates the receiver’s implementation of a method matching the name. Classes. it permits you to write code that might apply to any number of different kinds of objects. but it’s not available from the type declarations found in source code. these differences are isolated in the methods that respond to the message. and Paste. All Rights Reserved. 19 . Dynamic Binding A crucial difference between function calls and messages is that a function and its arguments are joined together in the compiled code. referred to as polymorphism. not when the code is compiled. any object that has a display method is a potential receiver. Different receivers may have different method implementations for the same method name (polymorphism). Therefore. users determine which objects receive messages from menu commands like Cut. Objective-C takes dynamic binding one step further and allows even the message that’s sent (the method selector) to be a variable that’s determined at runtime.CHAPTER 1 Objects. and Messaging In particular. (For more on this routine. This feature.
10.0. and Messaging Dynamic Method Resolution You can provide implementations of class and instance methods at runtime using dynamic method resolution. CGFloat xLoc = graphic.0.xLoc. as illustrated in the following example. .) operator. The code example above is exactly equivalent to the following: [myInstance setValue:10]. printf("myInstance value: %d". The dot syntax is purely “syntactic sugar”—it is transformed by the compiler into invocation of accessor methods (so you are not actually accessing an instance variable directly). Using the Dot Syntax Overview You can use the dot syntax to invoke accessor methods using the same pattern as accessing structure elements as illustrated in the following example: myInstance. General Use You can read and write properties using the dot (. BOOL hidden = graphic.color. It is particularly useful when you want to access or modify a property that is a property of another object (that is a property of another object. All Rights Reserved.0). Listing 1-1 Accessing properties using the dot syntax Graphic *graphic = [[Graphic alloc] init].0. and so on). Classes.value).) 20 Object Messaging 2009-10-19 | © 2009 Apple Inc. 20. } graphic.text. myInstance. int textCharacterLength = graphic.hidden. (@"Hello" is a constant NSString object—see “Compiler Directives” (page 118). See Dynamic Method Resolution in the Objective-C Runtime Programming Guide for more details.length. [myInstance value]).textHidden != YES) { graphic. printf("myInstance value: %d".) operator that offers a compact and convenient syntax you can use as an alternative to square bracket notation ([]s) to invoke accessor methods.text = @"Hello". NSColor *color = graphic.CHAPTER 1 Objects.value = 10. Dot Syntax Objective-C provides a dot (. 120.bounds = NSMakeRect(10. if (graphic.
0. CGFloat xLoc = [graphic xLoc]. the statement is treated as an undeclared property error. setProperty:). property) and setting it calls the set method associated with the property (by default. Despite appearances to the contrary. which will fail at runtime. 20. data. as long as they all have the same type (such as BOOL) then it is legal. NSColor *color = [graphic color]. 21 . // z is an undeclared property Note that y is untyped and the z property is undeclared. All Rights Reserved. [data setLength:[data length] / 4]. and Messaging Accessing a property property calls the get method associated with the property (by default. BOOL hidden = [graphic hidden]. if ([graphic isTextHidden] != YES) { [graphic setText:@"Hello"]. You can change the methods that are invoked by using the Declared Properties feature (see “Declared Properties” (page 67)). whereas at best it can only generate an undeclared method warning that you invoked a non-existent setProperty: method.length /= 4. then it is not ambiguous if there's only one declaration of a z property in the current compilation unit. There are several ways in which this could be interpreted. Classes. the dot syntax therefore preserves encapsulation—you are not accessing an instance variable directly. int textCharacterLength = [[graphic text] length].0. you could update the length property of an instance of NSMutableData using compound assignments: NSMutableData *data = [NSMutableData dataWithLength:1024]. data. 120.length *= 2. x = y.length += 1024. There is one case where properties cannot be used.CHAPTER 1 Objects. data. For properties of the appropriate C language type. One source of ambiguity would also arise from one of them being declared readonly. Object Messaging 2009-10-19 | © 2009 Apple Inc. For example.0. which is equivalent to: [data setLength:[data length] + 1024]. [data setLength:[data length] * 2]. If there are multiple declarations of a z property. 10. } [graphic setBounds:NSMakeRect(10. Consider the following code fragment: id y. If z is declared.z. The following statements compile to exactly the same code as the statements shown in Listing 1-1 (page 20). but use square bracket syntax: Listing 1-2 Accessing properties using bracket syntax Graphic *graphic = [[Graphic alloc] init]. the meaning of compound assignments is well-defined.0)]. Since this is ambiguous. An advantage of the dot syntax is that the compiler can signal an error when it detects a write to a read-only property.
xOrigin = aView. self If you want to access a property of self using accessor methods. you must explicitly call out self as illustrated in this example: self..y. if the property name does not exist. .name = @"Oxford Road". x = [[[person address] street] name]. The type of the property aProperty and the type of aVariable must be compatible. // the path contains a C struct // will crash if window is nil or -contentView returns nil y = window..address.. or if setName: returns anything but void. passing @"New Name" as the argument.CHAPTER 1 Objects.. For example.origin. All Rights Reserved. // an example of using a setter. Invokes the setName: method on anObject. Invokes the aProperty method and assigns the return value to aVariable. the set accessor method for the age property is not invoked: age = 10. person. Since the dot syntax simply invokes methods. Classes. If you do not use self. anObject.origin.origin. Invokes the bounds method and assigns xOrigin to be the value of the origin.name. 22 Object Messaging 2009-10-19 | © 2009 Apple Inc.y. Performance and Threading The dot syntax generates code equivalent to the standard method invocation syntax. you access the instance variable directly.x.street.x structure element of the NSRect returned by bounds. [[[person address] street] setName: @"Oxford Road"]. and Messaging nil Values If a nil value is encountered during property traversal. code using the dot syntax performs exactly the same as code written directly using the accessor methods.bounds. the result is the same as sending the equivalent message to nil.aProperty.age = 10.contentView. As a result.bounds. y = [[window contentView] bounds]. Usage Summary aVariable = anObject.name = @"New Name". In the following example. otherwise you get a compiler warning.street.address. no additional thread dependencies are introduced as a result of its use. the following pairs are all equivalent: // each member of the path is an object x = person. You get a compiler warning if setName: does not exist.
integerProperty = anotherObject.(void) setReadonlyProperty: (NSInteger)newValue. 23 . and Messaging NSInteger i = 10. but simply adding a setter for a property does not imply readwrite. for example. it will work at runtime. NSDictionary objects. and it defines a set of methods that all objects in the class can use. Classes An object-oriented program is typically built from a variety of objects. Since the property is declared readonly. it declares the instance variables that become part of every member of the class. this code generates a compiler warning (warning: assignment to readonly property 'readonlyProperty'). A program based on the Cocoa frameworks might use NSMatrix objects.).readonlyProperty = 5. /* method declaration */ .floatProperty = ++i. Because the setter method is present.floatProperty.retain. The pre-evaluated result is coerced as required at each point of assignment. you define objects by defining their class. Generates a compiler warning that setFooIfYouCan: does not appear to be a setter method because it does not return (void). Invokes lockFocusIfCanDraw and assigns the return value to flag.lockFocusIfCanDraw. /* property declaration */ @property(readonly) NSInteger readonlyProperty. Classes. Incorrect Use The following patterns are strongly discouraged. Generates a compiler warning (warning: value returned from property not used.fooIfYouCan = myInstance. NSText objects. Classes 2009-10-19 | © 2009 Apple Inc. anObject. flag = aView. Programs often use more than one object of the same kind or class—several NSArray objects or NSWindow objects. /* code fragment */ anObject.CHAPTER 1 Objects. anObject. In Objective-C. All Rights Reserved. NSFont objects. /* code fragment */ self. That is. the right hand side of the assignment is pre-evaluated and the result is passed to setIntegerProperty: and setFloatProperty:. and many others. /* method declaration */ . This does not generate a compiler warning unless flag’s type mismatches the method’s return type.(BOOL) setFooIfYouCan: (MyClass *)newFoo. The class definition is a prototype for a kind of object. Assigns 11 to both anObject.integerProperty and anotherObject. NSWindow objects.
class names begin with an uppercase letter (such as “Rectangle”). and Messaging The compiler creates just one accessible object for each class. Graphic. and an NSObject. Figure 1-1 illustrates the hierarchy for a few of the classes used in the drawing program. a Graphic. the names of instances typically begin with a lowercase letter (such as “myRectangle”). All instances of a class have the same set of methods. each new class that you define is based on another class from which it inherits methods and instance variables. a Shape. Each object gets its own instance variables. . Classes. It doesn’t need to duplicate inherited code.”) The class object is the compiled version of the class. and Graphic is a subclass of NSObject. it’s also a Rectangle. Shape. By convention. that root class is typically NSObject. So a Square object has the methods and instance variables defined for Rectangle. Inheritance links all classes together in a hierarchical tree with a single class at its root. (For this reason it’s traditionally called a “factory object. When writing code that is based upon the Foundation framework. Inheritance Class definitions are additive. Every class (except a root class) has a superclass one step nearer the root. but the methods are shared. The Square class defines only the minimum needed to turn a Rectangle into a Square. The new class simply adds to or modifies what it inherits. and NSObject. All Rights Reserved. Figure 1-1 Some Drawing Program Classes NSObject Graphic Image Text Shape Line Rectangle Square Circle This figure shows that the Square class is a subclass of the Rectangle class. a class object that knows how to build new objects belonging to the class. and any class (including a root class) can be the superclass for any number of subclasses one step farther from the root.CHAPTER 1 Objects. the Rectangle class is a subclass of Shape. the objects it builds are instances of the class. Each successive subclass further modifies the cumulative total of what’s inherited. Shape is a subclass of Graphic. as well as those defined specifically for Square. This is simply to say that a Square object isn’t only a Square. Inheritance is cumulative. The objects that do the main work of your program are instances created by the class object at runtime. 24 Classes 2009-10-19 | © 2009 Apple Inc. Every class but NSObject can thus be seen as a specialization or an adaptation of another class. and they all have a set of instance variables cut from the same mold.
The class must duplicate much of what the NSObject class does. width. Inheriting this ability from the NSObject class is much simpler and much more reliable than reinventing it in a new class definition. Note that the variables that make the object a Rectangle are added to the ones that make it a Shape.. Plenty of potential superclasses are available. For more information. the isa instance variable defined in the NSObject class becomes part of every object. and identify them to the runtime system. linePattern. Figure 1-2 Class NSPoint NSColor Pattern . All Rights Reserved.. *fillColor. Instances of the class must at least have the ability to behave like Objective-C objects at runtime. filled. Others you might want to adapt to your own needs by defining a subclass. you link it to the hierarchy by declaring its superclass. and so on. 25 . A class that doesn’t need to inherit any special behavior from another class should nevertheless be made a subclass of the NSObject class. Rectangle Instance Variables isa. Thus. Note: Implementing a new root class is a delicate task and one with many hidden hazards. declared in NSObject declared in Graphic declared in Shape declared in Rectangle Classes 2009-10-19 | © 2009 Apple Inc. and the ones that make it a Shape are added to the ones that make it a Graphic. and reusing work done by the programmers of the framework. all the way back to the root class.. and Messaging When you define a class. see the Foundation framework documentation for the NSObject class and the NSObject protocol. Classes. The NSObject Class NSObject is a root class. origin. For this reason. *primaryColor. You can thus create very sophisticated objects by writing only a small amount of code. the new object contains not only the instance variables that were defined for its class but also the instance variables defined for its superclass and for its superclass’s superclass. Figure 1-2 shows some of the instance variables that could be defined for a particular implementation of Rectangle. It imparts to the classes and instances of classes that inherit from it the ability to behave as objects and cooperate with the runtime system. and where they may come from. but leave some specifics to be implemented in a subclass. connect them to their class. Some framework classes define almost everything you need. and so doesn’t have a superclass. Cocoa includes the NSObject class and several frameworks containing definitions for more than 250 additional classes. It defines the basic framework for Objective-C objects and object interactions. Inheriting Instance Variables When a class object creates a new instance. every class you create must be the subclass of another class (unless you define a new root class). height. Some are classes that you can use “off the shelf”—incorporate into your program as is.CHAPTER 1 Objects. you should generally use the NSObject class provided with Cocoa as the root class. float float BOOL NSColor .. isa connects each object to its class. such as allocate instances.
A redefined method can also incorporate the very method it overrides. This type of inheritance is a major benefit of object-oriented programming. Although overriding a method blocks the original version from being inherited. . the implementation of the method is effectively spread over all the classes. and NSObject classes as well as methods defined in its own class. Graphic defines a display method that Rectangle overrides by defining its own version of display. You have to add only the code that customizes the standard functionality to your application. you can implement a new method with the same name as one defined in a class farther up the hierarchy. a Square object can use methods defined in the Rectangle. the compiler will complain. Shape. which instead perform the Rectangle version of display. If you try. your programs can take advantage of the basic functionality coded into the framework classes. The abstract class is typically incomplete by itself. Graphic.) 26 Classes 2009-10-19 | © 2009 Apple Inc. (Because abstract classes must have subclasses to be useful. but also to methods defined for its superclass. if it needs any instance variables at all. Overriding One Method With Another There’s one useful exception to inheritance: When you define a new class. Since an object has memory allocated for every instance variable it inherits. When it does. and Messaging A class doesn’t have to declare instance variables. These abstract classes group methods and instance variables that can be used by a number of different subclasses into a common definition. When several classes in the hierarchy define the same method. and subclasses of the new class inherit it rather than the original. instances of the new class perform it rather than the original. the new method serves only to refine or modify the method it overrides. For instance. and for its superclass’s superclass. For example. but contains useful code that reduces the implementation burden of its subclasses. Any new class you define in your program can therefore make use of the code written for all the classes above it in the hierarchy. Square might not declare any new instance variables of its own. When you use one of the object-oriented frameworks provided by Cocoa. Class objects also inherit from the classes above them in the hierarchy. For example. they’re sometimes also called abstract superclasses. All Rights Reserved. But because they don’t have instance variables (only instances do). The Graphic method is available to all kinds of objects that inherit from the Graphic class—but not to Rectangle objects. other methods defined in the new class can skip over the redefined method and find the original (see “Messages to self and super” (page 43) to learn how). Although a subclass can override inherited methods. you can’t override an inherited variable by declaring a new one with the same name. all the way back to the root of the hierarchy.CHAPTER 1 Objects. but each new version incorporates the version it overrides. they inherit only methods. It can simply define new methods and rely on the instance variables it inherits. it can’t override inherited instance variables. Classes. The new method overrides the original. Inheriting Methods An object has access not only to the methods defined for its class. Abstract Classes Some classes are designed only or primarily so that other classes can inherit from them. rather than replace it outright.
See “Enabling Static Behavior” (page 91) for more on static typing and its benefits. defines a data type. Static typing makes the pointer explicit. A class name can appear in source code wherever a type specifier is permitted in C—for example. but at runtime it’s treated as a Rectangle. For example. Static typing permits the compiler to do some type checking—for example. a Rectangle instance could be statically typed to the Graphic class: Graphic *myRectangle. Static Typing You can use a class name in place of id to designate an object’s type: Rectangle *myRectangle. In addition. as an argument to the sizeof operator: int i = sizeof(Rectangle).CHAPTER 1 Objects. in effect. You never use instances of the NSObject class in an application—it wouldn’t be good for anything. Objective-C does not have syntax to mark classes as abstract. However. it doesn’t defeat dynamic binding or alter the dynamic determination of a receiver’s class at runtime. Abstract classes often contain code that helps define the structure of an application. nor does it prevent you from creating an instance of an abstract class. on the other hand. it can make your intentions clearer to others who read your source code. Objects are always typed by a pointer. it’s known as static typing. since inheritance makes a Rectangle a kind of Graphic. to warn if an object could receive a message that it appears not to be able to respond to—and to loosen some restrictions that apply to objects generically typed id. Classes. When you create subclasses of these classes. 27 . Class Types A class definition is a specification for a kind of object. provides an example of an abstract class instances of which you might occasionally use directly. The NSObject class is the canonical example of an abstract class in Cocoa. the compiler considers myRectangle to be a Graphic. but it’s a Graphic nonetheless. Because this way of declaring an object type gives the compiler information about the kind of object it is. An object can be statically typed to its own class or to any class that it inherits from. The type is based not just on the data structure the class defines (instance variables). The NSView class. The class. it would be a generic object with the ability to do nothing in particular. For purposes of type checking. instances of your new classes fit effortlessly into the application structure and work automatically with other objects. Classes 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. This is possible because a Rectangle is a Graphic. id hides it. objects are statically typed as pointers to a class. and Messaging Unlike some other languages. Just as id is actually a pointer. but also on the behavior included in the definition (methods). It’s more than a Graphic since it also has the instance variables and method capabilities of a Shape and a Rectangle.
. and related methods. The compiler creates just one object. The class object has access to all the information about the class. Later sections of this chapter discuss methods that return the class object. just as instances inherit instance methods. The set of classes for which isKindOfClass: returns YES is the same set to which the receiver can be statically typed. In the following example.. isMemberOfClass:. All Rights Reserved. Elsewhere. A class object inherits class methods from the classes above it in the hierarchy. and Messaging Type Introspection Instances can reveal their types at runtime. Classes. report whether an object can respond to a message. it’s not an instance itself.. the class object is represented by the class name.CHAPTER 1 Objects. It’s able to produce new instances according to the plan put forward in the class definition. Class Objects A class definition contains various kinds of information. Introspection isn’t limited to type information. defined in the NSObject class. to represent the class. the class name stands for the class object only as the receiver in a message expression. In source code. The isMemberOfClass: method.. the Rectangle class returns the class version number using a method inherited from the NSObject class: int versionNumber = [Rectangle version]. Although a class object keeps the prototype of a class instance. . checks more generally whether the receiver inherits from or is a member of a particular class (whether it has the class in its inheritance path): if ( [anObject isKindOfClass:someClass] ) . a class definition can include methods intended specifically for the class object—class methods as opposed to instance methods. However. which means mainly information about what instances of the class are like. checks whether the receiver is an instance of a particular class: if ( [anObject isMemberOfClass:someClass] ) . It has no instance variables of its own and it can’t perform methods intended for instances of the class. you need to ask an instance or the class to return the class id. 28 Classes 2009-10-19 | © 2009 Apple Inc. See the NSObject class specification in the Foundation framework reference for more on isKindOfClass:. The isKindOfClass: method. also defined in the NSObject class. However.. Both respond to a class message: id aClass = [anObject class]. and reveal other information. a class object.
it generally needs to be more completely initialized. the metaclass object is used only internally by the runtime system. It describes the class object just as the class object describes instances of the class. That’s the function of an init method. The alloc method returns a new instance and that instance performs an init method to set its initial state. and are the agents for producing instances at runtime. where the class belongs to an open-ended set. It’s possible. and sometimes surprising. for example. and every instance has at least one method (like init) that prepares it for use. but they all begin with “init” . In the Application Kit. benefits for design. except the isa variable that connects the new instance to its class. receive messages. As these examples show. and Messaging id rectClass = [Rectangle class]. All Rights Reserved. is a method that might initialize a new Rectangle instance). Customization With Class Objects It’s not just a whim of the Objective-C language that classes are treated as objects. Initialization typically follows immediately after allocation: myRectangle = [[Rectangle alloc] init].CHAPTER 1 Objects. that is. But class objects can also be more specifically typed to the Class data type: Class aClass = [anObject class]. The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all. like all other objects. would be necessary before myRectangle could receive any of the messages that were illustrated in previous examples in this chapter. 29 . Class objects are thus full-fledged objects that can be dynamically typed. Classes. They’re special only in that they’re created by the compiler. myRectangle = [Rectangle alloc]. to customize an object with a class. an NSMatrix object can be customized with a particular kind of NSCell object. But while you can send messages to instances and to the class object. be typed id. for example. for example. Note: The compiler also builds a “metaclass object” for each class. and inherit methods from other classes. This line of code. Initialization methods often take arguments to allow particular values to be passed and have keywords to label the arguments (initWithPosition:size:. It’s a choice that has intended. Creating Instances A principal function of a class object is to create new instances. Every class object has at least one method (like alloc) that enables it to produce new objects. Classes 2009-10-19 | © 2009 Apple Inc. Using this type name for a class is equivalent to using the class name to statically type an instance. For an object to be useful. class objects can. All class objects are of type Class. Class rectClass = [Rectangle class]. This code tells the Rectangle class to create a new Rectangle instance and assign it to the myRectangle variable: id myRectangle. lack data structures (instance variables) of their own other than those built from the class definition. or one like it.
It can do this when the matrix is first initialized and later when new cells are needed. is to allow NSMatrix instances to be initialized with a kind of NSCell—with a class object. you’d also have to define a new kind of NSMatrix.CHAPTER 1 Objects. But this requires others to do work that ought to be done in the NSMatrix class. NSTextFieldCell objects to display fields where the user can enter and edit text. The visible matrix that an NSMatrix object draws on the screen can grow and shrink at runtime. Classes. perhaps in response to user actions. The inheritance hierarchy in Figure 1-3 shows some of those provided by the Application Kit. Moreover. the solution the NSMatrix class actually adopts. and it unnecessarily proliferates the number of classes. each with a different kind of NSCell. A better solution. All Rights Reserved. Because they would be implementing the methods. but there are many different kinds. programmers on different projects would be writing virtually identical code to do the same job. Since an application might need more than one kind of NSMatrix. and Messaging An NSMatrix object can take responsibility for creating the individual objects that represent its cells. The NSMatrix object uses the class object to produce new cells when it’s first initialized and whenever it’s resized to contain more cells. all to make up for NSMatrix's failure to do it. Every time you invented a new kind of NSCell. the matrix needs to be able to produce new objects to fill the new slots that are added. When it grows. . 30 Classes 2009-10-19 | © 2009 Apple Inc. or some other kind of NSCell? The NSMatrix object must allow for any kind of cell. But what kind of objects should they be? Each matrix displays just one kind of NSCell. It defines a setCellClass: method that passes the class object for the kind of NSCell object an NSMatrix should use to fill empty slots: [myMatrix setCellClass:[NSButtonCell class]]. One solution to this problem is to define the NSMatrix class as an abstract class and require everyone who uses it to declare a subclass and implement the methods that produce new cells. This kind of customization would be difficult if classes weren’t objects that could be passed in messages and assigned to variables. users of the class could be sure that the objects they created were of the right type. even types that haven’t been invented yet. should they be NSButtonCell objects to display a bank of buttons or switches.. it could become cluttered with NSMatrix subclasses.
you must define an external variable of some sort. subclasses. the initialize method could set up the array and even allocate one or two default instances to have them ready. are provided for the class. if a class maintains an array of instances. static variables cannot be inherited by. static MyClass *MCLSSharedInstance. you can specify instance variables. you can declare a variable to be static. This saves the step of allocating and initializing an instance. a class object has no access to the instance variables of any instances. see “Creating a Singleton Instance” in Cocoa Fundamentals Guide). it can’t initialize. If a class makes use of static or global variables. you can put all the object’s state into static variables and use only class methods. and provide class methods to manage it. Note: It is also possible to use external variables that are not declared static. initialized from the class definition. The simplest way to do this is to declare a variable in the class implementation file as illustrated in the following code fragment. For example. int MCLSGlobalVariable. the initialize method is a good place to set their initial values.) This pattern is commonly used to define shared instances of a class (such as singletons. or alter them. (Thus unlike instance variables. In the case when you need only one object of a particular class. Only internal data structures. it can approach being a complete and versatile object in its own right. @implementation MyClass // implementation continues In a more sophisticated implementation. or directly manipulated by. Although programs don’t allocate class objects. or manage other processes essential to the application. Objective-C does provide a way for programs to initialize them. Moreover. A class object can be used to coordinate the instances it creates. Classes. 31 . but the limited scope of static variables better serves the purpose of encapsulating data into separate objects. no “class variable” counterpart to an instance variable. read. } // implementation continues Static variables help give the class object more functionality than just that of a “factory” producing instances. however. and Messaging Variables and Class Objects When you define a new class. For all the instances of a class to share data. All Rights Reserved. Declaring a variable static limits its scope to just the class—and to just the part of the class that’s implemented in the file.CHAPTER 1 Objects. you may need to initialize it just as you would an instance. Every instance of the class can maintain its own copy of the variables you declare—each object controls its own data. There is. Initializing a Class Object If you want to use a class object for anything besides allocating instances. @implementation MyClass + (MyClass *)sharedInstance { // check for existence of shared instance // create if necessary return MCLSSharedInstance. Classes 2009-10-19 | © 2009 Apple Inc. dispense instances from lists of objects already created.
So that NSObject's methods don’t have to be implemented twice—once to provide a runtime interface for instances and again to duplicate that interface for class objects—class objects are given special dispensation to perform instance methods defined in the root class. Therefore.. the runtime system determines whether there’s a root instance method that can respond. . . If no initialization is required. The only instance methods that a class object can perform are those defined in the root class. This gives the class a chance to set up its runtime environment before it’s used.CHAPTER 1 Objects. For example. the runtime system sends initialize to it. you don’t need to write an initialize method to respond to the message. All Rights Reserved. class names can be used in only two very different contexts. use the template in Listing 1-3 when implementing the initialize method. Listing 1-3 Implementation of the initialize method + (void)initialize { if (self == [ThisClass class]) { // Perform initialization here. Because of inheritance. and for the appropriate class. These contexts reflect the dual role of a class as a data type and as an object: 32 Classes 2009-10-19 | © 2009 Apple Inc. Classes.. assume class A implements the initialize method. see the NSObject class specification in the Foundation framework reference. class A should ensure that its initialization logic is performed only once. because class B doesn’t implement initialize. } } Note: Remember that the runtime system sends initialize to each class individually. Therefore. To avoid performing initialization logic more than once. Methods of the Root Class All objects. even though the superclass has already received the initialize message. and only if there’s no class method that can do the job. in a class’s implementation of the initialize method. Just before class B is to receive its first message. and class B inherits from class A but does not implement the initialize method. an initialize message sent to a class that doesn’t implement the initialize method is forwarded to the superclass. When a class object receives a message that it can’t respond to with a class method. need an interface to the runtime system. classes and instances alike. Both class objects and instances should be able to introspect about their abilities and to report their place in the inheritance hierarchy. and Messaging The runtime system sends an initialize message to every class object before the class receives any other messages and after its superclass has received the initialize message. class A’s initialize is executed instead. But. It’s the province of the NSObject class to provide this interface. For more on this peculiar ability of class objects to perform root instance methods. you must not send the initialize message to its superclass. Class Names in Source Code In source code.
This function returns nil if the string it’s passed is not a valid class name. 33 . If you don’t know the class name at compile time but have it as a string at runtime... Classnames are about the only names with global visibility in Objective-C. the class name refers to the class object. Testing Class Equality You can test two class objects for equality using a direct pointer comparison. Here anObject is statically typed to be a pointer to a Rectangle. you must ask the class object to reveal its id (by sending it a class message). since they aren’t members of a class. Classes. All Rights Reserved. Classnames exist in the same namespace as global variables and function names.. The compiler expects it to have the data structure of a Rectangle instance and the instance methods defined and inherited by the Rectangle class. When this happens. The class name can stand for the class object only as a message receiver.. There are several features in the Cocoa frameworks that dynamically and transparently subclass existing classes to extend their functionality (for example. Static typing enables the compiler to do better type checking and makes source code more self-documenting. See “Enabling Static Behavior” (page 91) for details. Classes 2009-10-19 | © 2009 Apple Inc. The example below passes the Rectangle class as an argument in an isKindOfClass: message. In any other context. to get the correct class. It is important. When testing for class equality. A class and a global variable can’t have the same name.. Put in terms of API: [object class] != object_getClass(object) != *((Class*)object) You should therefore test two classes for equality as follows: if ([objectA class] == [objectB class]) { //. and Messaging ■ The class name can be used as a type name for a kind of object..CHAPTER 1 Objects. key-value observing and Core Data—see Key-Value Observing Programming Guide and Core Data Programming Guide respectively). It would have been illegal to simply use the name “Rectangle” as the argument. you should therefore compare the values returned by the class method rather those returned by lower-level functions. Only instances can be statically typed. but rather belong to the Class data type. For example: Rectangle *anObject. ■ As the receiver in a message expression. class objects can’t be. The class name can only be a receiver. you can use NSClassFromString to return the class object: NSString *className. if ( [anObject isKindOfClass:NSClassFromString(className)] ) . the class method is typically overridden such that the dynamic subclass masquerades as the class it replaces.. This usage was illustrated in several of the earlier examples.. if ( [anObject isKindOfClass:[Rectangle class]] ) . though. .
All Rights Reserved. .CHAPTER 1 Objects. Classes. and Messaging 34 Classes 2009-10-19 | © 2009 Apple Inc.
Separating an object’s interface from its implementation fits well with the design of object-oriented programs.m extension.h and defined in Rectangle. Categories are described in “Categories and Extensions” (page 79). classes are defined in two parts: ■ ■ An interface that declares the methods and instance variables of the class and names its superclass An implementation that actually defines the class (contains the code that implements its methods) These are typically split between two files.h extension typical of header files. Class Interface The declaration of a class interface begins with the compiler directive @interface and ends with the directive @end. sometimes however a class definition may span several files through the use of a feature called a “category.m. the name of the interface file usually has the . A single file can declare or implement more than one class. it’s customary to have a separate interface file for each class.” Once you’ve determined how an object interacts with other elements in your program—that is. indicating that it contains Objective-C source code. the interface and implementation are usually separated into two different files.” Categories can compartmentalize a class definition or extend an existing one. the Rectangle class would be declared in Rectangle. Interface and implementation files typically are named after the class. Because it’s included in other source files. 35 .) @interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end Source Files 2009-10-19 | © 2009 Apple Inc. Nevertheless. once you’ve declared its interface—you can freely alter its implementation without affecting any other part of the application. In Objective-C. (All Objective-C directives to the compiler begin with “@” . if not also a separate implementation file. An object is a self-contained entity that can be viewed from the outside almost as a “black box. For example. Source Files Although the compiler doesn’t require it. The interface file must be made available to anyone who uses the class. The name of the implementation file has the . The interface file can be assigned any other extension. Keeping class interfaces separate better reflects their status as independent entities.CHAPTER 2 Defining a Class Much of object-oriented programming consists of writing the code for new objects—defining new classes. All Rights Reserved.
For example: . class methods. it’s assumed to be the default type for methods and messages—an id. Circle has a radius method that could match a radius instance variable. For example. 36 Class Interface 2009-10-19 | © 2009 Apple Inc. If a return or argument type isn’t explicitly declared. .. braces enclose declarations of instance variables. as discussed under “Inheritance” (page 24).(void)setRadius:(float)aRadius. The names of methods that can be used by class objects. Argument types are declared in the same way: .makeGroup:group. The alloc method illustrated earlier returns id. Method return types are declared using the standard C syntax for casting one type to another: . Here’s a partial list of instance variables that might be declared in the Rectangle class: float width. Following the first part of the class declaration. just as a function would: . . you can define a class method and an instance method with the same name.. especially if the method returns the value in the variable.. If the colon and superclass name are omitted.CHAPTER 2 Defining a Class The first line of the declaration presents the new class name and links it to its superclass. a rival to the NSObject class. Arguments break the name apart in the declaration. This is more common. after the braces enclosing instance variables and before the end of the class declaration. are marked with a minus sign: . the new class is declared as a root class. The superclass defines the position of the new class in the inheritance hierarchy. Although it’s not a common practice. float height. Methods that take a variable number of arguments declare them using a comma and ellipsis points. NSColor *fillColor. the arguments are declared within the method name after the colons. the data structures that are part of each instance of the class. BOOL filled.(void)display. Methods for the class are declared next. A method can also have the same name as an instance variable. just as in a message. All Rights Reserved. instance methods. The methods that instances of a class can use. When there’s more than one argument.(float)radius.(void)setWidth:(float)width height:(float)height. are preceded by a plus sign: + alloc.
by importing its superclass. Class Interface 2009-10-19 | © 2009 Apple Inc. it gets interfaces for the entire inheritance hierarchy that the class is built upon.(void)setPrimaryColor:(NSColor *)aColor. you may prefer to import the precomp instead. implicitly contains declarations for all inherited classes. Note that if there is a precomp—a precompiled header—that supports the superclass. mentions the NSColor class. the interface files for all inherited classes. and arguments. or mentions an instance variable declared in the class. Referring to Other Classes An interface file declares a class and. this declaration . This directive simply informs the compiler that “Rectangle” and “Circle” are class names. the @class directive gives the compiler sufficient forewarning of what to expect. sends a message to invoke a method declared for the class. It doesn’t import their interface files. it must import them explicitly or declare them with the @class directive: @class Rectangle. except that it makes sure that the same file is never included more than once. an interface file begins by importing the interface for its superclass: #import "ItsSuperclass. When a source module imports a class interface. Circle. from NSObject on down through its superclass. It’s therefore preferred and is used in place of #include in code examples throughout Objective-C–based documentation. indirectly. If the interface mentions classes not in this hierarchy. The interface is usually included with the #import directive: #import "Rectangle. An interface file mentions class names when it statically types instance variables.h" @interface ClassName : ItsSuperclass { instance variable declarations } method declarations @end This convention means that every interface file includes. messages sent). All Rights Reserved.h" This directive is identical to #include. However. To reflect the fact that a class definition builds on the definitions of inherited classes. where the interface to a class is actually used (instances created. return values. 37 . Since declarations like this simply use the class name as a type and don’t depend on any details of the class interface (its methods and instance variables). For example.CHAPTER 2 Defining a Class Importing the Interface The interface file must be included in any source module that depends on the class interface—that includes any module that creates an instance of the class.
Although instance variables are most naturally viewed as a matter of the implementation of a class rather than its interface.CHAPTER 2 Defining a Class the class interface must be imported. The @class directive minimizes the amount of code seen by the compiler and linker. All Rights Reserved.m imports Rectangle. As a programmer. . it avoids potential problems that may come with importing files that import still other files. This is because the compiler must be aware of the structure of an object where it’s used. and the corresponding implementation file imports their interfaces (since it will need to create instances of those classes or send them messages). ■ The interface file tells users how the class is connected into the inheritance hierarchy and what other classes—inherited or simply referred to somewhere in the class—are needed. Every method that can be used outside the class definition is declared in the interface file. Because the implementation doesn’t need to repeat any of the declarations it imports. through its list of method declarations. an interface file uses @class to declare classes. The Role of the Interface The purpose of the interface file is to declare the new class to other source modules (and to other programmers). they must nevertheless be declared in the interface file. not just where it’s defined. except when defining a subclass. Finally. Typically. methods that are internal to the class implementation can be omitted. if one class declares a statically typed instance variable of another class. For example.h. and tells programmers what variables subclasses inherit. It contains all the information they need to work with the class (programmers might also appreciate a little documentation). every implementation file must import its own interface. Rectangle. and their two interface files import each other. the interface file lets other modules know what messages can be sent to the class object and instances of the class. The interface file also lets the compiler know what instance variables an object contains. neither class may compile correctly. ■ ■ Class Implementation The definition of a class is structured very much like its declaration. Being simple. however. you can generally ignore the instance variables of the classes you use. and is therefore the simplest way to give a forward declaration of a class name. It begins with the @implementation directive and ends with the @end directive: @implementation ClassName : ItsSuperclass { instance variable declarations } method definitions @end However. For example. it can safely omit: ■ ■ The name of the superclass The declarations of instance variables 38 Class Implementation 2009-10-19 | © 2009 Apple Inc.
. 39 . } Neither the receiving object nor its filled instance variable is declared as an argument to this method.. . the definition of an instance method has all the instance variables of the object within its scope..(void)setFilled:(BOOL)flag { filled = flag.h> ... } Methods that take a variable number of arguments handle them just as a function would: #import <stdarg. . You don’t need either of the structure operators (. This simplification of method syntax is a significant shorthand in the writing of Objective-C code. va_start(ap.. Class Implementation 2009-10-19 | © 2009 Apple Inc. the exact nature of the structure is hidden.h" @implementation ClassName method definitions @end Methods for a class are defined.CHAPTER 2 Defining a Class This simplifies the implementation and makes it mainly devoted to method definitions: #import "ClassName. . } Referring to Instance Variables By default. ..(void)setFilled:(BOOL)flag { . } . Although the compiler creates the equivalent of C structures to store instance variables.. within a pair of braces. } .. { va_list ap. but without the semicolon... All Rights Reserved..(BOOL)isFilled { . like C functions. or ->) to refer to an object’s data. For example: + (id)alloc { . Before the braces. the following method definition refers to the receiver’s filled instance variable: .getGroup:group. they’re declared in the same manner as in the interface file... yet the instance variable falls within its scope. For example. It can refer to them simply by name. group).
it also lets you explicitly set the scope at three different levels. } return twin. All Rights Reserved. . Suppose. as an instance variable: @interface Sibling : NSObject { Sibling *twin.makeIdenticalTwin { if ( !twin ) { twin = [[Sibling alloc] init]. instance variables are more a matter of the way a class is implemented than of the way it’s used. that the Sibling class declares a statically typed object. int gender. these changes won’t really affect its interface. But to provide flexibility. Each level is marked by a compiler directive: Directive @private Meaning The instance variable is accessible only within the class that declares it. Often there’s a one-to-one correspondence between a method and an instance variable. To enforce the ability of an object to hide its data. As a class is revised from time to time. the compiler limits the scope of instance variables—that is. the structure pointer operator (->) is used. An object’s interface lies in its methods.CHAPTER 2 Defining a Class When the instance variable belongs to an object that’s not the receiver. } As long as the instance variables of the statically typed object are within the scope of the class (as they are here because twin is typed to the same class). twin->appearance = appearance. even though the methods it declares remain the same. As long as messages are the vehicle for interacting with instances of the class. the choice of instance variables may change. Some methods might return information not stored in instance variables. and some instance variables might store information that an object is unwilling to reveal. twin->gender = gender.(BOOL)isFilled { return filled. } The Scope of Instance Variables Although they’re declared in the class interface. In referring to the instance variable of a statically typed object. struct features *appearance. not in its internal data structures. the object’s type must be made explicit to the compiler through static typing. } But this need not be the case. a Sibling method can set them directly: . twin. for example. limits their visibility within the program. as in the following example: . 40 Class Implementation 2009-10-19 | © 2009 Apple Inc.
@private int age. All Rights Reserved. and wage are protected. up to the next directive or the end of the list. name.CHAPTER 2 Defining a Class Directive Meaning @protected The instance variable is accessible within the class that declares it and within classes that inherit it. This is most useful for instance variables in framework classes. Class Implementation 2009-10-19 | © 2009 Apple Inc. This is analogous to private_extern for variables and functions. 41 . but @private outside. @public @package The instance variable is accessible everywhere. where @private may be too restrictive but @protected or @public too permissive. @protected id job. char *evaluation. an @package instance variable acts like @public inside the image that implements the class. job. Figure 2-1 The scope of instance variables The class that declares the instance variable @private @protected A class that inherits the instance variable @public Unrelated code A directive applies to all the instance variables listed after it. In the following example. float wage. Using the modern runtime. This is illustrated in Figure 2-1. Any code outside the class implementation’s image that tries to use the instance variable will get a link error. the age and evaluation instance variables are private. and boss is public. @interface Worker : NSObject { char *name.
CHAPTER 2
Defining a Class
@public id boss; }
By default, all unmarked instance variables (like name above) are @protected. All instance variables:
■
Once a subclass accesses an inherited instance variable, the class that declares the variable is tied to that part of its implementation. In later versions, it can’t.
■
To limit an instance variable’s.
42
Class Implementation
CHAPTER 2
Defining a Class
Messages to self and super:
■
self searches for the method implementation in the usual manner, starting in the dispatch table of the
receiving object’s class. In the example above, it would begin with the class of the object receiving the reposition message.
■
.(id)init { if (self = [super init]) { . Mid’s designer wanted to use the High version of negotiate and no other. under the circumstances. All Rights Reserved. } For some tasks. But before doing so. it’s right to avoid it: ■ The author of the Low class intentionally overrode Mid’s version of negotiate so that instances of the Low class (and its subclasses) would invoke the redefined version of the method instead. } the messaging routine will find the version of negotiate defined in High. the author of Mid’s makeLastingPeace method intentionally skipped over Mid’s version of negotiate (and over any versions that might be defined in classes like Low that inherit from Mid) to perform the version defined in the High class. } } Messages to self and super 2009-10-19 | © 2009 Apple Inc. super provides a way to bypass a method that overrides another method. but. Here it enabled makeLastingPeace to avoid the Mid version of negotiate that redefined the original High version.negotiate { . In sending the message to super.. The designer of Low didn’t want Low objects to perform the inherited method. ■ Mid’s version of negotiate could still be used. so classes initialize their instance variables in the order of inheritance: . but it would take a direct message to a Mid instance to do it. which initializes a newly allocated instance. each class in the inheritance hierarchy can implement a method that does part of the job and passes the message on to super for the rest.. . Each init method has responsibility for initializing the instance variables defined in its class. Not being able to reach Mid’s version of negotiate may seem like a flaw. and still incorporate the original method in the modification: . Each version of init follows this procedure. It ignores the receiving object’s class (Low) and skips to the superclass of Mid.. 45 .makeLastingPeace { [super negotiate]. is designed to work like this. Neither message finds Mid’s version of negotiate. return [super negotiate]. As this example illustrates. since Mid is where makeLastingPeace is defined... it sends an init message to super to have the classes it inherits from initialize their instance variables. Using super Messages to super allow method implementations to be distributed over more than one class. You can override an existing method to modify or add to it. The init method.CHAPTER 2 Defining a Class .
All Rights Reserved. This is typically left to the alloc and allocWithZone: methods defined in the NSObject class. self refers to the instance. This way. For example. } To avoid confusion. the array method of NSArray is inherited by NSMutableArray). Redefining self super is simply a flag to the compiler telling it where to begin searching for the method to perform. // EXCELLENT [newInstance setColor:color]. and have subclasses incorporate the method through messages to super.CHAPTER 2 Defining a Class Initializer methods have some additional constraints. For example. Class methods are often concerned not with the class object. it can still get the basic functionality by sending a message to super. It’s also possible to concentrate core functionality in one method defined in a superclass. return [newInstance autorelease]. // BAD [self setColor:color]. } See “Allocating and Initializing Objects” (page 47) for more information about object allocation. There’s a tendency to do just that in definitions of class methods. Inside an instance method. self refers to the class object. But that would be an error. But self is a variable name that can be used in any number of ways. return [newInstance autorelease]. often setting up instance variable values at the same time. 46 Messages to self and super 2009-10-19 | © 2009 Apple Inc. but with instances of the class. it might be tempting to send messages to the newly allocated instance and to call the instance self. it’s usually better to use a variable other than self to refer to an instance inside a class method: + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[Rectangle alloc] init]. even assigned a new value. return [self autorelease]. it’s used only as the receiver of a message. every class method that creates an instance must allocate storage for the new object and initialize its isa variable to the class structure. just as in an instance method. + (id)rectangleOfColor:(NSColor *)color { id newInstance = [[self alloc] init]. and the rectangleOfColor: message is received by a subclass. rather than sending the alloc message to the class in a class method. the instance returned will be the same type as the subclass (for example. If another class overrides these methods (a rare case). but inside a class method. In such a method. This is an example of what not to do: + (Rectangle *)rectangleOfColor:(NSColor *) color { self = [[Rectangle alloc] init]. self and super both refer to the receiving object—the object that gets a message telling it to perform the method. many class methods combine allocation and initialization of an instance. it’s often better to send alloc to self. and are described in more detail in “Allocating and Initializing Objects” (page 47). if the class is subclassed. . } In fact. // GOOD [newInstance setColor:color].
method normally initializes the instance variables of the receiver. In Objective-C. the method name is just those four letters. The following sections look first at allocation and then at initialization. The Returned Object An init.CHAPTER 3 Allocating and Initializing Objects Allocating and Initializing Objects It takes two steps to create an object using Objective-C. NSObject declares the method mainly to establish the naming convention described earlier. These methods allocate enough memory to hold all the instance variables for an object belonging to the receiving class. memory for new objects is allocated using class methods defined in the NSObject class. They don’t need to be overridden and modified in subclasses.. begin with the abbreviation “init” If the method takes no arguments. takes arguments. All other instance variables are set to 0.. and discuss how they are controlled and modified.. Every class that declares instance variables must provide an init. init. Each step is accomplished by a separate method but typically in a single line of code: id anObject = [[Rectangle alloc] init]. 47 . NSObject defines two principal methods for this purpose. It’s the responsibility of the method to return an object that can be used without error. all NSObject’s init method does is return self. Separating allocation from initialization gives you individual control over each step so that each can be modified independently of the other. All Rights Reserved. an object needs to be more specifically initialized before it can be safely used.. You must: ■ ■ Dynamically allocate memory for the new object Initialize the newly allocated memory to appropriate values An object isn’t fully functional until both steps have been completed. method to initialize them. However. The alloc and allocWithZone: methods initialize a newly allocated object’s isa instance variable so that it points to the object’s class (the class object). For example. an NSView object can be initialized with an initWithFrame: method. If it . The NSObject class declares the isa variable and defines an init method. labels for the arguments follow the “init” prefix. Usually. since isa is initialized when memory for an object is allocated. by convention. then returns it. Allocating and Initializing Objects 2009-10-19 | © 2009 Apple Inc. alloc and allocWithZone:. This initialization is the responsibility of class-specific instance methods that.
initWithName: might refuse to assign the same name to two objects. In some situations. indicating that the requested object can’t be created. if a class keeps a list of named objects. custom initializers are subject to more constraints and conventions than are most other methods. In such a case. you want to provide other default values for an object’s instance variables. For example. it’s important that programs use the value returned by the initialization method.CHAPTER 3 Allocating and Initializing Objects However. method might return an object other than the newly allocated receiver.. then you should check the return value before proceeding: id anObject = [[SomeClass alloc] init]. In Objective-C. [anObject init]. the init. All Rights Reserved. an initFromFile: method might get the data it needs from a file passed as an argument.. If the file name it’s passed doesn’t correspond to an actual file. it won’t be able to complete the initialization. method might return nil (see “Handling Initialization Failure” (page 50)). [anObject someOtherMessage]... method could free the receiver and return nil. not just that returned by alloc or allocWithZone:. method to do what it’s asked to do. If there’s a chance that the init. all bits of memory (except for isa)—and hence the values for all its instance variables—are set to 0. Implementing an Initializer When a new object is created. in some cases. The following code is very dangerous.. else . id anObject = [[SomeClass alloc] init]. the name of a custom initializer method begins with init. or you want to pass values as arguments to the initializer. it might provide an initWithName: method to initialize new instances. Constraints and Conventions There are several constraints and conventions that apply to initializer methods that do not apply to other methods: ■ By convention.. or even return nil. Because an init.. For example. in many others. if ( anObject ) [anObject someOtherMessage]. [anObject someOtherMessage]. it might free the newly allocated instance and return the other object—thus ensuring the uniqueness of the name while at the same time providing what was asked for.. In these other cases. When asked to assign a new instance a name that’s already being used by another object. to safely initialize an object. you should combine allocation and initialization messages in one line of code. . this may be all you require when an object is initialized. If there can be no more than one object per name. id anObject = [SomeClass alloc].. In a few cases. Instead. an instance with the requested name.. since it ignores the return of init. this responsibility can mean returning a different object than the receiver. it might be impossible for an init. 48 Implementing an Initializer 2009-10-19 | © 2009 Apple Inc. you need to write a custom initializer.
you typically do so using direct assignment rather than using an accessor method. For example. ■ The return type of an initializer method should be id. if a class requires its instances to have a name and a data source. ■ At the end of the initializer. } (The reason for using the if (self = [super init]) pattern is discussed in “Handling Initialization Failure” (page 50). The following example illustrates the implementation of a custom initializer for a class that inherits from NSObject and has an instance variable. however. This is because the initializer could return a different object than the original receiver. the message returns an instance of NSMutableString. or another of its own initializers that ultimately invokes the designated initializer. Implementing an Initializer 2009-10-19 | © 2009 Apple Inc.CHAPTER 3 Allocating and Initializing Objects Examples from the Foundation framework include. initWithObjects:. All Rights Reserved. though.) An initializer doesn’t need to provide an argument for each variable. the designated initializer is init. you must ultimately invoke a designated initializer. a full explanation of this issue is given in “Coordinating Classes” (page 51). that represents the time when the object was created: . } return self. setFriend:. ■ If you set the value of an instance variable.(id)init { // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init if (self = [super init]) { creationDate = [[NSDate alloc] init]. it might provide an initWithName:fromURL: method. it should invoke its own class’s designated initializer. but set nonessential instance variables to arbitrary values or allow them to have the null values set by default. Designated initializers are described in “The Designated Initializer” (page 53).) ■ In the implementation of a custom initializer. For example. Failed initializers are discussed in more detail in “Handling Initialization Failure” (page 50). The reason for this is that id gives an indication that the class is purposefully not considered—that the class is unspecified and subject to change. In brief. (See also. not NSString. NSString provides a method initWithFormat:. When sent to an instance of NSMutableString (a subclass of NSString). you must return self. unless the initializer fails in which case you return nil. it must invoke the superclass’ designated initializer. If you are implementing any other initializer. By default (such as with NSObject). 49 . initWithFormat:. ■ You should assign self to the value returned by the initializer. depending on context of invocation. the singleton example given in “Combining Allocation and Initialization” (page 55). and initWithObjectsAndKeys:. It could then rely on methods like setEnabled:. and setDimensions: to modify default values after the initialization phase had been completed. if you are implementing a new designated initializer. This avoids the possibility of triggering unwanted side-effects in the accessors. creationDate.
This is typically handled by the pattern of performing initialization within a block dependent on a test of the return value of the superclass’s initializer—as seen in previous examples: .(id)init { if (self = [super init]) { creationDate = [[NSDate alloc] init]. } return self.0. you should call [self release] and return nil.(id)initWithImage:(NSImage *)anImage { // Find the size for the new instance from the image NSSize size = anImage. } This example doesn’t show what to do if there are any problems during initialization. this is discussed in the next section. a subclass. or an external caller) that receives a nil from an initializer method should be able to deal with it. size. It shows that you can do work before invoking the super class’s designated initializer. In the unlikely case where the caller has established any external references to the object before the call. Handling Initialization Failure In general. NSRect frame = NSMakeRect(0.height). In this case. You must make sure that dealloc methods are safe in presence of partially-initialized objects. size. .size. ■ Note: You should only call [self release] at the point of failure. If you get nil back from an invocation of the superclass’s initializer.CHAPTER 3 Allocating and Initializing Objects The next example illustrates the implementation of a custom initializer that takes a single argument. the class inherits from NSView.0. . you should not also call release.width. } return self. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: if (self = [super initWithFrame:frame]) { image = [anImage retain]. 0. There are two main consequences of this policy: ■ Any object (whether your own class. You should simply clean up any references you set up that are not dealt with in dealloc and return nil. } The following example builds on that shown in “Constraints and Conventions” (page 48) to show how to handle an inappropriate value passed as the parameter: . All Rights Reserved.(id)initWithImage:(NSImage *)anImage { 50 Implementing an Initializer 2009-10-19 | © 2009 Apple Inc. this includes undoing any connections. if there is a problem during an initialization method.
size. 51 . Coordinating Classes The init. return nil...CHAPTER 3 Allocating and Initializing Objects if (anImage == nil) { [self release]. methods a class defines typically initialize only those variables declared in that class. You should typically not use exceptions to signify errors of this sort—for more information. a Graphic.(id)initWithURL:(NSURL *)aURL error:(NSError **)errorPtr { if (self = [super init]) { NSData *data = [[NSData alloc] initWithContentsOfURL:aURL options:NSUncachedRead error:errorPtr]. Inherited instance variables are initialized by sending a message to super to perform an initialization method defined somewhere farther up the inheritance hierarchy: . Because it comes first. } return self.. Implementing an Initializer 2009-10-19 | © 2009 Apple Inc. if (data == nil) { // In this case the error object is created in the NSData initializer [self release].size. } return self. All Rights Reserved. } // Find the size for the new instance from the image NSSize size = anImage. a Rectangle object must be initialized as an NSObject.0. } The message to super chains together initialization methods in all inherited classes. return nil. 0.(id)initWithName:(NSString *)string { if ( self = [super init] ) { name = [string copy]. it ensures that superclass variables are initialized before those declared in subclasses. there is a possibility of returning meaningful information in the form of an NSError object returned by reference: .height). see Error Handling Programming Guide For Cocoa. } The next example illustrates best practice where. and a Shape before it’s initialized as a Rectangle. For example.0.. // Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: if (self = [super initWithFrame:frame]) { image = [anImage retain]. size. } // implementation continues.width. NSRect frame = NSMakeRect(0. in the case of a problem.
CHAPTER 3 Allocating and Initializing Objects. if class A defines an init method and its subclass B defines an initWithName: method. as shown earlier. invoke the inherited method. in turn. For example. All Rights Reserved. The easiest way to do that is to replace the inherited init method with a version that invokes initWithName:: . Figure 3-2 includes B’s version of init: 52 Implementing an Initializer 2009-10-19 | © 2009 Apple Inc.init { return [self initWithName:"default"]. } The initWithName: method would. B must also make sure that an init message successfully initializes B instances. as shown in Figure 3-1. .
The Designated Initializer In the example given in “Coordinating Classes” (page 51). } For an instance of the C class. It’s a Cocoa convention that the designated initializer is always the method that allows the most freedom to determine the character of a new instance (usually this is the one with the most arguments. suppose we define class C. and implement an initWithName:fromFile: method. The relationship between these methods is shown in Figure 3-3: The Designated Initializer 2009-10-19 | © 2009 Apple Inc. The designated initializer is the method in each class that guarantees inherited instance variables are initialized (by sending a message to super to perform an inherited method). All Rights Reserved.initWithName:(char *)string { return [self initWithName:string fromFile:NULL]. It’s important to know the designated initializer when defining a subclass. . For example.CHAPTER 3 Allocating and Initializing Objects Figure 3-2 Covering an Inherited Initialization Model – init Class A – init Class B – initWithName: Covering inherited initialization methods makes the class you define more portable to other applications. It’s also the method that does most of the work. In addition to this method. This can be done just by covering B’s initWithName: with a version that invokes initWithName:fromFile:. If you leave an inherited method uncovered. 53 . the inherited init method invokes this new version of initWithName: which invokes initWithName:fromFile:. someone else may use it to produce incorrectly initialized instances of your class. initWithName: would be the designated initializer for its class (class B). we have to make sure that the inherited init and initWithName: methods also work for instances of C. a subclass of B. but not always). and the one that other initialization methods in the same class invoke.
.CHAPTER 3 Allocating and Initializing Objects Figure 3-3 Covering the Designated Initializer – init Class B – initWithName: Class C – initWithName: – initWithName:fromFile: This figure omits an important detail. Messages to self are shown on the left and messages to super are shown on the right. B. which invokes init again). and C are linked. All Rights Reserved. } General Principle: The designated initializer in a class must. sends a message to super to invoke an inherited initialization method. which invokes initWithName:fromFile:. invoke the designated initializer in a superclass. . Figure 3-4 shows how all the initialization methods in classes A. But which of B’s methods should it invoke. initWithName:fromFile: must invoke initWithName:: . init or initWithName:? It can’t invoke init. The initWithName:fromFile: method. Designated initializers are chained to each other through messages to super. while other initialization methods are chained to designated initializers through messages to self.initWithName:(char *)string fromFile:(char *)pathname { if ( self = [super initWithName:string] ) . 54 The Designated Initializer 2009-10-19 | © 2009 Apple Inc. for two reasons: ■ Circularity would result (init invokes C’s initWithName:. It won’t be able to take advantage of the initialization code in B’s version of initWithName:.. ■ Therefore. being the designated initializer for the C class. through a message to super.
it invokes C’s version. initialized instances of the class. NSArray defines the following class methods that combine allocation and initialization: + (id)array. All Rights Reserved.String has the following methods (among others): + (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc. 55 . Similarly. some classes define creation methods that combine the two steps of allocating and initializing to return new. Combining Allocation and Initialization In Cocoa. Therefore. .. Combining Allocation and Initialization 2009-10-19 | © 2009 Apple Inc. + (id)stringWithFormat:(NSString *)format. For example. where className is the name of the class. when the receiver is an instance of the B class... These methods are often referred to as convenience constructors and typically take the form + className..
of course. you can avoid the step of allocating a new instance when one isn’t needed. You must read Memory Management Programming Guide for Cocoa to understand the policy that applies to these convenience constructors. when initWithName: is passed a name that’s already taken. strong typing is appropriate—there is no expectation that this method will be overridden. It allocates and initializes a single shared instance: + (Soloist *)soloist { static Soloist *instance = nil. 56 Combining Allocation and Initialization 2009-10-19 | © 2009 Apple Inc.. It would open the file. It also makes sense to combine allocation and initialization in a single method if you want to avoid the step of blindly allocating memory for a new object that you might not use. put them in the List.. } return instance. } Notice that in this case the return type is Soloist *. .CHAPTER 3 Allocating and Initializing Objects + (id)arrayWithObject:(id)anObject. you might implement a listFromFile: method that takes the name of the file as an argument. and the file might contain enough data to initialize more than one object.. + (id)arrayWithObjects:(id)firstObj. if ( instance == nil ) { instance = [[self alloc] init]. and create a List object large enough to hold all the new objects. As mentioned in “The Returned Object” (page 47). method might sometimes substitute another object for the receiver. In this case. . This is for the same reason as for initializer methods.. For example. that an object is allocated and freed immediately without ever being used. This means. Notice that the return type of these methods is id.. it might free the receiver and in its place return the object that was previously assigned the name. it would be impossible to know how many objects to allocate until the file is opened. If the code that determines whether the receiver should be initialized is placed inside the method that does the allocation instead of inside init. and finally return the List. All Rights Reserved. see how many objects to allocate. Methods that combine allocation and initialization are particularly valuable if the allocation must somehow be informed by the initialization... For example. Important: It is important to understand the memory management implications of using these methods if you do not use garbage collection (see “Memory Management” (page 15)). if the data for the initialization is taken from a file. as discussed in “Constraints and Conventions” (page 48).. It would then allocate and initialize the objects from data in the file. Since this method returns a singleton share instance. In the following example. the soloist method ensures that there’s no more than one instance of the Soloist class. an init.
57 . What is of interest is whether or not a particular class conforms to the protocol—whether it has implementations of the methods the protocol declares. A protocol is simply a list of method declarations. Cocoa software uses protocols heavily to support interprocess communication through Objective-C messages. Protocols are useful in at least three situations: ■ ■ ■. All Rights Reserved. Classes in unrelated branches of the inheritance hierarchy might be typed alike because they conform to the same protocol. Protocols free method declarations from dependency on the class hierarchy. Thus objects can be grouped into types not just on the basis of similarities due to the fact that they inherit from the same class. so they can be used in ways that classes and categories cannot. some don’t. declare methods that are independent of any specific class. but also on the basis of their similarity in conforming to the same protocol. Informal and formal protocols. an Objective-C program doesn’t need to use protocols. on the other hand. but which any class. For example. might implement.CHAPTER 4 Protocols Protocols declare methods that can be implemented by any class. It all depends on the task at hand. Unlike class definitions and message expressions.(void)mouseUp:(NSEvent *)theEvent.(void)mouseDragged:(NSEvent *)theEvent. Any class that wanted to respond to mouse events could adopt the protocol and implement its methods. and perhaps many classes. . Some Cocoa frameworks use them. they’re optional. but the identity of the class that implements them is not of interest.(void)mouseDown:(NSEvent *)theEvent. Protocols list methods that are (or may be) implemented somewhere. these methods that report user actions on the mouse could be gathered into a protocol: . . especially where a project is divided among many implementors or it incorporates objects developed in other projects. unattached to a class definition. Protocols can play a significant role in object-oriented design. However. Declaring Interfaces for Others to Implement 2009-10-19 | © 2009 Apple Inc.
A protocol serves this purpose. For example. Suppose. 58 Methods for Others to Implement 2009-10-19 | © 2009 Apple Inc. if you develop an object that sends messages to objects that aren’t yet defined—objects that you’re leaving for others to implement—you won’t have the receiver’s interface file. } return NO. an object might delegate responsibility for a certain operation to another object. this communication is easily coordinated. . The sender simply imports the interface file of the receiver. you can’t know what kind of object might register itself as the assistant. you can only declare a protocol for the helpOut: method. whenever a message is to be sent to the assistant. You provide an assistant instance variable to record the outlet for these messages and define a companion method to set the instance variable. at the time you write this code. This method lets other objects register themselves as potential recipients of your object’s messages: . However. objects send messages as well as receive them. Protocols provide a way for it to also advertise the messages it sends. These declarations advertise the messages it can receive. In some cases.. It informs the compiler about methods the class uses and also informs other implementors of the methods they need to define to have their objects work with yours. that you develop an object that asks for the assistance of another object by sending it helpOut: and other messages. The imported file declares the method selectors the sender uses in the messages it sends. Communication works both ways.setAssistant:anObject { assistant = anObject.CHAPTER 4 Protocols Methods for Others to Implement If you know the class of an object. All Rights Reserved. for example. If you develop the class of the sender and the class of the receiver as part of the same project (or if someone else has supplied you with the receiver and its interface file). you can look at its interface declaration (and the interface declarations of the classes it inherits from) to find what messages it responds to. You need another way to declare the methods you use in messages but don’t implement. return YES. an object might be willing to notify other objects of its actions so that they can take whatever collateral measures might be required. you can’t import the interface file of the class that implements it. if ( [assistant respondsToSelector:@selector(helpOut:)] ) { [assistant helpOut:self].. } Since.(BOOL)doWork { . or it may on occasion simply need to ask another object for information. a check is made to be sure that the receiver implements a method that can respond: . } Then.
But you don’t need to know how another application works or what its components are to communicate with it. This is done by associating the object with a list of methods declared in a protocol. there would be no way to declare an interface to an object without identifying its class. the supplier must be willing to identify at least some of the messages that it can respond to. all you need to know is what messages you can send (the protocol) and where to send them (the receiver). a method in another class returns a usable object: id formatter = [receiver formattingService]. The sending application doesn’t need to know the class of the object or use the class in its own design. For example. For it to be of any use at all. the information in the protocol is sufficient. (Remote Messaging (page 105) in the Objective-C Runtime Programming Guide. All it needs is the protocol. of course. consider the following situations: ■ Someone who supplies a framework or a suite of objects for others to use can include objects that are not identified by a class name or an interface file. ■ You can send Objective-C messages to remote objects—objects in other applications. those classes are often grouped under an abstract class that declares the methods they have in common. However. Declaring Interfaces for Anonymous Objects 2009-10-19 | © 2009 Apple Inc. especially where only one object of its kind is needed. It doesn’t have to disclose anything else about the object. and internal logic. An application that publishes one of its objects as a potential receiver of remote messages must also publish a protocol declaring the methods the object will use to respond to those messages. Typically. A class message returns the anonymous object’s class. an object of unknown class. An anonymous object may represent a service or handle a limited set of functions.) Objects are not anonymous to their developers. the supplier must provide a ready-made instance. but the inheritance hierarchy and the common declaration in the abstract class captures the essential similarity between the subclasses. (Objects that play a fundamental role in defining an application’s architecture and objects that you must initialize before using are not good candidates for anonymity. The object returned by the method is an object without a class identity. discusses this possibility in more detail. Protocols make anonymous objects possible. Note: Even though the supplier of an anonymous object doesn’t reveal its class. As an outsider. there’s usually little point in discovering this extra information.CHAPTER 4 Protocols Declaring Interfaces for Anonymous Objects A protocol can be used to declare the methods of an anonymous object. All Rights Reserved. 59 .) Each application has its own structure. Without a protocol. Each subclass may re-implement the methods in its own way. Instead. classes. but they are anonymous when the developer supplies them to someone else. the object itself reveals it at runtime. at least not one the supplier is willing to reveal. users have no way of creating instances of the class. Lacking the name and class interface. Non-Hierarchical Similarities If more than one class implements a set of methods.
In this case. protocol names don’t have global visibility. the default is @required. the NSMatrix object could require objects representing cells to have methods that can respond to a particular set of messages (a type based on protocol).initFromXMLRepresentation:(NSXMLElement *)xmlString. just that it implemented the methods. Formal Protocols The Objective-C language provides a way to formally declare a list of methods (including declared properties) as a protocol.initFromXMLRepresentation:(NSXMLElement *)XMLElement. The matrix could require each of these objects to be a kind of NSCell (a type based on class) and rely on the fact that all objects that inherit from the NSCell class have the methods needed to respond to NSMatrix messages. Objects can be typed by this similarity (the protocols they conform to). For example. @end Unlike class names. the compiler can check for types based on protocols.CHAPTER 4 Protocols However. This limited similarity may not justify a hierarchical relationship. 60 Formal Protocols 2009-10-19 | © 2009 Apple Inc. If you do not specify any keyword. Alternatively. Optional Protocol Methods Protocol methods can be marked as optional using the @optional keyword. For example. the NSMatrix object wouldn’t care what class a cell object belonged to. These methods could be grouped into a protocol and the similarity between implementing classes accounted for by noting that they all conform to the same protocol. rather than by their class. Formal protocols are supported by the language and the runtime system.(NSXMLElement *)XMLRepresentation. . For example. sometimes it’s not possible to group common methods in an abstract class. there is a @required keyword to formally denote the semantics of the default behavior. . . you could declare an XML representation protocol like this: @protocol MyXMLSupport . Classes that are unrelated in most respects might nevertheless need to implement some similar methods. and objects can introspect at runtime to report whether or not they conform to a protocol. Declaring a Protocol You declare formal protocols with the @protocol directive: @protocol ProtocolName method declarations @end For example.(NSXMLElement *)XMLRepresentation. you might want to add support for creating XML representations of objects in your application and for initializing objects from an XML representation: . You can use @optional and @required to partition your protocol into sections as you see fit. an NSMatrix instance must communicate with the objects that represent its cells. Corresponding to the @optional modal keyword. They live in their own namespace. All Rights Reserved.
6 and later.(void)requiredMethod. you must use a formal protocol.(NSXMLElement *)XMLRepresentation. @end Note: In Mac OS X v10. 61 . protocols may not include optional declared properties. you can also define an informal protocol by grouping the methods in a category declaration: @interface NSObject ( MyXMLSupport ) . a category interface doesn’t have a corresponding implementation. the methods aren’t restricted to any part of the inheritance hierarchy. (It would also be possible to declare an informal protocol as a category of another class to limit it to a certain branch of the inheritance hierarchy.CHAPTER 4 Protocols @protocol MyProtocol . An informal protocol may be useful when all the methods are optional.5.) When used to declare a protocol. Because all classes inherit from the root class..(void)anOptionalMethod.(void)anotherRequiredMethod. This constraint is removed in Mac OS X v10. but (on Mac OS X v10. Informal Protocols In addition to formal protocols. @optional . . @end Informal protocols are typically declared as categories of the NSObject class.(void)anotherOptionalMethod. There’s no type checking at compile time nor a check at runtime to see whether an object conforms to the protocol. Being informal.5 and later) it is typically better to use a formal protocol with optional methods.initFromXMLRepresentation:(NSXMLElement *)XMLElement. such as for a delegate. @required . Informal Protocols 2009-10-19 | © 2009 Apple Inc. since that broadly associates the method names with any class that inherits from NSObject. protocols declared in categories don’t receive much language support. Instead. To get these benefits. . All Rights Reserved. but there is little reason to do so.
Prettifying > A class or category that adopts a protocol must implement all the required methods the protocol declares. a protocol name doesn’t designate the object—except inside @protocol(). otherwise the compiler issues a warning. Unlike a class name. . except that here it has a set of trailing parentheses. All Rights Reserved. Source code can refer to a Protocol object using the @protocol() directive—the same directive that declares a protocol. and at runtime they’re both represented by objects—classes by class objects and protocols by Protocol objects. Protocol objects are created automatically from the definitions and declarations found in source code and are used by the runtime system. Adopting a Protocol Adopting a protocol is similar in some ways to declaring a superclass. A class is said to adopt a formal protocol if in its declaration it lists the protocol within angle brackets after the superclass name: @interface ClassName : ItsSuperclass < protocol list > Categories adopt protocols in much the same way: @interface ClassName ( CategoryName ) < protocol list > A class can adopt more than one protocol. The Formatter class above would define all the required methods declared in the two protocols it adopts. names in the protocol list are separated by commas. or Referred to somewhere in source code (using @protocol()) Protocols that are declared but not used (except for type checking as described below) aren’t represented by Protocol objects at runtime. The methods declared in the adopted protocol are not declared elsewhere in the class or category interface. Source code that deals with a protocol (other than to use it in a type specification) must refer to the Protocol object. in addition to any it might have declared itself. protocols are similar to class definitions. Like class objects. They’re not allocated and initialized in program source code. formal protocols are represented by a special data type—instances of the Protocol class. The parentheses enclose the protocol name: Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport). Both assign methods to the class. They both declare methods. 62 Protocol Objects 2009-10-19 | © 2009 Apple Inc. The superclass declaration assigns it inherited methods. The compiler creates a Protocol object for each protocol declaration it encounters. the protocol assigns it methods declared in the protocol list. A class or category that adopts a protocol must import the header file where the protocol is declared. @interface Formatter : NSObject < Formatting. In many ways.CHAPTER 4 Protocols Protocol Objects Just as classes are represented at runtime by class objects and methods by selector codes. but only if the protocol is also: ■ ■ Adopted by a class. This is the only way that source code can conjure up a Protocol object.
Type Checking Type declarations for objects can be extended to include formal protocols. except that it tests for a type based on a protocol rather than a type based on the inheritance hierarchy. Since a class must implement all the required methods declared in the protocols it adopts. if Formatter is an abstract class. For example.CHAPTER 4 Protocols It’s possible for a class to simply adopt protocols and declare no other methods. this declaration Conforming to a Protocol 2009-10-19 | © 2009 Apple Inc. In a type declaration. Because it checks for all the methods in the protocol. For example. id <MyXMLSupport> anObject. but declares no instance variables or methods of its own: @interface Formatter : NSObject < Formatting. The conformsToProtocol: test is also like the isKindOfClass: test. one that’s more abstract since it’s not tied to particular implementations. 63 . Just as static typing permits the compiler to test for a type based on the class hierarchy. the following class declaration adopts the Formatting and Prettifying protocols. this is probably an error } (Note that there is also a class method with the same name—conformsToProtocol:. except that it tests whether a protocol has been adopted (and presumably all the methods it declares implemented) rather than just whether one particular method has been implemented. protocol names are listed between angle brackets after the type name: .(id <Formatting>)formattingService. It’s possible to check whether an object conforms to a protocol by sending it a conformsToProtocol: message. this syntax permits the compiler to test for a type based on conformance to a protocol. An instance of a class is said to conform to the same set of protocols its class conforms to. saying that a class or an instance conforms to a protocol is equivalent to saying that it has in its repertoire all the methods the protocol declares. Protocols thus offer the possibility of another level of type checking by the compiler. Prettifying > @end Conforming to a Protocol A class is said to conform to a formal protocol if it adopts the protocol or inherits from another class that adopts it. if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) { // Object does not conform to MyXMLSupport protocol // If you are expecting receiver to implement methods declared in the // MyXMLSupport protocol. conformsToProtocol: can be more efficient than respondsToSelector:. All Rights Reserved.) The conformsToProtocol: test is like the respondsToSelector: test for a single method.
All Rights Reserved. both classes and instances will respond to a conformsToProtocol: message. A class can conform to an incorporated protocol by either: ■ ■ Implementing the methods the protocol declares. id <Formatting> anObject. the class must also conform to them. @protocol Paging < Formatting > any object that conforms to the Paging protocol also conforms to Formatting. just as only instances can be statically typed to a class. Type declarations id <Paging> someObject. The compiler can make sure only objects that conform to the protocol are assigned to the type. (However. at runtime.. When a class adopts a protocol. If an incorporated protocol incorporates still other protocols. and conformsToProtocol: messages if ( [anotherObject conformsToProtocol:@protocol(Paging)] ) .) Protocols Within Protocols One protocol can incorporate other protocols using the same syntax that classes use to adopt a protocol: @protocol ProtocolName < protocol list > All the protocols listed between angle brackets are considered part of the ProtocolName protocol. In each case.. or Inheriting from a class that adopts the protocol and implements the methods. the type groups similar objects—either because they share a common inheritance. need to mention only the Paging protocol to test for conformance to Formatting as well.CHAPTER 4 Protocols Formatter *anObject. Only instances can be statically typed to a protocol. it must implement the required methods the protocol declares. In addition. if the Paging protocol incorporates the Formatting protocol. or because they converge on a common set of methods. 64 Protocols Within Protocols 2009-10-19 | © 2009 Apple Inc. groups all objects that conform to the Formatting protocol into a type. groups all objects that inherit from Formatter into a type and permits the compiler to check assignments against that type. it must conform to any protocols the adopted protocol incorporates. . as mentioned earlier. Similarly. regardless of their positions in the class hierarchy. The two types can be combined in a single declaration: Formatter <Formatting> *anObject. Protocols can’t be used to type class objects. For example. this declaration.
you occasionally find yourself writing code that looks like this: #import "B. 65 . @end In such a situation. @end where protocol B is declared like this: #import "A. It adopts the Formatting protocol along with Paging. To break this recursive cycle. Referring to Other Protocols When working on complex applications.h" @protocol B . Pager inherits conformance to the Formatting protocol from Formatter. If Pager is a subclass of NSObject. circularity results and neither file will compile correctly. but not those declared in Formatting. @protocol A .bar:(id <A>)anObject. It doesn’t import the interface file where protocol B is defined. that the Pager class adopts the Paging protocol.foo:(id <B>)anObject.foo:(id <B>)anObject. On the other hand. you must use the @protocol directive to make a forward reference to the needed protocol instead of importing the interface file where the protocol is defined. @interface Pager : Formatter < Paging > it must implement all the methods declared in the Paging protocol proper. @interface Pager : NSObject < Paging > it must implement all the Paging methods. Note that a class can conform to a protocol without formally adopting it simply by implementing the methods declared in the protocol.h" @protocol A . The following code excerpt illustrates how you would do this: @protocol B. for example. @end Note that using the @protocol directive in this manner simply informs the compiler that “B” is a protocol to be defined later. if Pager is a subclass of Formatter (a class that independently adopts the Formatting protocol). All Rights Reserved. including those declared in the incorporated Formatting protocol. Referring to Other Protocols 2009-10-19 | © 2009 Apple Inc.CHAPTER 4 Protocols Suppose.
CHAPTER 4 Protocols 66 Referring to Other Protocols 2009-10-19 | © 2009 Apple Inc. . All Rights Reserved.
writing accessor methods is nevertheless a tedious process—particularly if you have to write code to support both garbage collected and reference counted environments. according to the specification you provide in the declaration. All Rights Reserved. aspects of the property that may be important to consumers of the API are left obscured—such as whether the accessor methods are thread-safe or whether new values are copied when set. Overview 2009-10-19 | © 2009 Apple Inc. 67 . Moreover. you adhere to the principle of encapsulation (see “Mechanisms Of Abstraction” in Object-Oriented Programming with Objective-C > The Object Model). Property Declaration A property declaration begins with the keyword @property. explicit specification of how the accessor methods behave. @property can appear anywhere in the method declaration list found in the @interface of a class. Overview There are two aspects to this language feature: the syntactic elements you use to specify and optionally synthesize declared properties. Declared properties address the problems with standard accessor methods by providing the following features: ■ ■ The property declaration provides a clear. its declaration and its implementation.CHAPTER 5 Declared Properties The Objective-C “declared properties” feature provides a simple way to declare and implement an object’s accessor methods. By using accessor methods. ■ Property Declaration and Implementation There are two parts to a declared property. You typically access an object’s properties (in the sense of its attributes and relationships) through a pair of accessor (getter/setter) methods. Properties are represented syntactically as identifiers and are scoped. and a related syntactic element that is described in “Dot Syntax” (page 20). Although using accessor methods has significant advantages. @property can also appear in the declaration of a protocol or category. This means you have less code to write and maintain. so the compiler can detect use of undeclared properties. The compiler can synthesize accessor methods for you. You can exercise tight control of the behavior of the getter/setter pair and the underlying state management while clients of the API remain insulated from the implementation changes.
Thus @property float value. however. if you specify copy you must make sure that you do copy the input value in the setter method). you should ensure that it matches the specification (for example. 68 Property Declaration and Implementation 2009-10-19 | © 2009 Apple Inc. attribute2. If you implement the accessor method(s) yourself.(float)value.. given a property “foo” the accessors would be foo and .]). An optional parenthesized set of attributes provides additional details about the storage semantics and other behaviors of the property—see “Property Declaration Attributes” (page 68) for possible values. @end You can think of a property declaration as being equivalent to declaring two accessor methods. properties are scoped to their enclosing interface declaration. } @property float value. For property declarations that use a comma delimited list of variable names. All Rights Reserved. the code it generates matches the specification given by the keywords. provides additional information about how the accessor methods are implemented (as described in “Property Declaration Attributes” (page 68)). . Property Declaration Attributes You can decorate a property with attributes by using the form @property(attribute [. The following attributes allow you to specify custom names instead. . Like methods.CHAPTER 5 Declared Properties @property(attributes) type name. the property attributes apply to all of the named properties. is equivalent to: . .(void)setValue:(float)newValue. They are both optional and may appear with any other attribute (except for readonly in the case of setter=).. If you use the @synthesize directive to tell the compiler to create the accessor method(s). setFoo:. The getter must return a type matching the property’s type and take no arguments. Listing 5-1 Declaring a simple property @interface MyClass : NSObject { float value. each property has a type specification and a name. Like any other Objective-C type. @property declares a property. Accessor Method Names The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example. A property declaration. Listing 5-1 illustrates the declaration of a simple property. getter=getterName Specifies the name of the get accessor for the property.
you will get a compiler warning. retain and assign are effectively the same in a garbage-collected environment.6 and later.) The previous value is sent a release message. Moreover. copy Specifies that a copy of the object should be used for assignment. On Mac OS X v10. Setter Semantics These attributes specify the semantics of a set accessor. if you attempt to assign a value using the dot syntax. This is the default. Property Declaration and Implementation 2009-10-19 | © 2009 Apple Inc. If you specify that a property is readonly then also specify a setter with setter=. you can use the __attribute__ keyword to specify that a Core Foundation property should be treated like an Objective-C object for memory management. this attribute is valid only for Objective-C object types (so you cannot specify retain for Core Foundation objects—see “Core Foundation” (page 74)). retain Specifies that retain should be invoked on the object upon assignment. All Rights Reserved. which must implement the NSCopying protocol. The copy is made by invoking the copy method. This is the default. If you use @synthesize in the implementation block. assign Specifies that the setter uses simple assignment. They are mutually exclusive. see “Copy” (page 73). This attribute is valid only for object types. readonly Indicates that the property is read-only. readwrite Indicates that the property should be treated as read/write. If you use @synthesize in the implementation block. You typically use this attribute for scalar types such as NSInteger and CGRect. as illustrated in this example: @property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary. Writability These attributes specify whether or not a property has an associated set accessor.) The previous value is sent a release message. you get a compiler error. the getter and setter methods are synthesized. The setter method must take a single argument of a type matching the property’s type and must return void. For further discussion.6. Typically you should specify accessor method names that are key-value coding compliant (see Key-Value Coding Programming Guide)—a common reason for using the getter decorator is to adhere to the isPropertyName convention for Boolean values.CHAPTER 5 Declared Properties setter=setterName Specifies the name of the set accessor for the property. only a getter method is required in the @implementation. Prior to Mac OS X v10. They are mutually exclusive. 69 . only the getter method is synthesized. (The default is assign. If you specify readonly. (The default is assign. Both a getter and setter method will be required in the @implementation. or (in a reference-counted environment) for objects you don’t own such as delegates.
as illustrated in the following example: @property CGFloat x AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4. @property CGFloat y __attribute__((.) To decide which you should choose. (There is no keyword to denote atomic. if the property type can be copied.) nonatomic Specifies that accessors are non-atomic. . you need to understand Cocoa’s memory management policy (see Memory Management Programming Guide for Cocoa).. Markup and Deprecation Properties support the full range of C style decorators.)). however. For more details.CHAPTER 5 Declared Properties Different constraints apply depending on whether or not you use garbage collection: ■ If you do not use garbage collection. Atomicity This attribute specifies that accessor methods are not atomic. Properties are atomic by default so that synthesized accessors provide robust access to properties in a multi-threaded environment—that is. return result. retain) IBOutlet NSButton *myButton.. If you want to specify that a property is an Interface Builder outlet. IBOutlet is not. If you specify nonatomic. If you use garbage collection. you can use the IBOutlet identifier: @property (nonatomic. you can use the storage modifiers __weak and __strong in a property’s declaration: 70 Property Declaration and Implementation 2009-10-19 | © 2009 Apple Inc. a formal part of the list of attributes. see “Performance and Threading” (page 77). though. then in a reference counted environment a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value—the implementation will be similar to the following: [_internal lock]. to preserve encapsulation you often want to make a private copy of the object. retain or copy—otherwise you will get a compiler warning. then a synthesized accessor for an object property simply returns the value directly. for object properties you must explicitly specify one of assign. By default. accessors are atomic. (This encourages you to think about what memory management behavior you want and type it explicitly. if you don’t specify any of assign. All Rights Reserved. you don't get a warning if you use the default (that is. The default is usually what you want. // lock using an object-level lock id result = [[value retain] autorelease]. If you do not specify nonatomic. Properties can be deprecated and support __attribute__ style markup. retain or copy) unless the property's type is a class that conforms to NSCopying. the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently. [_internal unlock]. ■ If you use garbage collection.
it is used. @synthesize You use the @synthesize keyword to tell the compiler that it should synthesize the setter and/or getter methods for the property if you do not supply them within the @implementation block. for example: @synthesize firstName. All Rights Reserved. } @property(copy. Whether or not you specify the name of the instance variable. Listing 5-2 Using @synthesize @interface MyClass : NSObject { NSString *value. retain) __weak Link *parent. but again they are not a formal part of the list of attributes. Important: If you do not specify either @synthesize or @dynamic for a particular property. lastName. Property Implementation Directives You can use the @synthesize and @dynamic directives in @implementation blocks to trigger specific compiler actions. @end You can use the form property=ivar to indicate that a particular instance variable should be used for the property. There are differences in the behavior that depend on the runtime (see also “Runtime Difference” (page 78)): ■ For the legacy runtimes. and age should be synthesized and that the property age is represented by the instance variable yearsOld. readwrite) NSString *value. Note that neither is required for any given @property declaration. Other aspects of the synthesized methods are determined by the optional attributes (see “Property Declaration Attributes” (page 68)). @end @implementation MyClass @synthesize value. age = yearsOld. @synthesize can only use an instance variable from the current class. lastName. you get a compiler error. not a superclass.CHAPTER 5 Declared Properties @property (nonatomic. you must provide a getter and setter (or just a getter in the case of a readonly property) method implementation for that property. For the modern runtimes (see Runtime Versions and Platforms in Objective-C Runtime Programming Guide). 71 . it is used—otherwise. If an instance variable of the same name and compatible type as the property exists. instance variables are synthesized as needed. If an instance variable of the same name already exists. instance variables must already be declared in the @interface block of the current class. This specifies that the accessor methods for firstName. ■ Property Declaration and Implementation 2009-10-19 | © 2009 Apple Inc.
the fact that the property was redeclared prior to any @synthesize statement will cause the setter to be synthesized. The ability to redeclare a read-only property as read/write 72 Using Properties 2009-10-19 | © 2009 Apple Inc.(NSString *)value { return value. } . The same holds true for a property declared in a category or protocol—while the property may be redeclared in a category or protocol. readwrite) you must repeat its attributes in whole in the subclasses. readwrite) NSString *value. the property’s attributes must be repeated in whole. . a protocol. but (with the exception of readonly vs. . or “plain old data” (POD) type (see C++ Language Note: POD Types).CHAPTER 5 Declared Properties @dynamic You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. In the case of a class extension redeclaration.(void)setValue:(NSString *)newValue { if (newValue != value) { value = [newValue copy]. @end // assume using garbage collection @implementation MyClass @dynamic value. } @property(copy. The example shown in Listing 5-3 illustrates using direct method implementations—it is equivalent to the example given in Listing 5-2 (page 71). however. Listing 5-3 Using @dynamic with direct method implementations @interface MyClass : NSObject { NSString *value. Core Foundation data type. or a subclass—see “Subclassing with Properties” (page 76). If you declare a property in one class as readonly. } } @end Using Properties Supported Types You can declare a property for any Objective-C class. you can redeclare it as readwrite in a class extension (see “Extensions” (page 81)). see “Core Foundation” (page 74). Property Re-declaration You can re-declare a property in a subclass. All Rights Reserved. For constraints on using Core Foundation types.
// public header file @interface MyObject : NSObject { NSString *language. } } Although this works well for strings. copy) NSMutableArray *myArray. as illustrated in the following example. then the synthesized setter method is similar to the following: -(void)setString:(NSString *)newString { if (string != newString) { [string release]. If you synthesize the corresponding accessor. } @property (readonly. NSArray. @interface MyClass : NSObject { NSMutableArray *myArray. if you declare a property as follows: @property (nonatomic. copy) NSString *language. @end @implementation MyClass @synthesize myArray. In this situation. it may present a problem if the attribute is a collection such as an array or a set. @end // private implementation file @interface MyObject () @property (readwrite. Typically you want such collections to be mutable. 73 . Using Properties 2009-10-19 | © 2009 Apple Inc. } @property (nonatomic. copy) NSString *language. @end Copy If you use the copy declaration attribute. @end @implementation MyObject @synthesize language. an instance of NSMutableString) and you want to ensure that your object has its own private immutable copy. copy) NSString *string. The following example shows using a class extension to provide a property that is declared as read-only in the public header but is redeclared privately as read/write. you have to provide your own implementation of the setter method. you specify that a value is copied during assignment.CHAPTER 5 Declared Properties enables two common implementation patterns: a mutable subclass of an immutable class (NSString. All Rights Reserved. but the copy method returns an immutable version of the collection. This is useful for attributes such as string objects where there is a possibility that the new value passed in a setter may be mutable (for example. string = [newString copy]. For example. the synthesized method uses the copy method. and NSDictionary are all examples) and a property that has public API that is readonly but a private readwrite implementation internal to the class.
you declare a property whose type is a CFType and synthesize the accessors as illustrated in the following example: @interface MyClass : NSObject { CGImageRef myImage.(void)dealloc { [self setProperty:nil]. however. you cannot access the instance variable directly. myArray = [newArray mutableCopy]. provide a useful way to cross-check the implementation of your dealloc method: you can look for all the property declarations in your header file and make sure that object properties not marked assign are released. @end 74 Using Properties 2009-10-19 | © 2009 Apple Inc. as illustrated in this example: . the compiler only creates any absent accessor methods. } @property(readwrite) CGImageRef myImage. } } @end dealloc Declared properties fundamentally take the place of accessor method declarations. however. There is no direct interaction with the dealloc method—properties are not automatically released for you. Declared properties do. All Rights Reserved. and those marked assign are not released. therefore. } Core Foundation As noted in “Property Declaration Attributes” (page 68). [super dealloc].(void)dealloc { [property release]. so you must invoke the accessor method: . Note: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter).(void)setMyArray:(NSMutableArray *)newArray { if (myArray != newArray) { [myArray release].CHAPTER 5 Declared Properties .6 you cannot specify the retain attribute for non-object types. @end @implementation MyClass @synthesize myImage. [super dealloc]. . } If you are using the modern runtime and synthesizing the instance variable. when you synthesize a property. If. prior to Mac OS X v10.
CHAPTER 5 Declared Properties then in a reference counted environment the generated set accessor will simply assign the new value to the instance variable (the new value is not retained and the old value is not released). name is synthesized. but the setter will trigger a write barrier. so you should not synthesize the methods. @end Using Properties 2009-10-19 | © 2009 Apple Inc. Example The following example illustrates the use of properties in several different ways: ■ ■ The Link protocol declares a property. @property CGImageRef myImage. ■ ■ gratuitousFloat has a dynamic directive—it is supported using direct method implementations. This is typically incorrect. Listing 5-4 Declaring properties for a class @protocol Link @property id <Link> next. @property(copy) NSString *name. if the variable is declared __strong: . getter=nameAndAgeAsString) NSString *nameAndAge. it only requires a getter) with a specified name (nameAndAgeAsString). __strong CGImageRef myImage... creationTimestamp and next are synthesized but use existing instance variables with different names. In a garbage collected environment. it is supported using a direct method implementation (since it is read-only. @end @interface MyClass : NSObject <Link> { NSTimeInterval intervalSinceReferenceDate. then the accessors are synthesized appropriately—the image will not be CFRetain’d. but this is the default value.. } @property(readonly) NSTimeInterval creationTimestamp. 75 . next. @property CGFloat gratuitousFloat. MyClass also declares several other properties. you should implement them yourself. nameAndAge does not have a dynamic directive. . MyClass adopts the Link protocol so implicitly also declares the property next. @property(readonly. and uses instance variable synthesis (recall that instance variable synthesis is not ■ ■ supported using the legacy runtime—see “Property Implementation Directives” (page 71) and “Runtime Difference” (page 78)).. id <Link> nextLink. All Rights Reserved. CGFloat gratuitousFloat.
} . } . [name release]. [super dealloc]. the instance variable is synthesized. All Rights Reserved. value: @interface MyInteger : NSObject { NSInteger value. you could define a class MyInteger with a readonly property. } return self.(CGFloat)gratuitousFloat { return gratuitousFloat. . For example.(void)dealloc { [nextLink release]. } @end Subclassing with Properties You can override a readonly property to make it writable. } @property(readonly) NSInteger value. } . // Uses instance variable "nextLink" for storage. @synthesize next = nextLink. [NSDate timeIntervalSinceReferenceDate] intervalSinceReferenceDate]. .CHAPTER 5 Declared Properties @implementation MyClass @synthesize creationTimestamp = intervalSinceReferenceDate.(void)setGratuitousFloat:(CGFloat)aValue { gratuitousFloat = aValue. // in modern runtimes. } . // Synthesizing 'name' is an error in legacy runtimes.(NSString *)nameAndAgeAsString { return [NSString stringWithFormat:@"%@ (%fs)". // This directive is not strictly necessary.(id)init { if (self = [super init]) { intervalSinceReferenceDate = [NSDate timeIntervalSinceReferenceDate]. [self name]. name. @end @implementation MyInteger 76 Subclassing with Properties 2009-10-19 | © 2009 Apple Inc. @dynamic gratuitousFloat.
77 . property = [newValue copy]. . the method implementations generated by the compiler depend on the specification you supply. The declaration attributes that affect performance and threading are retain. The first three of these affect only the implementation of the assignment part of the set method.CHAPTER 5 Declared Properties @synthesize value. this may have a significant impact on performance. In a garbage collected environment. moreover a returned object is retained and autoreleased. In a reference counted environment. // retain if (property != newValue) { [property release]. as illustrated below (the implementation may not be exactly as shown): // assign property = newValue. If such accessors are invoked frequently. } // copy if (property != newValue) { [property release]. simply making all the properties in your class atomic does not mean that your class or more generally your object graph is “thread safe”—thread safety cannot be expressed at the level of individual accessor methods. most synthesized methods are atomic without incurring this overhead. the fact that you declared a property has no effect on its efficiency or thread safety. If you use synthesized properties. copy. @end @implementation MyMutableInteger @dynamic value. see Threading Programming Guide. Although “atomic” means that access to the property is thread-safe. property = [newValue retain]. MyMutableInteger. guaranteeing atomic behavior requires the use of a lock. It is important to understand that the goal of the atomic implementation is to provide robust accessors—it does not guarantee correctness of your code.(void)setValue:(NSInteger)newX { value = newX. All Rights Reserved. For more about multi-threading. assign. } @end Performance and Threading If you supply your own method implementation. and nonatomic. which redefines the property to make it writable: @interface MyMutableInteger : MyInteger @property(readwrite) NSInteger value. the synthesized accessors are atomic. By default. as illustrated in “Atomicity” (page 70). } The effect of the nonatomic attribute depends on the environment. @end You could then implement a subclass. Performance and Threading 2009-10-19 | © 2009 Apple Inc.
@property float differentName. @synthesize noDeclaredIvar. given the following class declaration and implementation: @interface MyClass : NSObject { float sameName. @end the compiler for the legacy runtime would generate an error at @synthesize noDeclaredIvar. @property float noDeclaredIvar. float otherName. There is one key difference: the modern runtime supports instance variable synthesis whereas the legacy runtime does not.CHAPTER 5 Declared Properties Runtime Difference In general the behavior of properties is identical on all runtimes (see Runtime Versions and Platforms in Objective-C Runtime Programming Guide). if you do not provide an instance variable. For @synthesize to work in the legacy runtime. @synthesize differentName=otherName. whereas the compiler for the modern runtime would add an instance variable to represent noDeclaredIvar. All Rights Reserved. . With the modern runtime. 78 Runtime Difference 2009-10-19 | © 2009 Apple Inc. you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the @synthesize statement. the compiler adds one for you. } @property float sameName. @end @implementation MyClass @synthesize sameName. For example."];
Adding Storage Outside a Class Definition
83
you could break the association between the array and the string overview using the following line of code: objc_setAssociatedObject(array.h> #import <objc/runtime. overview. 84 Retrieving Associated Objects 2009-10-19 | © 2009 Apple Inc. #import <Foundation/Foundation. overview is released and so in this case also deallocated. In general. Continuing the example shown in Listing 7-1 (page 83). you generate a runtime exception. &overviewKey). If you try to.CHAPTER 7 Associative References objc_setAssociatedObject(array. static char overviewKey. // (1) overview valid [array release]. // (2) overview invalid At point (1).” Complete Example The following program combines the code samples from the preceding sections. however (at point 2). (Given that the associated object is being set to nil. you could retrieve the overview from the array using the following line of code: NSString *associatedObject = (NSString *)objc_getAssociatedObject(array. nil. the policy isn’t actually important. &overviewKey. . you typically use objc_setAssociatedObject. passing nil as the value. you are discouraged from using this since this breaks all associations for all clients. OBJC_ASSOCIATION_RETAIN).h> int main (int argc. however. log the value of overview. Breaking Associations To break an association.) To break all associations for an object. &overviewKey. You only use this function if you need to restore an object to “pristine condition. [overview release]. OBJC_ASSOCIATION_ASSIGN). All Rights Reserved. When the array is deallocated. Retrieving Associated Objects You retrieve an associated object using the Objective-C runtime function objc_getAssociatedObject. you can use objc_removeAssociatedObjects. const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]. Continuing the example shown in Listing 7-1 (page 83). the string overview is still valid because the OBJC_ASSOCIATION_RETAIN policy specifies that the array retains the associated object. for example.
CHAPTER 7 Associative References NSArray *array = [[NSArray alloc] initWithObjects:@"One". &overviewKey. @"Two". objc_setAssociatedObject(array. 85 . &overviewKey. [overview release]. // For the purposes of illustration. } Complete Example 2009-10-19 | © 2009 Apple Inc. NSLog(@"associatedObject: %@". OBJC_ASSOCIATION_ASSIGN). nil. overview. [array release]. NSString *associatedObject = (NSString *)objc_getAssociatedObject(array. associatedObject). [pool drain]. OBJC_ASSOCIATION_RETAIN). &overviewKey). @"First three numbers"]. objc_setAssociatedObject(array. nil]. All Rights Reserved. use initWithFormat: to ensure we get a // deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@". return 0. @"Three".
. All Rights Reserved.CHAPTER 7 Associative References 86 Complete Example 2009-10-19 | © 2009 Apple Inc.
the corresponding documentation should make clear what property is iterated over—for example. NSDictionary. The syntax is concise. The iterating variable is set to nil when the loop ends by exhausting the source pool of objects. NSDictionary and the Core Data class NSManagedObjectModel provide support for fast enumeration. expression yields an object that conforms to the NSFastEnumeration protocol (see “Adopting Fast Enumeration” (page 87)). for example. the iterating variable is left pointing to the last iteration item. It should be obvious that in the cases of NSArray and NSSet the enumeration is over their contents. For other classes. and NSManagedObjectModel enumerates its entities.CHAPTER 8 Fast Enumeration Fast enumeration is a language feature that allows you to efficiently and safely enumerate over the contents of a collection using a concise syntax. 87 . The for…in Feature Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. Since mutation of the object during iteration is forbidden. and the code defined by statements is executed. and NSSet—adopt this protocol. The syntax is defined as follows: for ( Type newVariable in expression ) { statements } or Type existingItem. Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration. If the loop is terminated early. as does NSEnumerator. using NSEnumerator directly. The for…in Feature 2009-10-19 | © 2009 Apple Inc. There are several advantages to using fast enumeration: ■ ■ ■ The enumeration is considerably more efficient than. you can perform multiple enumerations concurrently. Adopting Fast Enumeration Any class whose instances provide access to a collection of other objects can adopt the NSFastEnumeration protocol. All Rights Reserved. The Cocoa collection classes—NSArray. NSDictionary enumerates its keys. The iterating variable is set to each item in the returned object in turn. for ( existingItem in expression ) { statements } In both cases. an exception is raised.
for (id element in array) { NSLog(@"Element at index %u is: %@". for (id element in array) { if (/* some test for element */) { // statements that apply only to elements passing test } 88 Using Fast Enumeration 2009-10-19 | © 2009 Apple Inc. as illustrated in the following example: NSArray *array = [NSArray arrayWithObjects: @"One". @"six". @"Two". index++. } } NSString *next = [enumerator nextObject]. element). nil]. NSArray *array = [NSArray arrayWithObjects: @"One". NSArray *array = /* assume this exists */. nil]. NSUInteger index = 0. . and if you want to skip elements you can use a nested conditional statement as shown in the following example: NSArray *array = /* assume this exists */. @"sex". so simply counting iterations will give you the proper index into the collection if you need it. the feature behaves like a standard for loop. nil]. NSEnumerator *enumerator = [array reverseObjectEnumerator]. element). NSString *key. You can use break to interrupt the iteration. @"Two". Latin: %@". for (NSString *element in array) { NSLog(@"element: %@". key. for (key in dictionary) { NSLog(@"English: %@. All Rights Reserved. @"five". } In other respects.CHAPTER 8 Fast Enumeration Using Fast Enumeration The following code example illustrates using fast enumeration with NSArray and NSDictionary objects. [dictionary valueForKey:key]). @"four". index. @"Four". @"Three". // next = "Two" For collections or enumerators that have a well-defined order—such as NSArray or NSEnumerator instance derived from an array—the enumeration proceeds in that order. @"Four". @"quinque". for (NSString *element in enumerator) { if ([element isEqualToString:@"Three"]) { break. @"Three". } NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor". } You can also use NSEnumerator objects with fast enumeration.
for (id element in array) { if (index != 0) { NSLog(@"Element at index %u is: %@". index. 89 . element). } } Using Fast Enumeration 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. you could do so as shown in this example: NSArray *array = /* assume this exists */. } if (++index >= 6) { break. NSUInteger index = 0.CHAPTER 8 Fast Enumeration } If you want to skip the first element then process no more than five further elements.
All Rights Reserved.CHAPTER 8 Fast Enumeration 90 Using Fast Enumeration 2009-10-19 | © 2009 Apple Inc. .
as described in “Dynamic Binding” (page 19). Note: Messages are somewhat slower than function calls. It also lets you turn some of its object-oriented features off in order to shift operations from runtime back to compile time. In the example above. In particular. The exact class of an id variable (and therefore its particular methods and data structure) isn’t determined until the program runs. typically incurring an insignificant amount of overhead compared to actual work performed. Default Dynamic Behavior 2009-10-19 | © 2009 Apple Inc. the compiler can’t check the exact types (classes) of id variables. 91 . Statically typed objects have the same internal data structures as objects declared to be ids. The exceptionally rare case where bypassing Objective-C's dynamism might be warranted can be proven by use of analysis tools like Shark or Instruments. thisObject can only be a Rectangle of some kind. To permit better compile-time type checking. Messages and methods are dynamically bound. the compiler restricts the value of the declared variable to be either an instance of the class named in the declaration or an instance of a class that inherits from the named class. Objects are dynamically typed. As many decisions about them as possible are pushed from compile time to runtime: ■ ■ The memory for objects is dynamically allocated at runtime by class methods that create new instances. it affects only the amount of information given to the compiler about the object and the amount of information available to those reading the source code. Objective-C allows objects to be statically typed with a class name rather than generically typed as id. A runtime procedure matches the method selector in the message to a method implementation that “belongs to” the receiver. In source code (at compile time). ■ These features give object-oriented programs a great deal of flexibility and power.CHAPTER 9 Enabling Static Behavior This chapter explains how static typing works and discusses some other features of Objective-C. Static Typing If a pointer to a class name is used in place of id in an object declaration. The type doesn’t affect the object. Rectangle *thisObject. including ways to temporarily overcome its inherent dynamism. Default Dynamic Behavior By design. any object variable can be of type id no matter what the object’s class is. Objective-C objects are dynamic entities. and to make code more self-documenting. but there’s a price to pay. All Rights Reserved.
which shows the class hierarchy including Shape and Rectangle. Rectangle *aRect. If Square is a subclass of Rectangle. (For reference. Type Checking With the additional information provided by static typing. A display message sent to thisObject [thisObject display]. ■ An assignment can be made without warning. it allows for compile-time type checking. It permits you to use the structure pointer operator to directly access an object’s instance variables. or inherits from. Statically typed objects are dynamically allocated by the same class methods that create instances of type id. the class of the variable receiving the assignment. The following example illustrates this: Shape *aShape. static typing opens up possibilities that are absent for objects typed id: ■ ■ In certain situations. provided the class of the object being assigned is identical to. A warning is issued if the receiver doesn’t have access to the method named in the message. When a statically typed object is assigned to a statically typed variable. the compiler generates a warning. the following code would still produce an object with all the instance variables of a Square. see Figure 1-2 (page 25). not the one in its Rectangle superclass. However. . The third is covered in “Defining a Class” (page 35). if the roles of the two variables are reversed and aShape is assigned to aRect. performs the version of the method defined in the Square class.) 92 Type Checking 2009-10-19 | © 2009 Apple Inc.CHAPTER 9 Enabling Static Behavior Static typing also doesn’t affect how the object is treated at runtime. It can free objects from the restriction that identically named methods must have identical return and argument types. Here aRect can be assigned to aShape because a Rectangle is a kind of Shape—the Rectangle class inherits from Shape. ■ The first two topics are discussed in the sections that follow. just as objects typed id are. By giving the compiler more information about an object. the compiler makes sure the types are compatible. The exact type of a statically typed receiver is still determined at runtime as part of the messaging process. not just those of a Rectangle: Rectangle *thisObject = [[Square alloc] init]. the compiler can make sure the receiver can respond. Messages sent to statically typed objects are dynamically bound. not every Shape is a Rectangle. the compiler can deliver better type-checking services in two situations: ■ When a message is sent to a statically typed receiver. aShape = aRect. aRect = [[Rectangle alloc] init]. All Rights Reserved. A warning is issued if they’re not.
Therefore. If you send the object a message to perform a Rectangle method. For example. However. . Static Typing to an Inherited Class An instance can be statically typed to its own class or to any class that it inherits from. The compiler has access to class-specific information about the methods. can be statically typed as NSObject.(double)worry. Return and Argument Types 2009-10-19 | © 2009 Apple Inc. This constraint is imposed by the compiler to allow dynamic binding. the compiler will treat it as a Shape. The following code is error-prone. the message is freed from the restrictions on its return and argument types. Because methods like alloc and init return ids. Rectangle’s version of the method is performed. The isFilled method is defined in the Rectangle class. Shape *myRectangle = [[Rectangle alloc] init]. aRect = [[Shape alloc] init]. if you send it a message to perform a method that the Shape class knows about. not in Shape. However. even though Rectangle overrides the method. the compiler will complain. At runtime. the compiler must treat all methods with the same name alike. methods in different classes that have the same selector (the same name) must also share the same return and argument types. When it prepares information on method return and argument types for the runtime system. Because the class of a message receiver (and therefore class-specific details about the method it’s asked to perform). it creates just one method description for each method selector. All instances. but is allowed nonetheless: Rectangle *aRect. All Rights Reserved. if you statically type a Rectangle instance as a Shape. BOOL solid = [myRectangle isFilled]. the class of the receiver is known by the compiler. Return and Argument Types In general. 93 . for example. Typing an instance to an inherited class can therefore result in discrepancies between what the compiler thinks would happen at runtime and what actually happens. suppose that the Upper class declares a worry method that returns a double. when a message is sent to a statically typed object. Similarly. [myRectangle display]. the compiler doesn’t ensure that a compatible object is returned to a statically typed variable. However. the compiler understands the class of a statically typed object only from the class name in the type designation. the compiler won’t complain.CHAPTER 9 Enabling Static Behavior There’s no check when the expression on either side of the assignment operator is an id. or an id to a statically typed object. can’t be known at compile time. and it does its type checking accordingly. A statically typed object can be freely assigned to an id.
but at runtime it actually returns an int and generates an error. .(int)worry. All Rights Reserved. it will think that worry returns an int. Errors will obviously result if a Middle instance is typed to the Upper class.CHAPTER 9 Enabling Static Behavior and the Middle subclass of Upper overrides the method and declares a new return type: . but it can do so reliably only if the methods are declared in different branches of the class hierarchy. 94 Static Typing to an Inherited Class 2009-10-19 | © 2009 Apple Inc. and if an instance is typed to the Middle class. The compiler will inform the runtime system that a worry message sent to the object returns a double. the compiler will think that its worry method returns a double. Static typing can free identically named methods from the restriction that they must have identical return and argument types. If an instance is statically typed to the Upper class.
you may need to convert a character string to a selector at runtime. refers to the unique identifier that replaces the name when the source code is compiled. All methods with the same name have the same selector. You can do this with the NSSelectorFromString function: setWidthHeight = NSSelectorFromString(aBuffer). It can be used to refer simply to the name of a method when it’s used in a source-code message to an object. It also. However. “selector” has two meanings. the compiler writes each method name into a table. rather than to the full method name. You can use a selector to invoke a method on an object—this provides the basis for the implementation of the target-action design pattern in Cocoa. and all methods with the same name have the same selector. 95 . It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. Conversion in the opposite direction is also possible. the selector for setWidth:height: is assigned to the setWidthHeight variable: SEL setWidthHeight. setWidthHeight = @selector(setWidth:height:). All Rights Reserved. Instead. Here. in some cases. Valid selectors are never 0. method = NSStringFromSelector(setWidthHeight). The runtime system makes sure each identifier is unique: No two selectors are the same. Methods and Selectors For efficiency. to distinguish them from other data. You must let the system assign SEL identifiers to methods. it’s futile to assign them arbitrarily. Compiled selectors are of type SEL. Methods and Selectors 2009-10-19 | © 2009 Apple Inc. then pairs the name with a unique identifier that represents the method at runtime. SEL. The @selector() directive lets you refer to the compiled selector.CHAPTER 10 Selectors In Objective-C. though. The NSStringFromSelector function returns a method name for a selector: NSString *method. SEL and @selector Compiled selectors are assigned to a special type. full ASCII names are not used as method selectors in compiled code.
they can have different argument and return types. and performSelector:withObject:withObject: methods. a message would be no different than a function call. and the method the receiver is asked to perform (request) is also determined at runtime (by the equally fictitious getTheSelector function). has the same selector as display methods defined in other classes. because of their separate domains. It discovers the return type of a method. A class method and an instance method with the same name are assigned the same selector. [helper performSelector:request]. 96 Varying the Message at Runtime 2009-10-19 | © 2009 Apple Inc. the receiver (helper) is chosen at runtime (by the fictitious getTheReceiver function). for example. [friend performSelector:@selector(gossipAbout:) withObject:aNeighbor]. If there were one selector per method implementation. is equivalent to: [friend gossipAbout:aNeighbor]. (Statically typed receivers are an exception to this rule. All Rights Reserved. there’s no confusion between the two. so it treats all methods with the same selector alike. However. Variable names can be used in both halves of a message expression: id helper = getTheReceiver(). The display method for one class. from the selector.CHAPTER 10 Selectors Methods and Selectors Compiled selectors identify method names. not method implementations. performSelector:withObject:. just as it’s possible to vary the object that receives the message. take SEL identifiers as their initial arguments. . In this example. Method Return and Argument Types The messaging routine has access to method implementations only through selectors. For example. This is essential for polymorphism and dynamic binding. Therefore. and the data types of its arguments. since the compiler can learn about the method implementation from the class type. All three methods map directly into the messaging function. dynamic binding requires all implementations of identically named methods to have the same return type and the same argument types.) Although identically named class methods and instance methods are represented by the same selector. SEL request = getTheSelector(). it lets you send the same message to receivers belonging to different classes. defined in the NSObject protocol. These methods make it possible to vary a message at runtime. A class could define a display class method in addition to a display instance method. except for messages sent to statically typed receivers. Varying the Message at Runtime The performSelector:.
For example. This would make it difficult for any object to respond to more than one button cell. menu items. Accordingly. NSControl objects are graphical devices that can be used to give instructions to an application. and a label. Each time you rearranged the user interface. This would be an unnecessary complication that Objective-C happily avoids. or the target object would have to discover which button the message came from and act accordingly. an error results. button cells and other controls would have to constrain the content of the message. a button labeled “Find” would translate a mouse click into an instruction for the application to start searching for something. casting doesn’t work for all types. (However. If the method that’s performed returns a different type. the Application Kit makes good use of the ability to vary both the receiver and the message. the method selector it should use in the message it sends. There would either have to be one target for each button. the name of the method would be frozen in the NSButtonCell source code. it should be cast to the proper type. an NSButtonCell instance can be initialized for an action message. All action messages take a single argument. The Application Kit defines a template for creating control devices and defines a few “off-the-shelf” devices of its own. [myButtonCell setAction:@selector(reapTheWind:)]. the object that should receive the message. Most resemble real-world control devices such as buttons. the NSButtonCell object sends a message instructing the application to do something. a label. The button cell sends the message using NSObject’s performSelector:withObject: method. When the user clicks the button (or uses the keyboard alternative). dials. They interpret events coming from hardware devices like the keyboard and mouse and translate them into application-specific instructions. an NSButtonCell object must be initialized not just with an image.CHAPTER 10 Selectors Note: performSelector: and its companion methods return an id. switches. the error often isn’t evident until the program executes.) The Target-Action Design Pattern In its treatment of user-interface controls. the NSButtonCell class defines an object that you can assign to an NSMatrix instance and initialize with a size. 97 . you would also have to re-implement the method that responds to the action message. a size. If Objective-C didn’t allow the message to be varied. all NSButtonCell objects would have to send the same message. a font. [myButtonCell setTarget:anObject]. the id of the control device sending the message. knobs. In software. Instead of simply implementing a mechanism for translating user actions into action messages. the method should return a pointer or a type compatible with a pointer. a picture. For example. It’s the same sort of error as calling a nonexistent function. these devices stand between the application and the user. But because messaging occurs at runtime. All Rights Reserved. and the like. To do this. but with directions on what message to send and who to send it to. and a target. The Target-Action Design Pattern 2009-10-19 | © 2009 Apple Inc. and a keyboard alternative. Avoiding Messaging Errors If an object receives a message to perform a method that isn’t in its repertoire. text fields.
"%s can’t be placed\n". if the message selector or the class of the receiver varies. If the receiver is statically typed. determines whether a receiver can respond to a message. The respondsToSelector: method. See Message Forwarding in Objective-C Runtime Programming Guide for more information. As you write your programs. even though the object responds to the message indirectly by assigning it to another object. the compiler performs this test for you. it appears that the object can handle the message. However. 98 Avoiding Messaging Errors 2009-10-19 | © 2009 Apple Inc. It takes the method selector as an argument and returns whether the receiver has access to a method matching the selector: if ( [anObject respondsToSelector:@selector(setOrigin::)] ) [anObject setOrigin:0.0 :0. it may be necessary to postpone this test until runtime.0]. else fprintf(stderr. For example. defined in the NSObject class.CHAPTER 10 Selectors It’s relatively easy to avoid this error when the message selector is constant and the class of the receiving object is known. [NSStringFromClass([anObject class]) UTF8String]). you can make sure that the receiver is able to respond. Note: An object can also arrange to have the messages it receives forwarded to other objects if it can’t respond to them directly itself. if you write code that sends a message to an object represented by a variable that others can set. . All Rights Reserved. The respondsToSelector: test is especially important when sending messages to objects that you don’t have control over at compile time. In that case. you should make sure the receiver implements a method that can respond to the message.
@try { [cup fill]. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3. Coupled with the use of the NSException. All Rights Reserved. by hardware as well as software. (This is illustrated in “Catching Different Types of Exception” (page 100). This article provides a summary of exception syntax and handling. NSError.) Exception Handling An exception is a special condition that interrupts the normal flow of program execution. Examples include arithmetical errors such as division by zero. A @catch() block contains exception-handling logic for exceptions thrown in a @try block. To turn on support for these features. You typically use an NSException object. and attempting to access a collection element out of bounds. @catch. calling undefined instructions (such as attempting to invoke an unimplemented method). which is essentially an Objective-C object. or custom classes. ■ ■ The example below depicts a simple exception-handling algorithm: Cup *cup = [[Cup alloc] init]. You can have multiple @catch() blocks to catch different types of exception.CHAPTER 11 Exception Handling The Objective-C language has an exception-handling syntax similar to that of Java and C++. see Exception Programming Topics for Cocoa. underflow or overflow.3 and later. (Note that this renders the application runnable only in Mac OS X v10. and @finally: ■ ■ Code that can potentially throw an exception is enclosed in a @try block. you can add robust error-handling to your programs. for more details.3 and later.) A @finally block contains code that must be executed whether an exception is thrown or not. You use the @throw directive to throw an exception. There are a variety of reasons why an exception may be generated (exceptions are typically said to be raised or thrown). Enabling Exception-Handling Using GNU Compiler Collection (GCC) version 3. Objective-C’s exception support revolves around four compiler directives: @try. Objective-C provides language-level support for exception handling. 99 . } Enabling Exception-Handling 2009-10-19 | © 2009 Apple Inc. @throw.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software. but are not required to.
} @catch (CustomException *ce) { // 1 . } @catch (NSException *ne) { // 2 // Perform processing necessary at this level. . The following list describes the numbered code-lines: 1. } @finally { // 3 // Perform processing necessary whether an exception occurred . 100 Catching Different Types of Exception 2009-10-19 | © 2009 Apple Inc. [exception reason]).. The @catch() blocks should be ordered from most-specific to the least-specific.. } @catch (id ue) { . use one or more @catch()blocks following the @try block. NSException *exception = [NSException exceptionWithName:@"HotTeaException" reason:@"The tea is too hot" userInfo:nil]. whether exceptions were thrown or not..... } @finally { [cup release]. as shown in Listing 11-1. Catches the most specific exception type. Catches a more general exception type.. such as the exception name and the reason it was thrown. All Rights Reserved. } Catching Different Types of Exception To catch an exception thrown in a @try block. [exception name]. That way you can tailor the processing of exceptions as groups. Throwing Exceptions To throw an exception you must instantiate an object with the appropriate information. ..CHAPTER 11 Exception Handling @catch (NSException *exception) { NSLog(@"main: Caught %@: %@". } or not. Listing 11-1 An exception handler @try { ... 2. Performs any clean-up processing that must always be performed. 3.
CHAPTER 11 Exception Handling @throw exception. You can throw any Objective-C object as an exception object. and provide information about the problem in an error object. For example. You can also subclass NSException to implement specialized types of exceptions. This can help make your code more readable. Important: In many environments. All Rights Reserved. see Error Handling Programming Guide For Cocoa. You are not limited to throwing NSException objects. Throwing Exceptions 2009-10-19 | © 2009 Apple Inc. you can re-throw the caught exception using the @throw directive without an argument. Instead you should use the return value of a method or function to indicate that an error has occurred. but you can implement your own if you so desire. Inside a @catch() block. such as file-system exceptions or communications exceptions. use of exceptions is fairly commonplace. Exceptions are resource-intensive in Objective-C. you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. 101 . The NSException class provides methods that help in exception processing. For more information. You should not use exceptions for general flow-control. or simply to signify errors.
All Rights Reserved.CHAPTER 11 Exception Handling 102 Throwing Exceptions 2009-10-19 | © 2009 Apple Inc. .
This object is known as a mutual exclusion semaphore or mutex. renders the application runnable only in Mac OS X v10. Synchronizing Thread Execution 2009-10-19 | © 2009 Apple Inc. use the -fobjc-exceptions switch of the GNU Compiler Collection (GCC) version 3. Other threads are blocked until the thread exits the protected code.(void)criticalMethod { @synchronized(self) { // Critical code.. You can take a similar approach to synchronize the class methods of the associated class. using the Class object instead of self. To protect sections of code from being executed by more than one thread at a time.3 and later. Note: Using either of these features in a program. The @synchronized() directive takes as its only argument any Objective-C object. that is. Before executing a critical process. Listing 12-1 shows an example of code that uses self as the mutex to synchronize access to the instance methods of the current object. only one thread at a time is allowed to execute a class method because there is only one class object that is shared by all callers. when execution continues past the last statement in the @synchronized() block. including self. All Rights Reserved. This means that two threads can try to modify the same object at the same time. Synchronizing Thread Execution Objective-C supports multithreading in applications. 103 . a situation that can cause serious problems in a program. In the latter case. The @synchronized()directive locks a section of code for use by a single thread. Objective-C provides the @synchronized() directive. It allows a thread to lock a section of code to prevent its use by other threads.3 and later because runtime support for exception handling and synchronization is not present in earlier versions of the software. which are explained in this article and “Exception Handling” (page 99).. You should use separate semaphores to protect different critical sections of a program. } } Listing 12-2 shows a general approach. To turn on support for these features. It’s safest to create all the mutual exclusion objects before the application becomes multithreaded to avoid race conditions. the code obtains a semaphore from the Account class and uses it to lock the critical section.CHAPTER 12 Threading Objective-C provides support for thread synchronization and exception handling. Listing 12-1 Locking a method using self . . of course. The Account class could create the semaphore in its initialize method.
releases the semaphore (so that the protected code can be executed by other threads). A thread can use a single semaphore several times in a recursive manner.. } The Objective-C synchronization feature supports recursive and reentrant code.CHAPTER 12 Threading Listing 12-2 Locking a method using a custom semaphore Account *account = [Account accountFromString:[accountField stringValue]]. and re-throws the exception to the next exception handler. . When code in an @synchronized() block throws an exception. every @synchronized() block is exited normally or through an exception. that is. other threads are blocked from using it until the thread releases all the locks obtained with it. id accountSemaphore = [Account semaphore].. the Objective-C runtime catches the exception. // Get the semaphore. 104 Synchronizing Thread Execution 2009-10-19 | © 2009 Apple Inc. @synchronized(accountSemaphore) { // Critical code. All Rights Reserved. .
where communication takes place between relatively self-contained units through messages that are resolved at runtime. in a typical server-client interaction. and messages for B wait in a queue until B is ready to respond to them: Distributed Objects 2009-10-19 | © 2009 Apple Inc. or it could isolate the processing work in a subordinate task. the threads are treated exactly like threads in different tasks. in different tasks) or in different threads of execution of the same task. Objective-C was initially designed for programs that are executed as a single process in a single address space. For example. and transfer data from one address space to another. (When remote messages are sent between two threads of the same task. It could simply display a dialog telling the user to wait while it was busy.CHAPTER 13 Remote Messaging Like most other programming languages. Objects in the two tasks would communicate through Objective-C messages. and the server might target specific client objects for the notifications and other information it sends. it is the remote object. the object-oriented model. Distributed Objects Remote messaging in Objective-C requires a runtime system that can establish connections between objects in different address spaces. It’s not hard to imagine Objective-C messages between objects that reside in different address spaces (that is. The proxy assumes the identity of the remote object. 105 . an application must first establish a connection with the remote receiver. To send a remote message. It then communicates with the remote object through the proxy. for most purposes. recognize when a message is intended for an object in a remote address space. Nevertheless.) Note that Cocoa’s distributed objects system is built on top of the runtime system. Using distributed objects. Or imagine an interactive application that needs to do a good deal of computation to carry out a user command. it doesn’t alter the fundamental behavior of your Cocoa objects. would seem well suited for interprocess communication as well. Remote messaging is illustrated in Figure 13-1 (page 106). Establishing the connection gives the application a proxy for the remote object in its own address space. leaving the main part of the application free to accept user input. Cocoa includes a distributed objects architecture that is essentially this kind of extension to the runtime system. where object A communicates with object B through a proxy. The application is able to regard the proxy as if it were the remote object. It must also mediate between the separate schedules of the two tasks. the client task might send its requests to a designated object in the server. All Rights Reserved. you can send Objective-C messages to objects in other tasks or have messages executed in other threads of the same task. it has no identity of its own. it has to hold messages until their remote receivers are free to respond to them.
The sending application doesn’t need to know how that application is designed or what classes it uses. The sending application doesn’t have to implement any of the methods in the protocol. Most of the issues are related to the efficiency of remote messaging and the degree of separation that the two tasks should maintain while they’re communicating with each other. arriving messages are placed in a queue and retrieved at the convenience of the receiving application. Its class is hidden inside the remote application. Its main function is to provide a local address for an object that wouldn’t otherwise have one. The receiving application declares it because the remote object must conform to the protocol. however. Therefore. So that programmers can give explicit instructions about the intent of a remote message. A proxy isn’t fully transparent. The sending application declares it to inform the compiler about the messages it sends and because it may use the conformsToProtocol: method and the @protocol() directive to test the remote receiver. but a lightweight substitute for it. A proxy doesn’t act on behalf of the remote object or need access to its class. is documented in the Foundation framework reference and Distributed Objects Programming Topics. Language Support Remote messaging raises not only a number of intriguing possibilities for program design. it’s transparent. including the NSProxy and NSConnection classes. So there’s no guarantee that the receiver is free to accept a message when the sender is ready to send it. an object that’s designated to receive remote messages advertises its interface in a formal protocol. a proxy doesn’t allow you to directly set and get an object’s instance variables. For instance. It isn’t a copy of the object. A remote receiver is typically anonymous.CHAPTER 13 Remote Messaging Figure 13-1 Remote Messages A Proxy for B B The sender and receiver are in different tasks and are scheduled independently of each other. It doesn’t need to use the same classes itself. Because of this. it simply passes the messages it receives on to the remote receiver and manages the interprocess communication. All Rights Reserved. Both the sending and the receiving application declare the protocol—they both import the same protocol declaration. . it declares the protocol only because it initiates messages to the remote receiver. The distributed objects architecture. All it needs to know is what messages the remote object responds to. it also raises some interesting issues for the Objective-C language. In a sense. Objective-C defines six type qualifiers that can be used when declaring methods inside a formal protocol: oneway in out inout bycopy 106 Language Support 2009-10-19 | © 2009 Apple Inc.
An asynchronous message can’t have a valid return value. Objective-C provides a return type modifier. Language Support 2009-10-19 | © 2009 Apple Inc. Sometimes it’s sufficient simply to dispatch the remote message and return.(BOOL)canDance. The following sections explain how these modifiers are used.CHAPTER 13 Remote Messaging byref These modifiers are restricted to formal protocols.(oneway void)waltzAtWill. has the advantage of coordinating the two communicating applications. they can’t be used inside class and category declarations. and the other message to send back the result of the remote calculation. two underlying messages are required—one message to get the remote object to invoke the method. However. All Rights Reserved. even if no information is returned. The sending application waits for the receiving application to invoke the method. it’s not always necessary or a good idea to wait for a reply. This is illustrated in the figure below: Figure 13-2 Round-Trip Message A Proxy for B initial message B return information Most remote messages are. the method looks at what’s stored in the address it’s passed. Pointer Arguments Next. at bottom. if a class or category adopts a protocol. to indicate that a method is used only for asynchronous messages: . Synchronous and Asynchronous Messages Consider first a method with just a simple return value: . the method is invoked and the return value provided directly to the sender. allowing the receiver to get to the task when it can. consider methods that take pointer arguments. two-way (or “round trip”) remote procedure calls (RPCs) like this one. Waiting for the receiver to finish. the sender can go on to other things. round-trip messages are often called synchronous. along with any return information requested. of keeping them both “in sync. Although oneway is a type qualifier (like const) and can be used in combination with a specific type name. In the meantime. complete its processing. When invoked. the only such combination that makes any sense is oneway void. such as oneway float or oneway id. Synchronous messages are the default. However. When a canDance message is sent to a receiver in the same application. 107 .” For this reason. But when the receiver is in a remote application. its implementation of the protocol methods can use the same modifiers that are used to declare the methods. and send back an indication that it has finished. oneway. A pointer can be used to pass information to the receiver by reference.
a string is represented as a character pointer (char *). a value from the other application must be sent back and written into the location indicated by the pointer.setTune:(struct tune *)aSong { tune = *aSong. pointers are sometimes used to represent composite values. . 108 Language Support 2009-10-19 | © 2009 Apple Inc. The only modifier that makes sense for arguments passed by value (non-pointers) is in. the value it points to doesn’t have to be sent to the other application. *theSong = tune. ship the value it points to over to the remote application. The method uses the pointer to find where it should place information requested in the message. store the value in an address local to that application. The runtime system for remote messaging must make some adjustments behind the scenes.. If. If the argument is used to pass information by reference. Although in notation and implementation there’s a level of indirection here. a string is an entity in and of itself. on the other hand. In neither case can the pointer simply be passed to the remote object unchanged. All Rights Reserved. in concept there’s not. ■ A third modifier.setTune:(in struct tune *)aSong... for which in is the default. it points to a memory location in the sender’s address space and would not be meaningful in the address space of the remote receiver. In the first case. the runtime system must dereference the pointer. the pointer is used to return information by reference. .getTune:(out struct tune *)theSong. Objective-C provides type modifiers that can clarify the programmer’s intention: ■ The type modifier in indicates that information is being passed in a message: . In C. In the second case. Because these cases result in very different actions on the part of the runtime system for remote messaging.adjustTune:(inout struct tune *)aSong. Instead. information is passed on the first leg of the round trip. } The same sort of argument can also be used to return information by reference. While in can be used with any kind of argument. Conceptually. indicates that an argument is used both to provide information and to get information back: . out and inout make sense only for pointers.getTune:(struct tune *)theSong { . The Cocoa distributed objects system takes inout to be the default modifier for all pointer arguments except those declared const. inout is the safest assumption but also the most time-consuming since it requires passing information in both directions. and pass that address to the remote receiver. ■ The modifier out indicates that an argument is being used to return information by reference: . .. } The way the pointer is used makes a difference in how the remote message is carried out. not a pointer to something else. inout.CHAPTER 13 Remote Messaging . For example. information is returned on the second leg of the round trip.
if ever. 109 . you will rarely. There are times when proxies may be unnecessarily inefficient. the out and inout modifiers make no sense with simple character pointers. You can override this behavior with byref.(bycopy)dancer. Since passing by reference is the default behavior for the vast majority of Objective-C objects. Messages sent to the proxy would be passed across the connection to the real object and any return information would be passed back to the remote application. however. All Rights Reserved. A danceWith: message passes an object id to the receiver. These conventions are enforced at runtime. The only type that it makes sense for bycopy or byref to modify is an object. consider a method that takes an object as an argument: . the distributed objects system automatically dereferences the pointer and passes whatever it points to as if by value. Objective-C provides a bycopy type modifier: . they would both be able to refer to the same aPartner object. The pointer that danceWith: delivers to a remote receiver is actually a pointer to the proxy. Proxies and Copies Finally. it cannot be anonymous. make use of the byref keyword. when it’s better to send a copy of the object to the remote process so that it can interact with it directly in its own address space. not by the compiler.danceWith:(id)aPartner. To give programmers a way to indicate that this is intended. The application that receives the object must have the class of the object loaded in its address space. This is true even if the receiver is in a remote application.danceWith:(bycopy id)aClone. It takes an additional level of indirection in a remote message to pass or return a string by reference: .adjustRectangle:(inout Rectangle **)theRect. bycopy can also be used for return values: .CHAPTER 13 Remote Messaging In cases like this. except that the receiver needs to refer to the object through a proxy (since the object isn’t in its address space). Language Support 2009-10-19 | © 2009 Apple Inc. for instance—that often these classes are written so that a copy is sent to a remote receiver. Therefore. instead of the usual reference. Note: When a copy of an object is passed to another application. whether dynamically typed id or statically typed by a class name. bycopy makes so much sense for certain classes—classes that are intended to contain a collection of other objects. If the sender and the receiver are in the same application. thereby specifying that objects passed to a method or objects returned from a method should be passed or returned by reference.getDancer:(bycopy out id *)theDancer.getTuneTitle:(out char **)theTitle. The same is true of objects: . It can similarly be used with out to indicate that an object returned by reference should be copied rather than delivered in the form of a proxy: .
All Rights Reserved.CHAPTER 13 Remote Messaging Although bycopy and byref can’t be used inside class and category declarations. For instance. they can be used within formal protocols. . 110 Language Support 2009-10-19 | © 2009 Apple Inc. you could write a formal protocol foo as follows: @Protocol foo . This allows you to construct protocols so that they provide “hints” as to how objects should be passed and returned by the methods described by the protocol. @end A class or category can then adopt your protocol foo.(bycopy)array.
and you can include pointers to C++ objects as instance variables of Objective-C classes.h> class Hello { private: id greeting_text. Mixing Objective-C and C++ Language Features 2009-10-19 | © 2009 Apple Inc. @interface Greeting : NSObject { @private Hello *hello. This Objective-C/C++ language hybrid is called Objective-C++. // holds an NSString public: Hello() { greeting_text = @"Hello. } void say_hello() { printf("%s\n". } Hello(const char* initial_greeting_text) { greeting_text = [[NSString alloc] initWithUTF8String:initial_greeting_text].(void)sayGreeting.mm * Compile with: g++ -x objective-c++ -framework Foundation Hello. Mixing Objective-C and C++ Language Features In Objective-C++.CHAPTER 14 Using C++ With Objective-C Apple’s Objective-C compiler allows you to freely mix C++ and Objective-C code in the same source file.mm */ #import <Foundation/Foundation. All Rights Reserved.(void)sayGreeting:(Hello*)greeting. Note: Xcode requires that file names have a “. Listing 14-1 illustrates this. } . .mm” extension for the Objective-C++ extensions to be enabled by the compiler.(id)init. 111 . . For example.(void)dealloc. you can call methods from either language in C++ code and in Objective-C methods. } }. Pointers to objects in either language are just pointers. [greeting_text UTF8String]). world!". and as such can be used anywhere. . With it you can make use of existing C++ libraries from your Objective-C applications. Listing 14-1 Using C++ and Objective-C instances as instance variables -o hello /* Hello. you can include pointers to Objective-C objects as data members of C++ classes.
monde!").. (This is consistent with the way in which standard C—though not C++—promotes nested struct definitions to file scope.(void)dealloc { delete hello. } . The object models of the two languages are thus not directly compatible. meaning that it is generally impossible to create an object instance that would be valid from the perspective of both languages. As previously noted.) To allow you to conditionalize your code based on the language variant. Greeting *greeting = [[Greeting alloc] init].(id)init { if (self = [super init]) { hello = new Hello().. the two type hierarchies cannot be intermixed. nor does it allow you to inherit Objective-C classes from C++ objects. the Objective-C++ compiler defines both the __cplusplus and the __OBJC__ preprocessor constants. the layout of Objective-C and C++ objects in memory is mutually incompatible. as specified by (respectively) the C++ and Objective-C language standards. [super dealloc]. More fundamentally.. 112 Mixing Objective-C and C++ Language Features 2009-10-19 | © 2009 Apple Inc. @interface ObjCClass: Base . } // > Hello. Objective-C++ does not allow you to inherit C++ classes from Objective-C objects. } @end int main() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]. // ERROR! Unlike Objective-C.. All Rights Reserved. } .. world! // > Bonjour. [pool release]. return 0. [greeting sayGreeting]. not nested within the Objective-C class. */ }. monde! As you can declare C structs in Objective-C interfaces.(void)sayGreeting:(Hello*)greeting { greeting->say_hello(). Hence.CHAPTER 14 Using C++ With Objective-C @end @implementation Greeting . objects in C++ are statically typed. class Base { /* . with runtime polymorphism available as an exceptional case. Hello *hello = new Hello("Bonjour. you can also declare C++ classes in Objective-C interfaces.(void)sayGreeting { hello->say_hello(). As with C structs. delete hello. [greeting sayGreeting:hello]. . } return self. [greeting release]. } . C++ classes defined within an Objective-C interface are globally-scoped.. @end // ERROR! class Derived: public ObjCClass .
} // OK } @end Bar *barPtr. as follows: @interface Foo { class Bar { . // OK } .. 113 . in declaration order immediately after the Objective-C object of which they are a member is allocated. (The fobjc-call-cxx-cdtors compiler flag is set by default in gcc-4.. All Rights Reserved. you can use instances of C++ classes containing virtual functions and nontrivial user-defined zero-argument constructors and destructors as instance variables.4 and later.2.. inside class_createInstance).CHAPTER 14 Using C++ With Objective-C You can declare a C++ class within an Objective-C class declaration. struct CStruct bigIvar. @interface Foo { struct CStruct { . The constructor used is the “public no-argument in-place constructor. inside object_dispose). // OK Objective-C allows C structures (whether declared inside of an Objective-C declaration or not) to be used as instance variables. Mixing Objective-C and C++ Language Features 2009-10-19 | © 2009 Apple Inc.” Destructors are invoked in the dealloc method (specifically.) Constructors are invoked in the alloc method (specifically. The compiler treats such classes as having been declared in the global namespace.. }. in reverse declaration order immediately before the Objective-C object of which they are a member is deallocated... if you set the fobjc-call-cxx-cdtors compiler flag. @end On Mac OS X 10.
protocol. C++ adds quite a few new keywords. even though class is a C++ keyword. For example. All Rights Reserved. SEL.CHAPTER 14 Using C++ With Objective-C Mac OS X v10. The compiler emits a warning in such cases. nor can you declare namespaces within Objective-C classes. they may be used as ordinary identifiers outside of Objective-C methods. or category. the compiler pre-declares the identifiers self and super. but you cannot use them for naming Objective-C classes or instance variables. nor can a C++ template be declared inside the scope of an Objective-C interface. Objective-C does not have a notion of nested namespaces. If any virtual member functions are present. In the parameter list of methods within a protocol. C++ Lexical Ambiguities and Conflicts There are a few identifiers that are defined in the Objective-C header files that every Objective-C program must include. Objective-C classes. }. Objective-C++ similarly strives to allow C++ class instances to serve as instance variables. int j). struct Class1 { virtual void foo(). the Objective-C runtime cannot initialize the virtual function table pointer. the Objective-C runtime cannot dispatch calls to C++ constructors or destructors for those objects. self and super are context-sensitive. }. out. Similarly. C++ template parameters can also be used as receivers or parameters (though not as selectors) in Objective-C message expressions. These are not keywords in any other contexts. they are not called. inout.. . @end C++ requires each instance of a class containing virtual functions to contain a suitable virtual function table pointer. unlike the C++ this keyword. Class. you can still use the NSObject method class: 114 C++ Lexical Ambiguities and Conflicts 2009-10-19 | © 2009 Apple Inc. protocols. #import <Cocoa/Cocoa. // WARNING . similarly to the keyword this in C++. These identifiers are id. in.3 and earlier. and categories cannot be declared inside a C++ template. If a C++ class has any user-defined constructors or destructors. the C++ class may not serve as an Objective-C instance variable. This is possible as long as the C++ class in question (along with all of its superclasses) does not have any virtual member functions defined. }. @interface Class0 Class1 Class1 Foo : NSObject { class0. and BOOL. However..h> struct Class0 { void foo(). because it is not familiar with the C++ object model. Inside an Objective-C method. there are five more context-sensitive keywords (oneway. IMP. You cannot declare Objective-C classes within C++ namespaces. // ERROR! *ptr.constructor not called! . // 'delete ptr' from Foo's dealloc Class2 class2. However. and bycopy). // OK class1. struct Class2 { Class2(int i. However. From an Objective-C programmer's point of view.3 and earlier: The following cautions apply only to Mac OS X v10. so the impact isn’t too severe. You can still use C++ keywords as a part of an Objective-C selector. Objective-C classes may serve as C++ template parameters. // OK—call 'ptr = new Class1()' from Foo's init.
an exception thrown in Objective-C code cannot be caught in C++ code and. Protocol and template specifiers use the same syntax for different purposes: id<someProtocolName> foo. multi-language exception handling is not supported. 115 . conversely. you cannot add constructors or destructors to an Objective-C object. The class hierarchies are separate. All Rights Reserved. Finally. Objective-C++ adds a similar case. That is. as in: label: ::global_name = 3. you cannot use class as the name of a variable: NSObject *class. Limitations 2009-10-19 | © 2009 Apple Inc. // Error In Objective-C. you can also have a category whose name matches that of a C++ class or structure. In Objective-C++. you cannot use Objective-C syntax to call a C++ object. Limitations Objective-C++ does not add C++ features to Objective-C classes. In addition. For more information on exceptions in Objective-C. To avoid this ambiguity. TemplateType<SomeTypeName> bar. nor does it add Objective-C features to C++ classes. see “Exception Handling” (page 99). both @interface foo and @interface(foo) can exist in the same source code.CHAPTER 14 Using C++ With Objective-C [foo class]. The space after the first colon is required. That is. and an Objective-C class cannot inherit from a C++ class. the compiler doesn’t permit id to be used as a template name. because it is a keyword. a C++ class cannot inherit from an Objective-C class. and you cannot use the keywords this and self interchangeably. // OK However. which also requires a space: receiver selector: ::global_c++_name. there is a lexical ambiguity in C++ when a label is followed by an expression that mentions a global name. the names for classes and categories live in separate namespaces. For example. an exception thrown in C++ code cannot be caught in Objective-C code.
CHAPTER 14 Using C++ With Objective-C 116 Limitations 2009-10-19 | © 2009 Apple Inc. All Rights Reserved. .
Note that the type of BOOL is char. For more information. or instance.. see the other chapters in this document.h. either YES or NO. Defined Types The principal types used in Objective-C are defined in objc/objc. This appendix lists all the additions to the language but doesn’t go into great detail. a compiler-assigned code that identifies a method name. A statically typed instance is declared to be a pointer to its class or to any class it inherits from. Messages 2009-10-19 | © 2009 Apple Inc. SEL IMP BOOL A selector. A Boolean value. class names can be used as type names to statically type instances of a class. . In addition. class. They are: Type id Definition An object (a pointer to its data structure). Class A class object (a pointer to the class data structure). A pointer to a method implementation that returns an id. All Rights Reserved. id can be used to type any kind of object.APPENDIX A Language Summary Objective-C adds a small number of constructs to the C language and defines a handful of conventions for effectively interacting with the runtime system. 117 .
118 Preprocessor Directives 2009-10-19 | © 2009 Apple Inc. except that it doesn’t include the same file more than once. (Class)0. @protected Limits instance variable scope to declaring and inheriting classes.APPENDIX A Language Summary The objc. (BOOL)1. . @implementation Begins the definition of a class or category. The following mutually exclusive directives specify the visibility of instance variables: Directive @private Definition Limits the scope of an instance variable to the class that declares it. . // Begins a comment that continues to the end of the line. All Rights Reserved. and protocols: Directive @interface Definition Begins the declaration of a class or category interface. Compiler Directives Directives to the compiler begin with “@” The following directives are used to declare and define classes. categories. A boolean false value.h header file also defines these useful terms: Type Definition nil Nil NO YES A null object pointer. or protocol. @public Removes restrictions on the scope of instance variables. (id)0. This directive is identical to #include. category. (BOOL)0. @protocol @end Begins the declaration of a formal protocol. A null class pointer. A boolean true value. Preprocessor Directives The preprocessor understands these special notations: Notation Definition #import Imports a header file. Ends the declaration/definition of a class.
All Rights Reserved. (The runtime from Mac OS X v10. the compiler generate accessor methods for which there are no custom implementations. 119 .APPENDIX A Language Summary The default is @protected. there are directives for these particular purposes: Directive @class @selector(method_name) Definition Declares the names of classes defined elsewhere. @finally Defines a block of code that is executed whether exceptions were thrown or not in a preceding @try block. Defines a constant NSString object in the current module and initializes the object with the specified string. for the properties whose names follow. @dynamic Instructs the compiler not to generate a warning if it cannot find implementations of accessor methods associated with the properties whose names follow. you can use UTF-16 encoded strings.4 and earlier. On Mac OS X v10. @protocol(protocol_name) Returns the protocol_name protocol (an instance of the Protocol class).5 to compile an application for Mac OS X v10.2 and later supports UTF-16 encoded strings. The following directives support the declared properties feature (see “Declared Properties” (page 67)): Directive @property Definition Begins the declaration of a declared property. @catch() Catches an exception thrown within the preceding @try block. These directives support exception handling: Directive @try @throw Definition Defines a block within which exceptions can be thrown. Throws an exception object. so if you use Mac OS X v10. you can also use UTF-16 encoded strings. @synthesize Requests that.0 and later). (@protocol is also valid without (protocol_name) for forward declarations.) @encode(type_spec) @"string" Yields a character string that encodes the type structure of type_spec. In addition.5 and later (with Xcode 3.2 and later. Returns the compiled selector that identifies method_name. the string must be 7-bit ASCII-encoded.) Compiler Directives 2009-10-19 | © 2009 Apple Inc. On Mac OS X v10.
If any protocols are listed.h" @interface ClassName : ItsSuperclass < protocol_list > { instance variable declarations } method declarations @end Everything but the compiler directives and class name is optional.. The interface file for its superclass must be imported: #import "ItsSuperclass.APPENDIX A Language Summary Directive Definition @"string1" @"string2" .h" @interface ClassName ( CategoryName ) < protocol list > method declarations @end The protocol list and method declarations are optional. If the colon and superclass name are omitted. a file containing a category definition imports its own interface: 120 Classes 2009-10-19 | © 2009 Apple Inc. .. The string @"stringN" created is the result of concatenating the strings specified in the two directives. the class is declared to be a new root class. Classes A new class is declared with the @interface directive. Defines a constant NSString object in the current module.h" @implementation ClassName method definitions @end Categories A category is declared in much the same way as a class. @synchronized() Defines a block of code that must be executed only by one thread at a time. All Rights Reserved. the header files where they’re declared must also be imported. A file containing a class definition imports its own interface: #import "ClassName. Like a class definition. The interface file that declares the class must be imported: #import "ClassName. the header files where they’re declared must also be imported. If any protocols are listed.
Formal Protocols 2009-10-19 | © 2009 Apple Inc. where the parentheses enclose the protocol name. A copy of the object.. The argument gets information returned by reference. to limit the type to objects that conform to the protocol ■ Within protocol declarations. Within source code. The protocol must import the header files that declare any protocols it incorporates. The @optional directive specifies that following methods are optional. to adopt the protocol (as shown in “Classes” (page 120) and “Categories” (page 120)) In a type specification. The argument both passes information and gets information. should be passed or returned.. to incorporate other protocols (as shown earlier) In a class or category declaration. The default is @required. You can create a forward reference to a protocol using the @protocol directive in the following manner: @protocol ProtocolName. The argument passes information to the remote receiver. 121 .>) are used to do three different things: ■ ■ In a protocol declaration. these type qualifiers support remote messaging: Type Qualifier Definition oneway in out inout bycopy The method is for asynchronous messages and has no valid return type. not a proxy. Protocol names listed within angle brackets (<. All Rights Reserved. protocols are referred to using the similar @protocol() directive. the @required directive directive specifies that following methods must be implemented by a class that adopts the protocol.APPENDIX A Language Summary #import "CategoryName.
. (However. Argument and return types are declared using the C syntax for type casting. ■ The default return and argument type for methods is id. Method Declarations The following conventions are used in method declarations: ■ ■ ■ ■ A “+” precedes declarations of class methods. for example: . Arguments are declared after colons (:).(void)setWidth:(int)newWidth height:(int)newHeight Typically. A “-” precedes declarations of instance methods. not a copy. All Rights Reserved. not int as it is for functions.) Method Implementations Each method implementation is passed two hidden arguments: ■ ■ The receiving object (self). a label describing the argument precedes the colon—the following example is valid but is considered bad style: . 122 Method Declarations 2009-10-19 | © 2009 Apple Inc. both self and super refer to the receiving object. should be passed or returned. super replaces self as the receiver of a message to indicate that only methods inherited by the implementation should be performed in response to the message. Deprecation Syntax Syntax is provided to mark methods as deprecated: @interface SomeClass -method __attribute__((deprecated)). Within the implementation. The selector for the method (_cmd). the modifier unsigned when used without a following type always means unsigned int.APPENDIX A Language Summary Type Qualifier Definition byref A reference to the object.(void)setWidthAndHeight:(int)newWidth :(int)newHeight Both labels and colons are considered part of the method name. Methods with no other valid return typically return void.
and protocol names generally begin with an uppercase letter. Method names beginning with “_” a single underscore character. Files that declare class and category interfaces or that declare protocols have the . 123 . Naming Conventions 2009-10-19 | © 2009 Apple Inc. Within a class.m extension. names can be freely assigned: ■ ■ ■ ■ ■ A class can declare methods with the same names as methods in other classes. are reserved for use by Apple.0 and later. Class. The names of variables that hold instances usually also begin with lowercase letters. However.APPENDIX A Language Summary @end or: #include <AvailabilityMacros.h extension typical of header files. or anything else. A program can’t have a global variable with the same name as a class. All Rights Reserved. Likewise. the names of methods and instance variables typically begin with a lowercase letter. class names are in the same name space as global variables and defined types. A method can have the same name as an instance variable.h> @interface SomeClass -method DEPRECATED_ATTRIBUTE. Naming Conventions The names of files that contain Objective-C source code have the . A class can declare instance variables with the same names as variables in other classes. In Objective-C. // or some other deployment-target-specific macro @end This syntax is available only in Objective-C 2. identical names that serve different purposes don’t clash. An instance method can have the same name as a class method. A category of one class can have the same name as a category of another class. category. . protocols and categories of the same class have protected name spaces: ■ ■ A protocol can have the same name as a class. a category.
All Rights Reserved. .APPENDIX A Language Summary 124 Naming Conventions 2009-10-19 | © 2009 Apple Inc.
Corrected minor typographical errors. Clarified use of the static specifier for global variables used by a class. noted use of ". Clarified the discussion of sending messages to nil. Corrected minor errors.mm" extension to signal Objective-C++ to compiler. . Corrected typographical errors. Date 2009-10-19 2009-08-12 2009-05-06 2009-02-04 2008-11-19 2008-10-15 2008-07-08 2008-06-09 Notes Added discussion of associative references.REVISION HISTORY Document Revision History This table describes the changes to The Objective-C Programming Language. Provided an example of fast enumeration for dictionaries and enhanced the description of properties. Corrected typographical errors. with several sections moved to a new Runtime Guide. All Rights Reserved. Updated article on Mixing Objective-C and C++." Corrected minor typographical errors. particularly in the "Properties" chapter. Significant reorganization. Made several minor bug fixes and clarifications. Clarified effect of sending messages to nil. Corrected minor typographical errors. 2008-02-08 2007-12-11 2007-10-31 2007-07-22 2007-03-26 2007-02-08 2006-12-05 2006-05-23 2006-04-04 2006-02-07 2006-01-10 2005-10-04 125 2009-10-19 | © 2009 Apple Inc. Extended the discussion of properties to include mutable objects. Corrected minor errors. Updated description of categories. Moved the discussion of memory management to "Memory Management Programming Guide for Cocoa. Clarified the description of Code Listing 3-3. Added references to documents describing new features in Objective-C 2.
Changed the font of function result in class_getInstanceMethod and class_getClassMethod. 2003-01-01 Documented the language support for declaring constant strings. Corrected definition of id.REVISION HISTORY Document Revision History Date 2005-04-08 Notes Corrected typo in language grammar specification and modified a code example. Clarified example in Listing 14-1 (page 111). Corrected the grammar for the protocol-declaration-list declaration in “External Declarations” . Moved function and data structure reference to Objective-C Runtime Reference. 126 2009-10-19 | © 2009 Apple Inc. Renamed from Inside Mac OS X: The Objective-C Programming Language to The Objective-C Programming Language. 2004-08-31 Removed function and data structure reference. Documented the Objective-C exception and synchronization support available in Mac OS X version 10. Added exception and synchronization grammar to “Grammar” . Moved “Memory Management” before “Retaining Objects” . Clarified when the initialize method is called and provided a template for its implementation in “Initializing a Class Object” . Replaced conformsTo: with conformsToProtocol: throughout document. Made technical corrections and minor editorial changes. Corrected definition of method_getArgumentInfo. . Added an index. Added exception and synchronization grammar. Documented the language support for concatenating constant strings in “Compiler Directives” (page 118). Corrected definition of the term conform in the glossary.3 and later in “Exception Handling and Thread Synchronization” . Fixed several typographical errors. 2004-02-02 2003-09-16 2003-08-14 Corrected typos in “An exception handler” . All Rights Reserved. Added examples of thread synchronization approaches to “Synchronizing Thread Execution” . Corrected the descriptions for the Ivar structure and the objc_ivar_list structure.
Fixed a bug in the Objective-C language grammar’s description of instance variable declarations. passive voice. Added runtime library reference material. and vice versa. Updated grammar and section names throughout the book to reduce ambiguities. Renamed from Object Oriented Programming and the Objective-C Language to Inside Mac OS X: The Objective-C Programming Language.1 introduces a compiler for Objective-C++. which allows C++ constructs to be called from Objective-C classes. Restructured some sections to improve cohesiveness. and archaic tone. All Rights Reserved. . 127 2009-10-19 | © 2009 Apple Inc.REVISION HISTORY Document Revision History Date 2002-05-01 Notes Mac OS X 10.
All Rights Reserved. .REVISION HISTORY Document Revision History 128 2009-10-19 | © 2009 Apple Inc.
a set of method definitions that is segregated from the rest of the class definition. category In the Objective-C language. class object In the Objective-C language. An instance conforms to a protocol if its class does. Application Kit A Cocoa framework that implements an application's user interface. adopt In the Objective-C language. 129 2009-10-19 | © 2009 Apple Inc. The Application Kit provides a basic program structure for applications that draw on the screen and respond to events. Class objects are created by the compiler. Decisions made at compile time are constrained by the amount and kind of information encoded in source files. Categories can be used to split a class definition into parts or to add methods to an existing class. asynchronous message A remote message that returns immediately. Protocols are adopted by listing their names between angle brackets in a class or category declaration. All Rights Reserved. but it can also be written to memory.Glossary abstract class A class that’s defined solely so that other classes can inherit from it. Objects that have the same types of instance variables and have access to the same methods belong to the same class. The interface to an anonymous object is published through a protocol declaration. An archived data structure is usually stored in a file. a method that can operate on class objects rather than instances of the class. archiving involves writing data to an NSData object. a class object is represented by the class name. only of its subclasses. a prototype for a particular kind of object. Cocoa is a set of frameworks with its primary programming interfaces in Objective-C. a class is said to conform to a protocol if it (or a superclass) implements the methods declared in the protocol. for later use. an object that represents a class and knows how to create new instances of the class. Cocoa An advanced object-oriented development platform on Mac OS X. or sent to another application. Thus. a class is said to adopt a protocol if it declares that it implements all the methods in the protocol. an instance that conforms to a protocol can perform any of the instance methods declared in the protocol. As the receiver in a message expression. compile time The time when source code is compiled. without waiting for the application that receives the message to respond. especially an object. archiving The process of preserving a data structure.” See also synchronous message. abstract superclass Same as abstract class. See also class object. class In the Objective-C language. and can’t be statically typed. class method In the Objective-C language. . Programs don’t use instances of an abstract class. but otherwise behave like all other objects. lack instance variables. The sending application and the receiving application act independently. copied to the pasteboard. In Cocoa. anonymous object An object of unknown class. and are therefore not “in sync. conform In the Objective-C language. A class definition declares instance variables and defines methods for all members of the class.
Through its superclass. 130 2009-10-19 | © 2009 Apple Inc. the hierarchy of classes that’s defined by the arrangement of superclasses and subclasses. implementation Part of an Objective-C class specification that defines its implementation. inheritance hierarchy In object-oriented programming. usually as a category of the NSObject class.. All other views in the window are arranged in a hierarchy beneath the content view. factory method Same as class method. a protocol that’s declared with the @protocol directive. Frameworks are sometimes referred to as “kits. All Rights Reserved. objects can respond at runtime when asked if they conform to a formal protocol. distributed objects Architecture that facilitates communication between objects in different address spaces. among others. framework A way to package a logically-related set of classes. dynamic typing Discovering the class of an object at runtime rather than at compile time. instance In the Objective-C language. other init. Through messages to self. an object that belongs to (is a member of ) a particular class. and other pertinent files. This section defines both public methods as well as private methods—methods that are not declared in the class’s interface. protocols and functions together with localized strings. event The direct or indirect report of external activity. dynamic binding Binding a method to a message—that is. factory object Same as class object. and any class may have an unlimited number of subclasses. dispatch table Objective-C runtime table that contains entries that associate method selectors with the class-specific addresses of the methods they identify. on-line documentation. factory Same as class object. especially user activity on the keyboard and mouse. formal protocol In the Objective-C language. This allows the implementation to be updated or changed without impacting the users of the interface. rather than at compile time. and the designated initializer. through a message to super. Classes can adopt formal protocols. but not to informal ones. Each class defines or inherits its own designated initializer. Instances are created at runtime according to the specification in the class definition. each class inherits from those above it in the hierarchy. dynamic allocation Technique used in C-based languages where the operating system provides memory to a running application as it needs it. the ability of a superclass to pass its characteristics (methods and instance variables) on to its subclasses.. Every class (except root classes such as NSObject) has a superclass. The language gives explicit support to formal protocols. a protocol declared as a category. id In the Objective-C language. the NSView object that’s associated with the content area of a window—all the area in the window excluding the title bar and border. delegate An object that acts on behalf of another object. methods in the same class directly or indirectly invoke the designated initializer. and instances can be typed by the formal protocols they conform to. informal protocol In the Objective-C language. designated initializer The init. the general type for any kind of object regardless of class. instead of when it launches.. inheritance In object-oriented programming. invokes the designated initializer of its superclass. encapsulation Programming technique that hides the implementation of an operation from its users behind an abstract interface.GLOSSARY content view In the Application Kit. finding the method implementation to invoke in response to the message—at runtime. . id is defined as a pointer to an object data structure. It can be used for both class objects and instances of a class.. method that has primary responsibility for initializing new instances of a class. Cocoa provides the Foundation framework and the Application Kit framework.” gdb The standard Mac OS X debugging tool.
” in German “Verlassen. and the protocols it conforms to. and public-method prototypes. message expressions are enclosed within square brackets and consist of a receiver followed by a message (method selector and arguments). Interface Builder A tool that lets you graphically specify your application’s user interface. the NSApplication object runs the main event loop.” main event loop The principal control loop for applications that are driven by events. instance variable In the Objective-C language. name space A logical subdivision of a program within which all names must be unique. In the Application Kit. key window The window in the active application that receives keyboard events and is the focus of user activity. any variable that’s part of the internal data structure of an instance. interface Part of an Objective-C class specification that declares its public interface. Symbols in one name space won’t conflict with identically named symbols in another name space. . nil In the Objective-C language. method In object-oriented programming. Objects are the principal building blocks of object-oriented programs. as are the class methods and instance variables. images. Used to synchronize thread execution. In Italian. in Objective-C. For example. an application localized in Spanish would display “Salir” in the application menu. waiting between events if the next event isn’t ready. introspection The ability of an object to reveal information about itself as an object—such as its class and superclass. menu A small window that displays a list of commands. a procedure that can be executed by an object. mutex Also known as mutual exclusion semaphore. Localization entails freeing application code from language-specific and culture-specific references and making it able to import localized resources (such as character strings. link time The time when files compiled from different source modules are linked into a single program. localize To adapt an application to work under various local conditions—especially to have it use a language selected by the user. For example.GLOSSARY instance method In the Objective-C language. which include its superclass name.” and in English “Quit. message In object-oriented programming. the method selector (name) and accompanying arguments that tell the receiving object in a message expression what to do. it would be “Esci. object A programming unit that groups together a data structure (instance variables) and the operations (methods) that can use or affect that data. From the time it’s launched until the moment it’s terminated. and sounds). instances variables. Objective-C doesn’t support multiple inheritance. Instance variables are declared in a class definition and become part of all objects that are members of or inherit from the class. It sets up the corresponding objects for you and makes it easy for you to establish connections between these objects and your own code where needed. the messages it can respond to. an object id with a value of 0. the ability of a class to have more than one superclass—to inherit from different sources and thus combine separately-defined behaviors in a single class. Only menus for the active application are visible on-screen. message expression In object-oriented programming. multiple inheritance In object-oriented programming. Decisions made by the linker are constrained by the compiled code and ultimately by the information contained in source code. 131 2009-10-19 | © 2009 Apple Inc. an expression that sends a message to an object. In the Objective-C language. any method that can be used by an instance of a class rather than by the class object. an application gets one keyboard or mouse event after another from the Window Manager and responds to them. All Rights Reserved. the instance methods of each class are in a separate name space.
by typing it as a pointer to a class. any class that’s one step below another class in the inheritance hierarchy. Decisions made at runtime can be influenced by choices the user makes. This technique allows one instance of an object to be safely shared among several other objects. each in its own way. procedural programming language A language. Because the application that sends the message waits for an acknowledgment or return information from the receiving application. When the object’s reference count reaches zero. subclass In the Objective-C language. synchronous message A remote message that doesn’t return until the receiving application finishes responding to the message. selector In the Objective-C language. reference counting Memory-management technique in which each entity that claims ownership of an object increments the object’s reference count and later decrements it. giving the compiler information about what kind of object an instance is. the object is deallocated. superclass In the Objective-C language. like C. that organizes a program as a set of procedures that have definite beginnings and ends. the ability of different objects to respond. . Compiled selectors are of type SEL.” See also asynchronous message. the name of a method when it’s used in a source-code message to an object. or the unique identifier that replaces the name when the source code is compiled. static typing In the Objective-C language. remote message A message sent from one application to an object in another application. a class that’s one step above another class in the inheritance hierarchy. surrogate An object that stands in for and forwards messages to another object. the declaration of a group of methods not associated with any particular class. and sometimes also used as a verb to mean the process of defining a subclass of another class. Outlet instance variables are a way for an object to keep track of the other objects to which it may need to send messages. runtime The time after a program is launched and while it’s running. receiver In object-oriented programming. the class through which a subclass inherits methods and instance variables.GLOSSARY outlet An instance variable that points to another object. Occasionally used more generally to mean any class that inherits from another class. the two applications are kept “in sync. remote object An object in another application. See also formal protocol and informal protocol. All Rights Reserved. protocol In the Objective-C language. the object that is sent a message. one that’s a potential receiver for a remote message. 132 2009-10-19 | © 2009 Apple Inc. polymorphism In object-oriented programming. to the same message.
81 and static typing 33 as receivers of messages 33 variables and 31 classes 23–33 root. 80 Class data type 29.(minus sign) before method names 36 // marker comment 118 @"" directive (string declaration) 119.c extension 10 A abstract classes 26. All Rights Reserved. 117 @class directive 37. 47 allocating memory 55 allocWithZone: method 47 anonymous objects 59 argument types and dynamic binding 93 and selectors 93 declaring 36 in declarations 122 arguments during initialization 48 hidden 122 in remote messages 107 type modifiers 108 variable 17 B behaviors of Cocoa objects 105 overriding 109 C language support 9 C++ language support 111–115 @catch() directive 99. 122 defined 28 of root class 32 using self 46 class object defined 24 initializing 31 class objects 28–32 and root class 32 and root instance methods 32. See root classes 133 2009-10-19 | © 2009 Apple Inc. 121 alloc method 29. . 119 class methods and selectors 96 and static variables 31 declaration of 36. 59 action messages 97 adaptation 24 adopting a protocol 62. 120 [“Dynamic Method Resolution”] 20 .Index Symbols + (plus sign) before method names 36 .
120. 103 exception handler 100 NSException 99. 119 formal protocols 60. 101 synchronization 104 system requirements 99. 103 throwing 100 and method declarations 122 and static typing 27. 120 designated initializer of 53 examples 13 identifying 15 implementation of 35. All Rights Reserved.h extension 35. 122 #import directive 37. See instance variables data types defined by Objective-C 117 designated initializer 53–55 development environment 9 directives. 28 naming conventions 123 subclasses 24 superclass 24 uses of 32 comment marker (//) 118 compiler directives. 121 See also protocols G GNU Compiler Collection 10 H . 123 hidden arguments 122 I id data type 117 D data members.INDEX abstract 26 and inheritance 24. 47 initialize method 32 initializing objects 45. 123 defining 35–42. 120 of methods 39. 55 inout type qualifier 121 instance methods 28 and selectors 96 declaration of 122 declaring 36 naming conventions 123 syntax 36 134 2009-10-19 | © 2009 Apple Inc. 118 implementation files 35. 38 implementation of classes 38–42. summary of 118–119 distributed objects 105 dynamic binding 19 dynamic typing 14 E @encode() directive 119 @end directive 35. 118 in type qualifier 121 #include directive 37 #include directive See #import directive informal protocols 61 See also protocols inheritance 24–26 of instance variables 51 of interface files 37 init method 29. 100. . 26 and instances 24 and namespaces 123 declaring 35–38. 118 exceptions 99–100 catching 100 clean-up processing 100 compiler switch 99. 91 as default method return type 36 of class objects 29 overview 14 IMP data type 117 @implementation directive 38. 38. 38 instance methods 28 interfaces 35 introspection 15. summary of 118 conforming to protocols 57 conformsToProtocol: method 106 conventions of this book 10–11 customization with class objects 29–30 F @finally directive 99. See instance variables data structures.
47. 25 NSSelectorFromString function 95 NSStringFromSelector function 95 M . 55 initializing a class object 31 instance variables 18 135 2009-10-19 | © 2009 Apple Inc. 28 isa instance variable 15. 17 selecting 19 specifying arguments 16 using instance variables 39 minus sign (-) before method names 36 . 91 examples 13 initializing 29.INDEX instance variables declaring 26. 96 O object 14 object identifiers 14 Objective-C 9 Objective-C++ 111 objects 24 allocating memory for 47 anonymous 59 creating 29 customizing 29 designated initializer 53 dynamic typing 14. 118 defined 13 encapsulation 40 inheriting 25–26. 45. 120 interface files 37. 36.m extension 10. 122 inheriting 26 instance methods 28 naming conventions 123 overriding 26 return types 93. 42 naming conventions 123 of the receiver 18 public access to 118 referring to 39 scope of 14. 19 and static typing 92 asynchronous 107 binding 92 defined 15. 117 message receivers 117 messages See also methods and selectors 16. 122 methods 13 See also behaviors See also messages adding with categories 79 and selectors 16. 17 synchronous 107 syntax 117 varying at runtime 19. 33 isMemberOfClass: method 28 and variable arguments 36 argument types 96 arguments 48. 123 memory allocating 47. 118. . 118 instances of a class allocating 47 creating 29 defined 24 initializing 29. 29 isKindOfClass: method 28. 96 messaging avoiding errors 97 to remote objects 105–110 metaclass object 29 method implementations 39. 118 NO constant 118 NSClassFromString function 33 NSException 99. 122 hidden arguments 122 implementing 39.mm extension 10 N name spaces 123 naming conventions 123 Nil constant 118 nil constant 14. 55 message expressions 15. 35. 117 sending 16. 93 calling super 51 class methods 28 declaring 36. 96 returning values 14. 40–42. 47–56 instances of the class See also objects @interface directive 35. 120 introspection 15. All Rights Reserved. 101 NSObject 24.
. 118 procedures. summary of 118 @private directive 40. 103 @synchronized() directive 103. 92 136 2009-10-19 | © 2009 Apple Inc. 118. 119. 119 type checking class types 91. 119 @try directive 99. 64 declaring 57. All Rights Reserved. 103 exceptions 104 mutexes 103 system requirements 99. 121 conforming to 57. 122 superclasses See also abstract classes and inheritance 24 importing 37 synchronization 103–104 compiler switch 99. 121 formal 60 forward references to 65. 118 selectors 95 and messaging errors 98 defined 16 self 43. 121 incorporating other protocols 64–65. declaring 119. 106. 121 informal 61 naming conventions 123 type checking 63 uses of 57–65 proxy objects 105 @public directive 41. 100. 119 96 plus sign (+) before method names 36 polymorphism defined 19 precompiled headers 37 preprocessor directives. 63. 121 Protocol objects 62 protocols 57–65 adopting 64.INDEX introspection 28 method inheritance 26 Protocol 62 remote 59 static typing 91 oneway type qualifier 121 out type qualifier 121 overriding methods 26 return types and messaging 96 and statically typed objects 93 declaration of 36 root classes See also NSObject and class interface declarations 36 and inheritance 24 categories of 81 declaration of 120 P performSelector: method 96 performSelector:withObject: method 96 performSelector:withObject:withObject: method S SEL data type 95. 118 @protocol directive 65. 120 subclasses 24 super variable 43. See methods @protected directive 41. 46. 120 R receivers of messages and class names 33 defined 117 in messaging expression 16 instance variables of 18 remote messages 105 remote objects 59 remote procedure calls (RPC) 107 respondsToSelector: method 98 T target-action paradigm 97 targets 97 this keyword 114 @throw directive 99. 45. 122 Smalltalk 9 specialization 24 static type checking 92 static typing 91–94 and instance variables 40 in interface files 38 introduced 27 to inherited classes 93 strings. 117 @selector() directive 95.
All Rights Reserved.INDEX protocol types 63 type introspection 28 types defined by Objective-C 117 U unsigned int data type 122 V variable arguments 36 void data type 122 Y YES constant 118 137 2009-10-19 | © 2009 Apple Inc. .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/doc/62156652/Apple-ObjC-Guide | CC-MAIN-2016-44 | refinedweb | 38,872 | 52.36 |
A game engine powered by python and panda3d
ursina
An easy to use game engine/framework for python.
Getting Started
Install Python 3.6 or newer
Make sure you have git installed.
Open cmd/terminal and type:
pip install git+
If you want to easily edit the source, it's recommended to clone the git repo and install as develop like this:
git clone python setup.py develop
Dependencies
- python 3.6+
- panda3d
- screeninfo, for detecting screen resolution
- hurry.size, for converting bytes to megabytes
- pillow, for texture manipulation
- psd-tools, for converting .psd files
- blender, for converting .blend files
Examples
from ursina import * # this will import everything we need from ursina with just one line. app = Ursina() ground = Entity( model = 'cube', color = color.magenta, z = -.1, y = -3, origin = (0, .5), scale = (50, 1, 10), collider = 'box', ) app.run() # opens a window and starts the game.
How do I make a game?
Ursina games are made by writing Python code. You can use any text editor you want, but personally I like to use Atom.
- Create an empty .py file called 'ursina_game.py'
- Copy this text into your new file:
from ursina import * # this will import everything we need from ursina with just one line. app = Ursina() player = Entity( model = 'cube' , # finds a 3d model by name color = color.orange, scale_y = 2 ) def update(): # update gets automatically called by the engine. player.x += held_keys['d'] * .1 player.x -= held_keys['a'] * .1 app.run() # opens a window and starts the game.
Type this in the terminal to start the game:
python ursina_game.py
If you use Atom, I recommend installing the package atom-python-run to tun your scripts with the press of a button.
You can now move the orange box around with 'a' and 'd'!
To close the window, you can by default, press shift+q or press the red x. to disable this, write 'window.exit_button.enabled = False' somewhere in your code.
GitHub
Get the latest posts delivered right to your inbox | https://pythonawesome.com/a-game-engine-powered-by-python-and-panda3d/ | CC-MAIN-2020-45 | refinedweb | 335 | 68.97 |
Aflați mai multe despre abonamentul Scribd
Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.
C/OS-II C/OS-Viewfor the NXP LPC2106 CPU(Using the IAR LPC2106-SK Evaluation Board)
Application NoteAN-1206
MicrimC/OS-II and C/OS-View for the NXP LPC2106 CPU
Table Of Contents1.00 1.01 1.02 2.00 2.01 2.02 3.00 3.01 3.02 4.00 Licensing References Contacts Introduction Directories and Files IAR Embedded Workbench Example Code Example Code, app.c Example Code, os_cfg.h Board Support Package (BSP) IAR-Specific BSP Files BSP, bsp.c and bsp.h C/OS-View 3 4 6 8 9 12 13 13 14 16 19 19 19
1.00
Introduction
This document shows example code for using C/OS-II and C/OS-View on a IAR LPC2106SK evaluation board, as shown in Figure 1, which employs NXPs ARM7TDMI-based LPC2106 microcontroller. This physically small but nevertheless flexible device provides support for external communications interfaces such as UART, SPI, and I2C. Its on-board peripherals include 2 32-bit timers and as many as 32 I/O ports. The processor has up to 128 kB of on-chip Flash memory and a 64 kB bank of RAM.
20-Pin J-Tag
LPC2106
UART0
UART1
LED1 - LED16
Push buttons
9-V DC Power
1.01
The code and documentation of the port are placed in directories in accordance with AN-2002, C/OS-II Directory Structure. The *.exe file that contains this document provides all of the files that are needed to run the example application described herein. As the previous section notes, this application features software components from Micrim, so the source files for C/OS-II are included in the zip file. Please note that these files, which are described below, are provided for evaluation purposes only. If you choose to use C/OS-II in a commercial product, you must contact Micrim to obtain the necessary licensing.
C/OS-II:\Micrium\Software\uCOS-II\Source This directory contains the processor independent code for C/OS-II. The version used was 2.83. \Micrium\Software\uCOS-II\Ports\ARM\Generic\IAR This directory contains the standard processor-specific files for the generic C/OS-II ARM port assuming the IAR toolchain. These files could easily be modified to work with other toolchains (i.e. compiler/assembler/linker/locator/debugger); however, you would place the modified files in a different directory. Specifically, this directory contains the following files: os_cpu.h os_cpu_a.asm os_cpu_c.c os_dcc.c os_dbg.c is included to provide additional information to Kernel Aware debuggers like IARs C-Spy.
With this port, you can use C/OS-II in either ARM or Thumb mode. Thumb mode, which drastically reduces the size of the code, was used in this example, but compiler settings may be switched to generate ARM-mode code without needing to change either the port or the application code. The ARM/Thumb port is fully described in application note AN-1014 which is available from the Micrium web site.
C/OS-View:\Micrium\Software\uCOSView\Source This directory contains the processor independent code for C/OS-View. The version used was 1.33. This directory contains the following files: os_view.c os_view.h
\Micrium\Software\uCOSView\Ports\ARM7\LPC2000\IAR This directory contains the LPC2000-specific port for C/OS-View: os_viewc.c os_viewc.h
Application Code:\Micrium\Software\EvalBoards\NXP\LPC210x-KickStartCard\IAR\OS-View This directory contains the source code for the example application, composed of the following files: app.c contains the test code for the example application including the functions that start C/OS-II, register tasks with the operating system, and update the user interface (the LEDs and PBs). The initialization functions of supplementary installed module (C/OS-View) are called from this file as well. app_cfg.h is a configuration file specifying stack sizes and priorities for all tasks and #defines for important global application constants. includes.h is a master include file used by the application. os_cfg.h is the C/OS-II configuration file. LPC2106-OS-View.* are the IAR Embedded Workbench project files.
\Micrium\Software\EvalBoards\NXP\LPC210x-KickStartCard\IAR\BSP This directory contains the Board Support Package for the IAR LPC2106-SK board: bsp.c contains the board support package which initializes critical processor functions (e.g., the clock generation unit) and provides support for peripherals such as the LEDs on the board. bsp.h contains prototypes for functions that may be called by the user. lpc2106_ram.xcl is an IAR linker file which contains information about the placement of data and code segments in the processors memory map. The data, execution stacks, and code are all mapped to the internal RAM. lpc2106_cstartup.s79
\Micrium\Software\uC-CPU\ARM\IAR This directory contains processor-specific code intended to be used with the IAR compiler for ARM processors. cpu_def.h, which is located directly in \Micrium\Software\uC-CPU, declares #define constants for CPU alignment, endianness, and other generic declarations. cpu.h defines the Micrim portable data types for 8, 16, and 32-bit signed and unsigned numbers (such as CPU_INT16U, which is a 16-bit unsigned type). These allow code to be independent of processor and compiler word size definitions. cpu_a.s contains generic assembly code for ARM7 or ARM9 processors which is used to enable and disable interrupts within the operating system. This code is called from C with OS_ENTER_CRITICAL() and OS_EXIT_CRITICAL().
1.02
We used the IAR Embedded Workbench (EW) V4.40a to test the example. Of course, C/OS-II can be used with other tools. We used the IAR Embedded Workbench (EW) V4.40a to test the example. Of course, C/OS-II can be used with other tools. To view the project you can either open the workspace file LPC2106-OS-View.eww (by left-clicking on the file) in the example project directory \Micrium\Software\EvalBoards\NXP\LPC210x-KickStartCard\OS-View or add the project file LPC2106-OS-View.ewp to a new workspace. To do the latter, open IAR EWARM and choose the Add Existing Project menu command under the Project menu. Figure 1-2 shows the project configuration tree in the EW.
2.00
Example Code
The example application performs one primary interface function: manipulating the on/off status of the boards LEDs. When started, the LEDs will begin blinking in a repetitive sequence: a chain of 5 LEDs will loop around the row of 16 LEDs. Two push buttons, PB2 (labelled ISP/INT1) and PB4 (labelled INT2) control the rate at which the LEDs blink. Pressing PB2 will cause the delay between change in the LED status to be decremented by 5 ms; pressing PB2 will cause the delay to increment by 5 ms. The user interface components are located on the LPC2106-SK evalueation board in Figure 2-1. PB1:Does Nothing
PB3:Does Nothing
PB2: LEDs:Blink Decrements Delay Time
PB4:Increments Delay Time
UART1:Enable
LED Jumpers:Connect to LEDs
2.01
A limited set of the LPC2106 capabilities are exhibited by the application code in app.c. A few tasks are created, one of which merely updates the LEDs on the board. However, the power and convenience of both C/OS-II Real-Time Kernel and the LPC2106 (in addition to the C/OS-II Kernel Awareness plug-in for C-Spy and C/OS-View) are amply demonstrated with this small application.
BSP_IntDisAll(); OSInit();
OSTaskCreateExt(AppTaskStart, /* (4) */ (void *)0, (OS_STK *)&AppTaskStartStk[APP_TASK_START_STK_SIZE - 1], APP_TASK_START_PRIO, APP_TASK_START_PRIO, (OS_STK *)&AppTaskStartStk[0], APP_TASK_START_STK_SIZE, (void *)0, OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR); #if OS_TASK_NAME_SIZE > 13 OSTaskNameSet(APP_TASK_START_PRIO, "Start Task", &err); #endif OSStart(); } /* (5) */
/* (6) */
L2-1(1) L2-1(2)
As with most C applications, the code starts in main(). All interrupts are disabled to make sure the application does not get interrupted until it is fully initialized. As with all C/OS-II applications, OSInit() must be called before creating a task or any other kernel object. We then create at least one task (in this case, using OSTaskCreateExt() to obtain additional information about your task). C/OS-II creates either one or two internal tasks in OSInit(). C/OS-II always creates an idle task, OS_TaskIdle(), and will create a statistics task, OS_TaskStat() if you set OS_TASK_STAT_EN to 1 in OS_CFG. As of V2.6x, you can now name C/OS-II tasks (and other kernel objects) and display task names at run-time or with a debugger. In this case, we name our first task as well as the two internal C/OS-II tasks. Because C-Spy can work with the Kernel Awareness Plug-In available from Micrium, task names can be displayed during debugging.
L2-1(3) L2-1(4)
L2-1(5)
L2-2(6)
Finally, C/OS-II is started by calling OSStart(). C/OS-II will then begin executing AppTaskStart() since that is the highest priority task created (both OS_TaskStat() and OS_TaskIdle() have lower priorities).
/* (3) */
L2-2(1)
BSP_Init() initializes the Board Support Packagethe I/Os, the tick interrupt, etc. (See Section 3.0 for details.)
10
L2-2(2)
OSStatInit() is initializes C/OS-IIs statistic task. This only occurs if you enable the statistics task by setting OS_TASK_STAT_EN to 1 in OS_CFG.H. The statistics task measures overall CPU usage (expressed as a percentage) and also performs stack checking for all the tasks that have been created with OSTaskCreateExt() with the stack checking option set. OSView_Init() initializes the C/OS-View module, including the UART interface, for which reason the baud rate of the RS-232C port connected to the Windows view is specified as an argument. If you purchased C/OS-View, please enable it according to the instructions contained in Section 4.00. The sole additional application task, AppTaskUserIF(), is created. See Listing 24. A mailbox is setup to channel the communication between the External Interrupt ISR handlers and this task. An ISR will use this mechanism to inform the start task that the interface delay should change after PB2 or PB4 is pressed See Listing 2-4 and for further details. The LPC2106s relevant external interrupts are configured. Each is located on an separate interrupt vector number and, for simplicity, separate interrupt service routines are used. PB2 will decrease the interface delay (the delay between changes in the status of the LEDs). PB4 will increase the interface delay. See Listing 2-4 for more details about these functions. Any task managed by C/OS-II must either enter an infinite loop waiting for some event to occur or terminate itself. In an infinite loop, this task will loop a string of 5 consecutive LEDs around the strip of 16. The argument to LED_Off() may appear somewhat cryptic, but this is only an extension of the typical mechanism used to navigate a circular buffer. Before the task enters the infinite loop, the final 4 LEDs (LED13, LED14, LED15, and LED16) are turned on; upon entering the loop, the first LED (LED1) is turned on. This statement will, upon its first execution, turn off LED12; thereby maintaining 5 lit LEDs that will appear to progress across the row and loop around. For this situation, the appropriate LED to turn off will be 16 ((16 i) + 5) % 16 = 16 (21 i) % 16.
L2-2(3)
L2-2(4) L2-2(5)
L2-2(7)
L2-2(8)
L2-2(9)
The mailbox EINT_Mbox is checked for messages. The message should either be the integer 1 or the integer 2. The former will cause the delay to be decremented by 5 millisecods. The latter will cause the delay to be incremented by 5 milliseconds. If there is no message in the mailbox, then the delay does not change.
11
/* (1) */
/* (2) */
The BSP functions PB_EINT1_Init() and PB_EINT2_Init() are called from AppStartTask() to initialize the external interrupts on the LPC2106 processor which will be used for the push buttons. After this initialization, an interrupt will be generated whenever one of the push buttons is pressed, whereby the code in these functionsthe interrupt handler attached to the appropriate vectorwill be invoked. If PB2 or PB4 has been pressed, then AppStartTask() will change the delay value it uses. L2-4(1) L2-4(2) If PB2 has been pressed, then the integer 1 will be sent to the user interface task, causing the interface delay to be decreased by 5 milliseconds. If PB4 has been pressed, then the integer 2 will be sent to the user interface task, causing the interface delay to be increased by 5 milliseconds.
2.02
This file is used to configure C/OS-II. Among the approximately 60 #defines in this file are included variables defining the maximum number of tasks that your application can have, which services will be enabled (semaphores, mailboxes, queues, etc.), and the size of the idle and statistic task. Each entry is commented and additional information about the purpose of each #define can be found in C/OS-II, the Real-Time Kernel by Jean Labrosse. os_cfg.h assumes you have C/OS-II V2.83 or higher.
12
3.00
The Board Support Package (BSP) provides functions to encapsulate common I/O access functions and make porting your application code easier. Essentially, these files are the interface between the application and the IAR LPC2106-SK board. Though one file, bsp.c, contains some functions which are intended to be called direcly by the user (all of which are prototyped in bsp.h), the other files serve the compiler (as with lpc2106_cstartup.s79).
3.01
The BSP includes two files intended specifically for use with IAR tools: lpc2106_ram.xcl and lpc2106_cstartup.s79. These serve to define the memory map and initialize the processor prior to loading or executing code. If the example application is to be used with other toolchains, the services provided by these files must be replicated as appropriate. Before the processor memories can be programmed, the compiler must know where code and data should be placed. To accomplish this, IAR requires a linker command file, such as lpc2106_ram.xcl, that provides directives to accomplish this. All code, data segments, and stack and heap segments are placed in the in the 64 kB internal Flash between 0x40000000 and 0x4000FFFF, with the first 64 bytes of RAM reserved for the exception vector table. In lpc2106_cstartup.s79 is code which will be executed prior to calling main. One important inclusion is the specification of the exception vector table (as required for ARM cores) and the setup of various exception stacks. After executing, this function branches to the IARspecific ?main function, in which the processor is further readied for entering application code.
13
3.02
Though the BSP provided with the application code provides only the limited set of capabilities need for the example application to run, the amount of code exceeds what can be practically discussed in this format. Consequently, only the salient features of the BSP, including any remarkable features, problems, or solutions, will be discussed.
The function BSP_Init() should be called before any of the boards features are accessed (such as the LEDs); however, because C/OS-II s timer is initialized herein, this function should not be called until multitasking is started (i.e., OSStart() is called). L3-1(1) L3-1(2) L3-1(3) L3-1(4) The ARM exception vectors located in the bottom 64 bytes of memory are initialized. The processors PLL and clocks are initialized. The I/O ports used on the board (for the LEDs, the PBs, and the UART) are intiailized. The vectors in the Vectored Interrupt Controller (VIC) is initialized and the VIC is enabled. The C/OS-II tick interrupt source is then initialized. See Listing 3-2 for details.
L3-1(5)
14
&= = = =
peripheral_clk_freq = BSP_CPU_ClkFreqPeripheral(); T0TCR T0PC T0MR0 T0MCR T0CCR T0EMR T0TCR } = 0; = 0; = peripheral_clk_freq / OS_TICKS_PER_SEC; = 3; = 0; = 0; = 1;
The interrupt controller is setup to vector to Tmr_TickISR_Handler() when timer #0 issues an interrupt. The VIC vector #2 is used for the timer ISR. The peripheral clock frequency BSP_CPU_ClkFreqPeripheral(). is calculated using the function
The timer is set to generate an interrupt when TC equals MR0 and to automatically reset TC.
15
4.00
C/OS-View
C/OS-View, a module that allows you to view useful statistics gathered from C/OS-II, can be readily added to the example application. After licensing C/OS-Views source files from Micrium and obtaining the modules Windows application, you can begin to use C/OS-View after completing a few simple operations. First, you will need to use a serial cable to connect the boards RS232 port (which is marked UART1) to an available serial port on your PC. Second, assign a value of 1 to the constant OS_VIEW_MODULE in os_cfg.h and reinclude C/OSViews source files and the LPC2106 port (as shown in Figure 4-1).
Click the check box in the upper-left corner name Exclude from build
16
After making these preparations, build and run your application and start C/OS-Views Windows application. Through the Setup dialog box, specify the COM port on your computer to which the board is connected and a baud rate of 38400. When you have completed these initializations, the Windows application will begin receiving packets from the board, eventually resulting in a graph resembling that which is shown in Figure 4-2.
The percentage of CPU time each task relative to all the tasks; The number of times each task has been 'switched-in'; and The execution profile of each task. C/OS-View also allows you to send commands to your target and allow your target to reply back and display information in a 'terminal window'. C/OS-View is licensed on a per-developer basis. In other words, you are allowed to install C/OS-View on multiple PCs as long as the PC is used by the same developer. If multiple developers are using C/OS-View then each needs to obtain his own copy. Contact Micrim for pricing information.
18
LicensingC/OS-II is provided in source form for FREE evaluation, for educational use or for peaceful research. If you plan on using C/OS-II in a commercial product you need to contact Micrim to properly license its use in your product. We provide ALL the source code with this application note for your convenience and to help you experience C/OS-II. The fact that the source is provided does NOT mean that you can use it without paying a licensing fee. Please help us continue to provide the Embedded community with the finest software available. Your honesty is greatly appreciated.
ReferencesC/OS-II, The Real-Time Kernel, 2nd Edition Jean J. Labrosse R&D Technical Books, 2002 ISBN 1-57820-103-9 Embedded Systems Building Blocks Jean J. Labrosse R&D Technical Books, 2000 ISBN 0-87930-604-1
ContactsIAR Systems Century Plaza 1065 E. Hillsdale Blvd Foster City, CA 94404 USA +1 650 287 4250 +1 650 287 4253 (FAX) e-mail: Info@IAR.com WEB : CMP Books, Inc. 1601 W. 23rd St., Suite 200 Lawrence, KS 66046-9950 USA +1 785 841 1631 +1 785 841 2624 (FAX) e-mail: rushorders@cmpbooks.com WEB:
Micrim 949 Crestview Circle Weston, FL 33327 USA +1 954 217 2036 +1 954 217 2037 (FAX) e-mail: Jean.Labrosse@Micrium.com WEB:
NXP 1110 Ringwood Court San Jose, CA 95131 +1 408 474 8142 WEB:
19
Mult mai mult decât documente.
Descoperiți tot ce are Scribd de oferit, inclusiv cărți și cărți audio de la editori majori.Anulați oricând. | https://ro.scribd.com/document/84997906/AN-1206 | CC-MAIN-2020-05 | refinedweb | 3,293 | 55.03 |
« TPAC 2007 - Making Video a First-Class Citizen of the Web | Main | TPAC 2007 - HTML Working Group holds first face-to-face meeting »
TPAC 2007 - Cracks and Mortar
Tim Berners-Lee is taking the floor: "The world is a mess of interconnected communities and it is why it is working."
- Content-Type: is a way to define the content available at a specific URI. It gives flexibility for evolution. It reminds me that we, olivier and I, gave at Keio University a talk on Web architecture and we talked about content-type. HTML 5 proposes to jeopardize the content-type ignoring the server part of the architecture.
- TAG Soup: Tim reminds that documenting existing practice is fine but evolving toward clean markup sounds like a good idea.
- Validation: it should allow extensibility, it should explain problems and motivation, and balance its level of disapprobation.
- Browsers: save as to help having a cleaner markup.
- Alternatives: central registry of terms - microformats, etc.
- New tags and attributes in HTML: validator complains, then microformats overload classes. This is a vicious circle.
- Canvas and SVG: Tim is asking for dialog between the communities. Look also at the comparison between the two.
- XML top-down dispatch offers a recursive dispatch.
- Multiple namespaces in RDF
The future open doors to new things linked data, Coumpound Document Format as an alternative to Silverlight and AIR, FOAF+Openid for blocking spam and makes open social networks, mobile web, video and more.
Filed by Karl Dubost on November 7, 2007 6:14 PM in Meetings, Opinions and Editorial, W3C Life, W3C・Resources
|. | http://www.w3.org/QA/2007/11/tpac-2007-cracks-and-mortar.html | CC-MAIN-2013-20 | refinedweb | 262 | 55.54 |
Linked by Kroc Camen on Tue 17th May 2011 12:05 UTC
Thread beginning with comment 473499
To view parent comment, click here.
To read all comments associated with this story, please click here.
To view parent comment, click here.
To read all comments associated with this story, please click here.
RE[3]: legal Problems are deep
by oiaohm on Wed 18th May 2011 04:43 in reply to "RE[2]: legal Problems are deep"
Doesn't Java have a Point class? Is that "Dangerous" to use as well? Or is it only "Dangerous" if used from C#?
The issue here is method used in the C# point class might be MS unique and patented. Same with every other class that is not contained in the ECMA. There maybe landmines. Safe bet is to be able to build on a landmine free field. What mono does not provide developers with.
Java if your Java is from Redhat, IBM or Oracle. It has a full patent coverage. All open source java engines form them are under GPL or LGPL.
Java has 3 approved suppliers that can make their own forms. Oracle cannot attack Redhat or IBM or product produced using Java patents. Same with reverse. IBM cannot use it patents that cover java against Redhat or Orcale building a JVM. And so on. Also this patent allowance does not have a timeframe. New patents taken out by IBM Orcale or Redhat cannot be applied against each other or their users over java.
Multi patent safe supply lines. Its also possible to build with a non extended Java. Redhat or Orcales base Java's provide. So you know you are inside the patent protected zone.
.Net. MS the only supplier with full unlimited supply protection. Novell had until the end of this year. If you were building with ECMA spec .net you would also have unlimited timeframe but there are basically no one is providing that.
Issue with mono is that there are many namespaces that cannot be disabled that are outside the patent shield of the community promise. So developers cannot simply check if they are inside or outside the protection.
Java is simple install the Orcale JVM or the Redhat JVM if you application works it using nothing from the JVM that does not have patent protection.
Now lets do .net. Application works fine on MS .net nop that is extended. It works fine on mono nop that is extended. This is not a suitable outcome.
Even with C and C++ I can restrict my build and runtime environments so only patent protection covered parts or too old to be patent protected out there. .Net currently too hard to be sure you are legally free and clear unless you restrict yourself to Microsoft products only.
Basically if you can present me with a method that I can be 100 percent sure I am running legally free and clear with .net on Linux OS X and so on. I maybe interested in the language.
Legal side must be answered. All the data of the legal issues of mono is out there. Been done many times over. Time to stop saying its not important.
GTK interfaces for mono most likely are not a legal issue since patent breach most likely would have to be in GTK so would have a heavy legal defense.
This is the critical thing. The most dangerous stuff is by MS and not covered by a patent grant.
Remember MS has been caught selling patents off to patent trolls to have those patents used against Linux. Yes so MS can patent attack Linux without their name on it. Nothing is stopping MS from selling patents off to trolls to attack mono users if mono ever becomes a threat to their market share.
MS is confirmed hostile to open source by their actions.
RE[4]: legal Problems are deep
by Slambert666 on Wed 18th May 2011 09:39 in reply to "RE[3]: legal Problems are deep"
This is the critical thing. The most dangerous stuff is by MS and not covered by a patent grant.
You are applying double standards here.
Microsoft has not issued a patent grant for the following technologies:
Python, PHP, Linux Kernel, (Free, Open, NET) BSD Kernel, ttf, rendering (numerous patents), application skinning (numerous patents), Ruby, LUA, IDE's, Libre Office etc. etc. etc. etc.
Obviously you must argue against their usage since there is no MS Patent Grant.
What on earth makes you think that Mono is somehow different?
Member since:
2008-10-30
You know that your linked article is just counting namespaces and not classes or use of patents.
For example a point struct is best kept in System.Drawing and therefore System.Drawing is included even if no "Patent Promise" exists for this namespace.
So how is it so "Dangerous" to use a point struct?
Doesn't Java have a Point class? Is that "Dangerous" to use as well? Or is it only "Dangerous" if used from C#?
Is short, your spin is disingenuous at best. | http://www.osnews.com/thread?473499 | CC-MAIN-2017-22 | refinedweb | 846 | 76.22 |
Swing 107
How many times have you opened a book in search of a solution and found not only an answer, but also an elegant enhancement to your application? How many times have you ignored an O'Reilly book on the same subject lying on your table? The answer is Manning's new book Swing authored by Mathew Robinson and Pavel Vorobiev. And that is my final answer.
The book (with just a 5-character title) is 917 pages long and is divided into four parts containing 23 chapters, an appendix and a bibliography. The first part, "Foundations," introduces Swing, its architecture and the key mechanism underlying Swing. Part II, mysteriously called "The Basics," explains the most commonly used and simpler classes of the Swing toolkit like labels, buttons, menus, list boxes, progress bars and sliders. The third part of the book, "Advanced topics," deals with using complicated components like trees, tables, text components and layered panes, as well as creating pluggable look and feel. The final part, "Special topics" introduces printing and the Java2D API.
Only two chapters of the final part are included in the book. The remaining four chapters which discuss accessibility, JavaHelp API, CORBA and some examples contributed by experienced Swing developers are available on the book's Web site.
The structure of each chapter is the same. Let's look at the chapter on tables as an example. The JTable class is introduced followed by related classes and interfaces. This is followed by discussions on row and column selections from JTable, column width and resizing and customizing the appearance of the table. The important methods related to these issues are discussed and short code samples are used to demonstrate the main features.
Then comes the meat of the chapter -- the examples. The first example shows how to display stock market data in a JTable. Complete code for the example is given and important sections are discussed. The examples that follow are enhancements to the first example. In the JTable chapter, they include adding custom renderers, customizing the data rendering, retrieving and displaying data from a database.
Each of the examples builds upon the previous one and as promised on the cover of the book, is production-quality code. While most other Swing books serve as expensive javadoc dumps of JFC with trivial, forgettable examples, Swing provides code that saves lots of time for the developer. The other applications that are developed in the book include a JPEG image editor, an ftp client, an X-Window-style desktop environment and a word processor.
This book is for the developer building applications using the Swing components of the Java Foundation Classes. The large number of examples make this a great cookbook providing code samples that will vastly reduce your development time. The language is simple and the examples are well defined. All the Swing components are discussed in detail with several screen shots.
The part I liked the most in this book is the section in each chapter about extending the Swing components to create custom components. These include creating an oval shaped border, polygonal buttons, and a tabbed pane which takes an image as the background. These examples provide knowledge to extend the components in ways limited only by your imagination.
The book is sprinkled with UI design guidelines by David Anderson related to usability and presentation. There is no reference to the Java Look and Feel Design Guidelines issued by JavaSoft. So I would recommend referring to that book (published by Sun Microsystems) if you want to design applications with consistent appearance and behavior.
The only minor annoyances in this book are the figures which display the component hierarchy, as they have an unprofessional look. But there are only a few of them.
To summarize, the unique examples and the exhaustive coverage of Swing makes this book very valuable for both beginners and advanced programmers.
Purchase this book at ThinkGeek.
Re:Hasn't Java had its day? (Score:1)
It is pretty hard to find a really good skier. Although a lot of skiers are good at something, few can do it all moguls, speed, techniques, etc... Same with C++, I know a lot of programmers but very very few good C++ programmers. Also most good C++ programmers are very specialized. For instance, I know a great graphics programmer but building a multi-threaded server was a huge challenge for him. He spent a lot of time reading up on pthreads. Also until you are a good skier or C++ programmer you don't have much fun. You are constantly hampered by lack of technique and cognitive overload. Too many things have to come together before you advance.
Now snow boarding was different. I picked it up very quickly and most importantly I had fun while I was learning. Java programming is very similar. Although learning to build a simple programming in Java and C++ is an equally challenging endeavor, advance programming is where java really shines.
In java building a multi-threaded server is pretty simple and adding checksum and compression is a breeze.
I have found with java the details are easy enough that I have very quickly start advance software design including design patterns and using concepts like Polymorphism and synchronized where they really pay off.
So I am a firm believer that Java's popularity as a programming language will continue. People forget, that enterprises would not touch 'C' until it had been around for a decade. Java is not even close to the 10-year mark and is very popular.
Finally the VM architecture is given unfair critics. Check your basics there is no theoretical basis why compiled code is to faster than interpreted. So yes in theory interpreted VM can be just as fast a compiled code!!
Hasn't Java had its day? (Score:1)
Forgive me if I've got the wrong end of the stick, but I was under the impression that Java had had its day and was pretty much on a downwards spiral. The basic premise of Java was an interesting one, and it was released at the best time for it to succeed, but due to various factors it hasn't, and there are few web sites where it is used..
All the websites I've seen have eschewed Java in favour of CGI scripting, a more reliable alternative. Writing an application in Java requires the use of the Java libraries, which involve some pretty bizarre methods of working for anyone used to another language.
While I appreciate there are some "hardcore" Java programmers out there, can anyone point me to a real-world application or website that actually uses Java? I mean properly, not just a tiny applet showing the time or something.
Re:claims != reality (Score:1)
There's Sybase's SQL Anywhere. It's JAVA (or was a few years ago.)
You might also be surprise to know Star Office is written in JAVA.
(Yes, there are OCI based JDBC drivers from Oracle, but they were not installed/selected.)
Is Anybody Really Using Java? (Honestly!) (Score:1)
I have had a number of encounters with Java-based GUI applications, and to a piece they have all been bad. All the Java GUI applications I have tried have been sluggish, unresponsive, and generally unimpressive.
They all seem to want to install their own JRE too, so it seems like I (as a user) am being punished because the Java compiler couldn't/wouldn't generate a native binary. But yet I have to install a native-binary version, because it installs a native-binary JRE as part of the package.
I have nothing particular against Java as a language - I don't like Bondage & Discipline languages myself, but language choice is very much a personal thing, and I don't presume that my personal preferences are best for the entire world. But Java as an implementation - as I have seen it - provides a really nasty end-user experience.
Ever tried the Netscape 4.1 Admin console? Bletcherous! Horrible! Nasty! Yechh!
Is anyone out there deploying Java applications with good results? Really?
Re:Java won't ever replace C++ for me until (Score:1)
Examples: They compare the number of "classes" used in the AIC vs. delegates case. (22 vs. 1) Yet they ignore to mention that delegates are actually classes under the covers (therefore, the answer is 22 vs. 22).
That AIC's need to be compiled in advance is rather irrelevant unless you are concerned about a 2-3% development footprint hit.
They also ignore that with some simple reflection, the number of AIC required for event handling can fall dramatically.
The source code differences are 9279 bytes vs. 10842. That's a difference of 1600 bytes, mainly from AIC syntactic-junk.
MS claims that delegates can be portable. That's nice, but that also means the onus is on MS to submit it to the Sun community process.
The multicast arguments are equally skewed. So because some events may be multi-castable, that justifies the usage of a non-standard construct that works just as well as AIC's, is just as fast, and has a slight flexibility advantage?
And based on my experiences on a 6-month WFC project, delegates are decent, but I see no real benefit of them over AIC's other than the class footprints (which again can be alieviated through judicious use of reflection).
Re:Swing - Good idea, badly implemented (Score:1)
Enhydra Users: Fed Ex, Time-Warner. . . (Score:1)
I don't know exactly what they have built, but it's using Java.
Re:claims != reality (Score:1)
Also, If Java is "useless" why is there so much work being done on integrating Java with Apache? Chack out java.apache.org. What are all these Java application server vendors doing? They have to be using Java for something.
Re:Java won't ever replace C++ for me until (Score:1)
class MyClass {
static final boolean debug = true;
public void mymethod() {
if(debug) {
}
}
}
want to disable all the debug code? just change the debug boolean to false. next time you'll compile, it will not compile the condition code, because since debug is *final* and set to false, he knows that this condition will always be false.
VB suffered from this problem too... (Score:1)
Small comfort I suppose, but VB'ers had to go through the same thing. I suppose C++ had this curve too. History repeats itself I guess.
OT: Postscript printing in Java? UML drawing app? (Score:1)
I assume there is a way to produce PS in Java. Which?
I want (to find or make) an UMl drawing app in Java... Where?
Sorry for OT.
It sounds like you needed to get a book ... (Score:1)
Synchronized (Score:1)
Is it just me... (Score:1)
I could probably write the equivalent program in QT/C++ in about 30 lines. Is it just a problem with swing (the API is very unpleasant), or is Java in general bad? I would have expected it to be reasonably fast on my system - but using JBuilder Foundation is terrible (click on a button - wait 3 seconds). And it's not RAM usage either - it was completely unusable with only 64MB RAM.
Why not do this:
NATIVELY compile code for platforms that support it. For those that don't, use bytecode. I'd guess this could get a MAJOR speedup.
Re:Java won't ever replace C++ for me until (Score:1)
:P).
Get TowerJ. It compiles. It runs on Linux. Sun doesn't provide it, but I thought that
/.ers whined when everything came from one source...
2) Give me paramterised types or templates. Writing our own collection classes and/or casting really really sucks. Some of the stuff that the folks who wrote Pizza are cool, anonymous functions for java
:D! (basically lambda expressions) and parameterised types. It's even compatable with current virtual machines, just most IDEs and compilers won't like it.
It's coming. The people who designed Pizza have now designed GJ, which is going to be incorporated into some future version of Java. In the meantime, you can download the GJ compiler (and a java.util package that has been modified to work with GJ) right now.
3) Delegates, I want MS 'delegate' style function pointers in java. Anonymous Inner Classes are horrific, and spoil Swing.
Delegaes sucked. Furthermore, delegates just compiled into anonymous inner classes. No gain, there.
4) ASSERT. We need asserts!!!! Lucky J++ has a simple preprocessor. So many bugs could be caught if people used ASSERT more, Sun don't even think we need them!
Sadly, ASSERT is coming to Java. However, it's a bad idea. Cafe au Lait has discussed why this is a bad idea in the past.
In the meantime, you can write your own assert facilities. Programmers at my company did so. It'll catch problems at run-time, not compile-time, which is how I remember ASSERT working, but it's been a few years.
Anything else?
-jon
Re:Java won't ever replace C++ for me until (Score:1)
Awwww.... yet another
/.er who whines when other people make them pay for their work. My heart bleeds for you.
Sun is not being stupid over the JVM. They release a reference JVM. TowerJ has written a Java->Native compiler which must include a JVM of sorts as well (things like dynamic class loading and reflection still need to work).
2) Templates are still "coming" (and have been for a while). Sun have been saying they'll integrate pizza features for over 2 years.
You have this pathetic fixation on having Mommy Sun give you all your software (and for free!). Go to
n dex.html and download GJ. Use it today.
3) Delegates rock. They use classes, NOT anonymous inner classes (get a clue). They have the same overhead as making a function call - unlike AIC.
Horseshit. Tell me how, in 20 words or less, Microsoft implemented first class function pointers without violating the Java Class File Format. The article from Microsoft's Java architect has disappeared from their WWW site, or I'd pass on a link to it to you. He says that delegates compile to anonymous inner classes. What, you know better?
Here is Sun's analysis of delegates: The analysis of how MS implemented delegates is given in
Yes, there are ways to hack ASSERT into java, but it usually involves using an if statement so the compiler will weed it out, rather than a simple "Assert" statement.
If you knew about HotSpot, you'd know that if branches that aren't ever taken will be compiled out. And since we're talking about long-running server processes (remember your whining about native compilers?), HotSpot's adaptive compiling is perfect.
-jon
Re:Java won't ever replace C++ for me until (Score:1)
For MS to claim that Gosling is wrong and delegates generate classes rather than inner classes is just spin. There is still going to be some sort of intermediate class automatically generated with a computer-generated name. What's the difference between that and an anonymous inner class? Nothing. What is the performance advantage? None. What was the point of delegates? Yet Another Pointless API Change for Lock-in. Yay Microsoft. I reiterate my original point: Delegates suck.
-jon
Using debug boolean (Score:1)
public interface Debug {
public static final boolean _debug;
}
public class foo implements Debug {
public void baz() {
if(_debug) {
}
}
}
public class bar implements Debug {
public void boo() {
if(_debug) {
}
}
}
(As an aside, any field in an interface is implicitly public static final. But I like to make things explicit.)
-jon
Re:One versus Many. (Score:1)
printf
Radix support for byte and short
A replace(string1, string2) method for strings
A windowing toolkit that doesn't eat all my swap space (unlike Swing)
Re:Swing - Good idea, badly implemented (Score:1)
Meanwhile, the rest of us have to sit here as Forte takes 10 MINUTES to load and another MINUTE to respond to menu selections, meanwhile eating 150 MB or so of swap space.
Re:claims != reality (Score:1)
Shipping products don't necessarily equate with wide usage. From the people I've talked to in the industry (and they represent a fair cross-section), Java is used overwhelmingly for internal use. Those coding efforts will never see the light of day publicly because they represent specific solutions to a specific internal problem. Many organizations use Java as sort of a glue-all; where Perl is considered the duct tape of the Internet, Java is more like a set of schematics and a trained team of engineers - Perl gets the job done, but Java can get the job done *right.*
What you're trying to do is equate Java's acceptance with the level of shipping products based on the language. Where your metric falls down - and will fall down with any language or utility - is if that language or utility isn't used in products that you can buy off the shelf. Java isn't used in many shipping products because it isn't suited very well towards client applications. Where it IS suited very well is on the server - a place of use that you miss completely by asking only for shipping products.
Re:shipping product != client application (Score:1)
>If Java is so great at creating the programs that fill these niches, why is no vertical market app vendor shipping a Java product to do so?
Asked and answered. These niches that you refer to are inherently specific. While you can lump them up and say, for instance, "servlets for accessing a database," the particulars vary. Company XYZ may require an *entirely* different servlet than Company ABC, because of the configuration of their database, how they intend to access and display the retrieved data, and any number of other variables. Company XYZ could package that up and ship it, but it would be doubtful that anymore than a handful of other companies would find the software useful without serious modification.
The next step above that would be to sell a generic servlet. But again, you run into the configuration issue. How much do you have to architect the servlet before it becomes applicable to more than a small handful of situations? How bloated does it have to become to encompass the vast variety of configurations out there? Many corporations would find it easier to simply write their own from scratch, ensuring that the servlet would be completely designed for optimal performance for a particular configuration.
As a result, much of the Java work that is done is done for company-specific purposes, and is not sold or otherwise distributed because it would be of extremely limited value to others without the source code to modify. It would be like the United States trying to sell the programming instructions inside a Patriot missile. Unless you *have* a Patriot missile (raise your hands, please) the code isn't going to be of direct value to you, and if you happen to have another type of missile, the Patriot code isn't going to work without serious modifications.
If you want to see what exactly is being shipped, I suggest you look at Java Solutions Marketplace [sun.com], where you can browse through the Java-related products and services to see whether anything qualifies for your stringent criteria.
>The only possible exception to the above are problems so crazy and stupid (and small) that no sane company would make a product to fix it.
You seem to want Java products that you can walk into a store and buy. It doesn't work like that. Should I dismiss Perl because I can't walk into CompUSA and buy a pure Perl software package? Perl has it's place as the glue that holds together the web. Java also has it's place in the software world - it's just not the visible, retail shelves that you are so desperate for.
>Now we're back to non-real-world uses.
I'd be interested in seeing how you define non-real-world uses. If it optimally solves a problem for a company, as far as I'm concerned that IS a real-world use (and is a much better real-world-use than some generic packaged product that has to be shoehorned into being merely an adequate solution).
The Authors do good work (Score:1)
cheers!
iceaxe
Re:Hasn't Java had its day? (Score:1)
Sure... by 2003 it'll all be RMI calls... no doubt in my mind.
shipping product != client application (Score:1)
The only possible exception to the above are problems so crazy and stupid (and small) that no sane company would make a product to fix it. Now we're back to non-real-world uses.
--
claims != reality (Score:1)
--
Re:claims != reality (Score:1)
I can name big companies, too. The point is specific examples of Java in use. Names of products that are currently shipping, for instance.
--
TogetherJ (Score:1)
They have a free(feature limited) version available
The site is [togethersoft.com]
Otherwise, dia from the gnome project is looking really good, even if it's not Java...
Re:What's the frequency? (Score:1)
awt components, on the other hand, are "heavyweight". They have an operating system peer that defines their behavior and appearance. java.awt.Button, for example, looks different in windows that it does in Motif, because the actual button is created by an operating system call.
With Swing!, all the components look the same regardless of the underlying operating system. This is a good thing (most of the time).
Mike
Re:Swing - Good idea, badly implemented (Score:1)
1.3 should be better, but last I checked the only version out was for windows. This is a temporary lag while they consolidate the Solaris builds, but it still keeps me from trying it out.
BTW, Swing! keeps getting faster and faster. When I was using the original point releases, it was much slower than it is now. As it is now, any pentium 2/celeron type machine should be able to draw swing components pretty fast. Almost as fast as native code. If your app is slower than that, then you are probably doing something wrong.
Or using a builder tool, instead of doing the layout work yourself.
Mike
Noting price wouldn't hurt archive, IMHO. (Score:1)
Re:Java in Industry. (Score:1)
Re:Java in Industry. (Score:1)
Re:claims != reality (Score:1)
Perl
SCHEME LISP
SNOBOL
Ada(although I could be wrong on this one)
HTML
Javascript
XML
Just because production/shrink wrap software is not written in Java, doesn't mean that it doesn't have a place.
--------------------------------------------
Re:Book Available Online! (Score:1)
OT: NASA (Score:1)
They're very succesful at being useless and setting back the development of a real space program by at least 20 years.
Bradley
Re:Price: US-$ 35... (Score:1)
Re:What's the frequency? (Score:1)
Not that I like VB the language over Java...just putting things into perspective.
BTW, I'm not an MSCE, and I am a computer science undergrad at a unix based university.
Re:What's the frequency? (Score:1)
swing is definately here to stay as far as java is concerened. it,s lightweight component set eliminates the problems the awt had with peers now once the performance is up to snuff....
Light weight? I don't think there's ever been a toolkit that's as heavy weight as Swing.
Swing is easish to learn, the object hierachy is pretty good, but the speed and memory usage is horrific. The average swing application uses more memory than Windows 2000 in total.
BTW, The even handling is TOTALLY SCREWED.
Anonymous inner classes? PULEEEASE. My HCI professor thinks it's one of the worse ideas ever.
Why don't sun JUST ADMIT that Microsoft's java delegates (function pointers for java) were a good idea and implement them. Saying delegates are not object oriented is like saying that methods aren't 'object oriented'.
Re:What's the frequency? (Score:1)?
Um, it will run 10 times faster. Put together the DB stuff with VB data designers, then write the web stuff using vb webclasses (compiled native binary code).
It's (mostly) not script based. The only script is some ASP that passes everything to the VB webclass.
I didn't assume you meant windows, was just talking about the speed of being able to put something together
If you aren't using windows, then I have no problem. Well I have no problem with using java for serverside stuff on Windows either.
What I said wasn't meant as an attack, just a comment.
Re:Java won't ever replace C++ for me until (Score:1)
Get it the truth about delegates from the guys who invented it.
blah [microsoft.com]
It's defintely done with classes, cause you can see the class files it generates.
Re:Java won't ever replace C++ for me until (Score:1)
I love these kinds of posts! Ignorant, bigoted people who haven't done any research...
Take that advice yourself. Firstly, NONE of these are available from Sun, like I said, 3rd party stuff that's not widely distributed is useless.
1) TowerJ is not free. And I was talking about sun stop being stupid over the JVM.
2) Templates are still "coming" (and have been for a while). Sun have been saying they'll integrate pizza features for over 2 years.
3) Delegates rock. They use classes, NOT anonymous inner classes (get a clue). They have the same overhead as making a function call - unlike AIC.
4) Why are asserts bad? You have GOT TO BE KIDDING ME.
Yes, there are ways to hack ASSERT into java, but it usually involves using an if statement so the compiler will weed it out, rather than a simple "Assert" statement.
Re:What's the frequency? (Score:1)
Almost all of VB's objects are written in C++, and VB itself has been natively compiled since version 5.
Re:Java won't ever replace C++ for me until (Score:1)
My HCI professors bawks at AIC cause of how ugly they are. People usually end up using AIC and making it just call a function.
It makes thing MUCH clearer about what is done, and code is well organised.
But I guess I can't expect Sun to respect people who want good looking code - code anyone can read (after looking at their source code, their source code commands, and their notational style).
Re:Java UML drawing app (Score:1)
Fundamentals of Object-Oriented Design in UML by Meilir Page-Jones if you want a refresher on OO along with a good UML intro (enough UML there for most projects).
UML Distilled by Martin Fowler.
The Unified Modeling Language User Guide by Booch, Jacobson and Rumbaugh.
Re:java is dead. Live with it! (Score:1)
Re:Java will find a limited niche (Score:1)
...
You have it exactly backwards, you know - it really frees the programmer to do interesting things.
I've read your reply several times, but haven't found your supporting evidence. Did you forget to include it?
Re:What's the frequency? (Score:1)
I'm back from school and can see your're still posting pro-MSFT drivel without due consideration of the facts. I have 2 friends who will be on the Visual Studio development team in the summer and even they do not take liberties with the facts like you have just done.
In a 3 tier app (DB, middleware, web) the speed bottlenecks are a.) the amount of time to do reads and writes to/from the database b.) the amount of time to send data over the network. Even if VB was 10 times faster than Java on the client (which is a bold faced lie in this age of Just-In-Time compilers that convert Java to native code) the two aforementioned bottlenecks will reduce the speed level of the entire application so that the difference between VB and Java implementations is negligible.
PS: With regards to speed of deployment, there is no contest, Visual Basic is king.
Re:Hasn't Java had its day? (Score:1)
and you should link to [cpan.org] if anything
not [python.org] for crying out loud..
---
i mean really
Re:Hasn't Java had its day? (Score:1)
I am sorry I must be imagining the 8 bazillion websites out there
Okay okay that was inflammatory and I do agree HTTP is a fairly poor one sided nightmare for client/server apps.
All of the preprocessors Php, ColdFusion
People are just pouring money into the web mostly websites and client/server apps that are mostly browser oriented, an anti trust lawsuit against MS is using browsers to attack them, there is just such an amount of websites and browser technology and money involved, its not just gonna 'die' off. You can implment new protocols maybe something better than HTTP via a plugin, but as long as the browser is in the hands of a closed corporation they will do what interests the corporation (as they should) not what interests the best thing for the rest of the world. You can just kiss idealism goodbye when you are talking about a profit margin. Anyways think about that.. I dont think web browser will go away. HTTP will die yes.. but even then the two are so closely tied its going to take time)
Re:Hasn't Java had its day? (Score:1)
Anyway, here are two java sites, Hallmark.com [hallmark.com] and The United States Postal Service [usps.com].
Re:java is dead. Live with it! (Score:1)
"Java is not dead, it just smells funny"
Re:claims != reality (Score:1)
Re:My complaint against sun (Score:1)
Re:OT: Postscript printing in Java? UML drawing ap (Score:1)
for more info.
/Adam
One versus Many. (Score:2)
Of course, in all Real Life projects, there are lots of developers working on various parts of a project. You've got to be *extremenly careful* while making a C based application with lots of developers, as there are an incredible amount of gotchas that can sneak up on you.. Spending days to hunt down an obscure but critical memory leak costs money...
Java is more strongly typed, and the built-in GC makes that memory leak less critical (yes, you can still cause leaks in Java, but they typically won't kill you like they will in a non-GC environment.) These types of features make it much easier to develop a large application with a teams of programmers with various skill levels and backgrounds.
Re:Swing - Good idea, badly implemented (Score:2)
Re:Swing - Good idea, badly implemented (Score:2)
Seriously, I bet you could probably find something out there by either doing a search, or subscribing to Java Developer Connection (at java.sun.com).
Swing - Good idea, badly implemented (Score:2)
Personally I think this is a real hinderance to Java mainstream acceptance. I've tried a number of XML editors written in Swing, and just went back to Windows or X editors instead, because quite simply they respond. Even Tk apps respond better than Swing apps, because the widgets are implemented in C, not in Java with a huge inheritance tree. Interestingly I fear this will be the same problem that Mozilla and XUL face.
Re:Swing - Good idea, badly implemented (Score:2)
I don't know how it's implemented in Java, but if it's anything like C++, then it's no big deal. It all boils down to a a funtion pointer in the vtable that really makes no great difference (on a PPro200, I was able to make of 5 million vtable invocations a second in C++, which is more than you need for UI work)
Hmmm... (Score:2)
No problems.
Yes, the UI take a while to instantiate all the objects and do all the needed set-up; I thread off an animated splash-screen and no one is the wiser that it's actually working.
Once there, the app is crisp - the slowest part is the network connection to the server. It's not as fast as C or Delphi apps, but then again, it was a piece of cake to develop the UI.
I don't know WHAT you might be doing that's so slow, but that is not my experience. Maybe trying to use Java like it was C? Comparing strings char by char? Creating new objects all the time instead of using available references? I'm not trying to pass judgement in any way - it's just that I've seen people try to use a pipe-wrench as a hammer before, and complain of bad performance.
For the record, 1.3 includes HotSpot. That made a difference. Using Swing rather than AWT, and not mixing the two, made a difference. Understanding the memory settings on the JVM - so the garbage collector isn't invoked too often, made a difference. These things help in programs larger than what you describe, but maybe JBF isn't getting started with enough JVM memory?? Just a thought.
You don't know what "lightweight" means (Score:2)
And it is. By "lightweight," Sun means that Swing components are not using native resources, but are drawn using Java only (no peers). This isn't strictly true for all Swing components (for example, JFrames need to be real frames at a certain level and popups that extend past the edge of the window need to be heavyweight to be drawn outside the bounds of their window.), but it's close enough to be approximately true.
If a 4-page cheat sheet can't cover more than 90% of the things one usually needs to do in GUI coding, the package is badly designed anyway.
As far as API size, Swing was NEVER intended to be small. It has over 2 dozen different widgets! It includes an HTML and RTF parser! A 4-page cheet sheet isn't going to cut it for anything but the very bare minimum. You couldn't adequately describe the functionality of a JTable with 4 pages. If you want bare minimum in Java, stick with AWT. There you only get a few widgets.
I tried Swing once, but discovered it was both slow and not yet widely deployed in browsers. But that was six months ago. Have things improved?
Swing in browers isn't going to be common, probably ever. You'd need the Java Plug-in installed to use it, and the vast majority of users currently have about a 28.8 connection. The 8MB download for the Java Plug-in isn't going to cut it. That's OK, because Swing functions best as an in-house, cross-platform VB app builder. Commercial apps on the order of Word or Photoshop couldn't be built in Swing right now. That doesn't make Swing useless, though.
-jon
Re:One versus Many. (Score:2)
There are several third party libs with this functionality.
Radix support for byte and short
Eh? That's been in the language since JDK 1.0.
In Byte:
public static byte parseByte(String s, int radix);
public static Byte valueOf(String s, int radix);
In Short:
public static short parseShort(String s, int radix);
public static Short valueOf(String s, int radix);
A replace(string1, string2) method for strings
It's in JDK 1.3. StringBuffer.replace(). Strings in Java aren't mutable.
A windowing toolkit that doesn't eat all my swap space (unlike Swing)
Use AWT. Or you might want to look at KFC (seriously!): ()
Any other nitpicking reasons? I know, you'll make up an excuse, but I want to see what it is
;-)
-jon
Re:claims != reality (Score:2)
I think you are wrong about Java not replacing C. C right now is used for low level OS stuff and device drivers and of course embedded machines. right now C is being replaced with C++ in most of these areas. The embedded machine domain is subject to Moore's law so with some delay the same developments as on larger computers take place there. Time to market and C are a bad combination, so other languages will find their way there if chips get fast enough.
Re:claims != reality (Score:2)
There are a lot of commercial and government installations who are using Servlets/EJB to do thier web business. Go to BEA or IBM's websites to see lists of successful implementations.
Go search a few web boards and look fr Java jobs. What are all of those people being hired for?
Java may have failed for Applets and other window dressing. It will never replace C as a systems programming language or Perl as a CGI/duct tape language. But many companies are using it for corporate IS development or web development.
Just beacuse it isn't fabulously popular in the open source world does NOT mean it isn't being used.
Re:What's the frequency? (Score:2)
Apparently you have never used the AWT, Swing's predecessor.
I'll admit Swing isn't the fastest and doesn't have the smallest footprint, but it is a big improvement.
Re:Is Anybody Really Using Java? (Honestly!) (Score:2)
As ever, performance is quite often a question of how well the code was written and designed. Java programs written by C++ coders tend to underperform for some reason.
I've seen some very clunky, very slow Java UI code from certain large, well-respected companies, where the performance is entirely down to bad coding. It's a shame that this sort of incompetence is sometimes taken as reflecting poorly on Java as a whole - it's just as easy to write lousy UI code in C/C++.
Re:Is Anybody Really Using Java? (Honestly!) (Score:2)
And yes, I have used the horror which is Netscape 4.1 Admin Console. That has to be the worst Swing app I've ever seen, at least user interface wise... if you are just adjusting values in the LDAP tree you might want to use the sample JNDI browser availiable from Javasoft [javasoft.com]. Look in the products&API's under JNDI, the browser is a sepreate sample download.
Re:claims != reality (Score:2)
That was a farily large, very data driven Swing app that had to run on P-90's with 32MB of memory running Win95.
Right now for a different telco I work on a production customer care site responsible for delivering performance data of network elements, trouble ticketing support, and other things on a customer facing web site. The whole thing is Java on the backend (apart from integrations into things like SecurID servers which are JNI layers). We are slowly migrating to EJB on this project, held back only by having to use Netscape Application Server and waiting for iPlanet.
I also know of many open projects at various companies desperate for Java EJB people. EJB has really gained a huge swell of support and is not any kind of fad - I personally find it hard to believe that there are that many people here not at least using servlets to some extent!
Re:Java will find a limited niche (Score:2)
- Reflection, the ability to dynamically examine type and object information at runtime.
- Dynamic class loading and custom class loaders so you can control where objects come from and load new classes without shutting the system down.
- Swing. Though it gets a bad rap here, it's really easy to customize and produce widgets that do a lot more than just sit there and look pretty. You can customize search capabilities for a combobox, or produce a table object tied right to a database for quick manipulation of data.
- JNI. You need to access some wierd hardware, a legacy system, or do something totally platform based? You have JNI, an easy and at least sort of portable way to get to native code if you really need to.
Re:Java will find a limited niche (Score:2)
When you say things like that with no supporting evidence, it only makes *you* look silly. In what way does Java reduce the degree of freedom for a programmer?
You have it exactly backwards, you know - it really frees the programmer to do interesting things. I would argue that instead of reducing your choices it offers you a great deal more.
I personally despise VB (and things of its ilk like Powerbuilder), and have developed C and C++ apps for many years. But now I prefer Java over both of these, for server side stuff as well as applications.
Re:Hasn't Java had its day? (Score:2).
You get into this very fast. These modifiers are used in a consistent way, and you have public/published/protected/private in about any other OOP language as well. Final is a method that cannot be overridden, abstract is one that has to be overridden in heirs. I haven't created a multithreaded app yet, so I'm not so sure about the synchronized thing
Re:Is Anybody Really Using Java? (Honestly!) (Score:2)
This means for the IBM-PC world: if you use a relatively modern system (P-II 266+) with enough RAM (64 MB+) and a 1.2+ JRE (1.3 RC-2 is out already) things should work out well. Yes, these requirements are still not matched by every system out there, but at least it is possible to use Java without waiting for that menu to pop up (I've experienced that myself some time ago).
Price: US-$ 35... (Score:2)
Re:Price: US-$ 35... (Score:2)
I found a very promising book recently only to learn that it costs US-$ 70
Hardly. (Score:2)
I know of several multimillion user sites which run their core functionality using Java Servlets. As far as I know, Amazon.com is based on Enterprise Java Beans. EJB is an ultra scalable (horizontal) technology. Applet's are kinda dumb, agreed, but server side Java rocks.
Re:Is Anybody Really Using Java? (Honestly!) (Score:2)
At the Internet startup that I work now, Java is also the language of choice. We are moving away from all Microsoft products. Of course we are a little concerned over Sun's grip on Java right now, but I strongly believe it will be standardized by IBM without Sun. Once standardized we will move to "standard Java" and away from any proprietary form.
To me, it's not so much it integration with web-stuff, but how easy it is to write large, complex, ever-evolving programs. As most of us probably know, the requirements for our projects are constantly changing. I find Java easy to re-use and easy to change/modify. I programmed C++ for 10 years and never felt comfortable with exceptions, re-usable code, and GUI APIs. Java is good at all those.
Your point regarding the speed of Java is an excellent point, but there are many ways to optimize java. For example, when writing a GUI app you always dedicate one thread to handling user actions and spawn worker threads to perform the behind-the-scenes work, right?
That's my opinion, YMMV.
-tim
Re:Swing - Good idea, badly implemented (Score:2)
Re:Java will find a limited niche (Score:2)
C is a crap language, I used it for years, I wrote Radar Display lists in it, I wrote X Server modifications, but fundametally its a poor project language. Its debug cycle is a nightmare on large scale projects. It works in Open Source thanks to the "many eyes" philosophy.
For myself the enterprise is an application with 000s of concurrent users and a lifecycle of around 10 years "active" (normally means 20). VB is not appropriate for that sort of enviroment as it does not guide the developer towards the sort design methodologies that save time on large scale projects.
Many people look down on Java as they see OO et al as an abomination. You can hack in C better than in Java, but you can code in a team better in Java.
So far with Java I've done servlets, client server, database, MQ, legacy et al et al et al. Pure Java does work, but it still requires a skillful designer. It isn't a silver bullet, but its better than #include.
Re:Book Available Online! (Score:2)
<META NAME="Generator" CONTENT="Microsoft Word 97">
And the table tags are so broken that Netscape Communicator 4.7/NT won't even render it. You have to use Exploder.
It sounds like a nice book, but it's like the saying: if you like sausage, don't ask how it's made.
--
Re:Java will find a limited niche (Score:2)
We aren't, so I'll stick to my premise that in any market for software (even internal), performance always wins.
My personal experience certainly doesn't support your claim. I'd say that in most cases, it is the functionality that wins. It doesn't matter if the thing works slightly slower today, just as long as it works! And just as long as it doesn't bring down the application or machine that's running it.
Functionality is the key. Java can bring a lot of functionality in a quite short development time and most of the time quite safely (in other words, no dangling pointers that crash the application.. exceptions still get there and can, and sometimes do, cause trouble but they can all be caught, logged and debugged with a lot less effort than random pointer bugs).
It's quite rare that I've seen performance being the first thing required... on the top of my head I can only think of one compiler project that was running on some old VAX machines as a batch during the night and had to squeeze every bit of performance out of those trusty work horses. Other than that, it has always been about functionality.
A quick look at the API collection that Java offers reveals why it is a winner.
Re:Hasn't Java had its day? (Score:2)
I beleive the reverse is true (after 2 years of using Java after C). This is my version of history:
In ye olde time, Sun produced Java, and saith " run things over the web. Cools Toys!".
And the people jumped for joy and enjoyed pointless applets for a time.
And so saith Sun "And now you can use it for writing all your applications - and have them run anywhere"
And the people trieth, and soon realised that Java was not up to the job, and so the people began to bitch and whine and saith that Java was sh*te
That was then, and this is now:
*Java is big. Expect 2x-3x memory usage over native code.
*Java is fast. *If you have the memory*. On win/solaris/linux, Java is really usable. The two caveats are a) you need the memory, and b) Swing is still slow, but not half as bad as it used to be. We have gotten Java scientific code running to within 5% of FORTRAN.
I use a Java program every day - in preference to numerous (native) alternatives. This is Borland JBuilder - so Java is certainly a usable platform these days for a "real world application".
Don't be put off by Java's history of underperformance, and Suns dodgy claims about world domination. If you're thinking of doing anything cross platform, Java is worth a good hard look.
IMHO,
Mike.
Java won't ever replace C++ for me until (Score:2)
I'm actually quite worried that since Sun essentially 'controls' everything, noone else can make extensions that become popular enough to become part of major IDEs. (IDEs with intellisense rocks).
Here's what java needs.
Don't sun realise a lot of people don't like java cause of how bloated and slow it is?
I can live with compile once run anywhere, but for speed's sake, let us have the option of write once run anywhere.
2) Give me paramterised types or templates. Writing our own collection classes and/or casting really really sucks.
Some of the stuff that the folks who wrote Pizza [unisa.edu.au] are cool, anonymous functions for java
3) Delegates, I want MS 'delegate' style function pointers in java. Anonymous Inner Classes are horrific, and spoil Swing.
4) ASSERT. We need asserts!!!! Lucky J++ has a simple preprocessor. So many bugs could be caught if people used ASSERT more, Sun don't even think we need them!
Anyway, until at all of these relatively small additions are made, C++ is going to rule supreme.
At least for me
Re:Java will find a limited niche (Score:2)
But all other things will NOT be equal...Java's main advantage (and the reason we use it more and more each day) is development time. We have built a major client/server system from the ground up (inclucing complex business analysis) in less than 3 months, with a team of 4 developers. In C/C++ we'd still be tracking down memory leaks for the next 6 months.
Java is NOT good for everything, performance is not optimal by any means (and Swing in particular needs a decent box to run well) but the JVM's are getting better rapidly, and for large scale server based apps it is fantastic. Take a look around - most of the big blue chip financial firms I deal with are switching to Java for much if not all of their internal development. These people have big budgets and some of the best developers/analysts around, and they love Java. Good enough for me...
Re:claims != reality .. (Score:2)
Fully clusterable, fault tolerant Application Server / Web server. Written in Java.
We designed our entire backend around it, thousands of users and it is extremely stable and has allowed us very fast development.
I program in C++, C and Java. Most of my work is C++. I have found Java is a better language to program in, it forces you to have better programming style.
Code that took me 4 weeks when using C++ takes me 2 weeks in Java and it is likely to have less bugs due to memory allocation problems etc..
We have also found that anyone that is pretty new to programming can pick up Java and become a useful programmer in 1/5 of the time it would take if they were using C++ or C.
Re:claims != reality (Score:2)
Headline News From Around The Industry April 11, 2000
Informative Graphics aims to make Java visualization tool standard front-end to Documentum
Documentum
(PR Newswire: April 11, 2000, 08:04 AM)
SilverStream to bundle Java e-business integrattion technology with application server suite
Cerebellum Software,Inc., and SilverStream Software, Inc., , today announced at the SilverSummit 2000 User's Conference that the Cerebellum(TM) Internet data integration product will be bu...
(PR Newswire: April 11, 2000, 08:03 AM)
Netcom Systems brings Java-based security to Cisco Security Associate program
CA-WORLD 2000 --NetCom Systems netForensics v1.2 has received validation from Cisco Systems, Inc. to become part of the Cisco Security Associate program. NetCom's netForensics(TM) , end-...
(PR Newswire: April 11, 2000, 08:03 AM)
BravePoint to resell and implement Cerebellum Java e-business integration technology
Cerebellum Software, Inc., whichdevelops the Cerebellum(TM) Internet data integration technology for linking e-business applications with corporate data systems, today announced an agreemen...
(PR Newswire: April 11, 2000, 08:03 AM)
Oracle8i adoption reaches 17,000 customers, 500,000 downloads
Oracle Corp. , the largest provider of software for e-business, today announced that since March 1999 more than 17,000 companies have purchased Oracle8i(TM), making it the fastest growin...
(PR Newswire: April 11, 2000, 08:02 AM)
RSA Security ads Java PKI to product lineup
Highlighting this week's inaugural RSA Conference 2000 Europe, RSA Security Inc. , the most trusted name in e-security, today unveiled an easier, faster and safer way to create Java-based PK...
(PR Newswire: April 11, 2000, 08:02 AM)
Merinta basks in limelight of Virgin Magastores Java Net appliance launch
Merinta, Inc., a subsidiary ofBoundless Corporation , announced today that its first customer, Internet Appliance Network began rollout of the first 10,000 Webplayer(TM) Internet Applian...
(PR Newswire: April 11, 2000, 08:01 AM)
QuickVideo for Linux shines with Java Media Framework
LAS VEGAS, Apr 11, 2000 - InfoValue Computing Inc. unveiled the industry's first complete, end-to-end video streaming solution for Linux workstations at NAB this week in Las Vegas....
(Business Wire: April 11, 2000, 06:45 AM)
Silverstream Software Licenses Sun's Java 2 Platform, Enterprise Edition-J2ee-
WASHINGTON, Apr 10, 2000 - SilverStream eBusiness Platform Based on J2EE Standard SilverStream Software, Inc. , The eBusiness Platform Company, today announced a strategic alliance...
(Business Wire: April 10, 2000, 09:21 AM)
Passcall And Jacada Partner to Deliver Enterprise
Re:Java in Industry. (Score:2)
Re:What's the frequency? (Score:2)
Java is an amazingly easy language and has great in support with the online API [sun.com] and the online tutorial [sun.com] that explain every aspect of the language. Last fall, I had no prior knowledge of Java and was an intermediate C++ programmer. With the above links as my primary guides I am now an excellent Java developer.
In fact, at the start of my spring break I wanted to create an online survey with the data stored in an Oracle database. With no prior knowledge of JDBC or servlets I created my survey [25hoursaday.com] within 3 days (most of which was spent configuring, java web servlet engines & battling the fact that Oracle doesn't support jdk 1.2).
My point is this, languages change and mature all the time. C today is not C of 20 years ago. C++ has changed enough in the last decade that a large number of developers in industry are mystified by several aspects of the language (STL? exception handling? namespaces?). Java is a mere 5 years old and to believe the language will not evolve further before stabilizing is wishful thinking. But at least in Java's case clicking a few webpages on Sun's webpage bring you up to speed rapidly.
PS: The MSCE crack is not a flame but a genuine question. I have noticed that MSCE's unlike computer science majors believe that once one learns something that's all they have to know. I guess it comes from getting certification after taking a few exams while CS majors usually use several languages in school and also since they spend 4 years in school usually see how languages change/mature before they get into the real world.
PPS: You actually have Swing as an item in your resume? Interesting.
Re:What's the frequency? (Score:2)
Yes, well you could do the same thing in VB in probably half the time, and it would run 10 times faster.?
Aight, gotta go to class, later.
Java UML drawing app (Score:2)
Argo/UML is open source (Score:2)
-ryan
"Any way you look at it, all the information that a person accumulates in a lifetime is just a drop in the bucket."
Another big book (Score:2)
I tried Swing once, but discovered it was both slow and not yet widely deployed in browsers. But that was six months ago. Have things improved?
Re:Hasn't Java had its day? (Score:2)
Today if you want to make your web service scalable and accessible by thousands and later by millions of customers your solutions can not be implemented as CGI.
To do heavy enterprise work n-tier solutions must be used. Enterprise Java Beans (EJB) for example used by Amazon (BEA Weblogic EJB server)
EJB servers allow scalability, session and transaction control, load balancing application management etc.
The era of CGI's was great, but CGI can not satisfy massive increase of usage.
Re:Is Anybody Really Using Java? (Honestly!) (Score:2)
Re:claims != reality (Score:3)
Its popular Developer tool also deploys all of its former platform-specific client-server apps to the web via Java with a recompile, and that's got lots of customers using it.
Fact is, Java is widely used for applications staged in corporate intranets. Just because you aren't using applets as you troll sites like Slashdot doesn't mean you have any grasp on "reality".
Re:Hasn't Java had its day? (Score:3)
Umm, websites that use Java, thats a tough one, after all CGI is such a scalable tool... long shot that one... is another one, and the list goes on.
Java is far from a dead language but many people see it as being it or CGI. It isn't Java is an _application_ language. Projects I have worked on have tended to have very thin client sides with Java running on a big piece of iron out back.
Java is far from dead, HTTP and Web-browsers however are a very poor means of communication and IMO will probably die in the next few years.
For cool toys in Java go to
In summary Java is a commercial application language that makes it simpler (its no silver bullet mind) to develop larger scale projects and deploy in a number of enviroments.
Java in Industry. (Score:3)
Off the top of my head, let me see Mail.com uses Java to serve its pages [netcraft.com]. Does Oracle's new Enterprise database [oracle.com] count?
And from Sun's page of industry news, we have companies like RSA, Oracle, Netcom, SAAB, Delta Air etc. using Java in mission critical situations on a daily basis. [sun.com]
Posts like this make me wonder about who composes slashdot's readership. Because only script kiddies and so-called web developers (HTML and javascript kiddies) use Java as a web app language. Also no one in his right mind uses Java for GUI development if the application has any degree of complexity. But as a middleware development language it is practically untouchable. When it comes to speed of development, maintainability and expandability for business applications few things beat Java. Add a native GUI or web interface depending on your application and a rock solid app has been created.
PS: Myth dispel mode Oh yeah, by the way Java pages are faster or at the very least as fast as CGI, it has to do with being memory resident a la the VM as opposed to being read from disk. Here's a benchmark [mindcraft.com] and a link [aspect.com.au] or two [scu.edu.au].
Re:Hasn't Java had its day? (Score:3)
I would even consider using it and what the hell. Learning this is NOT so bad actually, all of the concepts play with C++ ways of thinking so well.. so you are maybe at a loss of a couple of months of good studying at worst if you learn this. I know that is a lot of time for some.. But I dont think its gonna 'crash' and burn on a resume.
The thinking is much like C++ and If you aren an OO guy aching for a decent RAD language that has reasonable sane syntax and all the fun reusability of OO Java is it, and java is backed by a big company, there is even a microsoft product for it. Java was a LOT of hype, now that its calmed down I am seeing it does have a place and I happen to like this place
I dont know how much most people have noticed but lots and lots of VB shops (one I contract for included) are turning to Java just for windows platform because its a lot more sane than VB. This is kind of cool since it means these apps can migrate to Linux nearly painlessly.. Fight it all we want business is a factor in the computer industry and many application shops are looking to Java for a solution. Best to not get caught with yer pants down
Jeremy
Re:Is Anybody Really Using Java? (Honestly!) (Score:3)
I believe Java is used on the server side more than ever before. I see multiple ecommerce services thriving upon EJB technology.
Swing is of-course used on the client side but not heavily at all. It's mostly the control app's, custom made applications for companys' intranets. Whenever you want more control over your basic DHTML capable browser and if you must satisfy multiple browsers you use Java. The $100 question is are there that many browsers that are not IE out there (except for Linux/Unix/Mac users of-course) Well, Netscape has seing constant decline in PC world, that's just too bad. Opera or c-monkey browsers and other clones are invisible to the public so majority controls are built for Windows. This does not mean that Java is not used because it's bad it means that Java is not provided by those services that only target PC systems.
Book Available Online! (Score:5)
Available in HTML and (gasp!) Word format... | http://slashdot.org/story/00/03/23/124200/swing | crawl-003 | refinedweb | 10,314 | 64.41 |
Tutorials
In the following sections we work through some illustrative tutorials demonstrating some functional areas of the product.
Starting a business process on a schedule
There are times when we want a Business Process to be started on a repeatable schedule. Perhaps we want to run a process to start re-stocking at the end of each day. Fortunately, IBPM provides an elegant solution for just this capability. UCAs can be triggered to start at defined intervals and using a Start Message Event activity in a BPD allows a BPD to be associated with a UCA such that when the UCA is fired, the process instance can run.
Create a new General System service called Scheduled Start. Define an output variable called "
correlId" of type string. Define a Server Script node to set the value of the output variable to be "
XXX".
This will be the General Service that is started by the Scheduled UCA.
Add a new Under Cover Agent (UCA) called Scheduled Start and associate this with the General Service that we just created (also called Scheduled Start)
In the UCA implementation, selected all the entries in the right column that says that the start time for the UCA will be every 5 minutes:
Create a new BPD called Scheduled BPD. Build an wire the BPD as follows:
Add a private variable called "
correlId" of type String.
For the implementation of the Log activity, define it to be a piece of in-line JavaScript that logs that the BPD was started:
For the Start Message Event, associate it with the Scheduled Start UCA. For the UCA output mapping, map to the "
correlId" variable.
In the Pre & Post settings of the Start Message Event, give the correlId variable an initial value of "
XXX":
Create a snap shot of the Process App and deploy to a Process Server (not the Process Center).
If we now start a Process Admin session and visit Event Manager → Monitor, we will see a scheduled entry for our new Process App:
This shows the next time it will fire.
BUG!!! It seems that I have to create a new snapshot and deploy twice before it works.
Building a Monitor Model for BPMN events
In this tutorial we are going to walk through the construction of a Monitor Model from scratch to handle the processing of incoming Tracking Group events. This techniques does not start with a generated monitor model. It is assumed that you have skills in:
This is not a tutorial for newbies to either IBPM or Business Monitor.
In our story, we want to generate tracking events. To start we assume a new process application. Into this we create a new Tracking Group that, in this story is called "
sale":
The fields that we want to monitor when the process instances run are:
After having constructed this Tracking Group, we next build a BPD that includes an Intermediate Tracking Event to externalize the event for monitor consumption:
The fields of the tracking group are populated from a variable (not shown in this diagram).
The construction of the Monitoring Model is performed in Integration Developer. Start a copy of that and open the
Business MonitoringPerspective. This perspective owns all the editors and views needed to build the model.
We start by creating a Business Monitoring Project to hold all our artifacts.
We choose to call the project "
OrdersMon".
The incoming events that arrive from IBPM are in an XML data format. In order for Monitor to be able to work with these events, we need to describe the format of the events through XSD descriptions. The XSD descriptions are surprisingly not supplied with the products. Instead they are found in the InfoCenter here:
These three XSD files should be added into the
Event Definitionssection.
An individual Monitor Project can contain multiple Monitor Models. We have now created our project and now need to build our model. In the Monitor project, we create a new Monitor Model.
We call our new model "
OrdersMM".
Although we have added our event descriptions to our project, we have not yet said that they are to be associated with the model. In the model editor, select the Event Model tab and add each of the XSDs to the model. It appears that order of addition is important so add them in the order shown:
As we build out the XPath entries later on in the model, we will refer to some namespaces that need to be explicitly defined with their own prefixes.
|| |Prefix|Namespaces| |wle|
When the model was created, it was given a default key and name. We want the key of this monitoring context to be the Process ID instance. We rename the ID of the key to be "
processId"
And then rename the Name field to be "
Process ID".
We are now at the point where we start to add the core artifacts into the model. We start with an inbound event that signifies a new instance of a BPD process has started. We add a new inbound event.
And call it "
PROCESS_STARTED".
The input data is an "
eventPointData" object
and we need to take care to explicitly say where this eventPointObject can be found within the incoming event. Notice the addition of the "
mon:monitorEvent" part as shown in the following figure.
The final event types definition looks as follows:
Next comes the Filter Condition. It is the Filter Condition which specifies whether or not the incoming message is an instance of this kind of event.
We look at the mon:kind field of the EventPointData and check to see if it is a PROCESS_STARTED event. If it is, we have a match.
xs:string(PROCESS_STARTED/EventPointData/mon:kind) = '{}PROCESS_STARTED'
Next comes the correlation. Here we ask if we have seen this event before for an instance of a process. If all is well, we will NOT have an existing instance and we create a new monitoring context as a result.
PROCESS_STARTED/EventPointData/mon:correlation/wle:starting-process-instance = processId
In the preceding definition, we added a new inbound event type. Now we update the key metric to when an instance of this event is found. The expression used to source the process instance will be:
PROCESS_STARTED/EventPointData/mon:correlation/wle:starting-process-instance
We have previously defined what constitutes a start process event and seen how this creates a new monitoring context when seen. Each creation of a monitoring context should have a mechanism to complete that context. Now we define an inbound event that will be an indication that the process has completed. We call this event
PROCESS_COMPLETED. We define the event type details the same as we defined for the
PROCESS_STARTED event.
The filter condition which indicates that this is a Completion event is shown next.
xs:string(PROCESS_COMPLETED/EventPointData/mon:kind) = '{}PROCESS_COMPLETED'
Finally, we need to correlate to the correct monitoring context.
PROCESS_COMPLETED/EventPointData/mon:correlation/wle:starting-process-instance = processId
Now when a process completes, the monitor model will see it as a PROCESS_COMPLETED event.
The way we terminate a monitoring context is through a trigger. We create a new trigger definition.
we call the new trigger "
Terminate Context".
We next say that the trigger is fired when a PROCESS_COMPLETED event is detected.
Finally, in the definition of the trigger, we flag it as causing the termination of the monitoring context.
Now we are able to detect the start and end of the process in a monitoring model. It is possible that the recipe we have followed up until now will be repeated in many monitor models.
Now we build out more definitions specific for our sample. If we think back we have an intermediate tracking event in our process. We want to be able to catch this type of event so once again, we create a new inbound event definition. We will call this new inbound event "TRACKING GROUP SALE"
Just as before, we add an Event Part for the EventPointData but this time we add a second Event Part for the tracking point definitions. We call this event "TrackingPoint".
The path to this entry will be:
cbe:CommonBaseEvent/mon:monitorEvent/mon:applicationData/wle:tracking-point
The final result for the events parts looks as follows:
The filter condition that should be applied to an incoming event to see if this is an instance of our tracking event is more superficially complex but at a high level, it is true when:
xs:string(TRACKING_GROUP_SALE/EventPointData/mon:kind) = '{}EVENT_THROWN' and xs:string(TRACKING_GROUP_SALE/EventPointData/mon:model[1]/@mon:type) = '{}intermediateThrowEvent' and TRACKING_GROUP_SALE/TrackingPoint/@wle:groupName = 'sale'
As before, we want to determine which of the possible process instances and hence monitoring contexts the event should be associated with.
TRACKING_GROUP_SALE/EventPointData/mon:correlation/wle:starting-process-instance = processId
Now we are at the point where we can detect our tracking group event. This is the last of the inbound events we need to work with.
In our model, we wish to create a metric to hold the "
orderAmount". We create a new metric.
and give the metric the name "
orderAmount" and set its type to be "
Decimal".
The metric's value will be taken from the following expression. Note that it names the Tracking Group event as the source and hence will only be evaluated when a Tracking Group event is detected.
xs:decimal(TRACKING_GROUP_SALE/TrackingPoint/wle:tracked-field[@wle:name='orderAmount'])
We create a second metric to hold the US state in which the sale occurred.
TRACKING_GROUP_SALE/TrackingPoint/wle:tracked-field[@wle:name = 'usState']
Having completed all the steps in our model's development, what remains for us to do is generate the JEE artifacts and deploy them to a Monitor server.
At the completion of this step, the JEE projects will have been built and will be ready for deployment. We then deploy the project to a Monitor server through the Servers view.
After deployment we will see the application representing the monitor model deployed to the server.
Our construction is finished and now what remains is for us to run an instance of the BPD process.
After having run an instance of the process, we can bring up Business Space and an a monitoring instances widget to a page. In the configuration of the widget, select the metrics that we build in the model for display.
If all has gone as planned, we will see the following in the widget populated with data.
And this concludes the tutorial. At this point we have a Business Monitor model that is as clean as can possibly be and contains no superfluous processing. The construction of KPIs, diagrams, cube views and the other powerful capabilities of monitor usage are now as standard with the product with no involvement in its linking to IBPM.
Page 11 | https://learn.salientprocess.com/books/ibm-bpm/page/tutorials | CC-MAIN-2019-22 | refinedweb | 1,804 | 61.77 |
Hello fellow C programmers,
this is my first post on this forum so first and foremost, hello everybody.
Now for my question. The project I am working on is hunter-prey simulation game.
My error lays in the following part.
The function below will get parameters from another function. These parameters will tell the function how many meerkats (prey) and hunters will have to be created. It will also tell the function how big the world will be (nSquare, if nSquare is 4, the world will be created as a 4 x 4 world). The function will then allocate these 'animals' (structs). It will also calculate how many ground "animals" (non hunter nor prey animal structs) have to be created by doing nSquare^2 - nHunters - nMeerkats. After this all structs will be allocated. The square will be allocated as a two dimensional array. After that I want to put animals on the world by starting with meerkats. As you can see in the struct square, there can be 5 animals per square. After I'm finished with the meerkats I will put grounds "animals" (notice again that these aren't real animals, I say animals because of the struct name, it's just plain ground) on the world until there are no more. After that the remaining squares will have to be filled with hunters. There is where it goes wrong. When I give the world pointer as a parameter to my print function and try to print the rank of all squares of the world, I get a segmentation fault.
I'm guessing (I know) I'm doing something wrong at the part where I try to put everything in my 2D array, but I'm stuck at it. Can anyone help me?
Just ask me if you need more explanation on a part.
Kind regards,
boxden
Struct declaration:
note: typedef int boolean;note: typedef int boolean;Code:struct Square { struct Animal* animal[5]; struct Room* entrance; }; struct Animal { char rank; /* M meerkat H hunter G ground */ boolean danger; /* default false. when guard detects danger, his boolean will turn true, toggling the danger boolean to true for all animals (meerkats) */ boolean isGuard; };
Create surface function and print function:
Code:struct Square *createSurface(int nSquare, int nMeerkat, int nHunter, struct Room *entrance) { int i, j, k, meerCounter = 0, huntCounter = 0, groundCounter = 0, nGround; struct Square **square ; struct Animal *meerkat, *hunter, *ground; nGround = pow(nSquare, 2) - nMeerkat - nHunter; /* CREATION OF THE STRUCTS THE USER GAVE AS INPUT */ meerkat = (struct Animal*)malloc(nMeerkat * sizeof(struct Animal)); hunter = (struct Animal*)malloc(nHunter * sizeof(struct Animal)); ground = (struct Animal*)malloc(nGround * sizeof(struct Animal)); /* INITIALISATION OF THE STRUCTS CREATED ABOVE */ for (i = 0; i < nMeerkat; i++) { meerkat[i].rank = 'M'; meerkat[i].danger = FALSE; meerkat[i].isGuard = FALSE; } meerkat[0].isGuard = TRUE; /* first animal created is a guard */ for (i = 0; i < nHunter; i++) { hunter[i].rank = 'H'; hunter[i].danger = FALSE; /* not important */ hunter[i].isGuard = FALSE; /* not important */ } for (i = 0; i < nGround; i++) { ground[i].rank = 'G'; ground[i].danger = FALSE; ground[i].isGuard = FALSE; } /* CREATION OF THE WORLD */ square = (struct Square**)malloc(nSquare * sizeof(struct Square *)); /* two dimensional allocation */ for (i = 0; i < nSquare; i++) square[i] = (struct Square*)malloc(nSquare * sizeof(struct Square)); /* PUTTING ANINALS (MEERKAT, GROUND, HUNTER) ON WORLD */ for (i = 0; i < nSquare; i++) /* rows */ { for (j = 0; j < nSquare; j++) /* columns */ { for (k = 0; k < 5 && meerCounter < nMeerkat; k++, meerCounter++) /* 5 animals per square */ square[i][j].animal[k] = &meerkat[meerCounter]; } } for (i; i < nSquare; i++) /* rows */ /* I want i to continue where it stopped at the previous for loop */ { for (j; j < nSquare; j++) /* columns */ { for (k = 0; k < 5 && groundCounter < nGround; k++, groundCounter++) /* 5 animals per square */ square[i][j].animal[k] = &ground[groundCounter]; } } for (i = nSquare - 1; i > 0; i--) { for (j = nSquare - 1; j > 0; j--) { for (k = 0; k < 5 && huntCounter < nHunter; k++, huntCounter++) square[i][j].animal[k] = &hunter[huntCounter]; } } /* first animal created was a guard, first animal is on first square so this square will be an entrance */ /* has to point to an exit */ square[0][0].entrance = entrance; print(square, nSquare); return (&square[0][0]); } void allocIni() { /* allocate and ini stuff in here and give pointers back to surface function */ } void print(struct Square **world, int nSquare) { int i, j, k; for (i = 0; i < nSquare; i++) { for (j = 0; j < nSquare; j++) { for (k = 0; k < 5; k++) { printf("RANK: %c X: %i Y: %i Nde animal: %i \t", world[i][j].animal[k]->rank, i, j, k); } printf("\n"); } } } | http://cboard.cprogramming.com/c-programming/124383-segmentation-fault-nested-structures-two-dimensional-struct-array-allocation.html | CC-MAIN-2015-48 | refinedweb | 763 | 69.62 |
>>!!"
Dibs (Score:5, Funny)
Re:Dibs (Score:1)
Quite.
One big flat namespace for domains for namespaces is good...how?
Re:Dibs (Score:4, Insightful)
Re:Dibs (Score:1)
Re:Dibs (Score:2)
Or
Re:Dibs (Score:2)
Re:Dibs (Score:2)
And since your request was poorly formatted, it is I who call dibs on the info://pr0n/ namespace. MWAHAHA!
Re:Dibs (Score:3, Informative)
info:namespace/namespace-path
The "//" construct is usually used to signal the start of a machine name, whereas the following slash is used to signal the start of the path on that machine.
In this case, the notion of a machine is not used; it is more abstract than that. Hence, no "//"...
We now return you to your regularly scheduled program of Microsoft-bashing and templatized joke-recycling...
Verisign (Score:2, Interesting)
Re:Verisign (Score:1, Funny)
Wait until Microsoft geta a hold of this. An "all" namespace!
Re:Verisign (Score:2)
Next new thing: Namespace Squatting!
Slashdotted (Score:2, Informative)
Proposal for the IETF... (Score:4, Funny)
URI <info:goatsecx/hello>
I'm really confused (Score:5, Insightful)
Without strict discipline, users will create their own, incompatible URIs in the same namespace. Their needs to be a guiding hand in all this-a document or company that oversees this project VERY carefully. We don't want this turning into some aimless metanarrative like the "Information Superhighway".
Re:I'm really confused (Score:5, Informative)
Uh no.
There will be ONE new top-level scheme, "info". It will have (presumably a small-ish number of) second-level "namespaces". Each namespace will be a well-defined system run by some organization. So you could imagine an ISBN namespace, so a URI might look like "info:isbn:0465026567".
The "info" scheme, and therefore the list of namespaces, will be controlled by an existing standards body called NISO [niso.org]. It's their job to impose the discipline on these URIs. End-users won't get to create their own - only NISO-approved bodies with a well-run namespace can add to this system. Sounds like a good idea to me. I can rely on the fact that any legitimate "info" URI will be well-organized and sensible, I hope.
Genuinely reliable (Score:3, Funny)
Re:I'm really confused (Score:2, Funny)
or info:weather/06186 (hartford,ct)
or info:ustel/800-867-5309 (jenny)
or info:upc/3951080030 (sobe oolong)
or info:mac/00:30:48:21:97:62
or info:whois/slashdot.org
Interesting.
Re:I'm really confused (Score:2)
Re:I'm really confused (Score:2)
Re:I'm really confused (Score:2)
Re:I'm really confused (Score:2)
Domain squatters (Score:1, Insightful)
So who do I pay (Score:5, Interesting)
Re:So who do I pay (Score:5, Informative)
I haven't looked in on the politics of this one but there are two kinds of individual submissions
1 - Any idiot can mail something properly formatted to internet-drafts@ietf.org and get it published as an internet draft... don't believe me look here Individual Submissions [ietf.org] - you will find this draft somewhere on this page
2 - A working group is looking for a new working group item - so they ask the author to post an individual submission so they can consider his work before making a decision - These actually become RFCs
Want a clue on WG items in the ietf - they come in the form draft-ietf-WGName-topic-rev.txt - The key is to not be fooled by people that post draft-ietf-lastname-topic-rev.txt
Re:So who do I pay (Score:1)
National Information Standards Organization (NISO)
(Section 4 of the document)
Re:So who do I pay (Score:2)
Yay! (Score:1)
important info (Score:5, Informative)
"The "info" URI scheme explicitly decouples identification from resolution. Applications SHOULD NOT assume that an "info" URI can be dereferenced to a representation of the resource identified by the URI, though some business processes MAY make "info" URIs resolvable either directly or conditionally. The purposes of the "info" URI scheme are the identification of information assets and the standardization of rules for declaring and comparing identity of information assets without regard to any resolution of the URI or even whether the information asset identified by the URI is accessible on the Internet."
In other words, the info URI's will not be useful for anything other than providing context and identification. There is no resolution mechanism in place, nor do they intend to have any standard resolution mechanism, which makes the practical use of these URI's almost nonexistant (as current designed.)
Re:important info (Score:2)
If this ever comes about, I want the info://yhbt resource
:-)
Re:important info (Score:4, Insightful)
There is a big difference between not requiring a resolution mechanism and not assuming a resolution mechanism. It may very well be that a client knows how to resolve info:dcc/* but not info:ssn/* URIs. The point is that info: URIs will identify objects, rather than specify one location where a digital instance of the object may be accessible.
URIs have become the de-facto standard for referencing documents on the Internet. Don't you think it is more useful to reference documents/objects by their unique ID rather than a URL where one instance of that document may reside?
As for not being useful without a resolution mechanism... are you saying that ISBN's, SSN's (if in the USA), and UPC barcodes aren't useful? This URI scheme simply provides a way to identify objects (digital or not) using a common identification scheme. The resolution mechanism can be added after the fact (or not, depending on the type of object, or how it is used).
Re:important info (Score:2)
GUIDs have no built in resolution scheme yet look at how universally useful they are...
Re:important info (Score:4, Informative)
Oh, great... (Score:5, Funny)
Um.. (Score:5, Informative)
How exactly will browsers implement this new protocol?
I'm confused about the concept of a "public namespace". If these new URIs are intended to point to information, where will that information be stored and how will it be retrieved?
Re:Um.. (Score:3, Informative)
With the mighty Konqueror you only need a new kio slave
:). The others will require a plugin (a very simple one actually)
Re:Um.. (Score:2)
That should work, but it raises another issue: can we namespace our identifiers, like I did with unix:info?
Re:Um.. (Score:3, Informative)
It is simply a standardized (by NISO) format for identifying something. Like the example given in the
"info:lccn/2002022641" becomes the only way to refer to the given LCCN as a URI. No worries about "should it be 'LCCN', or 'LibraryCongressControlNumber', or should the number come first, or is 'lc' enough to let people know that its a library of congress number"... it explicitly sets the proper formatti
Re:Um.. (Score:2)
And the Congolese should be quite happy to accept such a ruling from a National standards organisation because
......
Re:Um.. (Score:2)
Web browsers probably won't implement this protocol. There might conceivably be an "Info browser" that would browse various classes of namespaces, but they would hardly be useful.
The only point here is to standardize object transaction namespaces for various fields. It is altogether fitting and proper that we do so, but it's not really an end-user protocol.
Take the Library of Congress book classification system (this or Dewey Decimal make good examples of "how" because the implementation would be trivial,:
Re:Some further possibilities (Score:5, Insightful)
Just a thought. I would hate to go looking for info:palm/model/P80900US and find 8 million links to people trying to get me to surf over to their porn site.
Re:Some further possibilities (Score:5, Funny)
No, that would be "info:palm/hairy"
Re:Some further possibilities (Score:2)
info:palm/model/P80900US isn't a *LINK* to anything. It's a way of encoding "this is a Palm model P809.."
If you think about it as a way to standardize the syntax of meta-keywords to make them more searchable, you'll be closer to the intent...
Re:Some further possibilities (Score:3, Informative)
Re:Some further possibilities (Score:2, Interesting)
One example: you can't search for "anime" anymore without getting thousands of pr0n sites (if I search for "anime" I don't want "hentai" - anime is a currently abused keyword used by pr0n sites).
Re:Some further possibilities (Score:2)
Re:Some further possibilities (Score:2)
Re:Some further possibilities (Score:2)
Re:Some further possibilities (Score:2)
Now you bring up a great possibility. Would the above belong to Palm or to Hand Readers Anonymous?
This is bad (Score:2, Insightful)
We don't need this sort of half-thought-out component to the domain name system. If you're going to do anything with resource identifiers, make a change to BIND to allow DN servers to map them to A records.
You know what's going to happen. People are going to register these namespaces and use them instead of domain names. Then we're going
Re:This is bad (Score:3, Insightful)
It's Already patented. (Score:4, Funny)
--Joe
Re:It's Already patented. (Score:2)
Re:It's Already patented. (Score:2)
Nice, but not quite perfect (Score:1)
There are only a bit over 17000 TLA's and there already are 3 candidates for DDC (according to)...
Re:Nice, but not quite perfect (Score:2)
defensedc
nycddc
that wasn't so hard, use your imagination!
How come... (Score:1)
is better than
Re:How come... (Score:1)
-------------------
Prof. Jonathan I. Ezor
Associate Professor of Law and Technology
Director, Institute for Business, Law and Technology (IBLT)
Touro Law Center
300 Nassau Road, Huntington, NY 11743
Tel: 631-421-2244 x412 Fax:
Re:How come... (Score:2) is apparently a hostname.
info:ddc/22/eng//004.678 is talking about a *DEWEY DECIMAL SYSTEM* number, *NOT* a URL on a host.
Consider this:
info:temp/C/23
Thats talking about a *temperature*, not a website called temp.
Way cool?! (Score:2, Funny)
Err, things haven't been way cool!! since the Eighties...
Isn't our industry trying to propel mankind into the future? Forwards is that way...
Re:Way cool?! (Score:2)
The term "Cool", like a T-Shirt and Jeans, is timeless(ok at least in the past 50 years or so). No matter what the passing fad may currently be, it never seems to go out of date.
Nifty, Groovy, Neato-Torpedo, Phat, Fly, Funky-Fresh, etc on the other hand...
Combine this with RFID... (Score:2, Interesting)
--
What karma?
What about oid namespaces (Score:2)
The URI namespace is already quite broad and has many ways to define "public" namespaces, usually based upon the URN [ietf.org] subset of the URI specification. Just a few open-ended namespaces so far include the OID-based URI namespace, such as "urn:oid:1.3.6.1.2.1.27", (RFC 3061 [ietf.org]). You also have RFC 3151 [ietf.org] for public identifier URIs.
Really, there is nothing new technically here. The only useful thing it brings beyond the URN spec is the new registration authority. It can still prove useful, but it's not like it's
Still need DNS equivalent... (Score:2)
Writing a spec is the easy part (and this one seems particularly trivial). Implementing it is a lot harder.
The main missing information seems to be a DNS equivalent function. It is one thing to introduce yet another central registrar to insure "against hostile usurpation or inappropriate usage of registered service marks" (groan!) but how are we going to access the information? Section 4.2 says
Re:Still need DNS equivalent... (Score:3, Insightful)
Don't expect to type these into your browser and view the results. This system is more for tagging and identificat
That's nothing (Score:2)
Re:That's nothing (Score:2, Funny)
And it works with Mozilla !
Try selecting this text (taken from the RFC) and pasting it on a browser window!
substr"> y wA AAAAMAAw
AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUU lvONmOZtfzgFz
ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5 yLWGsEbtLiOSp
a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfny cQZXZeYGejmJl
ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwv KOzrcd3iq9uis
F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo9
Re:That's nothing (Score:2)
Are these really URIs? (Score:2)
In other words, if I type a Dewey info: URI into Moz n+3, what do I get? The description for that code? A list of Gutenberg texts? A list of ISBNs? An Amazon search result?
Anybody have examples of how these URIs would be used in practice?
Re:Are these really URIs? (Score:2)
Yes, they do identify resources, or things. No, they don't tell you how or where to find them. This is the difference between a URI and a URL. A URI is just a name that identifies something, and that something doesn't even have to exist in the electronic world nor be reachable over the Internet.
It is always up to applications to determine what to do, if anything, with a URI which is not also a URL. It is foreseeable that Mozilla could develop a "info" uri plugin model, whereby a plugin could be writte
Here we go again. (Score:3, Insightful)
"H T T P colon slash slash W W W dot (pause) whatever dot (pause) com"
Are we going to have to relive that if new namespaces are added?
Dewey Decimal is not a good example (Score:2, Insightful)
And how is Mozilla going to handle this? (Score:1)
Very Interesting (Score:1)
Potential for abuse by stupid people (Score:4, Informative)
How quickly do you think that some unthinking government agency or financial institution will start including Social Security numbers into URIs, and make them publicly searchable? It will probably happen accidentally, given that so many institutions use SS#s as identifiers even though they're not supposed to.
*sigh*
[tourolaw.edu]
Re:Potential for abuse by stupid people (Score:2)
Private companies, individuals, etc. are not subject to these restrictions at all, so you could potentially see some abuse there. However, just as there is no law that says companies can't ask for your SSN, there's no
Re:Monopoly (Score:2)
Often, private companies have no legitamate use for your Social Security Number. You might be surprised how often they actually don't need it, and can use an invented number instead.
You may also be surprised how easy it is to not give it to people. Try it sometime. For more information, try reading here [cpsr.org].
Re:Potential for abuse by stupid people (Score:2, Insightful)
*sigh*
David Brin... (Score:3, Interesting)
When I first read this article, it was the first thing that came to mind. (Maybe because I'm reading it now!-el_D
:-)
Hah! (Score:2, Funny)
ahem.
too damn confusing (Score:1)
Just food for thought
Call me crazy, but.... (Score:1)
It's definitely not going to be a 'host lookup' mechanism.. It's kinda like a search engine
Instead of typing keywords into your "search engine", you type the URI into there...
THEN, all the pages that contain that URI in their page body will be returned as a list.
It's a way to specify data more closely, hence hoping to make for better search engines.
(That's enoguh of me talking out of my ass now)
This is URN in a new dress (Score:2)
2) the DDDS (name resolution that can be based on DNS) is already an Internet (proposed) standard that can be used to resolve arbitrary URIs with DNS support - if the authors so desire.
References at an RFC library near you.
Additional namespaces for UPC's, etc.? (Score:2)
UR* Jungle... (Score:5, Insightful)
7.2 Why Not Use a URN Namespace ID for Identifiers from Public Namespaces?
RFC 2396 [RFC2396] states that a "URN differs from a URL in that it's primary purpose is persistent labeling of a resource with an identifier". An "info" URI on the other hand does not assert persistence of resource names or of the resource itself, but rather declares namespaces of identifiers managed according to the policies and business models of the Namespace Authorities. Some of these namespaces will not have persistence of identifiers as a primary purpose, while others will have locator semantics as well as name semantics. It would therefore be inappropriate to employ a URN Namespace ID for such namespaces.
Which I read to mean that an info: URI may, or may not, be a URL (i.e., useful for actually accessing the resource); may, or may not, be a URN (i.e., provides some semblence of a chance that it means the same thing today as it did yesterday). Oh, did I mention that it may, or may not, be case sensitive, and may or may not be subject to scheme-specific normalization rules?
It seems that someone (say "Perfection") got fed up holding the fort agains a hoard of requests for top-level URI schemes - or someone (say "Kludge") got fed up with the demand that these schemes actually have some well defined semantics. Or both. Either way, they had this brilliant notion... why don't we have a junk^H^H^H^Hinfo: URI scheme with as little control over semantics as we can get away with? If some top-level URI scheme sucks, we'll just put it there. We'll spin off a company to be the registrar so "Perfection" will be able to pretend not to see it, and "Kludge" will be able to register all the junk^H^H^H^Hinformation URIs he wants!
I guess it does make some sort of twisted sense... In the meanwhile, proposals like the taguri proposal [ietf.org] languish. Here's a years-old proposal that attempts to define coherent semantics for time-persistant identifiers, without requiring a (new) registration agency. We can't have that, can we?
Sigh. Insert mandatory "I for one welcome the arrival of our new info:disposable:gjyr4784ghf89yf4h URI masters" post here...
Re:tag: URIs (Score:2)
I don't see why the draft can't be adopted as is. Then again, I have zero knowledge of the IETF processes involved. Is there a way the YAML community can promote the approval?
relationships with DOI? (Score:2, Insightful)
Could someone explain if and how this proposal is somehow similar to (or different from) the Digital Object Identifier [doi.org] standard (DOI)? DOI, although proprietary (like EAN, UPC, etc) is gaining momentum; for example, here in Italy is going to be adopted as a general standard for the public administration documents.
Re:relationships with DOI? (Score:2, Informative)
The info scheme will probably include doi as a namespace info:doi/ although the doi people want to get "doi:" in as a top-level uri scheme.
every item assigned a doi has to go into the doi registry; with info, only the namespaces will get registered
Better (Score:2)
Call me Verisign-boy
Example case requires Dewey Decimal license fee! (Score:2)
From their FAQ: May I use the DDC to organize information on my Web site? [oclc.org] us
OCLC is an author of the draft (Score:2)
Re:OCLC is an author of the draft (Score:2)
(tin foil hat on)
Just because they suggest it doesn't mean it'll be free. In fact, this draft could be seen as a way to generate revenue when relatively few people use the DDS on the internet now (AFAIK - for example, most bookstores use the ISBN).
Anther company tried to get their patents into an international standard, and then extract license fees from people who followed the standard. [techtv.com]
(tin foil hat off)
But I hope OCLC and all future owners of the DDS have
Why not URN? (Score:5, Insightful)
So now when I want to come up with a new way to label information internally, I have two avenues that are now, for most intents and purposes, competitors. If I want a persistent label (for my own definition of persistency, since either way, these are still my labels), I can go with URN or info at my discretion. If I don't want persistency, and want to be anal about my interpretation of a URN, I'm sort of "encouraged" to go with "info".
It just seems counter-productive to create something brand new when a URN is probably going to be good enough. Maybe we just need to use urn:dyn or urd: or urt: instead of urn: if we want to make it very clear that the namespace underneath that will be dynamic.
It just bugs me when standards bodies go off and start considering two different implementations of something that overlap 99% in purpose.
Am I missing something? Is the persistency thing really that much of a blocker that a URN is so inappropriate that something else entirely needs to be invented?
This is ridiculous! (Score:2, Insightful)
great idea! (Score:2)
Many people are well trained in looking things up in massive dead tree tomes of tenichal documents, Library drawers, etc. If you know how to use the Dewey Decimal system for example, you can find a book in a card catalog at a library even faster than using Google! It's all about the right tool for the job.
Also, unlike Google, these are very sp
Repositories suck (Score:2)
Way uncool! (Score:2)
The latter requires a new URI scheme (deployment of new URI schemes is expensive)
The latter requires a new registry
The other difference is that info: is not http:. But why exactly does a piece of software need to know that a URI identifies an "information asset"? HTTP URIs identify resources that may be (or may get or may have been) dereferencable using HTTP, no more semantics than that. Oh, and every organizati
Re:Way uncool! (Score:2)
Not necessarily. HTTP URIs identify resources; it's true that HTTP resources usually are web pages, but that's not the rule. With one can identify the thing; with one representation of it being readily available at the same address. Remember - multiple URIs may identify the same resource, and one particular representation may be in fa
Re:Way uncool! (Score:2)
According to some (including me), a URI may identify me. A URI may indentify a book the same way its Dewey code identifies it. The advantage of using a dereferencable URI is that you can presumably (not always, but usually) get a representation of
No, they don't (Score:2) | http://developers.slashdot.org/story/03/09/30/164210/ietf-draft-sets-up-public-namespaces | CC-MAIN-2015-18 | refinedweb | 3,797 | 63.29 |
22 January 2008 10:00 [Source: ICIS news]
(Recasts story, adds details on petrochemicals and closing stock prices)
By ?xml:namespace>
SINGAPORE (ICIS news)--Petrochemical stocks across Asia plunged for a second consecutive day on growing fears of a global recession, dragging crude oil prices further down from record highs.
Stock markets in
The Korea Composite Stock Price Index (KOSPI) slid 4.4% while Japan's Nikkei 225 slumped 5.7%.
In the greater
Among the petrochemical makers, Honam Petrochemical, LG Chem and PetroChina saw the sharpest falls.
Honam dived 12.2% to won (W) 77,000 ($81.20) while LG Chem fell 9.6% to W7,100. PetroChina tumbled 14.9% to
While fundamentals for some Asian petrochemical companies were still strong, the
“It will take a quarter or two to confirm weak demand will occur. This could be a very big risk,” said Thomas Yi, analyst from Samsung Securities.
Weak demand could become another burden for the petrochemical industry which was already weighed down by high crude oil costs, he said.
However, crude oil prices were expected to stabilise at $80/bbl because of the overall weak market conditions, he added.
NYMEX crude futures fell to below $87/bbl during intra-day trade, the lowest level since December, dragging down naphtha and aromatics values.
US crude futures for February fell to $86.69/bbl, down $3.88/bbl from Friday. March BRENT futures were down $1.95/bbl to $85.56/bbl.
Naphtha buy-sell ideas slipped to $840-841/tonne CFR (cost and freight)
However, one trader said it was unlikely that naphtha would fall very sharply, to November’s low levels.
“The crack spread [the spread between crude and naphtha] is still quite good, so we don’t anticipate a very sharp fall in naphtha,” he said.
The Asian jet kerosene market has also softened, on the back of declining crude and weaker demand. Traders said that FOB (free on board)
Tight olefins supply kept prices high, producers and traders said. Ethylene selling indications were above $1,470/tonne FOB
Propylene producers reiterated selling indications above $1,300/tonne CFR northeast Asia (
As some aromatics makers were just breaking even, the limited downside prevented prices from falling further, said a Daewoo trader.
Toluene bids for any March cargoes were pegged at $900-905/tonne FOB
Benzene offers fell $5/bbl to $1,005/tonne FOB
Styrene monomer (SM) was stable-to-soft $1,345-1,355/tonne CFR China, losing some $5/tonne from the previous day and paraxylene (PX) prices were assessed notionally unchanged at $1,115-1,125/tonne CFR Taiwan.
April crude palm oil (CPO) futures in Malaysia plunged ringgit (M$) 133/tonne ($40/tonne) to M$3,110/tonne by mid-day amid plummeting mineral oil prices, profit-taking before the public holiday in Malaysia on Wednesday and panic selling by speculators.
“Everybody was shouting for corrections after palm oil prices went over M$2,500/tonne,” Akshay Khandelwal, a Singapore-based palm oil trader said, adding that the current dive in prices was long overdue, and should not be completely blamed on the fall in crude oil prices.
($1=W948.52/HK$7.81/M$3.29)
Prema Viswanathan, Kew Jiahui, Helen Lee, Wan Hsin Hun, Serene Cheong, Salmon Aidan Lee, Hong Chou Hui and Jeremiah Ch | http://www.icis.com/Articles/2008/01/22/9094551/asia-markets-crude-tumble-for-2nd-day.html | CC-MAIN-2014-23 | refinedweb | 556 | 62.78 |
Handling Multiple Projects
We have been looking very closely at Trac and how we would use it in a multi project environment. Our conclusions are a little different to any of the proposals made so far.
We have a large code base. Much of that code is shared among a large number of projects. There is also a complex relationship between projects and milestones. For example, a milestone may change common code and result in several project releases. In other cases there is a one to one milestone/project mapping.
What the above means is that the relationship between a milestone, projects, timeline etc. can get quite complex. The issue is how to deal with that while providing a clean and understandable system which normal people can cope with. Neither of the other proposals for handling this (TracMultipleProjects/MultipleEnvironments and TracMultipleProjects/SingleEnvironment) deal with this complexity. We believe that TracMultipleProjects/MultipleEnvironments is a non-starter for this. There are some good ideas in TracMultipleProjects/SingleEnvironment which are extended by this proposal.
Requests like the one in #1048 and #586 are too simplistic as they only address multiple projects which have nothing in common.
Trac Data
Gary Oberbrunner made these suggestions on the mailing list:
- a new table, "project", looking like this:
id integer PRIMARY KEY, name text, description text
- make tickets, milestones, and wiki entries (and maybe components?) have a project id, so for instance you could have project "A" with milestone "v1.0" and project "B" with milestone "v1.0" but they are distinct milestones.
- the default project ID, 0, means "no project", i.e. current behavior.
- update various pages and sql queries to allow project selection, i.e. "where project_id = selected_project_id" or sometimes "where project_id = selected_project_id or project_id = 0" to also show the default (non-project-specific) items.
- add a new page for project maintenance (create, update, delete) (Or do it via trac-admin)
We would like to extend this so that:
- Milestones can be linked to more than one project. This would require an extra table to link milestones and projects.
- Milestone names would live in a flat namespace because of the above. I.e., Garys milestone naming proposal only works if there is a one to one relationship between project and milestone.
- Queries should support selecting multiple projects.
Project and the Repository
We would also like to define which repository paths belong to a project. Trac 0.9 permits a trac instance to work within a single path within a repository thus making multiple Tracs/one repository possible. For multiple projects within a single Trac this would need to be extended as many projects are composed from common parts which are scattered in the repository. Projects should also be linked to a section of the Wiki which would be done using naming conventions - subpages of pages named after the project would belong to that project.
With the above relationship defined query building for the timeline and the roadmap sections become possible, choosing a project the timeline section would show activity for the defined repository paths and the related part of the Wiki. Milestones are also linked to projects so relevent milestone changes would be displayed. Tickets are also linked to a project so only relevent ticket changes would be shown.
Ticket Changes
- A project field drop down list.
- A project version field drop down list which depends on the project field (i.e., each project has it's own set of versions). The current version field would become this field.
- The existing component field has to be dependent on the project. Each project will have it's own set of components, or, the component field could be optional so that those with multiple projects can remove it.
- The milestone field also has to be dependent on the project (selecting a project would only show milestones which are relevant to that project)
Milestones have to be associated with projects (maybe more than one project). Adding a milestone would entail selecting a list of projects affected by that milestone.
Timeline
Selecting a project would show a timeline based on the repository paths, Wiki location etc. for that project. However we don't believe that this simple relationship between a project and a timeline holds for all projects. So, it should also be possible to use query support added to the timeline page to select repository paths and possibly the Wiki location. These queries should allow the user to select a number of paths into the subversion repository to select repository checkins, a project choice to select tickets and milestones, and a Wiki path (or number of Wiki paths) to select Wiki pages (see Wiki section below). These queries should also be saved so project teams can build reports which are useful for their project. Using these queries most users requirements should be covered. Maybe the queries should be saved by project or milestone - that would be good but not strictly necessary.
In an ideal world there would be a way to link subversion commits to a project. This could be done using the bugtraq string which TortoiseSVN adds to a commit. The bugtraq id links to a ticket which is against a project. Perfect timelines then! The downside of this is that *every* commit *has* to specify a ticket. The Trac code which indexes repository revisions would have to search commit messages for the bugtrac id and link it to the ticket. I guess Trac could then log the commit in the ticket as well.
NOTE: There is an issue already posted to look at the bugtraq properties in Subversion. See issue #1947. Note that the only external client aside from the command line tools that supports the bugtraq properties right now (correctly) is TortoiseSVN.
Roadmap
This is rather simpler than for the timeline. Given that there needs to be a defined relationship between projects and milestones selecting a project should be all that is needed.
Browse Source
No need to change anything here unless multiple repositories were desired, as it is and should remain a view of the entire repository content.
Wiki
I think that by using the subpages or whatever it is you call pages which have a path (like MyProjectName/...) with the project name at the top level would neatly support multiple project documentation. The query for the timeline would use this path name to select project documentation changes.
Tickets Affecting Multiple Projects
Ticket #130 talks about assigning one ticket to multiple projects. I believe that this would be complex and prone to error. It is very difficult to know which projects a piece of common code will affect. It would be very useful to be able to have tickets depend on other tickets (see ticket #31) so that as problems are found on different projects which are caused by common code they can be linked to a single ticket.
Multi Project Overview
Robin Bowes requested the ability to view summaries of tickets, checkins etc., accross all projects.
Given that the default project (project zero) would give the current Trac single project behaviour if this project were always available for selection then activity on all projects would be visible in one view.
What this does not allow is viewing activity across a subset of the projects.
Schema
This is a possible schema.
Permissions
If you had multiple projects, you would quite likely want to give some users access to some but not all projects. Right now, the security model doesn't allow for this. One option would be to add a "project" column to the permission table, which would be optional. If left blank, the permission would be allowed for all projects.
Attachments
- MultiProjectSchema.png
(18.7 KB) - added by anonymous 3 years ago. | http://trac.edgewall.org/wiki/TracMultipleProjects/ByProductAndSearch | crawl-002 | refinedweb | 1,289 | 63.7 |
Split from -
I think I may be in the same class as rwill357 and I am having some problems getting my code correct too. I appreciate the help that you have given so far. I have made the changes that you suggested. I'm not sure where I'm going wrong now though. I am able to get my code to compile but it freezes up after I enter the ints I want to populate my list. Could you take a look and provide a little feedback?
#include<iostream> #include <assert.h> #include<stdio.h> #include<conio.h> using namespace std; class IntSLLNode { public: int info; IntSLLNode *next; IntSLLNode() {next = 0; } IntSLLNode *tmp; IntSLLNode(int el, IntSLLNode *ptr = 0) { info = el; next = ptr; } }; class IntSLList { public: IntSLList() { head = tail = 0; } void addToHead ( int el){ IntSLLNode *tmp = new IntSLLNode(el); if (head == NULL) head = tail = tmp; else tmp->next = head; head = tmp; } void addToTail(int el) { if (tail !=0) { tail->next = new IntSLLNode(el); tail = tail ->next; } else head = tail = new IntSLLNode (el); } int deleteFromHead(){ assert(head!=0); int el = head -> info; IntSLLNode *tmp = head; if (head == tail) head = tail = 0; else head = head -> next; delete tmp; return el; } int deleteFromTail (){ int el = tail->info; if (head == tail) { delete head; head = tail = 0; } else { IntSLLNode *tmp; for (tmp = head; tmp->next != tail; tmp = tmp->next); delete tail; tail = tmp; tail->next =0; } return el; } int deleteIthNode(int el) { IntSLLNode *tmp, *prev; int i; int counter = 0; if(head == NULL) { cout<<"\nEmpty List\n"; } else { int counter = 1; tmp=head->next; prev= head; while (tmp!= tail && counter < i) prev = tmp; tmp= tmp->next; } if (counter != i) { cout << "list doesn't contain that many nodes"; } else if (i= 1) { deleteFromHead(); } else if (tmp= tail) { deleteFromTail(); } else { IntSLLNode *pred, *tmp; for (pred = head, tmp= head-> next; tmp!= 0 &&(tmp->info == el); pred = pred->next, tmp= tmp->next); if (tmp !=0) { pred->next = tmp->next; if (tmp == tail) tail = pred; delete tmp; } } return 0; } void printALL() { IntSLLNode *tmp; if(head == NULL) cout <<"\nEmpty List\n"; else { for (tmp = head; tmp->next != tail; tmp = tmp->next); cout << tmp << " "; } cout << "\n"; } private: IntSLLNode *head, *tail; }; int main() { int n = 0; int i= 0; IntSLList list1; /*write the codes to add some nodes by using addtoTail function*/ cout << "Please enter a number you would like to add to the list.\nAfter each number press enter and when done enter n.\n"; while (n != 'n') { cin >> n; list1.addToTail(n); } list1.printALL(); cout <<"\nWhat is the position of the node that you would like to delete? "; cin >> i; int err = list1.deleteIthNode(i); cout<<"\ndeleting "<<endl; list1.printALL(); return 0; system ("PAUSE"); return 0; } | https://www.daniweb.com/programming/software-development/threads/256848/linked-list | CC-MAIN-2017-13 | refinedweb | 445 | 79.3 |
speedracerspeedracer
Collect performance metrics for your library/application.
Speed Racer is a performance runner, like a test runner, but for performance
See what's new in
InstallationInstallation
npm install -g speedracer
Speed Racer needs Google Chrome to run your files. It will run it headlessly if it finds a proper intallation of Canary (Mac OS X only for now).
UsageUsage
Speed Racer comes with two commands right now:
run: collect performance metrics and save them.
display: display a summary of generated reports.
Create racesCreate races
A race can be seen as a unit test. It contains a piece of code that will be profiled by Speed Racer. Under the hood, it uses Chrome DevTools protocol to drive Chrome and collect traces. Races can import
es6 /
commonjs modules and use most of
es6 features, depending on your version of Google Chrome: es6 support
Here is an example of a file containing a race:
import race from 'speedracer' race('my first race', () => { // ... stuff to profile })
You can define as many races as you want per file, Speed Racer will collect and run them sequentially.
You can also define asynchronous races like so:
import race from 'speedracer' race('my first async race', () => new Promise(resolve => { // ... stuff to profile resolve() }))
Run racesRun races
Then you need to collect metrics!
For each race, Speed Racer will produce two artifacts:
- a trace: a raw dump of Google Chrome tracing events, it contains a lot of detailed metrics about your race.
- a report: a report created by Speed Racer from those events, it summarizes important metrics.
Those artifacts will be saved in the
.speedracer directory by default.
To run races, type
speedracer run perf/*.js or simply
speedracer perf/*.js. Note that it will run all
.js files in the
perf directory by default, so you can omit
perf/*.js if you are using this directory.
For more details, type
speedracer run --help. You can browse examples here.
Display reportsDisplay reports
Once the artifacts have been created, you can quickly display a summary report for each run. Type
speedracer display to see all the reports or
speedracer display .speedracer/a-file-name/* to see the reports of a specific file.
For more details, type
speedracer display --help.
Go furtherGo further
Speed Racer is still a baby so it does not provide advanced analysis yet, just a basic summary. But it has several goals:
- regression testing: compare runs over time and report how it's faster/slower.
- benchmarking: compare several races to see which is the best.
- analysis: give precise insights of what is slow and why.
- auditing: give advices on how to improve performance.
If you want to use Speed Racer for one of this use cases, you can leverage it and analyze the traces and reports it produces. I would be glad to receive your feedback and ideas on the subject!
TracesTraces
Traces are
json files with the
.trace.gz extension. They are basically huge arrays of events produced by Google Chrome. Those events give tons of informations about the overall performance of race. Here is the detail format.
Traces can be pretty big, so they are saved
gziped.
You can analyze them the way you want or load them in the Timeline/Performance tab of Chrome like so:
- Locate and decompress your trace:
# first you need to locate and decompress the trace $ cd .speedracer $ ls text-fixtures-multiple $ cd text-fixtures-multiple $ ls render-60-frames.speedracer render-60-frames.trace.gz search-10e4-first-primes-very-long.speedracer search-10e4-first-primes-very-long.trace.gz $ gunzip render-60-frames.trace.gz
- Load it in Chrome Devtools or use DevTools Timeline Viewer and enjoy
🎉
ReportsReports
Reports are
json files with the
.speedracer extension. They provide a performance summary for a given race.
Here is the format:
{ "meta": { "title": "render 60 frames", "group": "test-fixtures-multiple", "id": "render-60-frames" }, "profiling": { "categories": { "scripting": 13.217000007629395, "rendering": 11.370999991893768, "painting": 9.248999938368797 }, "events": { "Animation Frame Fired": 7.994999974966049, "Composite Layers": 7.0119999796152115, "Update Layer Tree": 6.503000020980835, "JS Frame": 5.1060000360012054, "Recalculate Style": 4.867999970912933, "Paint": 2.236999958753586, "Run Microtasks": 0.11599999666213989 }, "functions": { "FireAnimationFrame": 7.994999974966049, "CompositeLayers": 7.0119999796152115, "UpdateLayerTree": 6.503000020980835, "UpdateLayoutTree": 4.867999970912933, "f:render@24": 2.32600000500679, "Paint": 2.236999958753586, "f:requestAnimationFrame@": 2.1010000109672546, "f:ws.onmessage@24": 0.1940000057220459, "f:finishRace@24": 0.15600000321865082, "f:@": 0.1300000101327896, "RunMicrotasks": 0.11599999666213989, "f:Promise@": 0.10099999606609344, "f:startRace@24": 0.09800000488758087 } }, "rendering": { "firstPaint": 0.00805, "fps": { "mean": 60.98, "variance": 3.9, "sd": 1.97, "lo": 56.92, "hi": 63.47 } } }
You can display, analyze or compare them depending on your needs. | https://www.ctolib.com/speedracer-speedracer.html | CC-MAIN-2019-04 | refinedweb | 768 | 70.5 |
Auth0 is an identity platform that offers comprehensive authentication solutions to cover customers in every market sector. One of our most popular features is Single Sign-On or SSO, for short. This feature lets users sign in only once to gain access to different sites and mobile and web applications.
To help secure one of the most popular web platforms in the world with the flexibility and power of SSO, Auth0 offers WordPress developers the Login by Auth0 plugin, which provides SSO between different WordPress installs and applications on any other platform.
The concept of SSO can be a little confusing for developers and site administrators that may be new to it. So in this post, we'll explore the different concepts associated with SSO and how our WordPress plugin can help you.
What Is SSO?
SSO allows multiple apps to share a single session from a central provider. Users log in once, in this case to an authorization server powered by Auth0, to establish the main session and then are redirected to the application to establish a session there. When that user visits a different site or application associated with the same authorization server, the existing first session is used to create a session without having to log in again.
When you delegate authentication, you hand off the responsibility of verifying a user's credentials (such as username and password) to a third party. In this post, that third party is Auth0 but it could also be Google, Facebook, or another identity provider. For SSO to work, you need to have two sessions:
- The session with the Auth0 authorization server, created when you log in.
- The session with WordPress, created when you're redirected back after logging in.
At Auth0, we use the term tenant to indicate a particular namespace. When you sign up for Auth0, you choose a tenant name which becomes part of your Auth0 domain used for OAuth and API endpoints.
When you log in to the Auth0 dashboard, the controls and menus that you see are for the specific tenant you are using. If you create a second tenant or are added to an existing one, you can switch tenants from the menu on the top right. The name next to your avatar is the tenant that you are currently using.
This tenant is a logical boundary around Auth0 functionality like Applications, Connections, Users, Rules, and more. All the Applications within a tenant can share a session (in other words, can use SSO between them) and can use the same Connections to log in if configured to do so.
This means that once you login to Auth0 and establish the first session, all the applications for that same tenant can use that session to determine whether the user is logged in or not. For the user, the process looks like this:
- Click "Login" on App 1
- Log in with Auth0
- The user is now logged in with App 1
- Visit App 2 and click on "Login" there. Note: The user may also be redirected to log in from a page that requires authentication
- The user bypasses any login forms and is now logged in with App 2 as well
- Visit App 3 and click "Login"
- The user is then logged in with App 3 as well
For a more detailed description of how this process works, see our Single Sign-On with Auth0 document.
As you can see, this is a great way to create a simple, low-friction authentication experience for users in your network of sites and apps. Learn more about SSO, here.
How Does Single Sign-On (SSO) Work in WordPress?
SSO in WordPress works the same as above, just replace "App" with "WP Site" anywhere in the process. SSO can happen between WordPress sites as well as with other web or mobile applications. As long as the different instances are using Auth0 and a browser for authentication, you can use SSO between them.
Let's see how that works in a little more detail:
- Users request a restricted page or try to take an action that requires authentication (like accessing the profile page).
- The site checks for a session in WordPress with
is_user_logged_in()(this checks for a specific cookie set by WordPress on login).
- If there is no session, users are redirected to check for an Auth0 session.
- If users already have a valid session with Auth0 (they are already logged in to Auth0 and it has not expired), they are prompted (if desired) to continue with the same account then redirected back to WordPress.
- Once redirected, the Auth0 authentication is verified and the WordPress session is re-started.
- Users proceed to view the restricted page or carry out the action they wanted to take.
While there is a lot going on behind the scenes, most of this will be transparent to the users. Their session was renewed without asking for credentials again and they were able to continue with their action.
This process works whether the users have an account with the second (or third or fourth) WordPress site or not. The plugin can be configured to allow new accounts to be created from Auth0 users even if site registration is turned off. This allows new sites to be added without requiring known users to register!
Additional Benefits of Enabling SSO
The benefits of enabling SSO for a network of sites and applications aren't limited to just simplifying the user experience, but also include storing users in a central location and improving sign-up conversions. You can easily bring these benefits to your WordPress project by implementing SSO with Auth0.
Auth0 connects to many different identity providers while also providing you with a central user database that can be associated with some or all of your WordPress sites and applications. This central user database creates a single source of truth for all user data and allows you to efficiently search for and update users in the dashboard or using our Management API.
A single database for multiple sites also allows you to streamline and enforce security measures across all the sites that use it. Password strength and composition, as well as username restrictions, can be enabled and managed in one place, improving the security of all sites within the network.
Finally, Auth0 provides additional login security, particularly when using the Universal Login Page. The WordPress login page URL is standard across all sites, making it a common target for enumeration and DDoS attacks. Putting Auth0 in front of your authentication flow protects from as-yet-unknown vulnerabilities, out-of-date core code, and additional holes that might be opened by plugins.
"Discover the benefits of enabling SSO in your WordPress applications."
Does SSO Work with Multisite Networks?
The Login by Auth0 plugin is regularly tested with WordPress multisite. That means that multisite networks can use SSO between networks with the same benefits as single sites. Network administration (such as managing access to each site for each user) still happens in WordPress but the initial authentication will happen in Auth0. To be clear, SSO with Auth0 does not happen between sites within a WordPress multisite network but can between networks.
There are some considerations regarding setup that are covered in our Auth0 WordPress plugin installation documentation. Also, the plugin settings can be set via PHP constants and will map to all sites in the multisite network. If you have any questions about plugin configuration or how it works, please see the end of this post for a link to our Community channel where you can connect with other WordPress developers like you using Auth0.
Try WordPress SSO with Auth0 Out
The best way to see how WordPress SSO works with Auth0 is to try it out yourself. This will require setting up two different WordPress sites and connecting them through Auth0. You can set this up between two existing sites but please note that while the Auth0 plugin is not destructive (it will not delete users, metadata, or roles), it does take control over your login process so it’s best to try the setup on test/development sites or on sites that only use authentication for site administration. Deactivating the plugin will return the login process to its original state.
For this setup and testing process, make sure to use the same browser window (separate tabs are fine) to guarantee that you’re using the same cookie store to make SSO work.
First, sign up for an Auth0 account here (it’s free for up to 7,000 users). If you want to get more familiar with the dashboard and what Auth0 has to offer, follow the tutorials that appear. Don’t worry about creating Applications or Connections for your test WordPress sites, that’s all done automatically during plugin setup.
Next, decide which two sites you want to connect, log in as an administrator and install the Login by Auth0 plugin on both (the login page will not change until the plugin is configured).
On one of the sites, activate the plugin and you’ll be redirected to a Setup Wizard.
Follow the Standard Setup instructions from this document to create an Application, Database Connection, and a user account for yourself. Before continuing, check your email and click on the verify email link that was sent.
Once the setup is complete, go to Auth0 > Settings > Features tab in your WordPress admin and make sure that Universal Login Page is turned on (this is a default setting in the latest version of the plugin).
To test that everything is working properly, log out of WordPress, then visit the
wp-login.php page. You should be redirected to the Universal Login Page on Auth0.
Try logging in with the same credentials used during Auth0 WordPress plugin setup to make sure it’s working properly.
If your site is set up to require verified email addresses, you'll see the following page if you haven't done so:
Once you are logged in, you'll see the home page of your first site:
On the second site, follow the same procedure to install and activate the plugin. There's one difference to have in mind when running through the Setup Wizard: on the screen where you’re asked for an admin password, click Skip this step.
You're going to use SSO to link your Auth0 account to your WordPress one. Once the setup completes, go to Auth0 > Settings > Features tab in your WordPress admin, make sure that Universal Login Page is turned on, and turn Single Logout off.
The Single Logout feature logs users out of Auth0 when they log out of WordPress. By turning this off, you allow users to keep an active session with the Auth0 authorization server even after they log out from one of your sites. Users are also allowed to log back into one of your sites using SSO and without having to re-enter their credentials.
Next, go to your Auth0 Dashboard > Setup > Applications and select the Application created for the second WordPress site.
If your dashboard looks different than the screenshots above, go to Auth0 Dashboard > Applications to select the application.
Click the Connections tab, turn off the database Connection created for this site, and turn on the Database Connection being used for the first site.
To avoid confusion, go to Auth0 Dashboard > Authentication > Database and delete the Connection created for the second site.
If your dashboard looks different than the screenshots above, go to Auth0 Dashboard > Connections > Database to delete the second database.
Select the database of the second WordPress application from the list and scroll down until you see a red button named "Delete" and click it:
Finally, confirm the database deletion in the modal that comes up.
You now have two Applications and one Database Connection that’s activated for both.
On the second site, you want to test that the account that was created during the setup of the first site, the one tied to the session created at Auth0, maps to the second site. Log out of the second site and visit the
wp-login.php page. You will see a pause in your browser followed by the homepage of your second site, where you are logged in.
Congrats, you just set up SSO between two WordPress sites! You can follow the steps for the second site for as many WordPress sites as you need. Just make sure they are all using the same Database Connection so that same Auth0 user account is used across applications.
"Learn how simple and easy is to add SSO to WordPress apps using Auth0."
Summary
We hope you learned a bit about SSO in general and, specifically, how it works with WordPress. If you have any questions about capability, configuration, or anything else, please post in the thread below and we’ll be happy to help! | https://auth0.com/blog/wordpress-sso-with-auth0/ | CC-MAIN-2020-16 | refinedweb | 2,154 | 58.01 |
State machines have always fascinated me. There is a clockwork precision to their inner workings that appeals to me on an aesthetic level. They are also an invaluable programming tool. In building libraries and applications, I have returned to them again and again. The .NET State Machine Toolkit grew out of my interest in state machines as well as my need for a small framework to create them.
This is the first of three articles about my .NET State Machine Toolkit. This article will cover the classes that make up the core of the toolkit as well as how to create a simple, flat state machine. Part II will cover creating hierarchical state machines as well as some of the more advanced features. Part III will cover code generation as well as creating state machines with XML. Special thanks to Marc Clifton for suggesting how I could break up my article into several parts. I had been struggling with this, and his suggestion made things clear. Thanks, Marc!
A state machine is a model of how something behaves in response to events. It models behavior by making its responses appropriate to the state that it is currently in. How a state machine responds to an event is called a transition. A transition describes what happens when a state machine receives an event based on its current state. Usually, but not always, the way a state machine responds to an event is to take some sort of action and change its state. A state machine will sometimes test a condition to make sure it is true before performing a transition. This is called a guard.
This description of state machines introduces several abstract concepts quickly, and is not meant to be formal or complete. It is just a starting point. We will explore what state machines are, more through example than definition.
We will look at a very simple state machine, a light switch. It has only two states: on and off. When the light switch is in the off state and receives an event turning it on, it transitions to the on state. When the light switch is in the on state and receives an event turning it off, it transitions to the off state. This is about as simple as it gets for state machines.
The above state chart diagram illustrates the light switch state machine. States are represented by rounded rectangles. Transitions are represented by arrowed curved lines connecting the states. The arrows indicate the direction of the transition, and the lines are labeled with the name of the event that triggered the transition.
When a state machine is created, it begins its life in one of its states. This state is called the initial state. A solid circle connected by an arrowed line points to the initial state. In the case of our light switch state machine, the initial state is the off state.
State charts can include other details as well. For example, each transition can be labeled with an action that describes what action the state machine performs during the transition. A transition can be labeled with a guard as well. For a more in depth look at state charts, go here.
With that brief introduction to state machines, we will now look at the .NET State Machine Toolkit. It is made up of a small number of classes described below. In addition to these classes are a number of classes used for code generation, which I will cover in Part III. I will describe the role of each class as well as some important points about how they behave.
The
StateMachine class is the abstract base class for all state machine classes. You do not derive your state machine classes from this class but rather from one of its derived classes, either the
ActiveStateMachine class or the
PassiveStateMachine class. When I talk about the
StateMachine class in the rest of the article, I'm describing functionality and behavior common to both the
ActiveStateMachine and
PassiveStateMachine classes.
Sending an event to a
StateMachine is done by using its
Send method. This places the event and its data, if any, at the end of the queue. Later, the
StateMachine will dequeue the event and dispatch it to its current
State. Additionally, there is a
SendPriority method that places the event at the head of the queue so that it will be handled before other events already in the queue. This method has protected access so that only
StateMachine derived classes can use it. It is useful when a
StateMachine needs to send an event to itself and needs that event to be dealt with before other events.
A
StateMachine raises the
TransitionCompleted event when it has finished firing a transition. The
TransitionCompletedEventArgs class accompanies the event. It has the following properties:
StateID- an integer value representing the ID of the current state, the target state of the transition. In the case of internal transitions, this value will not change from the previous transition.
EventID- an integer value representing the ID of the event that triggered the transition.
ActionResult- an object that represents the result of the action(s) associated with the transition. This property essentially allows transitions to return a value. This property can be
nullif no value was set by the transition's action(s).
Error- an
Exceptionobject representing an exception thrown by one of the transition's actions. This property will be
nullif no exception was thrown.
A client that uses a
StateMachine can listen for the
TransitionCompleted event to be fired after sending a
StateMachine an event. It can then examine the results and respond how ever it chooses. If an exception is thrown from an action, it is caught and passed along, after the transition completes through the
TransitionCompleted event.
The
ActiveStateMachine class uses the Active Object design pattern. What this means is that an
ActiveStateMachine object runs in its own thread. Internally,
ActiveStateMachines use
DelegateQueue objects for handling and dispatching events. You derive your state machines from this class when you want them to be active objects.
The
ActiveStateMachine class implements the
IDisposable interface. Since it represents an active object, it needs to be disposed of at some point to shut its thread down. I made the
Dispose method
virtual so that derived
ActiveStateMachine classes can override it. Typically, a derived
ActiveStateMachine will override the
Dispose method, and when it is called, will send an event to itself using the
SendPriority method telling it to dispose of itself. In other words, disposing of an
ActiveStateMachine is treated like an event. How your state machine handles the disposing event depends on its current state. However, at some point, your state machine will need to call the
ActiveStateMachine's
Dispose(bool disposing) base class method, passing it a
true value. This lets the base class dispose of its
DelegateQueue object, thus shutting down the thread in which it is running.
Unlike the
ActiveStateMachine class, the
PassiveStateMachine class does not run in its own thread. Sometimes using an active object is overkill. In those cases, it is appropriate to derive your state machine from the
PassiveStateMachine class.
Because the
PassiveStateMachine is, well, passive, it has to be prodded to fire its transitions. You do this by calling its
Execute method. After sending a
PassiveStateMachine derived class one or more events, you then call
Execute. The state machine responds by dequeueing all of the events in its event queue, dispatching them one right after the other.
The
State class represents a state a
StateMachine can be in during its lifecycle. A
State can be a substate and/or superstate to other
States.
When a
State receives an event, it checks to see if it has any
Transitions for that event. If it does, it iterates through all of the
Transitions for that event until one of them fires. If no
Transitions were found, the
State passes the event up to its superstate, if it has one; the process is repeated at the superstate level. This process can continue indefinitely until either a
Transition fires or the top of the state hierarchy is reached.
After processing an event, the
State returns the results to the
Dispatch method where the
State originally received the event. The results indicate whether or not a
Transition fired, and if so, the resulting
State of the
Transition. It also indicates whether or not an exception occurred during the
Transition's action (if one was performed). State machines use this information to update their current
State, if necessary.
The
SubstateCollection class represents a collection of substates. Each
State has a
Substates property of the
SubstateCollection type. Substates are added and removed to a
State via this property.
Substates are not represented by their own class. The
State class performs double duty, playing the role of substates and superstates when necessary. Whether or not a
State is a substate depends on whether or not it has been added to another
State's
Substates collection. And whether or not a
State is a superstate depends on whether or not any
States have been added to its
Substates collection.
There are some restrictions on which
States can be added as substates to another
State. The most obvious one is that a
State cannot be added to its own
Substates collection; a
State cannot be a substate to itself. Also, a
State can only be the direct substate of one other
State; you cannot add a
State to the
Substates collection of more than one
State.
The
Transition class represents a state transition. It can have a delegate representing a guard method which it will use to determine whether or not it should fire. It can also have one or more delegates representing action methods that it will execute when it fires. And, it can have a target
State that is the target of the
Transition.
The
TransitionCollection represents a collection of
Transitions. Each
State object has its own
TransitionCollection for holding its
Transitions.
When a
Transition is added to a
State's
TransitionCollection, it is registered with an event ID. This event ID is a value identifying an event a
State can receive. When a
State receives an event, it uses the event's ID to check to see if it has any
Transitions for that event (as described above).
Let's use the toolkit to build the light switch state machine described above. It will have two states:
on and
off. And two events:
TurnOn and
TurnOff First, we create a class that is derived from the
PassiveStateMachine class:
using System; using Sanford.StateMachineToolkit; namespace LightSwitchDemo { public class LightSwitch : PassiveStateMachine { public LightSwitch() { } #region Entry/Exit Methods #endregion #region Action Methods #endregion } }
This is the skeleton for our
PassiveStateMachine derived class. Notice that we created regions to mark off each of the method types we will be using. This is strictly to help the code be more readable.
Events are represented in the toolkit as integers. The values of the integers serve as IDs for the events. It is easiest to represent event IDs with an enumeration.
States are represented by the
State class. Each state has its own
State object. In addition, each state has its own ID. Like the event IDs, state IDs are integer values and are best represented by an enumeration. So, the next step is to create enumerations to represent the event and state IDs and add
State objects:
using System; using Sanford.StateMachineToolkit; namespace LightSwitchDemo { public class LightSwitch : StateMachine { public enum EventID { TurnOn, TurnOff } public enum StateID { On, Off } private State on; private State off; // ...
We made the enumerations public so that clients listening to the
TransitionCompleted event will have access to event and state ID values in order to identify the event and state associated with the transition.
Before going any further, let's add all of the methods for our state machine:
using System; using Sanford.StateMachineToolkit; namespace LightSwitchDemo { public class LightSwitch : StateMachine { private enum EventID { TurnOn, TurnOff } public enum StateID { On, Off } private State on; private State off; private State disposed; public LightSwitch() { } #region Entry/Exit Methods private void EnterOn() { Console.WriteLine("Entering On state."); } private void ExitOn() { Console.WriteLine("Exiting On state."); } private void EnterOff() { Console.WriteLine("Entering Off state."); } private void ExitOff() { Console.WriteLine("Exiting Off state."); } #endregion #region Action Methods private void TurnOn(object[] args) { Console.WriteLine("Light switch turned on."); ActionResult = "Turned on the light switch."; } private void TurnOff(object[] args) { Console.WriteLine("Light switch turned off."); ActionResult = "Turned off the light switch."; } #endregion } }
In previous versions of the toolkit, I described using "Facade" methods to serve as light wrappers for sending events to the
StateMachine. With this version of the toolkit, I've made the
Send method of the
StateMachine class
public instead of
protected. What this means is that the facade methods are not strictly necessary; events can be sent to the
StateMachine directly using the
Send method. However, you can still write facade methods if you choose; they help hide some of the machinery for sending events. It is a matter of style.
The Entry and Exit methods are optional. Entry methods are called by
States when they are entered, and Exit methods are called when they are exited. Here, we have Entry and Exit methods for both the
on and
off states and an Entry method for the
disposed state. As a matter of convention, we use the name Enter or Exit, with the name of the state it belongs to as a suffix. Notice that they do not take any parameters. Also, it is important to note that throwing an exception from an entry or exit method is illegal and will lead to undefined behavior.
Next, we have the Action methods. These methods represent the actions that are performed during transitions. Notice that they take an object array as their only parameter. This array represents the arguments passed to the
StateMachine's
Send method. The number of event data elements can vary from zero to many. In the case of our light switch state machine, no additional arguments are passed with the event. If something were to go wrong in our action methods, we could throw an exception. This is the only place in a
StateMachine where exceptions can be thrown. As described before, any exceptions thrown from an action are caught by the
StateMachine and passed along to the client via the
TransitionCompleted event.
In addition to the methods described above, you can have Guard methods. These are methods
Transitions use to determine whether or not they should fire. Our light switch state machine does not need any guards, so we have not added any.
Before we leave the
StateMachine's methods, let's look at how they are invoked, and how a
StateMachine typically handles an event:
In the case of
ActiveStateMachine derived classes:
StateMachinevia its
Sendmethod.
Dispatchmethod along with the event and any of its accompanying arguments, to its
DelegateQueue.
DelegateQueuedequeues the
Dispatchmethod and invokes it, passing it the event's arguments.
And in the case of
PassiveStateMachine derived classes:
StateMachinevia its
Sendmethod.
Executemethod is called, an event is dequeued. It is passed along with its arguments to the
Dispatchmethod.
At this point, the steps for both the passive and active state machines are the same:
Dispatchmethod dispatches the event to the
StateMachine's current
State.
Statechecks to see if it has any
Transitions for the event. If it does, the
Transitions are evaluated in the order in which they were added to the
Stateuntil one of them fires. It is during this process that the Guard methods are called, if any have been added to the
Transitions.
Transitionfires in response to an event and the
Transitionhas a target
State, the Exit methods are called. More than one
Statemay be exited. This depends on the path of the current
Stateto the target
State.
Transitionhas an action, it is performed at this point.
Transitionis fired, the
TransitionCompletedevent is raised.
Passive state machines will continue dispatching events until their event queue is empty.
Next, let's create the
States in the constructor:
public LightSwitch() { off = new State((int)StateID.Off, new EntryHandler(EnterOff), new ExitHandler(ExitOff)); on = new State((int)StateID.On, new EntryHandler(EnterOn), new ExitHandler(ExitOn)); }
Each
State is initialized with its ID. In addition, the
States are initialized with delegates to their Entry and Exit methods. Again, Entry and Exit methods are optional. You may choose not to use them, in which case you would only pass the state's ID to the
State's constructor.
In previous versions of the toolkit,
States needed to know the number of events they will receive. The reason for this is that their
TransitionCollection used an
ArrayList for storing
Transitions. Thus, event IDs had to be consecutive values from zero to one less than the total number of events. And the
TransitionCollection needed to know the number of events before hand. I've found this to be a brittle requirement. So I've switched over to using a hash table for storing transitions. This leaves you free to use any values for the event IDs you want. The number of events or their IDs do not have to be know by the
States beforehand.
Now, let's set up the state transitions so that when the state machine is in the
on state and receives a
TurnOff event, it transitions into the
off state, and when the state machine is in the
off state and receives a
TurnOn event, it transitions into the
on state:
public LightSwitch() { off = new State((int)StateID.Off, 3, new EntryHandler(EnterOff), new ExitHandler(ExitOff)); on = new State((int)StateID.On, 3, new EntryHandler(EnterOn), new ExitHandler(ExitOn)); Transition trans; trans = new Transition(on); trans.Actions.Add(new ActionHandler(TurnOn)); off.Transitions.Add((int)EventID.TurnOn, trans); trans = new Transition(off); trans.Actions.Add(new ActionHandler(TurnOff)); on.Transitions.Add((int)EventID.TurnOff, trans); Initialize(off); }
When we created a
Transition, we passed it a
State object representing the target of the
Transition. After creating a
Transition, it is added to a
State's
Transitions property.
Before leaving the constructor, we initialized the
StateMachine with the initial state. This is an important step and one that's easy to forget. If you forget, you will get an
InvalidOperationException when the
StateMachine receives an event. We initialized the
StateMachine so that it will initially be in the
off state. This is done here in the constructor, but it can be done at a later time. The important thing to remember is that it must be done before the
StateMachine receives its first event.
We are now ready to write a simple driver program to demonstrate our
LightSwitch state machine:
using System; using System.Threading; using Sanford.StateMachineToolkit; namespace LightSwitchDemo { class Class1 { [STAThread] static void Main(string[] args) { LightSwitch ls = new LightSwitch(); ls.TransitionCompleted += new TransitionCompletedEventHandler(HandleTransitionCompleted); ls.Send((int)LightSwitch.EventID.TurnOn); ls.Send((int)LightSwitch.EventID.TurnOff); ls.Send((int)LightSwitch.EventID.TurnOn); ls.Send((int)LightSwitch.EventID.TurnOff); ls.Execute(); Console.Read(); } private static void HandleTransitionCompleted(object sender, TransitionCompletedEventArgs e) { Console.WriteLine("Transition Completed:"); Console.WriteLine("\tState ID: {0}", ((LightSwitch.StateID)(e.StateID)).ToString()); Console.WriteLine("\tEvent ID: {0}", ((LightSwitch.EventID)(e.EventID)).ToString()); if(e.Error != null) { Console.WriteLine("\tException: {0}", e.Error.Message); } else { Console.WriteLine("\tException: No exception was thrown."); } if(e.ActionResult != null) { Console.WriteLine("\tAction Result: {0}", e.ActionResult.ToString()); } else { Console.WriteLine("\tAction Result: No action result."); } } } }
With the results when run:
Entering Off state. Entering Off state..
Notice that the
Off state is entered first. This is because when the
StateMachine is initialized with its initial
State, it automatically enters it.
When you download the demo projects, which includes the source code for the toolkit, you'll find that it won't build out of the box. This is because I've deleted the bin and obj folders from each project to make the zip file smaller. These folders contain the assemblies the projects depend on to build. For this reason, you'll need to go to my website to download the assemblies the State Machine Toolkit depends on. Then you'll need to add them to each project in the solution manually.
The State Machine Toolkit depends on two other of my namespaces, the
Sanford.Threading namespace and the
Sanford.Collections namespace. The toolkit depends directly on the
Sanford.Threading namespace by using its
DelegateQueue class.
ActiveStateMachines use this class as an event queue. The
DelegateQueue class previously belonged to the toolkit itself, but I decided that it was better suited in a different namespace; several of my other namespaces use it without needing other features of the toolkit.
The dependency on the
Sanford.Collections namespace is indirect. The
DelegateQueue class uses the
Deque class from
Sanford.Collections. So in order to use the
DelegateQueue class, the toolkit must not only reference the
Sanford.Threading assembly but also the
Sanford.Collections assembly. You can get these assemblies here.
As I said at the beginning, I find state machines appealing and fascinating. This toolkit has been incredibly satisfying to write. It has continued to evolve, and I hope that this latest version will be the easiest version to use yet. If you have found this article interesting and the toolkit looks useful to you, please take a look at Part II and Part III.
Take care, and as always, comments and suggestions are welcome.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/statemachinetoolkitparti.aspx | crawl-002 | refinedweb | 3,588 | 66.13 |
3 ), O(n 2 ) for each subarray and O(n) for finding gcd of a subarray.
Method 2
Find GCD of all subarrays using segment tree based approach discussedhere. Time complexity of this solution is O(n 2 logn), O(n 2 ) for each subarray and O(logn) for finding GCD of subarray using segment tree.
Method 3
The idea is to useSegment.
- Build segment tree so that we can quicky find GCD of any subarray using the approach discussedhere
- After building Segment Tree, we consider every index as starting point and do binary search for ending point such that the subarray between these two points has GCD k
Following is C++ implementation of above idea.
// C++ Program to find GCD of a number in a given Range // using segment Trees #include <bits/stdc++.h> using namespace std; // To store segment tree int *st; // Function to find gcd of 2 numbers. int gcd(int a, int b) { if (a < b) swap(a, b); if (b==0) return a; return gcd(b, a%b); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int findGcd(int ss, int se, int qs, int qe, int si) { if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2)); } //Finding The gcd of given Range int findRangeGcd(int ss, int se, int arr[], int n) { if (ss<0 || se > n-1 || ss>se) { cout << "Invalid Arguments" << "/n"; return -1; } return findGcd(0, n-1, ss, se, 0); } // A recursive function that constructs Segment Tree for // array[ss..se]. si is index of current node in segment // tree st int constructST(int arr[], int ss, int se, int si) { if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructSegmentTree(int arr[], int n) { int height = (int)(ceil(log2(n))); int size = 2*(int)pow(2, height)-1; st = new int[size]; constructST(arr, 0, n-1, 0); return st; } // Returns size of smallest subarray of arr[0..n-1] // with GCD equal to k. int findSmallestSubarr(int arr[], int n, int k) { // Find if k or its multiple is present int i; for (i=0; i<n; i++) { // If k is present, then subarray size is 1. if (arr[i] == k) return 1; // Break the loop to indicate presence of a // multiple of k. if (arr[i] % k == 0) break; } // If there was no multiple of k in arr[], then // we can't get k as GCD. if (i == n) return -1; // If there is a multiple of k in arr[], build // segment tree from given array constructSegmentTree(arr, n); // Initialize result int res = n+1; // Now consider every element as starting point // and search for ending point using Binary Search for (int i=0; i<n-1; i++) { // a[i] cannot be a starting point, if it is // not a multiple of k. if (arr[i] % k != 0) continue; // Initialize indexes for binary search of closest // ending point to i with GCD of subarray as k. int low = i+1; int high = n-1; // Initialize closest ending point for i. int closest = 0; // Binary Search for closest ending point // with GCD equal to k. while (true) { // Find middle point and GCD of subarray // arr[i..mid] int mid = low + (high-low)/2; int gcd = findRangeGcd(i, mid, arr, n); // If GCD is more than k, look further if (gcd > k) low = mid; // If GCD is k, store this point and look for // a closer point else if (gcd == k) { high = mid; closest = mid; break; } // If GCD is less than, look closer else high = mid; // If termination condition reached, set // closest if (abs(high-low) <= 1) { if (findRangeGcd(i, low, arr, n) == k) closest = low; else if (findRangeGcd(i, high, arr, n)==k) closest = high; break; } } if (closest != 0) res = min(res, closest - i + 1); } // If res was not changed by loop, return -1, // else return its value. return (res == n+1) ? -1 : res; } // Driver program to test above functions int main() { int n = 8; int k = 3; int arr[] = {6, 9, 7, 10, 12, 24, 36, 27}; cout << "Size of smallest sub-array with given" << " size is " << findSmallestSubarr(arr, n, k); return 0; }
Output: | http://www.shellsec.com/news/27712.html | CC-MAIN-2017-13 | refinedweb | 832 | 61.8 |
Problem :
Your manager gave you a text file with many lines of numbers to format and print. For each row of
3 space-separated doubles, format and print the numbers using the specifications in the Output Format section below.
Input Format :
The first line contains an integer,
T, the number of test cases.
Each of the
T subsequent lines describes a test case as
3 space-separated floating-point numbers:
A,
B, and
C, respectively.
Constraints :
1 <= T <= 1000
- Each number will fit into a double.
Output Format :
For each test case, print
3 lines containing the formatted
A,
B, and
C, respectively. Each
A,
B, and
C must be formatted as follows:
- : Strip its decimal (i.e., truncate it) and print its hexadecimal representation (including the
Oxprefix) in lower case letters.
- : Print it to a scale of
2decimal places, preceded by a
+or
-sign (indicating if it’s positive or negative), right justified, and left-padded with underscores so that the printed result is exactly
15characters wide.
- : Print it to a scale of exactly nine decimal places, expressed in scientific notation using upper case.
Sample Input :
1 100.345 2006.008 2331.41592653498
Sample Output :
0x64 _______+2006.01 2.331415927E+03
Solution :
#include <iostream> #include <iomanip> using namespace std; int main() { int T; cin >> T; cout << setiosflags(ios::uppercase); cout << setw(0xf) << internal; while(T--) { double A; cin >> A; double B; cin >> B; double C; cin >> C; cout << showbase << hex << left << nouppercase << long(A) << endl; cout << setw(15) << right << setfill('_') << showpos << fixed << setprecision(2) << B << endl; cout << scientific << noshowpos << uppercase << setprecision(9) << C << endl; } return 0; }
196. | https://sltechnicalacademy.com/print-pretty-hackerrank-solution/ | CC-MAIN-2021-04 | refinedweb | 270 | 52.09 |
…and Why Coding Is So Much Fun
A Gonzo Adventure In What You Can Learn When You’re Not Doing What You Are Supposed To Be Doing And You’ll Be Done In Just A Minute, It Almost Works…
[Read the VB version of this post here]
Two days ago I thought I was late getting the code done for my latest tutorial (it turns out that I was actually early but that is a different saga). I got up early and swallowed lots of pills and drank lots of coffee and took a short nap and then came into the office and sat down at the computer and said, “OK, I just need 20 pages on 3d in Silverlight 3; piece of cake. But anyone can write a tutorial on 3d, what I want to do is show how it fits into writing something real. It isn’t just a toy for little kids, this thing has sharp edges, a person could hurt themselves, we want to put this in context…”
Now, the coolest use of 3d I happened to have seen in the last six or seven minutes was a free program that gets the lyrics for whatever you’re listening to. Its entire UI (or UX as we RIA cognoscenti call it) is a panel about 400 x 600 pixels. This is nearly entirely filled with scrollable lyrics but there are a couple small icons, including, in the lower left hand corner, a very attractive italicized “i”
If you hover over that seductive little i, it lights up invitingly. Click on the i and hey! voila! the panel rotates 180 degrees revealing its “back” where you can find settings and other cool stuff that you don’t need every day but is very handy to have easily available.
When you finish playing with the settings and have put back all the things you broke, you click and the panel rotates back. Perfect. Useful, elegant, space saving and classy. I want one. More urgent: I want to build one.
Zo! That is the next tutorial, but that is not what I’m writing about here.
What I’m writing about here is what happened when I set out to build one, that I did not intend, and was not part of the project and I had no business spending time on. it was long ago and far away….
I had chosen to make my panel databound, and because I was listening to music at the time I was writing the code, I decided that the cards would provide basic information about a musician on the front, and the musician’s bio on the back.
To insinuate a tenuous business connection I created an Employee class to hold all this information (who knows, maybe these guys work for my record company?), and I used the same fields you would (more or less):
public string FullName { get; set; }
public string NickName { get; set; }
public DateTime Birthdate { get; set; }
public string Locality { get; set; }
public string Phone1 { get; set; }
public int Phone1Location { get; set; }
public string Phone2 { get; set; }
public int Phone2Location { get; set; }
public string JobTitle { get; set; }
public string JobNickName { get; set; }
public double JobLevel { get; set; }
public string Salary { get; set; }
public string Performance { get; set; }
public string Bio { get; set; }
Now, this was certainly not the final set of properties, and there was much to fix, but as I created the UI for the phone numbers, it was blazingly clear to me that I wanted the phone type to be in a combo box
That was when the trouble began. When you chose a new artist all the fields changed…. except the Phone Location (cell, home, etc.)
The more I looked at it the more baffled I became. Set aside that the code was a quick hack with insufficient decoupling of UI from data, it didn’t even work.
After a while this became the night’s obsession, culminating in my doing what I always tell others to do but never quite get around to doing myself: write a tiny program that demonstrates the problem in isolation and ask for help.
Thus was born: ComboBoxProblem.xaml
<UserControl x:Class=”ShowTheProblem.MainPage”
xmlns=””
xmlns:x=””
Width=”400″ Height=”300″>
<StackPanel x:Name=”mySP”>
<TextBlock x:Name=”Phone”
Height=”20″
VerticalAlignment=”Bottom”
Text=”{ Binding Phone, Mode=OneWay }” />
<ComboBox x:Name=”PhoneType”
HorizontalAlignment=”Left”
Width=”100″
VerticalAlignment=”Bottom”
SelectedIndex=”{Binding PhoneLocationID, Mode=OneWay}”
ItemsSource=”{Binding}”>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name=”PhoneTypeItem”
Text=”{Binding Location}” />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button x:Name=”mybutton”
Content=”Press Me”
Margin=”10″ />
</StackPanel>
</UserControl>
I’ll spare you the supporting code (I hate showing broken code) but I posted this on an internal list and immediately got back two interesting answers: there’s a bug in combo box (there isn’t) and if you set the Mode to TwoWay instead of OneWay everything works.
The Great White Whale
Now I know a Great White Whale when I see one, so call me Ishmael and I was off, spending much of the rest of the night trying to figure this out, and realizing as I went that I truly hated the fact that the Person object had to know so much about the phone location collection that populated the ComboBox.
It turns out that there were a number of interlocking problems here. Mike Hillberg (a Principal Architect at Microsoft) pointed out that with one-way binding as soon as the control changes SelectedItem, the binding is replaced with the new value. He also pointed out that I/we were having the person’s GetPhoneLocation return new objects, and just because two objects have locations set to the same string (e.g., “Home”) doesn’t mean the two references point to the same object in memory. (yes, yes, but by then it was very late).
His excellent blog post got me most of the way towards where I needed to go, but I rebelled at the idea of imposing WPF semantics on Silverlight, and I really wanted to constrain the values so that they were self-identifying; that is I wanted more of an enumeration than a class.
Another Microsoftie offered his solution, which I liked very much but his approach included the assumption that the person object would contain an ID that was an offset into the collection of phone numbers used to populate the combo box. That was where I choked.
How To Make An Enumeration Behave Like A Collection
What I wanted was to use an enumeration, with all the wonderful Intellisense support and the intuitive scoping it provides. But you can’t hand an enumeration to the ItemsSource property of a comboBox, nor can you treat enumerations as strings (at least, not without a little work).
After a bit of tinkering, (and then a little hammering, followed by some smashing and yelling) the solution that finally caught the leviathan (though I’m afraid ol’ Starbuck was never seen again) was this:
- Create a class that represents one location (so that you can have a collection of said locations, so that each member of the combobox can be an instance of that class).
- Obtain the enumeration semantics by giving the class a single member that is an enumerated constant.
public enum PhoneLocationEnum
{
Office,
Cell,
Other
};
public class PhoneLocation
{
public PhoneLocationEnum Location { get; set; }
}
You can now create a collection of these, initializing them with full support from Intellisense,
I’m so happy.
But I need an ItemsSource
What we need is an observable collection to serve as the ItemsSource for the comboBox. We’d like to add each of the PhoneLocation objects to that collection, but where will that collection live? What we really need is a class that is a collection of Phone Location objects. Aha!
public class PhoneLocations : ObservableCollection<PhoneLocation>
This sneaky bit of C# makes PhoneLocations a kind of or derived type of Observable collection of PhoneLocaitons and as such fully legal as an ItemsSource. To wire it up I need to create a namespace (local) that points to this assembly and then declare this puppy in the resources section of the Xaml file,
<UserControl.Resources>
<local:PhoneLocations x:
[ Thank you Hamid Mahmood for showing me this bit of Xaml ]
Now, finally, I can put the pieces together, Here is the Xaml
<UserControl x:Class="ComboBoxSample.Page"
xmlns=""
xmlns:x=""
xmlns:
<UserControl.Resources>
<local:PhoneLocations x:
<local:EnumToStringConverter x:
</UserControl.Resources>
<Grid x:
<StackPanel x:
<TextBlock x:
<ComboBox x:Name="PhoneType"
HorizontalAlignment="Left" Width="100"
VerticalAlignment="Bottom"
ItemsSource="{StaticResource phoneLocations}"
SelectedItem="{Binding PhoneLocVal,
Mode=TwoWay,
Converter={StaticResource converter},
ConverterParameter={StaticResource phoneLocations}}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Location}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<Button x:
</StackPanel>
</Grid>
</UserControl>
ComboBox has three important binding-related statements:
The ItemsSource is bound to the phoneLocations that was defined in the resources and thus tied to the observable collection of PhoneLocation objects
The SelectedItem is bound to PhoneLocVal which as you’ll see in a moment is the integer value stored in Person that is directly derived from the enumerated constant for the phone location
The DataTemplate is bound to Location which is the (only) property of the PhoneLocation object and which is of type PhoneLocationEnum
Type Conversion
There is a second statement in the resources section of the Xaml that I’ve glided right past,
<local:EnumToStringConverter x:
This declares a type converter, and we see it invoked in the ComboBox
SelectedItem="{Binding PhoneLocVal,
Mode=TwoWay,
Converter={StaticResource converter},
ConverterParameter={StaticResource phoneLocations}}" >
In this declaration we are saying that while we are binding to the PhoneLocVal property we don’t expect to know how to display that, and so we’ll need to use the declared converter and, further, we’ll pass in the phoneLocations as a parameter.
The code for the conversion implements IValueConverter, and thus has two methods: Convert and ConvertBack:
public class EnumToStringConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture )
{
int phoneLocationAsInteger = (int)value; ;
PhoneLocations locations = parameter as PhoneLocations;
if (locations != null)
{
foreach (PhoneLocation pl in locations)
{
if ((int)pl.Location == phoneLocationAsInteger)
return pl;
}
}
return null;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture )
{
throw new NotImplementedException();
}
}
We cast the value we’re given to an integer and the pareameter to a PhoneLocations collection. We then iterate through the collection checking to see if we find a member whose Location when cast to an int is equal to the value we were given. If so, we have our winner, and we return it. This converts an integer value to a Phone Location while ensuring that we stay within the boundaries of the enumerated constants.
Once I had that, I could sleep.
The complete source code is available here.
This code was built with Silverlight 3 Beta.
When i edit and save my dataform, it works. It doesn’t bind when i load the data though… ComboBoxes were so easy with VB… aaaaarghhhh!
Thanks!
Nice one for beginner
Looks like I spoke too soon. It looks like the combobox is only flaky when you use it in the context of the DataForm. I guess that explains why they kicked the DataForm out to the Toolkit.
I agree!!!! ComboBox is the Great White Whale! I would really like to start moving my Line of Business apps to Silverlight. I have spent days beating my head against the wall over the combobox issues. I’m don’t think I’ve ever made an app that didn’t require Comboboxes. How did Microsoft overlook this issue?????
It’s has got a little better with silverlight 4 they have improved support for the standard combobox.
I have put together a little example of how to data bind in a MVC silverlight V4 app using the now supported ‘SelectedValuePath’ ‘DisplayMemberPath’ and ‘SelectedItem’ properties. | http://jesseliberty.com/2009/04/02/why-databinding-with-comboboxes-is-nontrivial/ | CC-MAIN-2017-39 | refinedweb | 1,978 | 54.86 |
Unwrapping Decorators, Part 2
Ryan Palo
Updated on
・5 min read
Quick Recap
Last post, I wrote about the basics of decorators in Python. For those of you that missed it, here are the highlights.
- Decorators are placed before function definitions, and serve to wrap or add additional functionality to functions without obscuring the single purpose of a given function.
- They are used like this:
@custom_decorator def generic_example_function(): # ... pass
- When defining a decorator function, it should take a function as input and output a new/different/modified/wrapped function.
def custom_decorator(func): # *args, **kwargs allow your decorated function to handle # the inputs it is supposed to without problems def modified_function(*args, **kwargs): # Do some extra stuff # ... return func(*args, **kwargs) # Call the input function as it # was originally called and return that return modified_function
Okay. That about covers it. Let's get to the good stuff! I'm going to cover passing arguments to decorators (a la Flask's
@app.route('/')), stacking decorators, and Class-Based decorators.
Decorator Arguments
You can pass arguments to the decorator! It gets a little more complicated though. Remember how a basic decorator function takes in a function, defines a new function, and returns that? If you have arguments, you actually have to generate the decorator on the fly, so you have to define a function that returns a decorator function that returns the actual function you care about. Oy vey. Go go gadget code example!
from time import sleep def delay(seconds): # The outermost function handles the decorator's arguments def delay_decorator(func): # It defines a decorator function, like we are used to def inner(*args, **kwargs): # The decorator function defines the modified function # Because we do things this way, the inner function # gets access to the arguments supplied to the decorator initially sleep(seconds) return func(*args, **kwargs) return inner # Decorator function returns the modified function return delay_decorator # Finally, the outer function returns the custom decorator @delay(5) def sneeze(times): return "Achoo! " * times >>> sneeze(3) (wait 5 seconds) "Achoo! Achoo! Achoo!"
Again, it may look confusing at first. You can think about it this way: The outermost function,
delay in this case, behaves like it is being called right when you add the decorator. As soon as the interpreter reads
@delay(5), it runs the delay function and replaces the
@delay decorator with the modified returned decorator. At run-time, when we call
sneeze, it looks like
sneeze is wrapped in
delay_decorator with
seconds = 5. Thus, the actual function that gets called is
inner, which is
sneeze wrapped in a 5 second sleeping function. Still confused? Me too, a bit. Maybe just sleep on it and come back.
Stacking Decorators
I'd like to move to something easier, in the hopes that you continue processing the previous section in the background and by the end of this, it will magically make sense. We'll see how that works out. Let's talk about stacking. I can pretty much just show you. You'll get the gist.
def pop(func): def inner(*args, **kwargs): print("Pop!") return func(*args, **kwargs) return inner def lock(func): def inner(*args, **kwargs): print("Lock!") return func(*args, **kwargs) return inner @pop @lock def drop(it): print("Drop it!") return it[:-2] >>> drop("This example is obnoxious, isn't it") Pop! Lock! Drop it "This example is obnoxious, isn't "
As you can see, you can wrap a function that is already wrapped. In math (and, actually, in programming), they would call this Function Composition. Just as
f o g(x) == f(g(x)), stacking
@pop on
@lock on
drop produces pop(lock(drop(it))). Huey would be so proud.
Class-Based Decorators...
...With No Arguments
A decorator can actually be created out of anything that is callable, i.e. anything that provides the
__call__ magic method. Usually, I try to come up with my own examples, but the one that I found here illustrated what was happening so darn well, I'm going to poach it with minimal modification.
class MySuperCoolDecorator: def __init__(self, func): print("Initializing decorator class") self.func = func func() def __call__(self): print("Calling decorator call method") self.func() @MySuperCoolDecorator def simple_function(): print("Inside the simple function") print("Decoration complete!") simple_function()
Which outputs:
Initializing decorator class Inside the simple function Decoration complete! Calling decorator call method Inside the simple function
...With Arguments
Class-based decorators make decorator arguments much easier, but they behave differently from above. I'll say it again.
WARNING: Class-based decorators behave differently depending on whether or not they have arguments.
I'm not sure why. Someone who is smarter than me should explain it. Anyways, when arguments are provided to the decorator, three things happen.
- The decorator arguments are passed to the
__init__function.
- The function itself is passed to the
__call__function.
- The
__call__function is only called once, and it is called immediately, similar to how function-based decorators work.
Here's an example I promised to sneak in. It creates a simple-ish caching decorator, similar to the built-in
@lru_cache discussed in this post, except you can pre-load it with input/output pairs.
class PreloadedCache: # This method is called as soon as the decorator is attached to a function. def __init__(self, preloads={}): """Expects a dictionary of preloaded {input: output} pairs. I know it only works for one input, but I'm keeping it simple.""" if preloads is None: self.cache = {} else: self.cache = preloads def __call__(self, func): # This method is called when a function is passed to the decorator def inner(n): if n in self.cache: return self.cache[n] else: result = func(n) self.cache[n] = result return result return inner @PreloadedCache({1: 1, 2: 1, 4: 3, 8: 21}) # First __init__, then __call__ def fibonacci(n): """Returns the nth fibonacci number""" if n in (1, 2): return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) # At runtime, the 'inner' function above will actually be called! # fibonacci(8) never actually gets called, because it's already in the cache!
Pretty cool right? I submit that this version of creating a decorator is, at least for me, the most intuitive.
Bonus!
A bonus is that in Python, since functions are objects, you can add attributes to them. Thus, if you modify the
__call__ method above to add the following:
def __call__(self, func): # ... Everything except the last line inner.cache = self.cache # Attach a reference to the cache!!! return inner >>> fibonacci(10) 55 >>> fibonacci.cache {1: 1, 2: 1, 4: 3, 8: 21, 3: 2, 5: 5, 6: 8, 7: 13, 9: 34, 10: 55}
Wrap Up
Anyways, I know this is a lot. This topic is one of the more confusing Python topics for me, but it can really make for a slick API if you're making a library. Just look at Flask, a web framework or Click, a CLI framework. Both written by the same team, in fact! Actually, I wrote a brief post about Click a while ago, if you're interested.
Anyways anyways, if you have any questions about decorators (or anything else for that matter), don't hesitate to ask me! I'm always happy to help (even though I usually end up doing some vigorous googling before I am able to fully answer most questions). Ditto goes for if you can explain something better than I did or have extra input. ðŸ˜
Originally posted on my blog.
Edit: Changed
@delay_function to
@delay, was incorrect before. Thanks @RadimSuckr!
Edit again: Changed
func to
self.func in initial class example. @RadimSuckr keeping me honest.
What are the least intuitive fundamentals and best practices in software development?
Some things we do kind of make sense in and of themself. Some things have evolv...
| https://dev.to/rpalo/unwrapping-decorators-part-2 | CC-MAIN-2019-43 | refinedweb | 1,296 | 57.98 |
0
Hi guys, I was wondering if this was a good place to use a goto statement? I know this will get stuck in an infinite loop eventually and I am working to fix that right now. However I wanted everyones views on whether or not this is acceptable, the goto statement I meant. If not, how else would you have done it? Also is there anyway to make this code more efficient?
#include <iostream> #include <string> #include <time.h> #include <vector> #include <algorithm> using namespace std; vector<string> words; void print_permutations(string s) { short x=0; short y=0; vector<string>::iterator result; srand(time(NULL)); no_word_found: for(short i = 0; i < s.length(); ++i){ x = rand()%s.length(); //produces a random number between 0 and the length of the string. y = rand()%s.length(); if(x != y){ //if both i and j are the same number and you xor them you lose chars. s[x] = s[x] ^ s[y]; //takes random characters from the string and XOR's them s[y] = s[y] ^ s[x]; //in order to swap characters in place without allocating memory. s[x] = s[x] ^ s[y]; } } result = find(words.begin(), words.end(), s); if(result == words.end()){//if string not in vector array execute code words.push_back(s); cout << "Permutation: " << s << endl; } else if(result != words.end()) //if the permutation is in the array it will display this message goto no_word_found; } int main() { string word; do{ cout << "\nPlease enter a word" << endl << "Original Word: "; cin >> word; print_permutations(word); }while(word != "1"); return 0; }
Thank you
Edited by Johnathon332: n/a | https://www.daniweb.com/programming/software-development/threads/416885/acceptable-to-use-goto-statement | CC-MAIN-2017-17 | refinedweb | 267 | 66.33 |
Javadocs
Javadoc is a tool that generates Java code documentation in the HTML format from Java source code. The documentation is formed from Javadoc comments that are usually placed above classes, methods, or fields. For more information on the correct format of Javadocs, style guide, terms and conventions, refer to How to Write Doc Comments for the Javadoc Tool.
Add a new comment
Add a Javadoc using automatic comments
For documentation comments, IntelliJ IDEA provides completion that is enabled by default.
Type
/**before a declaration and press Enter. The IDE auto-completes the doc comment for you.
For information on how to disable this feature, refer to Disable automatic comments.
Add a Javadoc using context actions
Place the caret at the declaration in the editor, press Alt+Enter, and select Add Javadoc from the list.
In Kotlin, the
@param and other tags are not generated because the recommended style requires incorporating the description of parameters and return values directly into the documentation comment.
Disable automatic comments
In the Settings/Preferences dialog Ctrl+Alt+S, go to , and clear the Insert documentation comment stub checkbox.
Fix a Javadoc
If a method signature has been changed, IntelliJ IDEA highlights the tag that doesn't match the method signature and suggests a quick-fix. Press Alt+Enter to apply the fix.
You can also update an existing javadoc comment in order to account for the changes in the declaration using the Fix doc comment action:
Place the caret within a class, method, function, or a field, and press Ctrl+Shift+A.
Type
fix doc commentand press Enter.
Render Javadocs
IntelliJ IDEA allows you to render Javadocs in the editor. Rendered comments are easier to read, and they don't overload your code with extra tags.
Click
in the gutter next to the necessary documentation comment (or press Ctrl+Alt+Q) to toggle the rendered view; click
to edit the comment.
Rendered Javadocs allow you to click links to go to the referenced web pages, or view quick documentation for the referenced topics.
To change the font size, right-click a Javadoc in the editor and select Adjust Font Size from the context menu. Note that the rendered comments use the same font size as the quick documentation popup.
Render Javadocs by default
You can configure the IDE to always render Javadocs in the editor.
Right-click the icon in the gutter (
or
) and enable the Render All option.
Alternatively, in the Settings/Preferences dialog Ctrl+Alt+S, select and enable the Render documentation comments option.
To edit rendered Javadocs, click the
icon in the gutter next to the comment.
Generate a Javadoc reference
IntelliJ IDEA provides a utility that enables you to generate a Javadoc reference for your project.
From the main menu, select.
In the dialog that opens, select a scope — a set of files or directories for which you want to generate the reference, and set the output directory where the generated documentation will be placed.
The Output directory is a mandatory field: you cannot generate a Javadoc file as long it is empty.
Use the slider to define the visibility level of members that will be included in the generated documentation. Select one of the following options:
Private: to include all classes and members to the reference.
Package: to include all classes and members except the private ones.
Protected: to include public and protected classes and members.
Public: to include only public classes and members.
You can specify a locale (for example
en_US.UTF-8), command line arguments, and the maximum heap size.
Click OK to generate the reference.
View Javadocs in the editor
In IntelliJ IDEA, you can view Javadocs for any symbol or method signature right from the editor. To be able to do that, configure library documentation paths or add downloaded Javadocs to the IDE. For more information, refer to Configure library documentation..
For more information, refer to Quick documentation
Troubleshoot
javadoc: error - Malformed locale name: en_US.UTF-8
Clear the Locale field. In the Other command line arguments field, add
-encoding utf8 -docencoding utf8 -charset utf8.
-encoding specifies the encoding of the source files.
-docencoding specifies the encoding of the output HTML files and
-charset is the charset specified in the HTML head section of the output files. | https://www.jetbrains.com/help/idea/working-with-code-documentation.html | CC-MAIN-2021-31 | refinedweb | 712 | 55.54 |
Previous solutions are all using HashMap or Array to record message,which is unnecessary.With few variables and three operation( * and + and XOR),we can easily solve the problem.Here is my code.
To avoid Integer Overflow,I make some reduction.
public class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; char[] sArray = s.toCharArray(); char[] tArray = t.toCharArray(); int sSum = 0; int tSum = 0; long sMul = 1; long tMul = 1; int sXOR = 0; int tXOR = 0; for(int i = 0;i<s.length();i++){ sSum += sArray[i]; sMul *= sArray[i]-'a'+1; sXOR ^= sArray[i]; tSum += tArray[i]; tMul *= tArray[i]-'a'+1; tXOR ^= tArray[i]; } return (sSum == tSum) && (sMul == tMul) &&(sXOR == tXOR); } }
Perhaps it's not straight-forward,let me make some explaination.
Assume we have two Strings:"ab" and "cd"
Firstly I figure out:
sSum = a+b,tSum = c+d sMul = a*b,tMul = c*d
if sSum equals tSum ,and sMul equals tMul,we get the equations:
a+b = c+d a*b = c*d
After simplification we get the equation
a*a + b*b = c*c +d*d
We can prove that once the equation is satisfied,a is either c or d,and b is either d or c.
Great appreciation for @ManuelP 's counter-examples
Of course this is wrong, just like every other similar attempt. For example, it falsely claims that "ppppppphx" is an anagram of "ppppppppp".
@ManuelP
Not wrong.Just the product of all the chars causes Integer overflow(see the sMul and tMul variables are type of int).It can be solved by occasionally reducing the product,but it's somewhat awkward.
@sse.michael
sum is the sum of the char array,mul is the product of the char array.Is that clear to you?
@Horanol No, it is wrong. I already gave you a counter-example proving that it's wrong.
And no, you can't fix it like you think you can. Try it, show the code, and I'll give you a counter-example for that as well.
Actually you unsurprisingly already fail even without overflow, for example your code falsely claims "bln" is an anagram of "cip".
@ManuelP
Well,you're right,just addition and multiplication cannot guarantee the result.Previously I also included XOR operation in my code,but it seemed redundant to pass test cases of Leetcode,so I just gave it up.But it seems essential to pass your test. So now I've changed my code.Great appreciation for your counter-examples.
Now you for example falsely claim that "aanr" is an anagram of "abkt".
Wondering how long it'll take you to accept that this kind of approach is fundamentally wrong :-)
@ManuelP
I've changed the type from int to float to avoid the truncation of Integer when reducing the product and passed your test.
Of cause I cannot perfectly prove that in math,but by intuition I think it's right :)
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect. | https://discuss.leetcode.com/topic/58622/5ms-solution-in-java-using-arithmetic-operation-o-1-space-o-n-time | CC-MAIN-2018-05 | refinedweb | 514 | 65.12 |
Whether you like it or not, but there are many situations when you need to add logging information. It is easy to start with some print statements, but what if at certain point you want to put this information to a file? Redirecting output to a file will result in all-or-nothing situation since the contents of the file will be only visible at the end of execution. A more flexible and proper solution would be using a proper logging module.
To start off with
import logging LOG_FORMAT = '%(asctime)s [%(levelname)s] %(message)s' logging.basicConfig(format = LOG_FORMAT, level=logging.DEBUG) log = logging.getLogger(__name__)
And then instead of a print statement you can use the following statements:
log.debug('debug string') log.info('info string') log.error('error string')
which will result in
2014-03-01 20:27:19,314 [DEBUG] debug message 2014-03-01 20:27:32,900 [INFO] info string 2014-03-01 20:28:19,472 [ERROR] error string
Enjoy! | http://blog.bidiuk.com/2014/03/adding-basic-logging-to-your-python-script/ | CC-MAIN-2021-31 | refinedweb | 166 | 59.09 |
, Oct 29, 2008 at 10:31 PM, Paul Melis
<pyplusplus@...> wrote:
> Roman Yakovenko wrote:
>>>> Why do you want to exclude such declarations:
>>>> * to get "clean" build - without warnings. If so, in this specific
>>>> case you can decide that you trust Py++ and suppress the warning.
>>>> * other reasons - please explain.
>>>>
>>>>
>>> The reason is quite practical. Up till now I have not been able to even
>>> compile my generated wrappers because of W1005 warnings.
>>> I simply want to get some version of my wrappers working that I can get
>>> started with. From there I can work on replacing/handling the issues w.r.t.
>>> use of non-public classes.
>>>
>>
>> It sounds like a bug. Can you send me simple test case. I would like
>> to improve the situation.
>>
>
> After some digging it seems to be caused by the following pattern:
> - the code I'm wrapping uses its own smart pointer class, say smart_ptr<T>
> - the code contains a class, say C, with a protected inner class, say I
> - the smart_ptr class has one or more methods that either return or use
> a pointer to C::I
>
> In the gccxml I see lines <Class ...,
> which probably make Py++ generate wrappers for the smart_ptr methods.
No, it doesn't help. I don't understand why Py++ still generates them.
Are the functions [pure] virtual?
Also, I suggest you to read the following link:
--
Roman Yakovenko
C++ Python language binding | https://sourceforge.net/p/pygccxml/mailman/pygccxml-development/?viewmonth=200810&viewday=30 | CC-MAIN-2017-43 | refinedweb | 235 | 75.71 |
PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
NAMEclearerr — clear indicators on a stream
SYNOPSIS
#include <stdio.h>
void clearerr(FILE *stream);
DESCRIPTIONThe functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2017 defers to the ISO C standard.
The clearerr() function shall clear the end-of-file and error indicators for the stream to which stream points.
The clearerr() function shall not change the setting of errno if stream is valid.
RETURN VALUEThe clearerr() function shall not return a value.
ERRORSNo errors are defined.
The following sections are informative.
EXAMPLESNone.
APPLICATION USAGENone.
RATIONALENone.
FUTURE DIRECTIONSNone.
SEE ALSOThe Base Definitions volume of POSIX.1‐2017, <std . | https://man.archlinux.org/man/clearerr.3p.en | CC-MAIN-2022-21 | refinedweb | 160 | 51.24 |
Deferred Processing.NET, XML, SQL and Doing Things as Time Allows Server2006-08-06T15:36:00ZGimmie My XPath/community/blogs/dan/archive/2009/06/15/gimmie-my-xpath.aspx2009-06-15T18:41:00Z2009-06-15T18:41:00Z<p>I've posted a screencast on using XPath to create XLinq queries.</p> <p><a href=""></a></p> <p>Dan</p> <p> </p> <p> </p> <p> </p><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan and Memory/community/blogs/dan/archive/2009/02/18/perfmon-and-memory.aspx2009-02-18T14:28:00Z2009-02-18T14:28:00Z<p>I've posted a short screencast that shows what Perfmon is keeping track of, when it tracks virtual memory usage.</p> <p>It's at</p> <p><span style="font-size:11pt;color:#1f497d;font-family:'Calibri','sans-serif';"><a target="_blank" href=""><span style="color:#0000ff;"></span></a></span></p> <p><span style="font-size:11pt;color:#1f497d;font-family:'Calibri','sans-serif';"></span></p> <p> </p> <p> </p><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan Studio & XSLT Debugging/community/blogs/dan/archive/2008/11/10/visual-studio-amp-xslt-debugging.aspx2008-11-10T14:37:00Z2008-11-10T14:37:00Z<p>Visual Studio has a lot of features for working with XSLT. I've put together a short tutorial [1] on some of the XSLT debugging features in Visual Studio.</p> <p>Dan</p> <p>[1] <a href=""></a></p> <p> </p> <p> </p><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan At Work Part II/community/blogs/dan/archive/2007/03/12/46428.aspx2007-03-12T14:36:00Z2007-03-12T14:36:00Z<P>The next article in my series on PowerShell and SMO, <A href="">PowerSMO At Work Part II</A> is up on <A href="">Simple-Talk.com</A> now.</P> <P>Dan</P> <P> </P> <P> </P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan articles/community/blogs/dan/archive/2007/02/19/46147.aspx2007-02-19T11:22:00Z2007-02-19T11:22:00Z<P>I'm working on a series of articles on PowerSMO, my combination of PowerShell and SMO, for <A href=""></A>. The first few are on the site now.</P> <P>Some of the topics in these articles are covered in the <A href="">Applied SQL Server 2005</A> course.</P> <P>Dan</P> <P> </P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan XML with PowerShell II/community/blogs/dan/archive/2006/11/28/43561.aspx2006-11-28T18:12:00Z2006-11-28T18:12:00Z<P>In our previous blog article <A href=""><I>Processing XML with PowerShell</I></A>.</P> <P <A href=""></A>. Note that this will include the XSLT.ps1 script, updated for the xitems function, that was include in the ProcessingXMLPowerShell.zip file.</P> <P>We will start by looking at a file named Stock.xml. The Stock.xml file looks like:</P><PRE><CODE>> </CODE></PRE> <P.</P><PRE><CODE>PS C:\Demos> [xml]$s = get-content C:\Demos\Stock.xml PS C:\Demos> $s.GroceryList.Stock | %{$_.Dept.Name} | select-object -unique Produce Meat PS C:\Demos> </CODE></PRE> <P. </P> <P>It’s easy to come up with a rather wordy description of what this script is doing; It is saying something like <SPAN id=hierarchy>.”</SPAN> This sort of description could be applied to almost anything that manages hierarchical data including XPath, which we will be looking at later when we examine the xitems function.</P> <P>Thinking of this hierarchical description makes it seem that the script below would be alternate, more simple, way to find the names of the departments.</P><PRE><CODE>PS C:\Demos> [xml]$s = get-content C:\Demos\Stock.xml PS C:\Demos> $s.GroceryList.Stock.Dept.Name | select-object -unique PS C:\Demos> </CODE></PRE> <P>This, seemingly obvious, way of getting the children of the children, <I>etc.</I> did not produce any results. The dotted syntax is somewhat limited because of the way PowerShell models XML. If we take closer look at what is actually being returned for the GroceryList and Stock elements we will see why.</P><PRE><CODE> </CODE></PRE> <P.</P><PRE><CODE> </CODE></PRE> <P>It turns out that the Stock array is an array of XmlElements and piping it into a pipeline segment enumerates that array. The result is that inside the pipeline segment $_ is an XmlElement that has a Dept child element.</P> <P>So to drill into an XML hierarchy using the PowerShell object model you must break up what seems like a natural dotted syntax into pipeline segments, one pipeline segment for every two levels of depth you want to go into the XML hierarchy. The <A href="">word description</A> earlier of what is happening here, however, is in effect the definition of an XPath construct called a LocationPath.</P> <P>We used XPath expressions in <A href=""><I>Processing XML with PowerShell</I></A>.</P> <P>A node set is what the name seems to imply, it is a set of XML nodes. It might be a set of XML elements or attributes or a mixture of these an other kinds of XML nodes. The data model in the <A href="">XPath Recommendation</A> defines seven kinds of nodes that might be found in an XML documents. A <A href="">LocationPath</A>:</P><PRE><CODE>GroceryList/Stock/Dept/Name </CODE></PRE> <P>We can use this LocationPath with the xitems function to find the names of the departments in the stock.xml file, as we did at the beginning of this article.</P><PRE><CODE>PS C:\Demos> xitems C:\Demos\Stock.xml "GroceryList/Stock/Dept/Name" | select-object -property value -unique Value ----- Produce Meat PS C:\Demos> </CODE></PRE> <P. </P> <P>In the <A href=""><I>Processing XML with PowerShell</I></A>>This file uses quite a few namespaces, just to make things interesting and because typically when namespaces are used they are often used a lot. Lets do our department names calculation again, using the PowerShell xml object model.</P><PRE><CODE>PS C:\Demos> [xml]$s = get-content C:\Demos\StockNS.xml PS C:\Demos> $s.grocerylist.stock | %{$_.Item("Dept", "urn:identity").Name} | select-object -unique Produce Meat PS C:\Demos> </CODE></PRE> <P>Here we have used the Item property that PowerShell adds to an XML element to make it possible to access elements that are distinguished by their namespace. Here is a script that uses xitems to get the same results:</P><PRE><CODE>PS C:\Demos> xitems C:\Demos\StockNS.xml ` "p:GroceryList/i:Stock/id:Dept/i:Name" ` @{<I>Processing XML with PowerShell</I></A> we know that xeval can also process an XPathNavigator, so the output of the xitems function can also be passed into the xeval function. Let’s try that:</P><PRE><CODE>PS C:\Demos> xitems C:\Demos\Stock.xml "GroceryList/Stock" | %{xeval $_ "string(Dept/Name)"} | Select-Object -unique Produce Meat PS C:\Demos> </CODE></PRE> <P.</P> <P>Lastly xitems is similar to xeval in that you can pass it an array of LocationPaths and it will apply all of them to an XML file.</P><PRE><CODE>PS C:\Demos> xitems C:\Demos\Stock.xml "GroceryList/Stock/Dept/Area", "GroceryList/Stock/Dept/Name" | Group-object -property value Count Name Group ----- ---- ----- 1 Round {Area} 2 Produce {Name, Name} 1 Beef {Area} 1 Meat {Name} 1 Leaf {Area} PS C:\Demos> </CODE></PRE> <P>This may seem a strange query, but it does show us, for example, that there are two Stock elements that have Name children whose value is “Produce”.</P> <P>So far we have seen the basics of using the xitems function and that it shares much in common with xeval. Let’s now take a look at the implementation of xitems.</P> <P>First of all xitems is an alias for get-XSLT_XPathSelection. As the names implies this function is making an XPath selection.</P><PRE><CODE; } </CODE></PRE> <P>The xitems function starts off the same as the xeval function that we looked at in the <A href=""><I>Processing XML with PowerShell</I></A>.</P> .</P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan XML with PowerShell/community/blogs/dan/archive/2006/11/25/42506.aspx2006-11-25T16:25:00Z2006-11-25T16:25:00Z<P.</P> <P.</P> <P</P><PRE><CODE>> </CODE></PRE> <P>We can calculate the total of all of groceries using the PowerShell object model of XML with the following script;</P><PRE><CODE>PS C:\Demos> [xml]$list = get-content .\groceries.xml PS C:\Demos> $list.GroceryList.Item | &{begin {$sum=0} process{$sum += $_.Price} end {$sum}} 29.15 PS C:\Demos> </CODE></PRE> <P>There are other ways to do this in PowerShell, but all involve iterating through the items to produce a sum. It turns out there is a simple XPath expression that calculates sum of the prices of the items in the list:</P><PRE><CODE>sum(GroceryList/Item/Price) </CODE></PRE> <P>In fact it would be kind of nice if we had a way to “execute” and XPath expression easily in PowerShell. How about this?</P><PRE><CODE>PS C:\Demos> xeval groceries.xml "sum(GroceryList/Item/Price)" 29.15 PS C:\Demos> </CODE></PRE> <P.</P> <P>A script to build these functions and their associated aliases is in a file named XSLT.ps1. This file and the examples in this blog article are available at <A href=""><.</P> <P>The XSLT.ps1 file actually has some other extension functions that are not discussed in this blog article but will be in a future one. </P> <P <A href=""></A>.</P> <P>The XPath recommendation is certainly worth reading and contains many example of XPath expressions. Another good source to have at your side is “Essential XML Quick Reference” published by Addison-Wesley and written by Aaron Skonnard and Martin Gudgen. </P> <P.</P><PRE><CODE>PS C:\Demos> [xml]$list = get-content groceriesuc.xml Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "Root element is missing." At line:1 char:11 + [xml]$list <<<< = get-content GroceriesUC.xml PS C:\Demos> </CODE></PRE> <P>Hmmmm, that generated an error. What’s going on here?</P> <P.</P><PRE><CODE> </CODE></PRE> <P.</P><PRE><CODE>PS C:\Demos> [xml]$list = get-content GroceriesUC.xml -encoding BigEndianUnicode PS C:\Demos> $list.GroceryList.Item | &{begin {$sum=0} process{$sum += $_.Price} end {$sum}} 29.15 PS C:\Demos> </CODE></PRE> <P.</P><PRE><CODE>PS C:\Demos> xeval GroceriesUC.xml "sum(GroceryList/Item/Price)" 29.15 PS C:\Demos> </CODE></PRE> <P>It works just fine and we don’t have to tell it what the encoding is. The reason for this is a requirement of every XML processor, <I>i.e.</I>! </P> <P <I>Extensible Markup Language XML</I> recommendation at <A href=""></A>.</P> <P>There is another issue that comes up when you deal with XML, namespaces. There are some who feel that namespaces are an unnecessary complication to XML, but they are important enough to have their own specification, <I>Namespaces in XML</I> which is at <A href=""></A>. For those with an interest in such things the <I>Extensible Markup Language XML</I> is really just a grammar with a little over 80 productions with lots of comments in it, and <I>Namespaces in XML</I> just adds a few productions to that grammar. Regardless of how you feel about namespaces you will have to deal with them. Here is a different version of our grocery list. It is in the file named GroceriesNS.xml.</P><PRE><CODE>> </CODE></PRE> <P. </P><PRE><CODE>PS C:\Demos> $list = get-content GroceriesNS.xml PS C:\Demos> $list.GroceryList.Stock | &{begin {$sum=0} process{$sum += $_.Price[1]} end {$sum}} 30.15 PS C:\Demos> </CODE></PRE> <P.</P> <P.</P> <P>In any case the Item property allows us to specify both the name and the namespace of the element we want.</P><PRE><CODE>PS C:\Demos> $list = get-content GroceriesNS.xml PS C:\Demos> $list.GroceryList.Stock | %{$_.Item("Price", "urn:retail")} | &{begin {$sum = 0} process {$sum += $_.get_InnerText()} end {$sum}} 29.15 PS C:\Demos> </CODE></PRE> <P>Now we get the 29.15 just as we did when we processed the Groceries.xml file.</P> <P>Now let’s do the same thing using xeval function.</P><PRE><CODE>PS C:\Demos> xeval GroceriesNS.xml "sum(a:GroceryList/a:Stock/r:Price)" @{</div><img src="" width="1" height="1">dan-sullivan PowerSMO! I/community/blogs/dan/archive/2006/11/08/41964.aspx2006-11-09T01:33:00Z2006-11-09T01:33:00Z<P.</P> <P>This blog article assumes you have some familiarity with PowerSMO!, SQL Server, and PowerShell. The purpose of this blog article is to show how to make use of PowerSMO! to do some typical database operations.</P> <P>We start by making a database.</P><PRE><CODE>PS C:\demos> $server = SMO_Server PS C:\demos> $testdb = SMO_Database $server "TestDB_1" PS C:\demos> $testdb.DatabaseOptions.dan@pluralsight.com</A></P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan<P>Last year I wrote a blog article about using what was then called MSH with SQL Server Management Objects <A href=""></A>. MSH is now called PowerShell and mixing some SMO with it makes PowerSMO!</P> <P!.</P> <P>This article assumes you are reasonably familiar with SQL Server and have some familiarity with PowerShell. You can look at some of the previous articles I have blogged about PowerShell to get familiar with PowerShell. </P> <P>There are a number of reasons for using PowerSMO! You can script the management, testing, status, <I>etc.</I> of database objects. PowerSMO! also has pedagogical value too. I’ve been using PowerShell + SMO in the classes I teach because it provides such a quick way too cobble up <I>ad hoc</I> examples. It’s useful in development for the same reason, you can quickly try something out before you commit the time to edit/compile/test a C# program.</P> <P>To use PowerSMO! you need to start up PowerShell then run the InitPowerSMO.ps1 script. This script is available at <A href=""></A>.</P><PRE><CODE>Windows PowerShell Copyright (C) 2006 Microsoft Corporation. All rights reserved. PS C:\demos> . "C:\demos\InitPowerSMO.ps1" PS C:\demos> </CODE></PRE> <P>This script loads the SMO assemblies into PowerShell and a number of other things that we will look at later.</P> <P>Let’s start with some basics. The <CODE>new-object</CODE> cmd-let is used to make an instance of a .NET class. SMO has a class named <CODE>ManagedComputer</CODE>. An instance of <CODE>ManagedComputer</CODE> represents the root of one of the object models in SMO, the one that is used to manage the services provided by SQL Server, such as the database engine or full-text search. BTW, watch out for the line-wraps in the examples that follow.</P><PRE><CODE>PS C:\demos> $mc = new-object "Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer" PS C:\demos> $mc.services | %{$_.name} MSFTESQL MSSQLSERVER SQLBrowser SQLSERVERAGENT PS C:\demos> </CODE></PRE> <P>Here we used an instance of the <CODE>ManagedComputer</CODE> class find the SQL Server services on the local computer. We piped these services to a script that prints out the name of the service. Looks like a pretty typical SQL Server installation.</P> <P>This is handy but, as you can see, it is a bit tedious dealing with the full name of the class that <CODE>new-object</CODE> requires. PowerShell deals with this issue in a number of places by using what it calls a “type accelerator” or “type alias”. </P> <P>For example <CODE>[wmi]</CODE> is a type accelerator for <CODE>System.Management.ManagementObject</CODE> and you can use it instead of the fully spelled out class name when you need to specify that type. Unfortunately there is no provision in PowerShell for creating your own type aliases. PowerShell supports user defined aliases for cmdlets, functions, <I>etc.</I> but these are not useful as type accelerators.</P> <P>To save on typing PowerSMO! creates helper functions that can be used to create instances of the classes used by SMO. One of the reasons you see a delay when you run the <CODE>initPowerSMO.ps1</CODE> script is that it has to create all these functions. Below is a script that uses one of these functions and duplicates the operation of the previous example.</P><PRE><CODE>PS C:\demos> $mc = Get-SMO_ManagedComputer PS C:\demos> $mc.Services | %{$_.name} MSFTESQL MSSQLSERVER SQLBrowser SQLSERVERAGENT PS C:\demos> </CODE></PRE> <P>All of these helper functions have a preface of “Get-SMO_” followed by the name of the class that they create.</P> <P>All that the <CODE>Get-SMO_</CODE> helper functions and new-object are doing is running the constructor for the class requested. In the previous two samples we used the parameter-less constructor to make a <CODE>ManagedComputer</CODE> object. When you do this the managed computer is the one PowerShell is running on.</P> <P>One of the nice things about PowerShell is that you can always ask what kinds of things an object can do by piping it to the <CODE>get-member</CODE> cmdlet. For example:</P> <P>PS C:\demos> $mc | get-member</P><PRE><CODE> TypeName: Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer Name MemberType Definition ---- ---------- ---------- Equals Method System.Boolean Equals(Object obj) GetHashCode Method System.Int32 GetHashCode() GetSmoObject Method Microsoft.SqlServer.Management.Smo.Wmi.Wmi... ... </CODE></PRE> <P. </P><PRE><CODE> </CODE></PRE> <P>The <CODE>Get-SMO_ctors</CODE> function lists the constructors for the type passed, in parentheses to it. For every <CODE>Get-SMO_</CODE> function there is a <CODE>Get-SMOT_</CODE> that returns its type definition. The <CODE>Get-SMO_ctors</CODE> function requires a type definition, not the function that makes an instance of the type. Actually the <CODE>Get-SMO_ctors</CODE> function will work for any .NET type definition.</P><PRE><CODE> </CODE></PRE> <P>The example above shows using the <CODE>Get-SMO_ctors</CODE> function to find the various constructors for System.String class from .NET.</P> <P>All of the <CODE>Get-SMO_</CODE> function will accept parameters for a constructor. You pass the parameters on the command line as you would for any other PowerShell function.</P><PRE><CODE>PS C:\demos> $mc = Get-SMO_ManagedComputer "PARSEC5" PS C:\demos> </CODE></PRE> <P>In the example above <CODE>$mc</CODE> is attached to a computer name “PARSEC5”. </P> <P>Some constructors you will want to use require multiple parameters. The ServerConnection class serves a purpose similar to that for a SqlConnection in ADO.NET</P><PRE><CODE> </CODE></PRE> <P>Here you can see that there is a constructor that lets you can create a <CODE>ServerConnection</CODE> using a SQL login. It needs the name and password for that login.</P><PRE><CODE>PS C:\demos> $sc = Get-SMO_ServerConnection "PARSEC5" "ambler" "Ambler" PS C:\demos> $sc.ConnectionStringhammer</line></order>" </CODE></PRE> <P>We are going to look at a different way to load XML into an [xml] variable. </P><PRE><CODE>PS C:\demos> $xmldata = new-object "System.Xml.XmlDocument" PS C:\demos> $xmldata.LoadXml("<order><line price='100' qty='3'>hammer</line></order>") PS C:\demos> </CODE></PRE> <P.</P> <P>You can get back the XML in text form by using the get_InnerXml() method.</P><PRE><CODE>PS C:\demos> $xmldata.get_InnerXml() <order><line price="100" qty="3">hammer</line></order> PS C:\demos> </CODE></PRE> <P>If you were programming in C# you would use the InnerXml property of the <CODE>$xmldata</CODE>#.</P> <P>The root of an XML document is called the DocumentElement and for our document the name the root element is “order”. You can get a reference to it through the DocumentElement property and use its Name property to find its name.</P><PRE><CODE>PS C:\demos> $xmldata.get_DocumentElement().get_Name() order PS C:\demos> </CODE></PRE> <P>Here we used the get_DocumentElement method to get the DocumentElement and the get_Name method to get its name.</P> <P>You can modify an XmlDocument by adding or removing XML nodes. A node is part of XML, for example an element is a node as is an attribute. Let’s add another line to our order.</P><PRE><CODE> </CODE></PRE> <P.</P> <P>An XmlElement has a SetAttibute that is used to add attibutes to that element. We use the SetAttribute to add a “price” and “qty” attibute to the line element we created. SetAttribute is really a <I>shortcut</I> method. We could use <CODE>CreateAttribute</CODE> and <CODE>SetAttributeNode</CODE> instead, but SetAttribute is more straightforward.</P> <P.</P> <P <CODE>$d</CODE> variable.</P> <P>Last we use the get_InnerXml method of the XmlDocument see that we have in fact added a new line element to the document.</P> <P>Now that we have a document let’s do some processing of it. Each line has a <CODE>price</CODE> and <CODE>qty</CODE>. </P> <P>To start with let’s just calculate the extended prices.</P><PRE><CODE>PS C:\demos> $xmldata.order.line | %{$_.price * $_.qty} 100100100 23232323 PS C:\demos> </CODE></PRE> <P.</P> <P>Our <CODE>$xmldata</CODE> <CODE>100</CODE> repeated three times, the value of <CODE>qty</CODE> for the first line is “3”.</P> <P>We have to cast the price to a double to get what we want.</P><PRE><CODE>PS C:\demos> $xmldata.order.line | %{[double]$_.price * $_.qty} 300 92 PS C:\demos> </CODE></PRE> <P>Now we can use the sum function example from my previous blog article, <I>PowerShell and XML and SQL Server</I>, to find the value of the order.</P><PRE><CODE>PS C:\demos> function sumOrder { >> begin {$value = 0} >> process { $value += [double]$_.price * $_.qty} >> end {$value} >> } >> PS C:\demos> $xmldata.order.line | sumOrder 392 PS C:\demos> </CODE></PRE> <P>We can use the SelectNodes method of XmlDocument to get the same result. It makes use of an XPath expression which is a bit more flexible, though more complicated, than the dotted syntax that PowerShell provides for [xml] variables.</P><PRE><CODE>PS C:\demos> $xmldata.SelectNodes("//line") | sumOrder 392 PS C:\demos> </CODE></PRE> <P.</P> <P>One of the nice things about using XPath is that you can bury a lot of selection logic right into the XPath expression. What if we want to know the value of only the <I>expensive</I> items in our order? Our definition of expensive is when the price is more than 99.</P><PRE><CODE>PS C:\demos> $xmldata.SelectNodes("//line[@price>99]") | sumOrder 300 PS C:\demos> </CODE></PRE> <P>Here our XPath expression has a predicate, “[@price>99]”, that filters out any lines whose value is 99 or less. The following is the equivalent using the XML capabilities built into PowerShell.</P><PRE><CODE>PS C:\demos> $xmldata.order.line | ?{[double]$_.price -gt 99} | sumOrder 300 PS C:\demos> </CODE></PRE> <P>Notice that in this case it was important to cast the price as a [double] otherwise PowerShell would have taken the filter to check to see if the price lexically sorted after the string “99”.</P> <P. </P> <P>You have to be careful reading XML. For example below is an XML file that is encoded as big endian UTF-16. You can’t see the actual encoding on this page but you can download this test file from <A href=""></A> if you want to try it out.</P><PRE><CODE><?xml version="1.0" encoding="UTF-16BE"?> <Test/> </CODE></PRE> <P>The get-content command is a way to read the content of a file. For example you might try to read the sample file into a builtin [xml] datatype in PowerShell like this:</P><PRE><CODE>PS C:\demos> [xml]$x = get-content "c:\demos\testdocs\test.xml" Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "Root element is missing." At line:1 char:8 + [xml]$x <<<< = get-content "c:\demos\testdocs\test.xml" PS C:\demos> </CODE></PRE> <P>What PowerShell is doing here is reading in test.xml as string, then assigning that string to then <CODE>$x</CODE>.</P><PRE><CODE>PS C:\demos> get-content "c:\demos\testdocs\test.xml" -encoding Unknown ?????????????????????????????????????????????????????? PS C:\demos> </CODE></PRE> <P>However I happen to know the encoding for the file, as I said it big endian UTF-16, so I can do this:</P><PRE><CODE>PS C:\demos> [xml]$x = get-content "c:\demos\testdocs\test.xml" -encoding BigEndianUnicode PS C:\demos> $x.get_InnerXml() <?xml version="1.0" encoding="UTF-16BE"?><Test /> PS C:\demos> </CODE></PRE> <P>Now we are able to read our big endian UTF-16 file. But this defeats one of the most important features of XML; You can read an XML file without knowing the encoding.</P> <P>Fortunately because PowerShell supports all of the .NET framework we can get around this problem and read any XML file that the underlying .NET Framework can handle without knowing its encoding.</P><PRE><CODE>PS C:\demos> $doc = new-object "System.Xml.XmlDocument" PS C:\demos> $doc.Load($filePath) PS C:\demos> $doc.get_InnerXml() <?xml version="1.0" encoding="UTF-16BE"?><Test /> PS C:\demos> </CODE></PRE> <P>Here we initialize <CODE>$doc</CODE>.</P> <P>Now that we can read XML lets process some XML files. Microsoft Word 2003 can be saved as XML. We have a few files that have been saved this way.</P><PRE><CODE> </CODE></PRE> <P>Actually some of the files in this directory are not Office documents, so we need a way to distinguish them. All Office XML files have on thing in common, they start with something called a processing instruction that looks like:</P><PRE><CODE><?mso-application</A>. Also these test documents can be found at <A href=""></A>. </P> .</P> <P>Another thing about Word documents that we haven’t you looked at is that they make heavy use of XML namespaces. So before we try anything with a complete Word document let’s look at simple document that has namespaces in it.</P><PRE><CODE> </CODE></PRE> <P>This document is a mini-Word document with all the things we don’t care about stripped out of it.</P> .</P><PRE><CODE>PS C:\demos> $ PS C:\demos> </CODE></PRE> <P.</P><PRE><CODE> </CODE></PRE> <P>Here we start off with a new XML document, <CODE>$x2</CODE> that contains just a wordDocument. We use an <CODE>if</CODE> construct to test the <CODE>$x2</CODE> to see if it contains CustomDocumentProperties element. If if it does not we create on and add it. Then we check to make sure the element was added.</P> <P>This will be a useful for what we do next so let’s save it as a function.</P><PRE><CODE) } } </CODE></PRE> <P>Note that the addCustomProps function always returns a CustomDocumentProperties.</P> <P>Now we have everthing we need to modify a Word document by adding a custom property to it.</P><PRE><CODE) </CODE></PRE> <P>We start off by setting the <CODE>$filePath</CODE> variable to the path of a Word document. Next we load that Word document into the <CODE>$doc</CODE> variable.</P> <P>We use the <CODE>$doc</CODE> variable to create a PowerShell element, and fill it out with the current time. We also add a <CODE>dt</CODE> attribute to specify that this is a string property and put the PowerShell element in the “urn:schemas-microsoft.com:office:office” namespace. Both of these are required for a custom property added to a Word document.</P> <P>Finally we pass the <CODE>$doc</CODE> property through a pipeline our addCustomProps function. This function always returns the CustomDocumentProperty element so we can use the next segment of the pipeline to append our PowerShell property to it.</P> <P>If you now open the “test document 1.xml” file in Word and navigate to its custom properties you will see that is now has a PowerShell property.</P> <P>So we can use the full set of features available from the System.Xml namespace in .NET. The key to really making use of the is to become familiar with XPath. We really have just scratched the surface of its capabilities.</P> <P>Dan</P> <P><A href="mailto:dan@pluralsight.com">dan@pluralsight.com</A></P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan and ADO.NET/community/blogs/dan/archive/2006/10/29/41389.aspx2006-10-29T18:48:00Z2006-10-29T18:48:00Z <I>ad hoc</I>.</P> <P>Actually it’s pretty common to take the “work on the data locally” approach in C# applications. These applications use ADO.NET to build a DataSet in the application, then data bind, or add a little procedural programming or otherwise poke at it. But writing, compiling and running an <I>ad hoc</I> application each time you want to make a little change isn’t really practical. What does make this technique practical though is <B>PowerShell</B>.</P> <P>In this article we’re going to look at the basics of using ADO.NET inside of PowerShell. This article assumes you know the basics of using ADO.NET in C#.</P> .</P> <P>First of all we will need a query that returns all the data from the Customers table.</P><PRE><CODE>$dan@pluralsight.com</A></P> <P>PS Thanks to Jeffery Stover for pointing out the column properties on DataTables.</P><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan and XML and SQL Server/community/blogs/dan/archive/2006/10/28/41337.aspx2006-10-28T18:16:00Z2006-10-28T18:16:00Z<P>PowerShell offers support for XML data directly though its [xml] datatype and this article is going to look at that.</P> <P>First of all to make use of the builtin [xml] datatype just prefix a variable name with [xml] when you assign something to it.</P><PRE><CODE>PS C:\demos> [xml]$> </CODE></PRE> <P>At first glance this appears to be an ordinary assignment of a string to a variable. But it is doing more than that, it is checking the string to make sure that it is well-formed XML, <I>i.e.</I> text that conforms to the XML specification. For example the following will produce an error</P><PRE><CODE>PS C:\demos> [xml]$</div><img src="" width="1" height="1">dan-sullivan XML in SQL Server 2005/community/blogs/dan/archive/2006/09/01/36829.aspx2006-09-01T11:37:00Z2006-09-01T11:37:00Z<H1>Comparing XML in SQL Server 2005</H1> <P>Xml is not text so a literal compare of two xml documents may lead to a false negative, that is it may indicate that two documents are not equal when in fact they are. For example these two xml documents are the same: </P><PRE> <item x="1" y="2"/> <item y="2" x="1"/> </PRE> <P>because the order of attributes in xml is not signicant. SQL Server has not "built in" way to compare xml documents and in fact makes a point about the fact that it cannot compare xml documents. This is not a deficiency of SQL Server, it is just due to the fact that xml may not be treated as ordinary text. </P> <P>You can try to compare to xml documents by converting them to a string or a varbinary type, but this will lead to false negatives. For example: </P><PRE> DECLARE @x1 xml DECLARE @x2 xml set @abc</a:Simple >'<BR>RETURN @t<BR>END</P> <P>It's basically inserting a lot of ignorable space into the the xml. A fragment of the xml it generates looks like:</P> <P><a:Simple ></P> <P>Actually it has a lot more spaces than that. To try this next you should drop all the tables and recreate them, then use the batch that fill the tables, but change the source of the xml to dbo.XmlTestData1(). After you run that batch that finds the sizes you see something like:</P> <P>table name type_description used pages<BR>XmlBinSizeTest IN_ROW_DATA 2<BR>XmlBinSizeTest LOB_DATA 252<BR>XmlTextSizeTest IN_ROW_DATA 2<BR>XmlTextSizeTest LOB_DATA 252<BR>XmlSchemaSizeTest IN_ROW_DATA 3<BR>XmlSchemaSizeTest LOB_DATA 0<BR>XmlSizeTest IN_ROW_DATA 3<BR>XmlSizeTest LOB_DATA 0</P> <P><BR>It looks like saving this xml as text or binary takes up about two orders of magnitude more space than just saving it as xml!</P> <P>When SQL Server saves xml it need not save it as literal text, and it doen't. It doesn't have to save the the "pointies" and it doesn't have to save whitespace that doesn't matter. And most of the the time the whitespace between consecutive opening tags doesn't matter. In other words SQL Server 2005 goes out of its way to efficiently store xml.</P> <P>So it not a slam dunk to figure out which way of storing xml takes up the least amount of space. The point here isn't that xml will always take about the same or less as a corresponding VARCHAR(MAX), because sometimes the VARCHAR(MAX) or VARBINARY(MAX) will take up less space. But you will probably find that the difference isn't as great as you might suspect. In any case this is a database we are talking about, you should store xml as xml.</P> <P><BR>Dan</P> <P> </P> <P> </P> <P> </P> <P><BR> <BR></P></a:Simple ><div style="clear:both;"></div><img src="" width="1" height="1">dan-sullivan | http://www.pluralsight.com/community/blogs/dan/atom.aspx | crawl-002 | refinedweb | 5,753 | 58.18 |
This article is about getting controls found in Windows Vista to make use of the new Windows Vista user interface. Included in the project are some components (
Commandlinks,
ImageButton,
SplitButton) that work just like the Windows Vista themed controls.
The article would aim to achieve most of the interface effects (like the fade-in/out) effects seen throughout Windows Vista.
Most users of Windows Vista would probably notice the new user interface. Each control is a step nicer compared to that of Windows XP, and it comes complete with nice little fade effects. However, Microsoft Visual Studio does not support the full Vista themes by default. Although Visual Studio 2005 attempts to address the visual styles problem, it still does not allow controls to achieve all the visual effects seen throughout Windows Vista.
This article covers on:
Buttons,
Checkboxes,
Radiobuttons,
Textboxes,
Comboboxes)
Buttons, and preserving fade-effects
Toolbars
MainMenus and
ContextMenus
CommandLinks and
SplitButtons
Progressbars
ListBoxes and
TreeViews
It utilizes the user32.dll
SendMessage() function, as well as the uxtheme.dll
setwindowtheme() function for certain controls in order to render some of the controls to the desired level.
You will need the following things to complete this tutorial:
Some other useful things (optional):
Most of the controls are already ready for the Windows Vista theming. I'm sure you have heard of
EnableVisualStyles() right?
EnableVisualStyles() is usually called to allow theme-aware controls to gain the user interface theme. While Visual Studio 2005 already has this done, Visual Studio 2003 does not have this on by default. If you want to enable theming for common controls, you can view Heath Steward's article on Windows XP Visual Styles for Windows Forms.
EnableVisualStyles() affects the following controls:
TextBox
RichTextBox
HScrollBar
VScrollBar
ProgressBar
TabControl (Partially)
MainMenu
ContextMenu
ComboBox
DataGrid
listBox
listView
TreeView
DateTimePicker
MonthCalendar
Splitter
TrackBar
StatusBar
ToolBar
TreeView
listView
Button
Groupbox (Partially)
While Visual Studio 2005 supports Visual Theming amongst controls, these controls do not have the "full" theme, which includes the fade effects. This problem can be addressed by setting
FlatStyle to
System. However, doing this means that images would not be displayed on such controls. This problem can be addressed fairly easily in the next section.
By setting the
button's
FlatStyle to
System makes
buttons and some other images fail to display on these
buttons. But, this section aims to address this problem, by using as little code as possible.
How to get this done? Well, we need to play around with the
SendMessage() function found in user32.dll.
First, we would need to declare the function (but first, you will need to import
System.Runtime.InteropServices):
//Imports the user32.dll [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage (IntPtr hWnd, int msg, int wParam, int lParam);
To set the image of a control, we will need to use the
BM_SETIMAGE [
0x00F7] message. For now, we would use an
icon (Declared in
System.Drawing) as an image, as it is easy to get a handle on the
icon.
const int BM_SETIMAGE = 0x00F7; private Icon buttonicon; //Sets the button to use an icon void SetImage() { IntPtr iconHandle = IntPtr.Zero; // Get the icon's handle. if (this.buttonicon != null) { iconHandle = this.Icon.Handle; } //Sets the icon SendMessage(this.button1.Handle, BM_SETIMAGE, 1, (int)iconHandle); }
What this code does is to retrieve the handle of the
icon which you want to display on the button (called "
button1"), and sends a message to Windows to set the
button to use the
icon.
You can set what
icon you want by setting "
buttonicon". You can do so by using the following code:
buttonicon = new Icon(SystemIcons.Exclamation, 40, 40); SetImage();
This uses the system's exclamation
icon. What you would get:
If you would want to use a bitmap/image instead of an icon, you can use the
GetHIcon() method from the
Bitmap to retrieve the
bitmap's handle and use the handle to set the
button's image.
IntPtr iconhandle = IntPtr.Zero; Bitmap image = new Bitmap("C:\images\an_image.png"); iconhandle = image_.GetHicon(); SendMessage(this.Handle, VistaConstants.BM_SETIMAGE, 1, (int)iconhandle);
This
button still supports the fade effects other normal buttons have.
However, there is one small problem associated with using this method. If this
button's
text is set to "", no image would be displayed. This problem can be solved by using the
createParams() function and assigning the
BS_ICON theme to the
button.
//CreateParams property protected override CreateParams CreateParams { get { CreateParams cParams = base.CreateParams; if (this.ShowIconOnly == true) { //Render button without text cParams.Style |= 0x00000040; // BS_ICON value } return cParams; } }
This method is best done from a class which is inherited from
button.
CommandLinks are really just buttons, assigned with a different theme. Their themes and their values (taken from CommCtrl.h in the Windows Vista SDK) are as follows:
BS_COMMANDLINK [0x0000000E]
The first step would be to create a class inherited from
button. Then, we can override the
CreateParams() function to make the
button use the respective theme. For the theme to take effect, you would need to set the
button's
flatstyle to
system. Below is the class for the
CommandLink:
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices public class CommandLink : Button { const int BS_COMMANDLINK = 0x0000000E; //Set button's flatstyle to system public CommandLink() { this.FlatStyle = FlatStyle.System; } protected override CreateParams CreateParams { get { CreateParams cParams = base.CreateParams; //Set the button to use Commandlink styles cParams.Style |= BS_COMMANDLINK; return cParams; } } }
You can then build the project and use the component in your Windows Forms just like a normal
button (since it is inherited from a normal
button). The
CommandLink looks like:
*The mouse is over the
CommandLink, but
PrintScreen would not capture the mouse.
The
button supports the fade effects just like the actual controls.
But wait? where's the
CommandLink's "note"? Well, we can implement that feature by sending the
BCM_SETNOTE [
0x00001609] message to Windows. We can incorporate it into a property to set the note of the
CommandLink with ease.
const uint BCM_SETNOTE = 0x00001609; //Imports the user32.dll [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SendMessage (HandleRef hWnd, UInt32 Msg, IntPtr wParam, string lParam); //Note property private string note_ = ""; public string Note { get { return this.note_; } set { this.note_ = value; this.SetNote(this.note_); } } //Sets the button's note void SetNote(string NoteText) { //Sets the note SendMessage(new HandleRef(this, this.Handle), BCM_SETNOTE, IntPtr.Zero, NoteText); }
You would get:
You can also use the same method for showing icons/images on
Buttons for
CommandLinks:
Just like
CommandLinks,
SplitButtons are just simply buttons. You can set its style to that of the
SplitButton's using the
CreateParams method:
BS_SPLITBUTTON [0x0000000C]
However, even after setting the style, how are you going to associate a menu (contextmenu) to the
button? We can do this by first associating an event which would be fired whenever a person clicks on the "dropdown" on the
splitbutton. First, we would listen to all messages sent to the
button by overriding the
wndproc() method. It happens that the
BCN_SETDROPDOWNSTATE [
0x1606] message would be sent whenever the dropdown is clicked. This message is fired several times, but only one of the messages happen to be unique, with
WPARAMS having the value of "
1". The filtering of messages is best done within another class. This sample code would fire a custom event (
DropDown_Clicked) whenever the dropdown is pushed.
protected override void WndProc(ref Message m) { // Listen for operating system messages; // Filter out a lot of messages here //The dropdown glyph changes: //Mousedown (at dropdown area) => Dropdown Event fired // => Glyph changes => MouseUp => Glyph Changes switch (m.Msg) { case (VistaControls.VistaConstants.BCM_SETDROPDOWNSTATE): //PROBLEM: other buttons also have would encounter this message if (m.HWnd == this.Handle) { ////This message seems to occur when the drop down is clicked; ////Occurs several times, but one of them have the value of 1 ////in WParams if (m.WParam.ToString() == "1") { DropDown_Clicked(); } } break; } base.WndProc(ref m); }
Using this custom event, we can show a contextmenu whenever the dropdown part of the button is pressed (full code in the demo). This isn't all though. We have only assigned an event that would be fired whenever the Dropdown is pushed. We would need to make the dropdown glyph change at the right time. There are a few messages that we can use to achieve the correct painting of the glyphs. They are the
WM_PAINT [
0x0F],
WM_LBUTTONDOWN [
0x201],
WM_MOUSELEAVE [
0x2A3],
WM_LBUTTONUP [
0x202] and
WM_KILLFOCUS [
0x08] messages. We can run code whenever these messages are sent by overriding the
WndProc() message. (The code is too messy to be placed here, but the full code can be found via the Windows Vista Controls Demo.)
This control also supports the fade-effects.
Some
TextBoxes in Windows Vista hint the user what they should type in (e.g. the search box). It usually appears as some grey text on the text box that would disappear when the user attempts to type things into the
textbox. This feature is know as "cue banner". You can enable this feature on a
textbox by using the
EM_SETCUEBANNER [
0x1501] message.
SendMessage(textbox1.Handle, 0x1500 + 1, IntPtr.Zero, "Please type in something.");
The default
MainMenus (or
MainMenuStrip) and
ContextMenus (or
ContextMenuStrip) in Visual Studio 2005 do not fully support the Windows Vista theme:
If you want to get the Windows Vista theme on your main menus and context menus, you would need to use the Visual Studio 2003 version, or the backwards compatible version on Visual Studio 2005 (Called "
MainMenu" and "
ContextMenu").
You can assign
ContextMenus to controls using it's
ContextMenu property (might be hidden in VB.NET in Visual Studio 2005).
While the default
toolbars in Visual Studio 2005 do have the Windows Vista look (if the
Rendermode is set to
System), it does not have all of it. Most
toolbars on Windows Vista have the fade effects. To get it, you will need to use the Visual Studio 2003 version or the backwards compatible version on Visual Studio 2005 (and above), and set its
Appearance as
Flat to get the fade effects.
You can use
ImageLists on
toolbar
buttons as well. For
Toolbars to use the
ImageList properly in Visual Studio 2003, call the
applications.DoEvents() function after the
application.EnableVisualStyles() function (Bugfix for Application.EnableVisualStyles Bug by Don Kackman).
In Windows Vista,
progressbars come in different flavors, the most common
progressbar being the green one. However, there are also the red and yellow versions as well (there is a blue version, known as a meter, but that is inaccessible). The
progressbar colors seem to correspond to specific
progressbar states. You can set these states using the
PBM_SETSTATE [
0x40F] message. The states are
PBST_NORMAL [
0x0001],
PBST_ERROR [
0x0002] and
PBST_PAUSE [
0x0003].
SendMessage(progressbar1.Handle, 0x400 + 16, 0x0001, 0); //Normal; Green SendMessage(progressbar1.Handle, 0x400 + 16, 0x0002, 0); //Error; Red SendMessage(progressbar1.Handle, 0x400 + 16, 0x0003, 0); //Pause; Yellow
By default,
TreeViews and
ListViews do not have the same look as that of Explorer:
However, with a bit of code, you can make it look like this:
You would need to use the
SetWindowTheme() function found in the UXTheme.dll file. You can do this by using the following code:
//Imports the UXTheme DLL [DllImport("uxtheme", CharSet = CharSet.Unicode)] public extern static Int32 SetWindowTheme (IntPtr hWnd, String textSubAppName, String textSubIdList);
Then, you can set the relevant control to use the styles by using the following code:
SetWindowTheme(listView1.Handle, "explorer", null);
Where "
listView1" is your
ListView. You can do this for
TreeViews as well.
But there is more. In Windows Explorer, these
ListViews have the semi-transparent selection as well. You can do this by calling the
LVS_EX_DOUBLEBUFFER [
0x00010000] extended style.
SendMessage(listview1.Handle, 0x1000 + 54, 0x00010000, 0x00010000);
Treeviews in Windows Explorer also have the fade effects. This can be achieved via the
TVS_EX_FADEINOUTEXPANDOS [
0x0040] extended style.
SendMessage(treeview1.Handle, 0x1100 + 44, 0x0040, 0x0040);
The
treeviews also have the "auto-scroll" feature. You can enable this via the
TVS_EX_AUTOHSCROLL [
0x0020] extended style.
SendMessage(treeview1.Handle, 0x1100 + 44, 0x0020, 0x0020);
There might be several messages or functions that can be used to modify the theme of controls that may not be found in the limited documentation on Windows Vista. Of course, it is kind of unusual that we have to use older versions of controls (like
MainMenu and
ContextMenu) in order to achieve the full potential of the new Windows Vista graphical user interface.
I have not tested the above codes on Visual Studio 2003, nor have I run the application on Windows XP (I didn't make it backwards compatible "yet").
Some custom controls in the demo that may not work on legacy Windows versions are the
CommandLinks,
SplitButtons and
ProgressBars.
It was tested in Visual Studio 2005 and Windows Vista.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/vista/themedvistacontrols.aspx | crawl-002 | refinedweb | 2,139 | 65.22 |
How to sort a 2D array by a column. yes we can do this and for that we have to use the "sort" function available in the numpy library. In this if we want to sort 2D numpy array by 2nd column then we have to change the positions of all the rows based on the sorted values of the column (2nd column) with an column index for e.g 1 we can say.
import numpy as np
Sample_array = np.array([[100, 101, 500, 104], [201, 202, 203, 204], [301, 300, 600, 307]]) print("This is Sample 2D array :","\n", Sample_array)
This is Sample 2D array : [[100 101 500 104] [201 202 203 204] [301 300 600 307]]
Index = 2 Array_sort = Sample_array[Sample_array[:,Index].argsort()] print("The original array is:","\n","\n", Sample_array, "\n") print("The sorted array is:", "\n", "\n", Array_sort)
The original array is: [[100 101 500 104] [201 202 203 204] [301 300 600 307]] The sorted array is: [[201 202 203 204] [100 101 500 104] [301 300 600 307]]
Here we can see the array has been sorted according to the given Index number that we have passed in "Indexed" variable i.e 2. So we can see the 3rd column is been sorted now as before it was not. | https://www.projectpro.io/recipes/sort-2d-array-by-column-numpy | CC-MAIN-2021-39 | refinedweb | 215 | 71.07 |
Most of the complexities that requirements impose on today's software products are behavioral and functional, resulting in component implementations with complex business logic. The most common way to implement the business logic in a J2EE or J2SE application is to write Java code that realizes the requirements document's rules and logic. In most cases, this code's intricacy and complexity makes maintaining and updating the application's business logic a daunting task, even for experienced developers. And any change, however simple, incurs recompilation and redeployment costs.
A rules engine helps you resolve (or at least reduce) the issues and difficulties inherent in the development and maintenance of an application's business logic. You can think of a rules engine as a framework for implementing complex business logic. Most rules engines let you use declarative programming to express the consequences that are valid given some information or knowledge. You can concentrate on facts that are known to be true and their associated outcomes — that is, on an application's business logic.
Several rules engines are available, including commercial and open source choices. Commercial rules engines usually let you express rules in a proprietary English-like language. Others let you write rules using scripting languages such as Groovy or Python. This updated article introduces you to the Drools engine and uses a sample program to help you understand how to use Drools as part of your business logic layer in a Java application.
Drools is an open source rules engine, written in the Java language, that uses the Rete algorithm to evaluate the rules you write (see Resources). Drools lets you express your business logic rules in a declarative way. You can write rules using a non-XML native language that is quite easy to learn and understand. And you can embed Java code directly in a rules file, which makes the experience of learning Drools even more attractive. Drools also has other advantages. It is:
- Supported by an active community
- Easy to use
- Quick to execute
- Gaining popularity among Java developers
- Compliant with the Java Rule Engine API (JSR 94) (see Resources)
- Free
The current Drools version.
This article shows how to use Drools as part of the business logic layer in a sample Java application. To follow along, you should be familiar with developing and debugging Java code using the Eclipse IDE. And you should be familiar with the JUnit testing framework and know how to use it within Eclipse.
The following assumptions set the scenario for the fictitious problem the application solves:
- A company named XYZ builds two types of computer machines: Type1 and Type2. A machine's type is defined by its architecture.
- An XYZ computer can serve multiple functions. Four functions are currently defined: DDNS Server, DNS Server, Gateway, and Router.
- XYZ performs several tests on each machine before it is shipped out.
- The tests performed on each machine depend on each machine's type and functions. Currently, five tests are defined: Test1, Test2, Test3, Test4, and Test5.
- When tests are assigned to a computer, a tests due date is also assigned to the machine. Tests assigned to the computer should be conducted no later than this due date. The due date's value depends on the tests that were assigned to the machine.
- XYZ has automated much of the process for executing the tests using an internally developed software application that can determine a machine's type and functions. Then, based on these properties, the application determines which tests to execute and their due date.
- Currently, the logic that assigns the tests and tests due date to a computer is part of this application's compiled code. The component that contains this logic is written in the Java language.
- The logic for assigning tests and due dates is changed more than once a month. The developers must go through a tedious process every time they need to implement it in the Java code.
Because the company incurs high costs whenever changes are made to the logic that assigns tests and due dates to a computer, the XYZ executives have asked their software engineers to find a flexible way to "push" changes to the business rules to the production environment with minimal effort. Here's where Drools comes into play. The engineers have decided that if they use a rules engine to express the conditions for determining which tests should be performed, they can save much time and effort. They would only need to change the content of a rules file and then replace this file in the production environment. This seems simpler and less time consuming to them than changing compiled code and going through the long process mandated by the organization whenever compiled code is to be deployed in the production environment (see the sidebar When do you use a rules engine?).
Currently, these are the business rules that must be followed when assigning tests and their due dates to a machine:
- If a computer is of Type1, then only Test1, Test2, and Test5 should be conducted on it.
- If a computer is of Type2 and one of its functions is DNS Server, then Test4 and Test5 should be conducted.
- If a computer is of Type2 and one of its functions is DDNS Server, then Test2 and Test3 should be conducted.
- If a computer is of Type2 and one of its functions is Gateway, then Test3 and Test4 should be conducted.
- If a computer is of Type2 and one of its functions is Router, then Test1 and Test3 should be conducted.
- If Test1 is among the tests to be conducted on a computer, then the tests due date is three days from the machine's creation date. This rule has priority over all following rules for the tests due date.
- If Test2 is among the tests to be conducted on a computer, then the tests due date is seven days from the machine's creation date. This rule has priority over all following rules for the tests due date.
- If Test3 is among the tests to be conducted on a computer, then the tests due date is 10 days from the machine's creation date. This rule has priority over all following rules for the tests due date.
- If Test4 is among the tests to be conducted on a computer, then the tests due date is 12 days from the machine's creation date. This rule has priority over all following rules for the tests due date.
- If Test5 is among the tests to be conducted on a computer, then the tests due date is 14 days from the machine's creation date.
The current Java code that captures the preceding business rules for assigning tests and a tests due date to a machine looks similar to code in Listing 1:
Listing 1. Using if-else statements to implement business-rules logic
The code in Listing 1 isn't overly complicated, but it's not simple either. If you were to make changes to it, you'd need to be extremely careful. A bunch of entangled if-else statements are trying to capture the business logic that has been identified for the application. If you knew little or nothing about the business rules, the code's intent would not be apparent from a quick look.
Importing the sample program
A sample program that uses the Drools rules engine is provided with this article in a ZIP archive. The program uses a Drools rules file to express in a declarative way the business rules defined in the preceding section. It contains an Eclipse 3.2 Java project that was developed using the Drools plug-in and version 4.0.4 of the Drools rules engine. Follow these steps to set up the sample program:
- Download the ZIP archive (see Download).
- Download and install the Drools Eclipse plug-in (see Resources).
- In Eclipse, select the option to import Existing Projects into Workspace, as shown in Figure 1:
Figure 1. Importing the sample program into your Eclipse workspace
- Select the archive file you downloaded and import it into your workspace. You'll find a new Java project named
DroolsDemoin your workspace, as shown in Figure 2:.
Figure 2. Sample program imported into your workspace
If you have the Eclipse Build automatically option enabled, then the code
should be compiled and ready to use by now. Otherwise, build the
DroolsDemo project now.
Now you'll take a look at the code in the sample program. The core set of Java
classes for this program is in the
demo package. There
you'll find the
Machine and
Test domain object classes. An instance of the
Machine class represents a computer to which tests and
a tests due date are assigned. Take a look at the
Machine class, shown in Listing 2:
Listing 2. Instance variables for the
Machineclass
You can see in Listing 2 that among the properties for the
Machine class are:
type(represented as a
stringproperty) - Holds the type value for a machine.
functions(represented as a
list) - Holds the functions for a machine.
testsDueTime(represented as a
timestampvariable) - Holds the assigned tests due date value.
tests(a
Collectionobject) - Holds the set of assigned tests.
Note that more than one test can be assigned to a machine and that a machine can have one or more functions.
For the sake of simplicity, the creation-time value for a machine is set to the
current time when an instance of the
Machine class is
created. If this were a real-world application, the creation time would be set to
the actual time when the machine is finally built and ready to be tested.
An instance of the
Test class represents a test that
can be assigned to a machine. A
Test instance is
uniquely described by its
id and
name, as shown in Listing 3:
Listing 3. Instance variables for the
Testclass
The sample program uses the Drools rules engine to evaluate instances of the
Machine class. Based on the values of a
Machine instance's
type and
functions properties, the rules engine determines which
values should be assigned to the
tests and
testsDueTime properties.
In the
demo package, you'll also find an
implementation of a data access object (
TestDAOImpl)
for
Test objects, which lets you find
Test instances by ID. This data access object is
extremely simple; it does not connect to any external resources (such as
relational databases) to obtain
Test instances.
Instead, a predefined set of
Test instances is
hardcoded in its definition. In a real-world scenario, you would probably have a
data access object that does connect to an external resource to retrieve
Test objects.
One of the more important classes (if not the most important) in the
demo package is
RulesEngine.
An instance of this class serves as a wrapper object that encapsulates the logic
to access the Drools classes. You could easily reuse this class in your own Java
projects, because the logic it contains is not specific to the sample program.
Listing 4 shows the properties and constructor of this class:
Listing 4. Instance variables and constructor for the
RulesEngineclass
As you can see in Listing 4, the
RulesEngine class's
constructor takes as an argument a string value that represents the name of the
file that contains a set of business rules. This constructor uses an instance of
the
PackageBuilder class to parse and compile the rules
contained in the source file. (Note: This code assumes the rules file is
located in a folder called rules in the program's classpath.) Once this is done,
the
PackageBuilder instance is used to merge all the
compiled rules into a binary
Package instance. This
instance is then used to configure an instance of the Drools
RuleBase class, which is assigned to the
RulesEngine class's
rules
property. You can think of an instance of this class as an in-memory
representation of the rules contained in your rules file.
Listing 5 shows the
RulesEngine class's
executeRules() method:
Listing 5.
executeRules()method of the
RulesEngineclass
The
executeRules() method is pretty much where all
the magic in the Java code happens. Invoking this method executes the rules that
were previously loaded in the class's constructor. An instance of the Drools
WorkingMemory class is used to assert or declare the
knowledge that the rules engine should use to determine which
consequences should be executed. (If all the conditions of a rule are met, then
the consequences of that rule are executed.) Think of knowledge as the data or
information that a rules engine should use to determine whether the rules should
be fired. For instance, a rules engine's knowledge can consist of the current
state of one or more objects and their properties.
Execution of a rule's consequences occurs when the
WorkingMemory object's
fireAllRules() method is invoked. You might be
wondering (and I hope you are) how the knowledge is inserted into the
WorkingMemory instance. If you take a closer look at
this method's signature, you'll notice that the argument that is passed in is an
instance of the
WorkingEnvironmentCallback interface.
Callers of the
executeRules() method need to create an
object that implements this interface. This interface requires developers to
implement only one method, as shown in Listing 6:
Listing 6.
WorkingEnvironmentCallbackinterface
So, it's up to the caller of the
executeRules()
method to insert the knowledge into the
WorkingMemory
instance. I'll show how this is done soon.
The
TestsRulesEngine class
Listing 7 shows the
TestsRulesEngine class, also found
in the
demo package:
Listing 7.
TestsRulesEngineclass
The
TestsRulesEngine class has only two instance
variables. The
rulesEngine property is an instance of
the
RulesEngine class. The
testDAO property holds a reference to a concrete
implementation of the
TestDAO interface. The
rulesEngine object is instantiated using the
"testRules1.drl" string as the parameter for its
constructor. The testRules1.drl file captures the business rules in
The problem to solve in a declarative way. The
TestsRulesEngine class's
assignTests() method invokes the
RulesEngine class's
executeRules() method. In this method, an anonymous
instance of the
WorkingEnvironmentCallback interface is
created, which is then passed as a parameter to the
executeRules() method.
If you take a look at the implementation of the
assignTests() method, you can see how knowledge is
inserted into the
WorkingMemory instance. The
WorkingMemory class's
insert() method is called to state the knowledge that
the rules engine should use when evaluating rules. In this case, the knowledge
consists of an instance of the
Machine class. Objects
that are inserted are used to evaluate a rule's conditions.
If you need your rules engine to have references to objects that are not
to be used as knowledge when evaluating conditions, you should use the
WorkingMemory class's
setGlobal() method. In the sample program, the
setGlobal() method passes a reference to the
TestDAO instance to the rules engine. The rules engine
then uses the
TestDAO instance to look up any
Test instances it might need.
The
TestsRulesEngine class is the only Java code in
the sample program that contains logic pertaining specifically to the
implementation of the business rules for assigning tests and a tests due date to
machines. The logic in this class may never need to change, even if the business
rules need to be updated.
As I previously mentioned, the testRules1.drl file contains the rules that the rules engine should follow to assign tests and a tests due date to a machine. It uses the Drools native language to express the rules it contains.
A Drools rules file has one or more
rule
declarations. Each
rule declaration is composed of one
or more conditional elements, and one or more consequences or
actions to execute. A rules file can also have multiple (that is, zero or
more)
import declarations, multiple
global declarations, and multiple
function declarations.
The best way to understand the composition of a Drools rules file is to look at a real one. Take a look at the first section of the testRules1.drl file, shown in Listing 8:
Listing 8. First section of the testRules1.drl file
In Listing 8, you can see how the
import declarations
let the rules execution engine know where to find the class definitions of the
objects you'll be using in your rules. The
global
declaration lets the rules engine know that an object should be accessible from
within your rules but that it should not be part of the knowledge used to evaluate
the rules' conditions. You can think of
global
declarations as global variables within your rules. For a
global declaration, you need to specify its type (that
is, class name) and the identifier you want to use to refer to it (that is,
variable name). This identifier name in the
global
declaration should match the identifier value that was used when the
WorkingMemory class's
setGlobal() method was invoked, which in this case is
testDAO (see Listing 7).
The
function keyword is used to define a Java function
(see Listing 9). If you see code that's repeated in your
consequences (which I discuss soon), then you should probably extract that code
and write it as a Java function. However, when doing this you should be careful to
avoid writing complex Java code in the Drools rules file. The Java functions
defined in a rules file should be short and easy to follow. This is not a
technical limitation of Drools. If you want to write complex Java code in your
rules file, you can. But doing so will probably make your code harder to test,
debug, and maintain. Complex Java code should be part of a Java class. If you need
the Drools rules execution engine to invoke complex Java code, then you can pass a
reference to the Java object that contains the complex code to the rules engine as
global data.
Listing 9. Java functions defined in the testRules1.drl file
Listing 10 shows the first rule in the testRules1.drl file:
Listing 10. First rule defined in testRules1.drl
As you can see in Listing 10, the
rule declaration
has a
name that uniquely identifies it. You can also
see that the
when keyword defines the conditional part
of a rule, and the
then keyword defines the consequence
part. The rule shown in Listing 10 has one conditional element that references a
Machine object. If you go back to
Listing 7, you'll see that a
Machine object was inserted into the
WorkingMemory object. That same object is the one used
in this rule. The conditional element evaluates the
Machine instance (which is part of the knowledge) to
determine whether the consequences of the rule should be executed. If the
conditional element evaluates to
true, the consequences
are then fired or executed. You can also see in Listing 10 that a consequence is
simply a Java language statement. By taking a quick look at this rule, you can
easily recognize that it's the implementation of the following business rule:
- If a computer is of Type1, then Test1, Test2, and Test5 should be the only tests conducted on this machine.
Therefore, this rule's conditional element checks whether the value of the
type property (of the
Machine object) is
Type1.
(In a conditional element, you can access an object's properties without needing
to invoke the getter methods, as long as the object follows the Java bean
pattern.) If this evaluates to
true, then a reference
to the
Machine instance is assigned to the
machine identifier. This reference is then used in the
consequence part of the rule to assign tests to the
Machine object.
The only statements in this rule that might look somewhat strange are the last
three consequence statements. Recall from the business rules in
"The problem to solve" section that the value that
should be assigned as a tests due date depends on the tests that are assigned to
the machine. So the tests that are assigned to a machine need to become part of
the knowledge that the rules execution engine should use when evaluating the
rules. This is exactly what the three statements do. These statements use a method
named
insert to update the knowledge in the rules
engine.
Determining rule execution order
Another important aspect of a rule is the optional
salience attribute. You use it to let the rules
execution engine know the order in which it should fire the consequence statements
of your rules. The consequence statements of the rule with the highest salience
value are executed first, the consequence statements of the rule with the
second-highest salience value are executed second, and so on. This is important
when you need your rules to be fired in a predefined order, as you'll see in a
moment.
The next four rules in the testRules1.drl file implement the remaining business
rules that pertain to the assignment of tests to machines (see Listing 11). These
rules are similar to the first rule I just discussed. Note that the
salience attribute value is the same for these first
five rules; the outcome of executing these five rules will be the same regardless
of the order in which they are fired. If the outcome were affected by the order in
which your rules are fired, then you would need to specify a different salience
value for your rules.
Listing 11. Remaining rules in testRules1.drl that pertain to assignment of tests
Listing 12 shows the remaining rules in the Drools rules file. As you've probably guessed, these rules pertain to the assignment of the tests due date:
Listing 12. Rules in testRules1.drl that pertain to assignment of the tests due date
The implementation of these rules is a little simpler than the implementation of the rules for assigning tests, but I find them a little more interesting, for four reasons.
First, note that the order in which these rules should execute does matter. The
outcome (that is, the value assigned to a
Machine
instance's
testsDueTime property) is affected by the
order in which these rules are fired. If you review the business rules detailed in
The problem to solve, you'll notice that the rules for
assigning a tests due date have a precedence order. For instance, if Test3, Test4,
and Test5 have been assigned to a machine, then the tests due date should be 10
days from the machine's creation date. The reason is that the tests due date rule
for Test3 has precedence over the tests due date rules for Test4 and Test5. How do
you express this in a Drools rules file? The answer is the
salience attribute. The value of the
salience attribute of the rules that set a value to the
testsDueTime property is different. The tests due date
rule for Test1 has precedence over all the other tests due date rules, so this
should be the last rule to be fired. In other words, the value assigned by this
rule is the one that should prevail in the case that Test1 is among the tests that
were assigned to a machine. So, the value of the
salience attribute for this rule is the lowest one: 10.
Second, each one of these rules has two conditional elements. The first element
simply checks for the existence of a
Machine instance
in the working memory. (Note that no comparisons are performed on the
Machine object's properties.) Whenever this element
evaluates to
true, it assigns a reference to the
Machine object that is then used in the consequence
part of the rule. Without this reference assignment, there would be no way to
assign a tests due date to the
Machine object. The
second conditional element checks the
id property of
the
Test object. Only when both conditional elements
evaluate to
true are the rule's consequence elements
executed.
Third, the conditional parts of these rules are not (and cannot be) evaluated by
the Drools rules execution engine until an instance of the
Test class is part of the knowledge (that is, contained
in the working memory). This seems quite logical, because if an instance of the
Test class isn't in the working memory yet, the rules
execution engine has no way to perform the comparison contained in these rules'
conditions. If you're wondering when a
Test instance
becomes part of the knowledge, recall that one or more
Test instances are inserted into the working memory
during the execution of the consequences of the rules that pertain to the
assignment of tests (see Listing 10 and
Listing 11).
Fourth, note that the consequence part of these rules is quite short and simple.
The reason is that in all of them an invocation is made to the
setTestsDueTime() Java method that was defined earlier
in the rules file using the
function keyword. This
method is where the actual assignment of a value to the
testsDueTime property occurs.
Now that you've gone over the code that implements the business-rules logic, it's
time to see if it works. To execute the sample program, run the
TestsRulesEngineTest JUnit test found in the
demo.test package.
In this test, five
Machine objects are created, each
one with a different set of properties (serial numbers, types, and functions). The
TestsRulesEngine class's
assignTests() method is invoked, iteratively, for each
one of these five
Machine objects. Once the
assignTests() method finishes its execution, assertions
are performed to verify that the business-rules logic specified in the
testRules1.drl is correct (see Listing 13). You could modify the
TestsRulesEngineTest JUnit class to add a few more
Machine instances with different properties and then
use assertions to verify that the outcome is as expected.
Listing 13. Assertions in
testTestsRulesEngine()to verify that the business logic's implementation is correct
A few more comments on knowledge
It's worth mentioning that besides inserting objects into the working memory, you
can also modify objects in it or retract them from it. You can do this within a
rule's consequence part. If an object that's part of the current knowledge is
modified in a consequence statement, and if the modified property is used in a
conditional element to determine whether a rule should be fired, you should invoke
the
update() method in the rule's consequence part.
When you invoke the
update() method, you let the Drools
rules execution engine know that an object has been updated and that any
conditional element (of any rule) that references this object (for instance,
inspects the value of one or more of the object's properties) should be
reevaluated to determine if the condition's result is now
true or
false. This means
that even the conditions of the current active rule (the rule that modifies the
object in its consequence part) can be reevaluated, which might cause the rule to
be fired again and could lead to an infinite recursion. If you don't want the
active rule to be reevaluated, you should include the
rule's optional
no-loop
attribute and give it a value of
true.
Listing 14 demonstrates this situation with pseudocode for the definition of two
rules.
Rule 1 modifies
property1 of
objectA. It
then invokes the
update() method to let the rules
execution engine know about this change, which should trigger a reevaluation of
the conditional elements of the rules that reference
objectA. Hence, the condition for firing
Rule 1 should be reevaluated. And because this
condition should evaluate again to
true (the value of
property2 is still the same because it was not changed
in the consequence part of the rule),
Rule 1 should be
fired again, resulting in the execution of an infinite loop. To prevent this
situation, you add the
no-loop attribute and give it a
value of
true, which prevents the current active rule
from reexecuting.
Listing 14. Modifying an object in the working memory and using the rule element's
no-loopattribute
If an object should no longer be part of the knowledge, then you should retract
that object from the working memory (see Listing 15). You do this by calling the
retract() method in the consequence part of your rule.
When an object is removed from the working memory, any conditional elements (of
any rule) that had a reference to this object cannot be evaluated now. Because the
object no longer exists as part of the knowledge, the rule has no chance of being
fired.
Listing 15. Retracting an object from the working memory
Listing 15 contains pseudocode for the definition of two rules. Assume the
conditions for firing both rules evaluate to
true.
Then,
Rule 1 should be fired first because
Rule 1 has a higher salience value than
Rule 2. Now, note that in the consequence part of
Rule 1,
objectB is retracted
from the working memory (that is,
objectB is no longer
part of the knowledge). This action alters the "execution agenda" of the rules
engine because
Rule 2 won't be fired now. The reason is
that the condition for firing
Rule 2 that was once true
is not true anymore because it references an object
(
objectB) that is no longer part of the knowledge. If
Listing 15 contained more rules referencing
objectB
that have not been fired yet, they would now no longer be fired.
As a concrete example of how to modify current knowledge in the working memory,
I'll rewrite the rules source file I discussed earlier. The business rules are
still the same as outlined in "The problem to solve"
section. However, I'll use a different implementation for the rules to achieve the
same results. With this approach, a
Machine instance is
the only knowledge available to the working memory at all times. In other words,
the conditional elements of the rules will perform comparisons only on properties
of a
Machine object. This is different from the earlier
approach, which also made comparisons of properties of
Test objects (see Listing 12).
This new implementation of the rules is captured in the sample application's
testRules2.drl file. Listing 16 shows the rules in testRules2.drl that pertain to
tests assignment:
Listing 16. Rules in testRules2.drl that pertain to assignment of tests
If you compare the definition of the first rule in Listing 16 to the definition
shown in Listing 10, you can see that instead of
inserting the
Test instances that were assigned to the
Machine object into the working memory, the consequence
part of the rule invokes the
update() method to let the
rules engine know that the
Machine object has been
modified. (
Test instances were added/assigned to it.)
If you look at the remaining rules in Listing 16, you should see that this is the
approach also taken whenever tests are assigned to a
Machine object: one or more
Test instances are assigned to a
Machine instance and, consequently, the working
knowledge is modified, and the rules engine is notified about it.
Note also the
active-lock attribute used for all rules
shown in Listing 16. The value of this attribute is set to
true; if it weren't, you'd end up with an infinite loop
when executing these rules. Setting it to
true ensures
that when a rule updates the knowledge in the working memory, you don't end up
with rules being reevaluated and reexecuted, which could then cause an infinite
recursion. You can think of the
active-lock attribute
as a stronger version of the
no-loop attribute. The
no-loop attribute ensures that the rule modifying the
knowledge is not invoked again as a consequence of its own update, whereas the
active-lock attribute ensures that any rules (with this
attribute set to
true) in your file are not reexecuted
as a consequence of modifying the knowledge.
Listing 17 shows how the remaining rules were changed:
Listing 17. Rules in testRules2.drl that pertain to assignment of the tests due date
These rules' conditional elements now inspect a
Machine object's
tests
collection to determine if it contains a specific
Test
instance. Hence, as I mentioned earlier, with this approach the rules engine is
dealing with only one object in the working memory (a
Machine instance), as opposed to multiple objects
(
Machine and
Test
instances).
To test the testRules2.drl file, just edit the
TestsRulesEngine class provided in the sample
application (see Listing 7): change the
"testRules1.drl" string to
"testRules2.drl" and then run the
TestsRulesEngineTest JUnit test. All tests should
succeed just as they did with testRules1.drl as the rules source.
As I mentioned before, the Drools plug-in for Eclipse allows you to place breakpoints in your rules file. Be aware that these breakpoints are enabled only when you debug your program as a "Drools Application." Otherwise, the debugger ignores them.
For example, suppose you want to debug the
TestsRulesEngineTest JUnit test class as a "Drools
Application." Open the general Debug dialog in Eclipse. In this dialog window, you
should see a "Drools Application" category. Under this category, create a new
launch configuration. In the Main tab for this new configuration, you should see a
Project field and a Main class field. For the Project field, select the
Drools4Demo project. For the Main class field, enter
junit.textui.TestRunner (see Figure 3).
Figure 3. Drools application launch configuration for
TestsRulesEngineTestclass (Main tab)
Now select the Arguments tab and enter
-t demo.test.TestsRulesEngineTest as a program argument
(see Figure 4). Once you are done entering the argument, save your new launch
configuration by clicking on the Apply button on the bottom right corner of
the dialog. You can then click the Debug button to start debugging the
TestsRulesEngineTest JUnit class as a "Drools
Application." If you added breakpoints to testRules1.drl or testRules2.drl, the
debugger should stop at them when using this launch configuration.
Figure 4. Drools Application launch configuration for
TestsRulesEngineTestclass (Arguments tab)
Using a rules engine can significantly reduce the complexity of components that implement the business-rules logic in your Java applications. An application that uses a rules engine to express rules using a declarative approach has a higher chance of being more maintainable and extensible than one that doesn't. As you've seen, Drools is a powerful and flexible rules engine implementation. Using Drools' features and capabilities, you should be able to implement the complex business logic of your application in a declarative manner. And as you've seen, Drools makes learning and using declarative programming quite easy for Java developers.
The Drools classes that this article showed you are Drools-specific. If you were to use another rules engine implementation with the sample program, the code would need a few changes. Because Drools is JSR 94-compliant, you could use the Java Rule Engine API (as specified in JSR 94) to interface with Drools-specific classes. (The Java Rule Engine API is for rules engines what JDBC is for databases.) If you use this API, then you can change your rules engine implementation to a different one without needing to change the Java code, as long as this other implementation is also JSR 94-compliant. JSR 94 does not address the structure of the rules file that contains your business rules (testRules1.drl in this article's sample application). The file's structure would still depend on the rules engine implementation you choose. As an exercise, you can modify the sample application so that it uses the Java Rule Engine API instead of referencing the Drools-specific classes in the Java code.
Information about download methods
Learn
- Drools Web site: Get more information about the Drools rules engine project.
- "The Logic of the Bottom Line: An Introduction to The Drools Project" (N. Alex Rupp, TheServerSide.com, May 2004): A good introduction to the Drools rules engine.
- "Getting Started With the Java Rule Engine API (JSR 94): Toward Rule-Based Applications" (Qusay H. Mahmoud, Sun Developer Network, July 2005): An introduction to the Java Rule Engine API.
- JSR 94: Java Rule Engine API: The official JSR 94 specification.
- Drools documentation: The Drools documentation library.
- "The Rete Matching Algorithm" (Bruce Schneier, Dr. Dobb's Portal, December 1992): A description of the pattern-matching algorithm underlying Drools.
- Technology bookstore: Browse for books on these and other technical topics.
- The Java technology zone: Hundreds of articles about every aspect of Java programming.
Get products and technologies
- Drools: Download the latest Drools distribution and Drools plug-in for Eclipse.
- Eclipse: Download the latest version of the Eclipse IDE for the Java platform.
Discuss
- developerWorks blogs: Get involved in the developerWorks community.
Ricardo Olivieri is a software engineer in IBM Global Services.. | http://www.ibm.com/developerworks/java/library/j-drools/index.html | crawl-002 | refinedweb | 6,135 | 61.26 |
Hadoop has been growing clusters in data centers at a rapid pace. Is Hadoop the new corporate HPC?
Is Hadoop the New HPC?
Apache Hadoop has been generating a lot of headlines lately. For those who are not aware, Hadoop is an open source project that provides a distributed filesystem and MapReduce framework for massive amounts of data. The primary hardware used for Hadoop is clusters of commodity servers. File sizes can easily be in the petabyte range and use hundreds or thousands of compute servers.
Hadoop also has many components that live on top of the core Hadoop filesystem (HDFS) and MapReduce mechanism. Interestingly, HPC and Hadoop clusters share some features, but how much crossover you will see between the two disciplines depends on the application. Hadoop strengths lie in the sheer size of data it can process and its high redundancy and toleration of node failures without halting user jobs.
Who Uses Hadoop
Many organizations use Hadoop on a daily basis, including Yahoo, Facebook, American Airlines, eBay, and others. Hadoop is designed to allow users to manipulate large unstructured or unrelated data sets. It is not intended to be a replacement for a RDMS. For example, Hadoop can be used to scan weblogs, on-line transaction data, or web content, all of which are growing each year.
Map Reduce
To many HPC users, MapReduce is a methodology used by Google to process large amounts of web data. Indeed, the now famous Google MapReduce paper was the inspiration for Hadoop.
The MapReduce idea is quite simple and, when used in parallel, can provide extremely powerful search and compute capabilities. Two major steps constitute the MapReduce process. If you have not figured it out, they are the “Map” step followed by a “Reduce” step. Some are surprised to learn that mapping is done all the time in the *nix world. For instance consider:
grep "the" file.txt
In this simple example, I am “mapping” all the occurrences, by line, of the word “the” in a text file. Although the task seems somewhat trivial, suppose the file was 1TB. How could I speed up the mapping step. The answer is also simple: Break the file into chunks and put a different chunk on a separate computer. The results can be combined when the job is finished because the map step has no dependencies. The popular mpiBLAST tool takes the same approach by breaking the human genome file into chunks and performing “BLAST” mapping on separate cluster nodes.
Suppose you want to calculate the total number of lines containing ‘the’. The simple answer is to pipe the results into wc (word count):
grep "the" file.txt | wc -l
You have just introduced a “Reduce” step. For the large-file parallel mode, each computer would perform the above step (grep and wc) and send the count to the master node. That, in a nutshell, is how MapReduce works – with, of course, a few more details, like key-value pairs and “the shuffle” – but for the purposes of this discussion, MapReduce can be that simple.
With Hadoop, large files are placed in HDFS, which automatically breaks the file into chunks and spreads them across the cluster (usually in a redundant fashion). In this way, parallelizing the Map process is trivial; all that needs to happen is to place a separate Map process on each node with the file chunk. The results are then sent to Reduce processes, which also run on the cluster. As you can imagine, large files produce large amounts of intermediate data: thus, multiple reducers help keep things moving. Several aspects to the MapReduce process worth noting:
- MapReduce can be transparently scalable. The user does not need to manage data placement or the number of nodes used for their job. The underlying hardware has no dependencies.
- Data flow is highly defined and in one direction from the Map to the Reduce, with no communication between independent mapper or reducer processes.
- Because processing is independent, failover is trivial. A failed process can be restarted, provided the underlying filesystem is redundant like HDFS.
- MapReduce, while powerful, does not fit all problem types.
To understand the difference between Hadoop and a typical HPC cluster, I’ll compare several aspects of both systems.
Hardware
Many modern HPC clusters and Hadoop clusters use commodity hardware, comprising primarily x86-based servers. Hadoop clusters usually include a large amount of local disk space (used for HDFS nodes), whereas many HPC clusters rely on NFS or a parallel filesystem for cluster-wide storage. HPC uses diskless and diskful nodes, but in terms of data storage, a separate group of hardware is often used for global file storage. HDFS daemons run on all nodes and store data chunks locally. It does not support the POSIX standard. Hadoop is designed to move the computation to the data; thus, HDFS needs to be distributed throughout the cluster.
In terms of networking, Hadoop clusters almost exclusively use gigabit Ethernet (GigE). As the price continues to fall, newer systems are starting to adopt 10GigE. Although, there are many GigE and 10GigE HPC clusters, InfiniBand is often the preferred network.
Many new HPC clusters are using some form of acceleration hardware on the nodes. These additions are primarily from NVidia (Kepler) and Intel (Phi). They require additional programming (in some cases) and can provide substantial speed-up for certain applications.
Resource Scheduling
One of the biggest differences between Hadoop and HPC systems is resource management. HPC requires fine-grained control of what resources (cores, accelerators, memory, time, etc.) are given to users. These resources are scheduled with tools like Grid Engine, Moab, LoadLeveler, and so on. Hadoop has an integrated scheduler that consists of a master Job Tracker, which communicates with Task Trackers on the nodes. All MapReduce work is supervised by the Job Tracker. No other job types are supported in Hadoop (Version 1).
One interesting difference between an HPC resource scheduler and the Hadoop Task Tracker is fault tolerance. HPC schedulers can detect down nodes and reschedule jobs (as an option), but if the job has not been checkpointing, it must start from the beginning. Hadoop, because of the nature of the MapReduce algorithm, can manage failure through the Job Tracker. Because the Task Tracker is aware of job placement and data location, a failed node (or even a rack of nodes) can be managed at run time. Thus, when an HDFS node fails, the Job Tracker can reassign a task to a node where a redundant copy of the data exists. Similarly, if a Map or Reduce process fails, the job can be restarted on a new node.
The next-generation scheduler for Hadoop is called YARN (Yet Another Resource Negotiator) and offers better scalability and more fine-grained control over job scheduling. Users can request “containers” for MapReduce and other jobs (possibly MPI), which are managed by individual per-job Application Masters. With YARN, the Hadoop scheduler starts to look like other resource managers; however, it will be backward compatible with many higher level Hadoop tools.
Programming
One of the big differences between Hadoop and HPC is, synchronization, I/O, debugging, and possibly checkpointing/restart operations. These tasks often are not easy to get right and can take significant time to implement correctly and efficiently.
Hadoop, by offering the MapReduce paradigm, only requires that the user create a Map step and Reduce step (and possibly some others, i.e., a combiner). These tasks are devoid of all the minutia of HPC programming. Users only need concern themselves with these two tasks, which can be debugged and tested easily using small files on a single system. Hadoop also presents a single-namespace parallel file system SIMD (single-instruction, multiple-data), programing extends Apache Pig with sequence analysis capability, and MR-MSPolygraph is a MapReduce implementation of a hybrid spectral library–database search method for large-scale peptide identification. In the case of MR-MSPolygraph, results demonstrate as things like YARN begin to give existing Hadoop clusters more HPC capabilities. Many companies are finding Hadoop to be the new Corporate HPC for big data. | http://www.admin-magazine.com/HPC/Articles/Is-Hadoop-the-New-HPC/(tagID)/321 | CC-MAIN-2019-18 | refinedweb | 1,351 | 63.09 |
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Swing / AWT / SWT
Author
looking for a graphical representation
Kevin Tysen
Ranch Hand
Joined: Oct 12, 2005
Posts: 255
posted
Oct 26, 2009 16:57:11
0
I am trying to think of a good way to represent graphically a logical framework.
Specifically, it's something like this:
Suppose you have some Strings A, B, C, D, E, F, and another
String
K which you want to evaluate.
You want to evaluate K like this:
K score is initially 0.
If K contains A or B, add 4 to the score.
If K contains C, add 10 to the score.
If K contains D, E, or F, add 5 to the score.
The program user wants to see a graphic representation of this logic.
I thought of two possible ways to represent this logic graphically.
One way is to put A through F on a table.
In the first row is the number 4, then A and B. In the second row is 10 and C, and in the third row is 5, D, E, and F.
Another way to represent this graphically is to put them in a
JTree
. The
JTree
has three nodes named '4', '10', and '5'.
The 4 node contains A and B, the 10 node contains C, and the 5 node contains D, E, and F.
Well, these are the two ways I thought of to represent the logic graphically. Any other ideas?
Craig Wood
Ranch Hand
Joined: Jan 14, 2004
Posts: 1535
posted
Oct 27, 2009 23:17:20
0
import java.awt.*; import java.awt.font.*; import javax.swing.*; public class AnIdea extends JPanel { Font font = new Font("Monospaced", Font.PLAIN, 18); Font checkFont = new Font("Monospaced", Font.PLAIN, 14); final int PAD = 20; final int VPAD = 5; final int CPAD = 30; final int SPAD = 125; final int NPAD = 105; protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); FontRenderContext frc = g2.getFontRenderContext(); LineMetrics lm = font.getLineMetrics("0", frc); float sh = lm.getAscent() + lm.getDescent(); g2.setFont(font); g2.setPaint(Color.blue); g2.drawRect(0,0,getWidth()-1,getHeight()-1); g2.setPaint(Color.black); // K float x = PAD; float y = PAD + lm.getAscent(); g2.drawString("K", x, y); x += SPAD; g2.drawString("abcd", x, y); x += NPAD; g2.drawString("0", x, y); // A and B section y = drawSection(g2, y, sh, "Add 4:", "4", frc, lm); y = drawLine(g2, y, sh, "A", "b", "\u2611"); y = drawLine(g2, y, sh, "B", "y", "\u2610"); // C section y = drawSection(g2, y, sh, "Add 10:", null, frc, lm); y = drawLine(g2, y, sh, "C", "f", "\u2610"); // D, E and F section y = drawSection(g2, y, sh, "Add 5:", "5", frc, lm); y = drawLine(g2, y, sh, "D", "a", "\u2611"); y = drawLine(g2, y, sh, "E", "n", "\u2610"); y = drawLine(g2, y, sh, "F", "x", "\u2610"); // Total y += lm.getDescent() + VPAD; x = PAD + SPAD + NPAD + PAD; int x1 = PAD; int y1 = (int)(y); int x2 = (int)(x); int y2 = y1; g2.drawLine(x1, y1, x2, y2); y += sh; x = PAD; String s = "Total:"; g2.drawString(s, x, y); x += SPAD + NPAD; s = "9"; g2.drawString(s, x, y); } private float drawSection(Graphics2D g2, float y, float sh, String s1, String s2, FontRenderContext frc, LineMetrics lm) { y += sh + VPAD; float x = PAD; g2.drawString(s1, x, y); float sw = (float)font.getStringBounds(s1, frc).getWidth(); int x1 = PAD; int y1 = (int)(y + lm.getDescent()); int x2 = (int)(x1 + sw); int y2 = y1; g2.drawLine(x1, y1, x2, y2); if(s2 != null) { x += SPAD + NPAD; g2.drawString(s2, x, y); } return y; } private float drawLine(Graphics2D g2, float y, float sh, String s1, String s2, String check) { y += sh + VPAD; float x = PAD; g2.drawString(s1, x, y); g2.setFont(checkFont); g2.drawString(check, x+CPAD, y); g2.setFont(font); x += SPAD; g2.drawString(s2, x, y); return y; } public static void main(String[] args) { AnIdea idea = new AnIdea(); idea.setPreferredSize(new Dimension(400,400)); JOptionPane.showMessageDialog(null, idea, "", -1); } }
Kevin Tysen
Ranch Hand
Joined: Oct 12, 2005
Posts: 255
posted
Oct 27, 2009 23:59:34
0
Wow, that is a nice program! Thank you. I'll take a close look at it and use some of the main ideas in the program.
I agree. Here's the link:
subject: looking for a graphical representation
Similar Threads
JTree: Setting node to be a JPanel
JTable In JTree
JTree
JTree help
collapsing JTree
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/468217/GUI/java/graphical-representation | CC-MAIN-2015-06 | refinedweb | 785 | 73.78 |
It returns 5.0 instead of 4.5 when [4,5,5,4] goes in. You cannot take the int()s out because then it'll say you cannot use floats as indices of a list.
15/15: What is wrong with this code?
Let's see if we can reduce this to a simple algorithm:
def median(n): n.sort() j = len(n)/2. k = int(j) if j == k: m = (n[k] + n[k-1])/2. else: m = n[k] return m print median([4,5,5,4]) # 4.5
It is another thing altogether to attempt to access the array elements by their median, since in even count arrays, the median is a float, and not necessarily a value in the array. We can use midpoint arithmetic to zero in on the two middle elements, which is easy enough to reason out. | https://discuss.codecademy.com/t/15-15-what-is-wrong-with-this-code/9015 | CC-MAIN-2018-51 | refinedweb | 145 | 77.23 |
1 /*2 * ====================================================================3 * 4 * The Apache Software License, Version 1.15 *6 * Copyright (c) 2000.vxml;59 60 /**61 This class implements the error element62 63 @author Written by <a HREF="mailto:jcarol@us.ibm.com">Carol Jones</a>64 */65 public class Error extends VXMLElement66 {67 68 /**69 Basic constructor. You need to set the attributes using the70 set* methods.71 */72 public Error()73 {74 super("error");75 }76 77 78 /**79 This constructor creates a <error> tag.80 @param theMessage the error message81 */82 public Error(String theMessage)83 {84 this();85 addElement(theMessage);86 }87 88 89 } 90
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/apache/ecs/vxml/Error.java.htm | CC-MAIN-2016-50 | refinedweb | 117 | 59.3 |
Racism in our schools
Yet another study has come out, confirming what anyone with eyes and ears and a high school education should already know: Black students are treated less like students and more like potential criminals in our public schools. In this case, the study in question found that black students are FOUR TIMES more likely to be suspended than white kids for the SAME infractions, and that in middle and high school, they are likely to be treated as or more harshly for their FIRST infraction than white students are for their SECOND one. ()
In that study, principals were asked to assign punishments and to decide whether students were “troublemakers” by reviewing similar scenarios in which the student had a “white” name or a “black” one. The results replicated what we see ANY time such a study is done, whether it’s in the arena of education, employment, housing, etc. Racism is very real in the culture in general. But it seems particularly poignant when it affects children too young to understand that they don’t deserve the treatment they receive and whose futures are seriously jeopardized by the actions of those tasked with setting them on the road to success. As lifelong educator myself, I have been, and continue to be, a part of this problem.
Why, when study after study shows the same results, hasn’t education as a discipline, cleaned up its racist act?
After all, Education should be the silver bullet when it comes to racism, right? It should be how we replace historical and cultural ignorance with an understanding of how this country used four hundred years of slave labor to establish itself as an economic leader, how lands were stolen from those who lived there for untold generations , leaving them to be treated as trespassers and worse, how our own founding fathers made sure that the playing field was not only raked in favor of white men, but that many of their fellow Americans weren’t even allowed in the game.
Education should be the first step in breaking free from the nightmare of racism. Instead, it is one of racism’s best tools in replicating itself. And it doesn’t start in a grade school teacher’s classroom. Or the principal’s office. It starts before teachers and administrators have their first contact with students.
I went to the most diverse (and socio-economically depressed) middle and high schools in my town. Because my schools were a combination of some of the best AND worst teachers I had experienced, I decided to become a teacher — in order to emulate the former and replace the latter. To become a teacher, I got a BA in my subject area, and completed a teacher education program at my university’s College of Education.
When I was training to teach high school, race was touched on in only one class: something called Multicultural concerns (it is now called Socio-cultural Concerns, but I’m willing to bet the reading list hasn’t changed in 20+ years.). When I took this class, I had some SMALL awareness of how race could impact a child’s education because I had seen the way it affected my friends in middle and high school. Our honors track at my high school, for example, had literally NO students of color for my “year” (class of 1985). Latinx students were regularly placed in remedial classes regardless of their ability of mastery of English. And white students regularly won athletic scholarships while black students could really only hope for athletic ones.
The rest of the Multicultural class was made up of white, middle/upper-middle class women preparing to be teachers (for all the wrong reasons, but that’s another discussion). In this, it looked like pretty much every other education class I took.
Throughout the class, we read interesting texts, full of first and third-person accounts of the very real impacts that current (and largely unchanged) educational system practices and personal prejudices cause for students of color (and for black and Latinx students specifically). The instructor was a white youngish man (there was almost no faculty of color at the College of Education at the time), and really tried to help the class see how black, brown, and poor students face overt obstacles, low expectations, are tracked into remedial classes, special ed, and other “alternative ed” programs, and are subject to the impact of personal interactions in the classroom that leave them with the clear message that they are “less than.”
All of this made sense to me because of my background: I had seen it in action, and these texts and the professor’s lectures just showed me how systemic these practices were. But every other student in the class fought back against this data.
And a large portion of their arguments (such as they were — mostly it was just flat-out denial) came down to their inability to see ANY experience different from their own. I and the instructor listened as racial epithets in the classroom were dismissively compared to “that one time my teacher yelled at me for borrowing a pencil for the umpteenth time.” Systemic tracking of black students into remedial classes was written off as “parents too lazy to work with their kids on their homework.” “Underperformance” on standardized tests was “lack of willingness to work” on the part of kids of color (despite the instructor talking about Maslow’s hierarchy of needs, kids who got their one and only half decent meal of the day at school as part of the free-lunch programs, and the proven cultural bias of such tests (“They just need to stop thinking the rest of the world is gonna learn Ebonics!”).
My fellow students assumed that the material and cultural conditions of all students are identical to their own, growing up. Thus the needs of all students are identical. Thus no change is necessary on the part of the teacher, regardless of the make-up of the class. Thus failure can NEVER be the fault of the system. If white kids succeed, it’s PROOF that everyone else simply isn’t working hard enough. When you add this “righteous” justification to the fact that many people decide to become teachers simply because they had the educational system “dialed” as high schoolers, knowing how to put in a minimum of effort for maximum return (in the form of grades), and wanted to continue to exist in a system that had already benefited them so much, you can see how it becomes a cycle in which all the same mistakes are replicated endlessly.
The one thing that we were NEVER encouraged to do was to reflect on our actions. We were never taught about implicit bias. We were NEVER called out during our student teaching for ANYTHING that might have been impacted by implicit or overt bias. And after that class, race ceased to be an issue except when it came to choosing what schools we would work in (when those same students showed an amazing ability to suddenly “see” the color that they had, up to that moment, claimed didn’t exist in their eyes): they knew the schools with more black and brown kids were the most under-funded schools and thus, those were last on their future employment wish-list.
Which also meant that even those of us, like me, who stupidly thought we were more enlightened, were trained in a system that made it not just okay but even beneficial to ignore our own implicit bias, even up to the point of fostering “white savior” syndrome. After all, if you did actively choose to teach in my old high school, for example, it was widely acknowledged that you were making a sacrifice, that your job would be more difficult, you’d have less parental support, and you’d have to put more of your own money into your classroom. You were a “hero,” and told so both by your classmates AND your instructors and advisors.
A system like that is self-reinforcing, and you enter it the moment you decide to teach.
It’s also important to consider that colleges of education, rather than being places of innovation and new thought, are actually places where you are actively told to sit down and shut up and that whatever the current methodology is, it works equally well for ALL students. When you have (white) people going into a broken system and you are actively teaching them not to ask inconvenient questions, not to challenge the system, and not to reflect on their own part in supporting that system, it’s just a recipe for disaster for students who are not white, middle-class, and (often) male.
In the end, what this then boils down to is a situation where teachers can read all the studies on how black and brown children are under-served, over-disciplined, and tracked into the school-to-prison pipeline and always be thinking one of two things (based on their backgrounds). If they are like one of the women in my class, they think “there’s missing information that accounts for the real cause” (and sometimes, as we all know, that “real” cause is just that black and brown people are intellectually inferior and more violent). And if they are one of the “good liberals” like me, then this injustice is always something unfortunate that happens “over there” somewhere, and is NOT playing itself out in our classrooms (because we cannot see ourselves capable of this shit, when the truth is that we ALL — me included — are doing it all the time).
Because the system is so enclosed and controlled and punishes real reflection on classroom management outside of pure methodology, it seems that the only way to change the system is to recruit more teachers of color, and this starts with the colleges of Education hiring more professors of color. I don’t remember ANY professors of color in my years in my College of Education. Looking back now, only five faculty members out of sixty are black or brown. Yes, the Dean himself is black. But none of the professors in the graduate programs in “Equity and Diversity” appear to be black (and the one Lebanese professor is the only brown one). This is important for reasons beyond representation (which is itself powerful).
Because I don’t think that my classmates would have felt as comfortable assigning blame for racial injustice on black and brown children and their parents had they had to do that to a black professor (since, as I said, challenging power of current methodology — or your professors — is verbotten in most colleges of education). Had they been forced to LISTEN, rather than allowed to justify…had they had their own implicit bias pointed out to them in class by a Latina professor, as they were doing it, I think they might have actually absorbed some of the material as having a relation to their futures as teachers. Had I been challenged on these things, I likely would have made fewer mistakes than I did once I was in a classroom and lessened the damage I have done.
And race/gender/orientation/socioeconomic status needs to be something dealt with in ALL education classes. I started my teaching program in 1989, the same year Peggy McIntosh published “White Privilege: Unpacking the Invisible Knapsack” and yet, in five years in that college, I never heard “white privilege” (or ANY kind of privilege) discussed, nor was I introduced to the idea that certain students carried heavier backpacks than I did. Either of these ideas would have been powerful messages for both me and my classmates. We were frequently presented with scenarios and potential solutions for our classrooms, for example, but race, gender, orientation, or socioeconomic status was never (except in the last case, since even white kids can be poor, I suppose) part of those scenarios. Such thought experiments should include all these elements and we should be asked to think them through IN LIGHT of these heavier backpacks.
But that’s not enough. We really need to actively recruit black and brown people to be teachers. And we need to do it WITHOUT putting them in a bad place economically (because teachers’ salaries already suck). We need to offer top-performing high school black and brown students a cost-free college education in exchange for going into teaching (so no college loans to financially cripple them), and cash incentives (paid yearly as a bonus, maybe — haven’t figured that part out) for them to teach in schools with higher populations of students of color. This will help everyone, regardless of their racial or any other status. After all, studies also show that students — whatever their skin tone — prefer teachers of color. ()
We also need to remember that the tone of a school is set by the principal and others in the office, and so training in school administration needs to include a heavy emphasis on implicit bias. If we also required principals — and others involved in discipline — to track their disciplining of students and then fed those metrics BACK to them AND made them part of reports on their school, that would go far in remedying the problem. School staff in charge of discipline aren’t tracked on most of this stuff now unless they are actively part of a study. But wouldn’t it be great to be able, as a parent, look at your local schools’ rating and see a metric about the equity of discipline dispensed and the performance of students of color compared to white students before deciding whether to send you child there or ask for a school variance? More school administrators of color would be excellent as well, preferably recruited from among successful teachers in the same schools, if possible.
To be clear, none of this is meant as an excuse for current teachers or administrators — “they didn’t teach me to understand bias!” — because there isn’t one. Being is an enclosed system that reproduces racism is no more forgiveable than being your average white person who doesn’t give a damn about racism or who “doesn’t see color.” We all have eyes. We all have ears. And the truth is there for those who want to begin the life-long journey of anti-racism.
The two differences I see between generic racism and educational racism are that one, this involves kids, and if your job is kids, then it is part of your job description as a teacher to pull your head out of your ass to try to understand the challenges students of color face and how you are either adding to that burden or trying to relieve it. If you cannot do that, you have no business in a classroom with children of ANY color, since you are just replicating harm and those who harm.
And two, this is a good place to start as a culture. If we can place teachers in our classrooms who understand (or better, experienced) implicit bias, then not only can we change the experience of the students in the classroom, but we can change the sensitivity of ALL children to these obstacles and harmful behaviors. They can help white students to see the racism they are conditioned to and act in support of, and they can help black and brown children by giving them better support in navigating (and not internalizing) that racism. And because education is a closed system, the minute we start generating STUDENTS who have this more enlightened perspective, we can encourage them to stay in that system by becoming teachers, and then admins, and then college professors at colleges of education. (It would be faster to do this top down, but I honestly don’t think we are willing to do that because it would require more abrupt admission that the system is rigged.) Once it’s in the system, it’ll be hard to shake.
I realize that, in the solutions I am proposing, I am putting a lot of this labor on black and brown people. But I don’t think there’s another way, if only because we, as white people, are too blind, too untrustworthy, and too inculcated to create the level of change necessary. After all, there are PLENTY of “good liberal” whites already teaching in the school system, and we haven’t moved the needle.
I also think that black and brown teachers and administrators leading the way is one of the quickest ways to effect change at the societal level because it would put an end to the ways we damage black and brown children in the environment they are required to be in by law. Remove that damage, and black and brown children will grow up with less self-doubt, confusion, pain, and fear as adults. They are owed that freedom — it is long overdue. But I no longer feel as though that’s something that a white-led education system can deliver.
Instead, we need to remember that our first duty is to the students, and our students benefit from having teachers of color in the classroom and in the school office. White teachers, administrators and professors have failed to correct the racism that plagues the school system ourselves. We need to be prepared to elevate those who can, and to learn from them. We owe our students nothing less. | https://medium.com/@lauraakers/racism-in-our-schools-7f9855a7928f?source=post_internal_links---------2---------------------------- | CC-MAIN-2022-27 | refinedweb | 2,932 | 59.87 |
In this article we will be building the stack of resources needed to run the application we prepared and containerized in the first part:
Our backend (app.py) is a Flask application that simulates an expensive computation and returns it in a formatted…hackernoon.com
The application source and CloudFormation stack file can be found here:
Independently Scalable Multi-Container Microservices Architecture on AWS Fargate - docwhite/ecsfsgithub.com
Overview
The ideas and requirements for this application, ecsfs, are:
- Backend and frontend services not to be public-facing.
- Nginx will sit on the front, publicly accessible.
- Nginx would proxy the request to the frontend.
- The frontend requests from the backend.
- Auto-scalable backend (since it performs expensive computations).
In order to address (1) and (2) we will require private and public subnets. To forward all traffic to the nginx server (2) we will set up an Application Load Balancer (ALB). For the communication between components (3) (4) we will make use of service discovery.
As we will be using ECS (Elastic Container Service) all the Fargate services will need to pull images from Docker Hub, that will involve outgoing traffic from the private network containers (1) to be routed to a NAT —otherwise the Internet is not reachable.
Let us have a look at the complete diagram:
I broke down this diagram and explained each piece separately following this structure: VPC and subnets, networking and routes, security groups, how to configure the load balancer, defining our services using ECS Fargate, setting up the auto-scaling and finally stressing our application to see the scaling happen.
You can skip sections if you are already familiarised with them.
How to deploy CloudFormation stacks
Either using command line or from the web console.
Using Command Line
First you will need to install and configure the AWS CLI. You can follow the docs:
TL;DR Basically you will need to install it with pip:
pip install awscli --upgrade --user
And configure it (specify your default region too so you don’t have to type it on each subsequent command):
aws configure
To actually deploy the stack you have two choices (a) and (b)…
a) If you have no hosted zones set up (associated with a Route 53 domain):
aws cloudformation create-stack \
--stack-name ecsfs \
--template-body \
--capabilities CAPABILITY_NAMED_IAM \
--parameters ParameterKey=HostedZoneName,ParameterValue=
b) If you have a hosted zone, you can pass it in an the application will be available under the subdomain ecsfs.<your-hosted-zone-name>, e.g. ecsfs.example.com. Simply pass the parameter flag instead of leaving it empty:
--parameters ParameterKey=HostedZoneName,ParameterValue=foo.com.
(!) the trailing dot is needed ^
Using AWS Web Console
Log in into your account and then visit the CloudFormation section. Then:
- Click the Create Stack button.
- Click on Choose File and upload the stack.yaml file.
- Give the Stack a name: ecsfs.
- In the parameters section, you will see HostedZoneName. It is up to you if you want to use one of your hosted zones (domains) for instance foo.com. — do not forget the trailing dot — so the application would then be configured to run on a subdomain of it — like ecsfs.foo.com. You can leave it empty.
- Click Next.
- Click Next one more time.
- On the Capabilities section check the box I acknowledge that…
Deleting all the resources that have been created
Either from the web console or from CLI. To do it from the web console go to the CloudFormation section and delete it there. The command line equivalent is:
aws cloudformation delete-stack – stack-name ecsfs
Stack Parameters, Conditions and Outputs
In the stack file apart from resources we define parameters, conditions and outputs.
Parameters are variables the user can provide when deploying the stack that can be accessed within the resource definitions.
Conditions allows to define boolean variables that we can use to conditionally build some resources. You can set conditions for resource building by adding the Conditions yaml property under the resource.
In our case outputs let us have a quick way to expose attributes or any other information in the stack so we can for instance get handles to some resources we constructed (such as the DNS name for our application load balancer).
Virtual Private Cloud (VPC)
A VPC is simply a logically isolated chunk of the AWS Cloud.
Our VPC has two public subnetworks since it’s a requirement for an Application Load Balancer. The nginx container will use them too.
Then we will isolate backend and frontend to a private subnet so they can’t be reached directly from the Internet.
You will the word CIDR in various places, it is used for subnet masking.
CIDR blocks describe the Network ID and IP ranges to assign in our subnets. It basically tells what part of the address is reserved for IPs and what part is for the network ID.
E.g. 10.0.0.0/24 would mean that the first 3 octets (3 x 8 = 24) are going to be exclusively defining the Network ID, which would result in all the IPs that are given out would start with 10.0.0.x.
This video explains it very well: IPv4 Addressing: Network IDs and Subnet Masks
Networking Setup: Routing and Subnetting
Let’s revisit the main elements that conform a subnet and how we are going to use them in our application.
Internet Gateway
Allows communication between the containers and the internet. All the outbound traffic goes through it. In AWS it must get attached to a VPC.
All requests from a instances running on the public subnet must be routed to the internet gateway. This is done by defining routes laid down on route tables.
Network Address Translation (NAT) Gateway
When an application is running on a private subnet it cannot talk to the outside world. The NAT Gateway remaps the IP address of the packets sent from the private instance assigning them a public IP so when the service the instance wants to talk you replies, the NAT can receive the information (since the NAT itself is public-facing and reachable from the Internet) and hand it back to the private instance.
An Elastic IP needs to be associated with each NAT Gateway we create.
The reason why we traffic private tasks’ traffic through a NAT is so tasks can pull the images from Docker Hub whilst keeping protection since connections cannot be initiated from the Internet, just outbound traffic will be allowed through the NAT.
Routes and Route Tables
Route tables gather together a set of routes. A route describes where do packets need to go based on rules. You can for instance send any packets with destination address starting with 10.0.4.x to a NAT while others with destination address 10.0.5.x to another NAT or internet gateway (I cannot find a proper example, I apologise). You can describe both in and outbound routes.
The way we associate a route table with a subnet is by using Subnet Route Table Association resources, pretty descriptive.
Security
Security groups act as firewalls between inbound and outbound communications of the instances we run.
We need to create a security group shared by all containers running on Fargate and another one for allowing traffic between the load balancer and the containers.
The stack has one security group with two ingress (inbound traffic) rules:
- To allow traffic coming from the Application Load Balancer (PublicLoadBalancerSecurityGroup)
- To allow traffic between running containers (FargateContainerSecurityGroup)
Load Balancer
The Application Load Balancer (ALB) is the single point of contact for clients (users). Its function is to relay the request to the right running task (think of a task as an instance for now).
In our case all requests on port 80 are forwarded to nginx task.
To configure a load balancer we need to specify a listener and a target group. The listener is described through rules, where you can specify different targets to route to based on port or URL. The target group is the set of resources that would receive the routed requests from the ALB.
This target group will be managed by Fargate and every time a new instance of nginx spins up then it will register it automatically on this group, so we don’t have to worry about adding instances to the target group at all.
Automatically distribute incoming traffic across multiple targets using an Application Load Balancer.docs.aws.amazon.com
If a hosted zone got specified when running this stack, we create a subdomain on that zone and route it to the load balancer. For instance, say example.com. is specified as HostedZoneName, then all the traffic going to ecsfs.example.com would go to the load balancer.
Elastic Container Service (ECS)
ECS is a container management system. It basically removes the headache of having to setup and provision another management infrastructure such as Kubernetes or similar.
You define your application in ECS through task definitions, they act as blueprints which describe what containers to use, ports to open, what launch type to use (EC2 instances or Fargate), and what memory and CPU requirements are needed.
Then you got the service, which is in responsible for taking those tasks definitions to generate and manage running processes from them in a cluster. Those running processes instantiated by the service are called tasks.
Summarised:
— A cluster is a grouping of resources: services, task definitions, etc…
— On a task definition…
- … you can describe one or more containers for it to run.
- … you specify desired CPU and memory needed to run that process.
— A service takes a task definition and instantiates it into running tasks.
— Task definitions and services are configured per-cluster.
— Tasks run in a cluster.
— Auto-scaling is configured on the service-level.
Amazon Elastic Container Service (Amazon ECS) is a highly scalable, fast, container management service that makes it…docs.aws.amazon.com
Cluster
Logging
Write out logs from tasks within our cluster under the same group. There is one log stream per task running. An aggregated result can be viewed from the web console under the page for the service the task is part of.
IAM Roles
We need to allow Fargate to perform specific actions on our behalf.
- ECS Task Execution Role: This role enables AWS Fargate to pull container images from Amazon ECR and to forward logs to Amazon CloudWatch Logs.
- ECS Auto Scaling Role: Role needed to perform the scaling operations on our behalf, that is, to change the desired count of running tasks on the services.
With IAM roles for Amazon ECS tasks, you can specify an IAM role that can be used by the containers in a task…docs.aws.amazon.com
If you still get confused by the various roles to use on ECS Fargate I recommend reading the voted answer on here:
I am trying to set up a ECS but so far I have encountered a few permission issue for which I have created some…serverfault.com
Task Definitions
Service Discovery
In our application, we want the backend to be reachable at ecsfs-backend.local, the frontend at ecsfs-frontend.local, etc… You can see the names are suffixed with .local. In AWS we can create a PrivateDnsService resource and add services to them, and that would produce the aforementioned names, that is,
<service_name>.<private_dns_namespace>.
By creating various DNS names under the same namespace, services that get assigned those names can talk between them, i.e. the frontend talking to a backend, or nginx to the frontend.
The IP addresses for each service task are dynamic, they change, and sometimes more than task might be running for the same service… so… how do we associate the DNS name with the right task? 🤔 Well we don’t! Fargate does it all for us.
There is a whole section on the documentation explaining it in detail:
Your Amazon ECS service can optionally be configured to use Amazon ECS Service Discovery. Service discovery uses AWS…docs.aws.amazon.com
Services
The application load balancer routes the requests to the nginx service, therefore we need to wait for the ALB to be initialized before we can actually spin up the nginx service (DependsOn property).
Auto-Scaling
We are just interested in scaling the backend. For scaling a service you need to define a Scalable Target, which is where you specify what service do you want to scale, and a Scaling Policy, where you describe how and when do you want to scale it.
There’s two modes when scaling a service, we use Target Tracking Scaling, in which you specify a target value for a metric (say for instance 75% of CPU usage) and then Fargate would spin more instances when the average of all the tasks running that service exceed the threshold.
In our case we will scale the backend between 1 and 3 instances and we will specify a target CPU usage percentage of 50%.
Usually each service task spits out metrics every 1 minute. You can see these metrics on the CloudWatch page on the AWS web console. Use that for inspecting how Fargate reacts to changes when you stress the application.
Stressing Our Application
You can use the
ab unix command (Apache Benchmark) to send many requests to you application load balancer and see how Fargate starts scaling up the backend service.
First go to the web console under the EC2 page and look for the Load Balancers category.
In there look for the DNS name. You can also click the Outputs tab from the CloudFormation stack to see that URL. It should look like:
Then run the following command to stress the application. It will perform 10,000 requests (1 per second) printing all the responses.
ab -n 10000 -c 1 -v 3 http://<application_load_balancer_dns_name>/
I noticed that CloudWatch will wait until it has 3 consecutive measurements (metric points) exceeding the target value specified (50%). It is then when it then when it sets an alarm and Fargate reacts by adding extra running tasks until the metrics stabilize.
If then the CPU decreases and doesn’t need many tasks running anymore it would wait some minutes (around 15 metric points, that is, 15 min) to start scaling down.
Wrapping Up
What I expected readers to take out from this guide is not how to deploy services on Fargate but as a one more way to deploy them.
I also wrote that article for myself to come back at it if have to reproduce a similar structure, so I use this as some sort of skeleton or boilerplate. I wanted to share it with you in case it might serve the same purpose aforementioned.
I can think about three questions you might have after seeing this architecture case, let me answer them beforehand just in case 🙂.
Is the NAT really necessary?
For this particular case it is not, since if you stored your docker images in the Amazon ECR instead of Docker Hub you would not have the need to provide outbound interent access to the private tasks.
But if say for instance the frontend would perform requests to external APIs out there (like polling tweets from Twitter) then you would need the NAT.
NAT provides outbound traffic to your tasks retaining the isolation from the outside world so no one out there can initiate connections with them.
Why would you place the frontend on a private network?
It would make sense to have it in the public side, yes. I guess I would place it in a private subnet for two reasons:
- For security. So nobody messes with them directly.
- IPs are limited resources. In the future if I scaled frontend tasks to very high counts, each running task would have an IP if they sit on the public side.
Why bother with nginx, wouldn’t the load balancer do the job?
I guess in that case yes. I did it because it’s common in architectures and because nginx offers more features rather than just forwarding requests.
Similar Resources
I would like to link to Nathan Peck’s articles and specifically point you to the one that helped me get started as it’s very well written and informative. I built my project following his skeleton and expanded it for my particular case. | https://hackernoon.com/microservices-on-fargate-part2-f29c6d4d708f?source=rss----3a8144eabfe3---4 | CC-MAIN-2019-39 | refinedweb | 2,724 | 60.85 |
The Qt set up correctly & you can start creating your applications! The following examples are written for Python 3 with PyQt5, but can be easily adapted for other versions.
PyQt5 is not officially supported on Python 2.7, and trying to use it just makes things more difficult. If you *can * use Python 3 you should.
Creating an application
Below is a bare-minimum PyQt application, which actually doesn't even include a window. If you run it "nothing" will happen, but it should work.
import sys from PyQt5.QtWidgets import QApplication # You need one (and only one) QApplication instance per application. # Pass in sys.argv to allow command line arguments for your app. # If you know you won't use command line arguments QApplication([]) is fine. app = QApplication(sys.argv) # Start the event loop. app.exec_() # Your application won't reach here until you exit and the event # loop has stopped.
Stepping through the code line-by-line, we start by importing the PyQt5 classes that we need for the application,
from the
QtWidgets submodule.
Next we create an instance of
QApplication, passing in
sys.arg (which contains
command line arguments). This allows us to pass command line arguments to our
application. If you know you won't be accepting command line arguments you can
pass in an empty list instead, e.g.
app = QApplication([])
Finally, we call
app.exec_() to start up the event loop. If you watch the console while your application is running
you'll notice it does not reach the
print("Finished") until you exit the app. This is because Qt sits in the
app.exec_()
event loop until the application is quit.
If you need anything to happen during start-up it should be before this line. Usually a simple solution is to
handle setup during the
__init__ for your main window object.
Creating a window
The last example was pretty boring, because there was nothing to see. Let's add a window to our desktop application so we have something to look at. The code below is a bare-minimum single-window application in PyQt.
import sys from PyQt5.QtWidgets import QApplication, QWidget app = QApplication(sys.argv) window = QWidget() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec_()
Any
QWidget without a parent (containing widget) is it's own window. This is a fine way to create windows,
however there is also a specific
QMainWindow class. This has a few advantages for use as a main window in an
application including support for toolbars, status bars and dockable widgets. To use
QMainWindow just swap
it out in the code:
import sys from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication(sys.argv) window = QMainWindow() window.show() # IMPORTANT!!!!! Windows are hidden by default. # Start the event loop. app.exec_()
Running the above you should see an empty window on your desktop, the below is the appearance on Mac OS. Exciting isn't it?
Want to build your own apps?
Then you might enjoy this book! Create Simple GUI Applications with Python & Qt is my guide to building cross-platform GUI applications with Python. Work step by step from displaying your first window to building fully functional desktop software.
My first widget
So that was still pretty dull, just opening up an empty window on your desktop. Let's make it a little bit more
interesting by adding a basic text
QLabel widget. A
QMainWindow can only hold a single widget,
which you set via
.setCentralWidget().
If you want to add more widgets and arrange them, you need to use Qt layouts.
import sys from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow from PyQt5.QtCore import Qt # Subclass QMainWindow to customise your application's main window class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setWindowTitle("My Awesome App") label = QLabel("This is a PyQt5 window!") # The `Qt` namespace has a lot of attributes to customise # widgets. See: label.setAlignment(Qt.AlignCenter) # Set the central widget of the Window. Widget will expand # to take up all the space in the window by default. self.setCentralWidget(label) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec_()
When you run this you should see the window on your desktop as before, but this time also with the label from the
QLabel
visible in the middle. The window is resizeable by dragging the edges, and the alignment setting should keep the
text centered in the window.
| https://www.twobitarcade.net/article/create-first-window-pyqt5/ | CC-MAIN-2019-09 | refinedweb | 748 | 60.51 |
Lesson 1 - Introduction to Windows Forms applications
Welcome to the first lesson of the course, where we'll learn how to create form (window) applications in C# .NET and try using individual components. We'll work with buttons, text fields, tables, but also with images, timers and other controls available in these applications.
I wrote the course so that you don't need any advanced knowledge. I assume, however, that you know at least the basics of object-oriented programming.
Windows Forms
Windows Forms is the first framework from .NET that allows creating form applications easily using a graphic designer. We can find there a full set of ready-made controls (sometimes referred to as components) for most situations. And if we wouldn't be satisfied with them, we can of course create our own or modify an existing one. It's Windows Forms that we're going to focus on in this course.
Currently there's one more modern framework - WPF (Windows Presentation Foundation) along with WinForms. It separates logic and the user interface better, supports faster rendering, animations, bindings, and other new technologies. In practice, both frameworks are used to build form applications, newer applications use WPF, existing applications mostly use WinForms. Currently, WinForms isn't marked as obsolete and is still in use, its use is simple and you'll surely encounter many applications written in WinForms. So you should at least be aware of them, although it's certainly better to create new applications in WPF, which is technologically much further.
Our First Form Application
We won't start with anything other than the classic Hello World application,
this time in forms
If you
haven't read local course, let me repeat that it's a simple application that
does nothing but write some text.
Create a new project, select Windows Forms Application as the project type.
Type
HelloForms as the project name:
Your Visual Studio window should now look something like this:
Let's describe its individual parts, which we'll use to develop form applications. Important parts are highlighted in red in the image above.
- Designer - In the Designer we see what the form looks like. So far, it's just an empty window.
- Properties - In the Properties window, we can see the properties of the currently selected element on the form. If you don't see the window, enable it in View -> Properties Window.
- Toolbox - Toolbox is a sliding window that serves as a palette with individual controls that we can add to the form.
Setting control properties
When we select an element on the form or the form itself, we can change the properties of that element in the Properties window.
Since we got no element on the form, it's the form what is selected. We'll
change the title to
"Hello". Find the
Text property
and enter
Hello in it. The result is reflected in the designer
immediately. This way we'll set the properties of all elements on the form.
Adding Controls to the Form
Now we'll open the Toolbox and select the
Label control, which
is a text label. We'll insert it into the form either by double-clicking on it
or by dragging it. Reduce the form size and simply drag the label in the middle.
In the Properties window, set the label to
"Hello from forms".
As always, you can start your first window application with the green Play button or the F5 key. You should get a similar result:
Under the Hood
Let's explain how the application works inside. The form itself is of course
an object (how else
). It's
declared as the
Form1 class which we can find in the
Form1.cs file. Of course you can rename the file in Solution
Explorer, the class will also be renamed. For our application, the form could be
named
HelloForm, rename it so you can navigate in it better.
Visual Studio displays either a visual preview of the form or its source code. We can switch between these modes either by right-clicking on the form (resp. on the code) and selecting View Code (resp. View Designer). It's useful to know the keyboard shortcuts Shift + F7 to move to the designer and Ctrl + Alt + 0 to move to the code. It must be the zero on the alphanumeric keyboard (the left one).
Move to form code that looks like this (I omitted the initial
using statements):
namespace HelloForms { public partial class HelloForm : Form { public HelloForm() { InitializeComponent(); } } }
We can see that the form is a class inherited from the
Form
class. We can't see any trace of anything we added or set to the form, only the
constructor calls the strange
InitializeComponent() method.
The class is marked as
partial, meaning it's defined in multiple
files. Specifically, there's also a
HelloForm.Designer.cs file that
contains less readable code that is automatically generated by us clicking in
the designer.
This code is separated into another file on purpose, to make the form's
source code clear. Never tamper with the
Designer.cs file manually,
you even wouldn't have to know that it exists. But let's look at its content to
understand how the application works:
namespace HelloForms { partial class HelloForm { /// .SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(75, 32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(135, 17); this.label1.TabIndex = 0; this.label1.Text = "Hello from forms"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(282, 80); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Helloz"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; } }
In the code, we see the hidden
InitializeComponent() method,
which does nothing but create all the elements on the form one by one and set
the appropriate properties we've chosen. Here we can see how our label is
created and its properties set. The method is then called in the constructor to
initialize the form. An unaware programmer is then completely encapsulated from
the code that the designer generates. Of course, this is mainly to prevent them
from breaking it
However,
it's important to know how it works to be able to, for example, add controls at
runtime or fix errors in the designer file.
Today's project can be downloaded in the article's attachment, including the source code, and it'll always be like this. If you had any problems, you can easily find your mistake like this. In the next lesson, Simple Calculator in C# .NET Windows Forms, we'll explain how events work and program a simple calculator.
Download
Downloaded 0x (199.27 kB)
Application includes source codes in language C#
No one has commented yet - be the first! | https://www.ict.social/csharp/forms/winforms/introduction-to-windows-forms-applications | CC-MAIN-2020-05 | refinedweb | 1,152 | 58.18 |
I'm doing a practice problem where I have to decipher a certain string by moving each letter back two places in the alphabet, I also need to wrap it around if letter is the first or second letter of the alphabet. It works ok except when the letter is in the first or second position, it seems to decipher letter and print which is great though does it an additional time which is peculiar, I've been trying for many hours and still can't figure out small bug.
Here is my code:
import java.util.ArrayList; public class CCipher{ public static void main(String[]args){ System.out.println(decode("ABC", 1)); } public static String decode(String cipherText, int shift){ String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","X","Y","Z"}; ArrayList<String>cText = new ArrayList<String>(); String returnString = ""; //seperate individual letters and add them to arrayList for(int i = 0;i<cipherText.length();i++){ cText.add(cipherText.substring(i,i+1)); } //loop through no. of shifts needed for(int i=0;i<shift;i++){ //loop through arrayList for(String cTEXT: cText){ //loop through alphabet for(int j=0;j<alphabet.length;j++){ if(cTEXT.equals(alphabet[j])){ if(j<1){ cTEXT = alphabet[alphabet.length-2]; returnString += cTEXT; }else if(j<2){ cTEXT = alphabet[alphabet.length-1]; returnString += cTEXT; }else if(j>=2){ cTEXT = alphabet[j-2]; returnString += cTEXT; } } } } } return returnString; } }
--- Update ---
Sorry for not giving an example. e.g.If I input "CCC" I get "AAA" output which is great, though if I input "ACC" I get "YVAA" as output, the "Y" is a good thing though I can' understand why from "Y" it is shifted a further two places. | http://www.javaprogrammingforums.com/whats-wrong-my-code/33145-small-problem.html | CC-MAIN-2015-48 | refinedweb | 298 | 51.58 |
.Keysource
Bases: object
An immutable datastore key.
For flexibility and convenience, multiple constructor signatures are supported.
The primary way to construct a key is using positional arguments: - Key(kind1, id1, kind2, id2, …).
This is shorthand for either of the following two longer forms: - Key(pairs=[(kind1, id1), (kind2, id2), …]) - Key(flat=[kind1, id1, kind2, id2, …])
Either of the above constructor forms can additionally pass in another key using parent=<key>. The (kind, id) pairs of the parent key are inserted before the (kind, id) pairs passed explicitly.
You can also construct a Key from a ‘url-safe’ encoded string: - Key(urlsafe=<string>)
For esoteric purposes the following constructors exist: - Key(reference=<reference>) – passing in a low-level Reference object - Key(serialized=<string>) – passing in a serialized low-level Reference - Key(<dict>) – for unpickling, the same as Key(**<dict>)
The ‘url-safe’ string is really a websafe-base64-encoded serialized Reference, but it’s best to think of it as just an opaque unique string.
Additional constructor keyword arguments: - app=<string> – specify the application id - namespace=<string> – specify the namespace
If a Reference is passed (using one of reference, serialized or urlsafe), the args and namespace keywords must match what is already present in the Reference (after decoding if necessary). The parent keyword cannot be combined with a Reference in any form.
Keys are immutable, which means that a Key object cannot be modified once it has been created. This is enforced by the implementation as well as Python allows.
For access to the contents of a key, the following methods and operations are supported:
repr(key), str(key) – return a string representation resembling the shortest constructor form, omitting the app and namespace unless they differ from the default value.
key1 == key2, key1 != key2 – comparison for equality between Keys.
hash(key) – a hash value sufficient for storing Keys in a dict.
key.pairs() – a tuple of (kind, id) pairs.
key.flat() – a tuple of flattened kind and id values, i.e. (kind1, id1, kind2, id2, …).
key.app() – the application id.
key.id() – the string or integer id in the last (kind, id) pair, or None if the key is incomplete.
key.string_id() – the string id in the last (kind, id) pair, or None if the key has an integer id or is incomplete.
key.integer_id() – the integer id in the last (kind, id) pair, or None if the key has a string id or is incomplete.
key.namespace() – the namespace.
key.kind() – a shortcut for key.pairs()[-1][0].
key.parent() – a Key constructed from all but the last (kind, id) pairs.
key.urlsafe() – a websafe-base64-encoded serialized Reference.
key.serialized() – a serialized Reference.
key.reference() – a Reference object. The caller promises not to mutate it.
Keys also support interaction with the datastore; these methods are the only ones that engage in any kind of I/O activity. For Future objects, see the document for ndb/tasklets.py.
key.get() – return the entity for the Key.
key.get_async() – return a Future whose eventual result is the entity for the Key.
key.delete() – delete the entity for the Key.
key.delete_async() – asynchronously delete the entity for the Key.
Keys may be pickled.
Subclassing Key is best avoided; it would be hard to get right.
- delete_async(**ctx_options)source
Schedule deletion of the entity for this Key.
This returns a Future, whose result becomes available once the deletion is complete. If no such entity exists, a Future is still returned. In all cases the Future’s result is None (i.e. there is no way to tell whether the entity existed or not). | https://cloud.google.com/appengine/docs/standard/python/refdocs/google.appengine.ext.ndb.key?hl=zh-tw | CC-MAIN-2020-40 | refinedweb | 600 | 57.98 |
Created on 2016-06-14 18:52 by msapiro, last changed 2020-10-19 23:11 by miss-islington. This issue is now closed.
The attached file, bad_email, can be parsed via
msg = email.message_from_binary_file(open('bad_email', 'rb'))
but then msg.as_string() prodices the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/email/message.py", line 159, in as_string
g.flatten(self, unixfrom=unixfrom)
File "/usr/lib/python3.5/email/generator.py", line 115, in flatten
self._write(msg)
File "/usr/lib/python3.5/email/generator.py", line 189, in _write
msg.replace_header('content-transfer-encoding', munge_cte[0])
File "/usr/lib/python3.5/email/message.py", line 559, in replace_header
raise KeyError(_name)
KeyError: 'content-transfer-encoding'
One additional observation. The original message contained no Content-Transfer-Encoding header even though the message body was raw koi8-r characters. Adding
Content-Transfer-Encoding: 8bit
to the message headers avoids the issue, but that is not a practical solution as the message was Russian spam received by a Mailman list and the resultant KeyError caused problems in Mailman.
We can work on defending against this in Mailman, but I suggest that the munge_cte code in generator._write() avoid the documented possible KeyError raised by replace_header() by using __delitem__() and __setitem__() instead as in the attached generator.patch.
While I was reviewing I noticed the KeyError and it made me thing "hmm, I wonder if this should be turned into one of the email package errors"?
Any updates on this? I'm having the same problem with some non-spam emails while trying to use some mail-handling tools written in Python.
replace_header has a different semantic than del-and-set (replace_header leaves the header in the same location in the list, rather than appending it to the end...that's it's purpose). If replace_header is throwing a key error, then I guess we need a look-before-you-leap if statement.
And a test :)
Note that a correct fix would preserve the broken input email, but since we're obviously already doing munging I'm fine with just making this work for now.
I considered look before you leap, but I decided since we're munging the headers anyway, preserving their order is not that critical, but the patch is easy enough. I'll work on that and a test.
Fix:
Testcase:
Can start a PR once my CLA signature goes through I guess.
It looks like Johannes beat me to it. Thanks for that, but see my comments in the diff at
Ah, didn't even see your comment before I did it! Fix to the comments are on the same branch, will be rebased before PR is up.
maybe we could merge the PR, and I could propose a backport for 3.5 and 3.6.
2.7 is affected ?
I'm going to try to review this this weekend.
ok, I have tested on 3.6 and 3.5, just with the test. and in this case, we get the errors on both.
if we apply the patch of Johannes, the test passes and there is no issues.
+1 the backports for 3.5 and 3.6 is just a git cherry-picking.
Ping?
Note: I reviewed this a while ago but the review comments haven't been addressed.
Requested a small additional change to the new tests, and then this will be ready to go in.
Ping on an ETA for this fix?
@r.david.murray, it appears that all your requested changes have been addressed on the PR. Please re-review this when you get a chance. Thanks!
any chance of getting this merged? A work-around is not obvious
I work around it with
```
class Message(email.message.Message):
def as_string(self):
# Work around for and
#.
try:
value = email.message.Message.as_string(self)
except (KeyError, LookupError, UnicodeEncodeError):
value = email.message.Message.as_bytes(self).decode(
'ascii', 'replace')
# Also ensure no unicode surrogates in the returned string.
return email.utils._sanitize(value)
```
This is easy for me because it's Mailman which already subclasses email.message.Message for other reasons. It is perhaps more difficult if you aren't already subclassing email.message.Message for other purposes.
New changeset bf838227c35212709dc43b3c3c57f8e1655c1d24 by Mark Sapiro in branch 'master':
bpo-27321 Fix email.generator.py to not replace a non-existent header. (GH-18074)
New changeset 371146a3f8a989964e2a9c0efc7d776815410fac by Miss Skeleton (bot) in branch '3.8':
bpo-27321 Fix email.generator.py to not replace a non-existent header. (GH-18074)
New changeset 72ce82abcf9051b18a05350936de7ecab7306662 by Miss Skeleton (bot) in branch '3.9':
bpo-27321 Fix email.generator.py to not replace a non-existent header. (GH-18074) | https://bugs.python.org/issue27321 | CC-MAIN-2021-10 | refinedweb | 786 | 69.48 |
I have a large list of emails I am running through. A lot of the emails have typos. I am trying to build a string that will check valid emails.
this is what I have for regex.
def is_a_valid_email?(email)
end
hello.me_1@email.com # <~~ valid
foo.bar#gmail.co.uk # <~~~valid
f.o.o.b.a.r@gmail.com # <~~~valid
f...bar@gmail.com # <~~ not valid
get_at_m.e@gmail #<~~ valid
You seem to be complicating things a lot, I would simply use:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
which is taken from michael hartl's rails book
since this doesn't meet your dot requirement it can simply be ammended like so:
VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
As mentioned by CAustin, there are many other solutions. | https://codedump.io/share/Z9VjbiUscNJt/1/ruby-email-validation-with-regex | CC-MAIN-2017-13 | refinedweb | 140 | 88.53 |
On Mon, 23 Apr 2007, Andrew Morton wrote:> > OK. I hope. the mapping_gfp_mask() here will have come from bdget()'s> mapping_set_gfp_mask(&inode->i_data, GFP_USER); If anyone is accidentally> setting __GFP_HIGHMEM on a blockdev address_space we'll cause ghastly> explosions. Albeit ones which were well-deserved.I've not yet looked at the patch under discussion, but this remarkprompts me... a couple of days ago I got very worried by the varioushard-wired GFP_HIGHUSER allocations in mm/migrate.c and mm/mempolicy.c,and wondered how those would work out if someone has a blockdev mmap'ed.I tried to test it out before sending a patch, but found no problem atall: maybe I was too timid (fearing to corrupt my whole system), maybe I've forgotten how that stuff works and wasn't doing the right thingto reproduce it (I was mmap'ing /dev/sdb1 readonly, at the same timeas having it mounted as ext2 - when I forced migration to random pages,then cp'ed /dev/zero to reuse the old pages, I was expecting ext2 toget very upset with its metadata; mmap'ing while mounted isn't veryrealistic, but my earlier sequence hadn't shown any problem either,so I thought the cache got invalidated in between).Here's the patch I'd suggest adding if you believe there really isa problem there: it's far from ideal (I can imagine mapping_gfp_maskbeing used to enforce other restrictions, but the __GFP_HIGHMEM issueseems to be the only one in practice; and it would be a shame torestrict all the architectures which have no concept of HIGHMEM).If there's no such problem, sorry for wasting your time.(If vma->vm_file is non-NULL, we can be sure vma->vm_file->f_mappingis non-NULL, can't we? Some common code assumes that, some does not:I've avoided cargo-cult safety below, but don't let me make it unsafe.)Is there a problem with page migration to HIGHMEM, if pages weremapped from a GFP_USER block device? I failed to demonstrate anyproblem, but here's a quick fix if needed.Signed-off-by: Hugh Dickins <hugh@veritas.com>--- 2.6.21-rc7/include/linux/migrate.h 2007-03-07 13:08:59.000000000 +0000+++ linux/include/linux/migrate.h 2007-04-24 13:18:31.000000000 +0100@@ -2,6 +2,7 @@ #define _LINUX_MIGRATE_H #include <linux/mm.h>+#include <linux/pagemap.h> typedef struct page *new_page_t(struct page *, unsigned long private, int **); @@ -10,6 +11,13 @@ static inline int vma_migratable(struct { if (vma->vm_flags & (VM_IO|VM_HUGETLB|VM_PFNMAP|VM_RESERVED)) return 0;+#ifdef CONFIG_HIGHMEM+ if (vma->vm_file) {+ struct address_space *mapping = vma->vm_file->f_mapping;+ if (!(mapping_gfp_mask(mapping) & __GFP_HIGHMEM))+ return 0;+ }+#endif return 1; } -To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/4/24/187 | CC-MAIN-2014-52 | refinedweb | 474 | 54.02 |
Ulrich Drepper wrote:> I don't like special cases. For me things better come in quantities 0,> 1, and unlimited (well, reasonable high limit). Otherwise, who gets to> use that special namespace? The C library is not the only body of code> which would want to use descriptors.Valgrind could certainly make use of it. It currently reserves a set offds "high enough", and tries hard to hide them from apps, but/proc/self/fd makes it intractable in general (there was only so muchsimulation I was willing to do in Valgrind). J-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/5/30/421 | CC-MAIN-2013-20 | refinedweb | 121 | 65.83 |
Drag and Drop within a ListView or a Column
I wanted to create a simple list of buttons that the user can reorder by dragging them with the mouse. Looking at the drag and drop example with the GridView [1] I first tried to recreate it using a simple Column with a repeater and a model, but I never got it working. Since the example uses a view I then tried with ListView, here is what I ended up with:
import QtQuick 2.5 import QtQuick.Window 2.2 import QtQml.Models 2.2 Window { id: root visible: true width: 100 height: 200 DelegateModel { id: visualModel model: ListModel { id: model ListElement { name: "red"; value: "#f00" } ListElement { name: "green"; value: "#0f0" } ListElement { name: "blue"; value: "#00f" } } delegate: MouseArea { id: mouseArea property int visualIndex: DelegateModel.itemsIndex width: 80 height: 20 hoverEnabled: true drag.target: rect Rectangle { id: rect radius: 6 width: 78 height: 18 color: model.value Drag.active: mouseArea.drag.active Drag.source: mouseArea Drag.hotSpot.x: width / 2 Drag.hotSpot.y: height / 2 } DropArea { anchors { fill: parent } onEntered: { var from = drag.source.visualIndex var to = mouseArea.visualIndex console.log("From " + from + " to " + to) visualModel.items.move(from, to) } } } } ListView { id: list anchors { centerIn: parent fill: parent } interactive: false displaced: Transition { NumberAnimation { properties: "x,y"; easing.type: Easing.OutQuad } } model: visualModel } }
It works, but does not reposition the item dragged by the user after releasing the mouse button. So here are my two questions:
Is it possible to implement rearranging by drag and drop within a simple Column? If not what differs the different Views from the Row / Column items so that they can work with drag and drop?
I could not figure out why after releasing the rectangles are automatically repositioned in the grid in the Qt example: If you drag a rectangle just away from the others and not on another rectangle
onEnteredis called on the same Drop are to which the Rectangle belongs. This also happens in my code, but the Item does not get repositioned afterwards, why?
[1] | https://forum.qt.io/topic/62210/drag-and-drop-within-a-listview-or-a-column | CC-MAIN-2018-34 | refinedweb | 341 | 54.73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.