summary
stringlengths
15
147
text
stringlengths
1
19.3k
answer
stringlengths
32
22.6k
labels
float64
0.33
1
answer_summary
stringlengths
5
164
Help understanding an egrep expression
I stumbled across the following egrep expression: egrep '^([^aieou]*[aieou]){5,7}[^aieou]*$' /usr/share/dict/words on this page: http://matt.might.net/articles/sculpting-text The expression is supposed to find the words that contain between 5 and 7 vowels. I understand the first ^ meaning from the beginning of the line and the second ^ to negate any of the aieou followed by any number of characters and one of the aeiou between 5 and 7 times. But I did not get how the first and last expressions: [^aieou] help here?
It looks for zero or more consonants ([^aieou]*) followed by 5 to 7 vowels (([aieou]){5,7}) followed by zero or more consonants ([^aieou]*). The entire regular expression is anchored to the beginning of the line (^) and the ending, ($). Example $ egrep '^([^aieou]*[aieou]){5,7}[^aieou]*$' \ /usr/share/dict/words | head -10 abacinate abacination abacterial abaisance abalation abalienate abalienated abalienating abalienation abandonable Details So when it matches say this first word, abacinate, the first letter a has 0 consonants to the left, so we match that part. As additional vowels with either zero or more consonants are found on the left and/or right, we match those situations too. If we find 5 to 7 of them, then we match.
0.888889
The entire regular expression is anchored to the beginning of the line and the ending, ($).
How to upload to WebDAV using a web browser?
I've setup and configured webdav on debian using the following tutorial: http://www.unix-tutorials.com/go.php?id=3711 I want to be able to download and upload files to the webdav share using a web browser. I can download and upload files to the webdav share if I mount it to my file system but we don't want the other people accessing this to have to do that. We want people to be able to go to the URL in their web browser, authenticate, and do everything, download, upload in their browser. When I go to the webdav URL in my browser and authenticate I'm given a list of the webdav share's contents and I can download the files but I don't see any way to upload files? How can I upload files to the webdav share using a web browser? Thanks in advance.
You don't say which browser. I thought it was built-in with Internet Explorer by simply using drag-and-drop. I seem to recall a Firefox add-on. I am looking for it now. Edit: Webfolders is a firefox extension that gives you the ability to view the contents of WebDAV servers in the browser and use the full functionality of the WebDAV protocol. webfolder add-on for Firefox
0.777778
Firefox add-on for Firefox
Is potential energy and "work done" the same thing?
Is potential energy and "work done" the same thing? If they are not one and the same thing then why is potential energy always associated with "work done"? Could you explain me with some examples?
Potential energy and work done are the same thing as much as kinetic energy and work done are the same thing. Potential energy is a state of the system, a way of storing energy as of virtue of its configuration or motion, while work done in most cases is a way of chaning this energy from one body to another. For ex when a body is dropped from a height, its gravitational energy a virtue of its configuration with respect to the earth is converted into kinetic energy a virtue of its motion, due to the work done by gravity in bringing it down.
1
Potential energy is a state of the system, a way of storing energy from one body to another
form save progress indication
In our app, when you save/submit a form, two things happen submit button greys out(becomes disabled) there's a progress bar running at the top of the page(similar to medium.com), which is an indicator used across the app for an ongoing action(not limited only to saving forms, since it's an SPA app) Do you think it's clear enough for the user that things are being saved, or it would be better to add a loader directly associated with the form(inside the button for example)? Here's what it looks like at the moment. https://youtu.be/xzc7P8R751M
In my opinion, When user submits form by clicking 'Submit button' instead of making that button disabled, show the 'progress bar' in that button. This will not break user's focus and attention.
0.666667
When user submits form by clicking 'Submit button', show 'progress bar'
rsync partial LVM volume to Remote Directory
Can I rsync a full hdd partition (which is inaccessible) to a remote directory? Inaccessible means it cannot be mounted, it was part of LV volume merged with other HDD which is faulty and removed from the server. I tried to mount it but not working unknown filesystem type 'LVM2_member' so I'm using rsync to mount it on remote desktop. Advise me what's the best solution? rsync -avz /dev/sda1 user@ip:/backup/ I want to copy all files and directories of /dev/sda1 to remote device at the directory backup.
You can do dd if=/dev/sda of=back.sda bs=10M You can increase or reduce the bs(block size) based on your i/o capacity(fast increase,slow decrease),then copy the back.sda with scp or rsync on backup. Later you can mount the image and recovery the files,this will work if sda is not broken disk,if is corrupted you can try a fsck. Rsync works for files,i have never tried on block device but i think rsync sda copy only the sda block file(size 0) on remote backup If the problem is unavaliable partition, you will resolve nothing with rsync,you must use kpartx,search google for kpartx lvm Or try this pvscan vgscan vgchange -ay See the output and mount the volume
1
dd if=/dev/sda of=back bs=10M
gradle execute task after build
I am using the build in gradle. My build.gradle file like this: project('a'){ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'application' buildDir = 'build' [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' repositories { mavenCentral() } dependencies { compile 'org.slf4j:slf4j-api:1.7.7' } } When I input the gradle build in the command, I want gradle execute task after build. I found a mustRunAfter on the Internet. I have tried a variety of ways but failed. Please tell me if you know how.
What you need is finalizedBy, see the following script: apply plugin: 'java' task finalize << { println('finally!') } build.finalizedBy(finalize) Here are the docs.
1
What you need is finalizedBy
php escape sequence not working
I just want to echo out some text on the webpage display with a tab space before a word. I have the following codes in php: <?php echo "\t\t hello!<br>"; echo "\t\t", "hello!<br>"; echo "\t\t"."hello!<br>"; ?> I tried all sorts of combinations, but it just won't show the tab spacing before the word. OUTPUT: hello! hello! hello! I visited some links like: Newline escape sequence not working on php but I am not echoing it from a function. I just simply want to echo it out from a .php file.
Try This: <pre><?php echo "\t\t hello!<br>"; echo "\t\t", "hello!<br>"; echo "\t\t"."hello!<br>"; ?></pre> I would say you are probably viewing the generated page (html) rather than the page source.
1
tt hello!
Scrabble variation: use double and triple word scores (but not double/triple letter scores) twice?
Is there a popular Scrabble variation that: lets you play double/triple word scores twice, once vertically and once horizontally? does NOT let you play double/triple letter scores twice? This is how I've always played, so it surprised me to learn that official Scrabble rules do NOT permit using double/triple word scores twice. Perhaps this was true in an older version of Scrabble (I started playing in the 70s).
I searched Changes to the Box Top Rules, 1949 - 1999 and found the following clarification was made in 1953: 1953: If a word is formed that covers two premium WORD squares, the score is doubled and then re-doubled (4 times letter count), or tripled and then re-tripled (9 times letter count) as the case may be. Nowhere in the rules was there any mention of being able to use the same premium square twice. The Diamond Anniversary Edition rules includes some interesting variations, but does not mention your scoring rules. Personally, I would find your scoring variation confusing and prone to error, since Scrabble tiles are not transparent, and therefore a novice may have trouble realizing that they are reusing a premium word square.
1
The Diamond Anniversary Edition rules include some interesting variations .
AD via LDAP - How can I return all ancestor groups from a query?
I am querying Active Directory via LDAP (from Java and PHP) to build a list of all groups that a user is a member of. This list must contain all least all groups (organizational-units optional) that contain groups the user is directly a member of. For example: User1 is a member of GroupA, GroupB, and GroupC. GroupA is a member of GroupD. I am looking for a way to construct an LDAP query that will return GroupA, GroupB, GroupC, and GroupD all at once. My current implementation is below, but I am looking for a more efficient way to gather this information. Current Naive Implementation (In pseudo-code) user = ldap_search('samaccountname=johndoe', baseDN); allGroups = array(); foreach (user.getAttribute('memberOf') as groupDN) { allGroups.push(groupDN); allGroups = allGroups.merge(getAncestorGroups(groupDN)); } function getAncestorGroups(groupDN) { allGroups = array(); group = ldap_lookup(groupDN); parents = group.getAttribute('memberOf'); foreach (parents as groupDN) { allGroups.push(groupDN); allGroups = allGroups.merge(getAncestorGroups(groupDN)); } return allGroups; }
You need to map the directory tree, as you move through it, so you can check to see if you have previously explored a DN, some Active Directories contain looped group inclusions. So you'll need to guard against it. This solution also doesn't require recursion. In some pseudo code def getGroupsOfDN(userDN) groups = [] groupsExplored = [] groupsToExplore = [] current = userDN groupsToExplore << userDN while(!groupsToExplore.empty?) ldapentry = ldap_lookup(current) if (!ldapentry.nil?) groups << current current_groups = ldapentry.getAttributes("memberOf") current_groups.each do |groupDN| if(groupsExplored.indexOf(groupDN) != -1) groupsToExplore << groupDN groupsExplored << groupDN end end end groupsToExplore.remove(current) if (!groupsToExplore.empty?) current = groupsToExplore.get(0) end return groups end
1
How to map a directory tree?
ip2nation - don't understand how the ip value is stored
The ip2nation table stores ip values like such: IP COUNTRY 687865856 za 689963008 eg How does this translate into an actual IP address block range?
Just look at the Sample Scripts: SELECT c.country FROM ip2nationCountries c, ip2nation i WHERE i.ip < INET_ATON("'.$_SERVER['REMOTE_ADDR'].'") AND c.code = i.country ORDER BY i.ip DESC LIMIT 0,1
0.888889
SELECT c.country FROM ip2nationCountries
Securely Connecting to SQL Azure
According to this page, All communications between Microsoft Azure SQL Database and your application require encryption (SSL) at all times. If this is the case, what is the difference between using the standard connection string of: server.database.windows.net and requiring security and using the "Secure Connection String" of: server.database.secure.windows.net
The link you posted talks about validating the SSL Certificates used to make the Sql Connection to validate that a "man in the middle" attack cannot get your Sql UserName/Password. http://en.wikipedia.org/wiki/Man-in-the-middle_attack It is your application that needs to validate the SSL Certificate to validate it is coming from SqlAzure. I don't see how changing the hostname and not requiring security will keep you safe.
1
Sql Connection Validating SSL Certificates
Are scientifically detached professors referred to as ‘clinical’?
I have come across this term fairly often, where full/associate/assistant professors are referred to by the term ‘clinical’. Given that their departments had nothing to do with medicine, I thought the term referred to the second meaning of clinical: scientifically detached; strictly objective Is this interpretation correct? If yes, isn’t such a branding offensive?
There can be clinical professors in fields other than medicine, though they may be labeled something else. The definition of a "clinical professor" is not limited to medicine: "The prefix Clinical identifies appointments that primarily provide practical instruction and application of practical knowledge. On the Medical Campus, the title describes faculty whose primary activity is limited to clinical or public health practice and associated teaching. The duties, terms of appointment, and salaries (if any) of such persons are specified in the letter of appointment. In general, the applicable rank and any subsequent promotions should be determined by the relevant academic achievements, professional accomplishments, and demonstrated effectiveness of the appointee." (Boston University faculty handbook) So, though I don't know much about engineering, I imagine that a professional from an engineering firm that specializes in a particular process could be hired as a clinical professor. S/he would teach about the particular niche they occupy in the industry.
1
Clinical professors can be labeled "clinical professors"
Why is it best to use a prime number as a mod in a hashing function?
If I have a list of key values from 1 to 100 and I want to organize them in an array of 11 buckets, I've been taught to form a mod function $$ H = k \bmod \ 11$$ Now all the values will be placed one after another in 9 rows. For example, in the first bucket there will be $0, 11, 22 \dots$. In the second, there will be $1, 12, 23 \dots$ etc. Let's say I decided to be a bad boy and use a non-prime as my hashing function - take 12. Using the Hashing function $$ H = k \bmod \ 12$$ would result in a hash table with values $0, 12, 24 \dots $ in the first bucket, $1, 13, 25 \dots$ etc. in the second and so on. Essentially they are the same thing. I didn't reduce collisions and I didn't spread things out any better by using the prime number hash code and I can't see how it is ever beneficial.
Whether a collision is less likely using primes depends on the distribution of your keys. If many of your keys have the form $a+k\cdot b$ and your hash function is $H(n)=n \bmod m$, then these keys go to a small subset of the buckets iff $b$ divides $n$. So you should minimize the number of such $b$, which can be achieved by choosing a prime. If on the other hand you like to have $11$ to $12$ buckets and you know that differences which are multiples of $11$ are more likely than differences which are multiples of $2$ and $3$, you may choose $12$ for your very special application.
1
Whether collision is less likely using primes depends on the distribution of your keys
Why is it best to use a prime number as a mod in a hashing function?
If I have a list of key values from 1 to 100 and I want to organize them in an array of 11 buckets, I've been taught to form a mod function $$ H = k \bmod \ 11$$ Now all the values will be placed one after another in 9 rows. For example, in the first bucket there will be $0, 11, 22 \dots$. In the second, there will be $1, 12, 23 \dots$ etc. Let's say I decided to be a bad boy and use a non-prime as my hashing function - take 12. Using the Hashing function $$ H = k \bmod \ 12$$ would result in a hash table with values $0, 12, 24 \dots $ in the first bucket, $1, 13, 25 \dots$ etc. in the second and so on. Essentially they are the same thing. I didn't reduce collisions and I didn't spread things out any better by using the prime number hash code and I can't see how it is ever beneficial.
If your hash function is of the form $h(k)=a\times k \mod m$ where $m$ is prime and $a$ is chosen at random, then the probability that 2 distinct keys hash to the same bucket is $1\over m$. So for $m=1009$, $Pr\{h(x)=h(y), x\neq y\}=0.00099108027$ which is very small. This scheme is known as: Universal Hashing.
0.666667
Hash function of the form $h(k)=atimes k mod m$
"wouldn't" vs. "won't" & "couldn't" vs "can't"
If we were talking about the importance of energy and that even machines need it what should we say? What's the difference between these two sentences: Machines wouldn't work without energy & Machines won't work without energy and between: Machines couldn't work without energy & Machines can't work without energy
As other answers have said the first sentence sounds hypothetical. The reason this statement is hypothetical is that the machines being talked about do have energy. With context it might read: Of course, all machines are either connected to an electricity supply or powered by some other energy source. Machines wouldn't work without energy. The second sentence could either be talking about the future or a present 'habit'. Assuming the idea is to describe a habit that machines have, with context it might read: It is common to see machines connected to some kind of power source: Machines won't work without energy. The third sentence is quite similar to the first, this time the emphasis being on hypothetical capability. Machines can function but they only have this capability because of energy. Machines are capable of performing amazing tasks but of course they need a power source. Machines couldn't work without energy. The final statement is one of fact about machines' capabilities - true now, true in the past, true always. It is impossible for machines to operate unconnected to a power supply: Machines can't work without energy.
1
The first sentence sounds hypothetical
Is it ethical to profit by having my students buy my textbook?
This question was suggested to me by How can I sell my text book to my students in e-book format? which asked about the practicalities, but attracted many comments about the ethics. So this question is to ask about the ethics directly. Suppose I have written and published a textbook, and I want to use it as the text for a course I am teaching. I receive royalties from each copy of my book that is sold, so if my students are required to buy my textbook for the course, I will make some money. Is it ethical to do so? Well-reasoned opinions would be useful answers, but even more useful would be pointers to institutional policies, professional codes of ethics, etc, that address this issue. Of course, there are many ways to avoid profiting from the sale of my book to my students. If my contract with my publisher allows it, I could distribute PDFs to my students, or have the university bookstore print out copies and sell them at cost. Another approach I've heard of is to compute how much I earn in royalties on each copy, and refund that amount from my pocket to each student who buys a copy. Or, use my royalty earnings to buy pizza for the class. Certainly these are nice gestures, but I would like opinions on whether they are ethically required. Edit: To address some questions that have arisen in the comments: This question is hypothetical. I haven't published any textbooks myself and have no immediate plans to do so. In any case, my personal preference would be to make the book available to students for free, if at all possible. So I've phrased this question in the first person for rhetorical convenience only. I had intended the question to be only about the potential financial conflict of interest that could arise if I make money by assigning my own book. Some of the answers feel that it is improper for me to assign my own textbook at all, whether I make money or not, but I don't think this point of view is prevalent within the academic community. If it happens that my book (as a pithy but now-deleted comment put it) "blows", I think most would agree that my decision to assign it is pedagogically unfortunate, but not unethical. I don't literally mean that students would be required to buy the book, only that they'd be expected to have it. I might assign readings or homework problems from the book, so that the student needs access to the book in order to do them, but they could certainly achieve this by getting a used copy or borrowing from a friend. But probably most students would buy new copies anyway, since that is the most convenient way.
Unethical I think it is unethical to profit by having students buy your textbook because you're their lecturer and they expect you to inform them and provide them with some useful resources for learning. The students also usually get a bad feeling when you keep recommending your book unless it was vote one of the best to use in tackling the given subject. I don't know/understand how you may be able to provide other books to your students at no cost while you provide your book at a cost. It looks fishy. If you feel that you can't give each student a copy of the book then you can recommend the university to buy the books so as to restock the library or you can offer your own copy or a single donated copy strictly for class use. This depends on the number of students you're dealing with and how often they have to use the book. Ethical In a case where you had published the book before meeting the students, you're allowed to sell the book to them at the market price or you may subsidize it for your students. Logic Its always difficult to teach using your book especially when you reach a point where there are few discrepancy from other books. In the process of defending your ideas from the book, you may end up being seen as superior, dictator, rigid etc.
1
Unethical I think it is unethical to profit by having students buy your textbook .
Permissions required to alter a database file
Totally at the beginning in administering a database. Using EMS SQL Manager ... latest version. How do I over come below ALTER DATABASE joneslocker2 MODIFY FILE ( NAME = joneslocker2, MAXSIZE = UNLIMITED ) GO which results in an error: User does not have permission to alter database 'joneslocker2', the database does not exist, or the database is not in a state that allows access checks. I don't have a clue what to set next.
You need to GRANT ALTER DATABASE permission to the user. GRANT ALTER ON DATABASE:: joneslocker2 TO username Below script will help you to find what permissions are assigned at the database level : SELECT prin.[name] [User], sec.state_desc + ' ' + sec.permission_name [Permission] FROM [sys].[database_permissions] sec JOIN [sys].[database_principals] prin ON sec.[grantee_principal_id] = prin.[principal_id] WHERE sec.class = 0 ORDER BY [User], [Permission]; Check my answer here for an example on why you are getting the error. Refer to : Database Engine Permission Basics
0.555556
GRANT ALTER ON DATABASE: joneslocker
How do I map a key into the shift key in Windows? (see picture of Canadian French keyboard)
As luck would have it, my computer dealer shipped me a laptop with a Canadian French keyboard instead of a US keyboard Instead of saying how much Canadians from sea to sea hate this keyboard layout and hate being transitioned into it in the last couple of years, I'd like to ask for a software solution. Is there a software that can map the [>>/<<] key to [Shift] and the [> < }] to [Enter], et cetera? +1 if you can suggest how to type the "\". -1 if you suggest, 'Just order a US keyboard. Replacing it takes a minute.' :)
You might check out the question I asked earlier about key mapping. I put up a tut there for how to assign keys using the registry and another user, Yosh, put a link to some software that will do this for you. I've never tried this on a french keyboard before but if you decide to do it manually, this hex key should map '\' to alt+1 00,00,00,00,00,00,00,00,3,00,00,00,2B,00,78,00,78,00,2B,00,00,00,00,00
1
How to assign keys using the registry
Would it be possible to show line numbers as part of the pdf document
Would it be possible to show line numbers as part of the pdf document. What option should I use?
I've found the following answer regarding your question. According to the second paragraph, it's almost impossible to do what you want. Answer by user grantm on perlmonks.org: It may be possible - it depends on how the PDF was generated. If the option was used to convert text to curves then you're probably out of luck. Also the PDF file format has no concept of 'lines'. Characters in a particular font family, weight, size (etc) are placed at X/Y coordinates on the page. They can be placed in any order (ie: not just left-right, top to bottom). So if it were possible, one approach would be to find the y coordinate of every piece of text on the page; reduce that to a unique set; sort them and assign line numbers; go down and add the line numbers as text elements at the same y coordinate on the right hand side of the page. For the first part, you might find that the CAM::PDF module has some useful tools (eg: it can render just the text elements of a PDF page). Overlaying new text elements is the easy part. I tend to use PDF::Reuse but I'm sure that PDF::API2 could be used too.
1
PDF file format has no concept of 'lines'
Is my session-less authentication system secure?
So, I've created an authentication system. Poured over it for any kind of security flaws and tested the crap out of it. I think it's fairly secure, but there is one "different" by-design aspect of it that's not usual of a web authentication system. Basically, I wanted to make it so that authentication could be done without keeping track of each user's session. This means less load on the database, and trivial to scale and cache. Here are the "secrets" kept by the server: A private-key is kept in the source code of the application A randomly generated salt is kept for each user To make it sessionless, but making forging cookies not easy, this is the format of my cookies expires=expiretimestamp secret=hash(privatekey + otherinfo + username + hashedpassword + expires) username=username (with otherinfo being things like IP address, browser info, etc and with hashedpassword=hash(username + salt + password + privatekey) My understanding is that forging login cookies (not cracking the passwords) requires: Source code access to the application, or a way to trick it to spit out the private key Read-only access to the database to get the salt and hashedpassword Whereas the traditional session method requires: Write and read access to the database (to inject the session, or trick the web app into doing it for you) Possibly source code access depending on how it works Anyway, does this seem overly insecure to anyone? Are there any ways for me to improve on it and make it more secure(while keeping with the stateless/sessionless model)? Are there any existing authentication systems which use this stateless model? Also, the hashing method can be basically anything, ranging from SHA256 to Blowfish
Your basic concept is not new: you want to have some state associated with the user, but you do not want to store that state yourself. Instead, you store it on the client (in a cookie). Since you want to protect against alterations of such a state (e.g. a client building a cookie from scratch), you need an integrity check, such as a Message Authentication Code. Your construction with a hash function is a crude MAC. It so happens that it is a weak MAC with the usual hash functions, because of the length extension attack. If you want a MAC, use a strong one, and that means HMAC. It is standard and widespread. Of course, storage of the secret key (for MAC computations) is a tricky point. Something embedded in the "source code" of the application exists as a file, which (by nature) the application can read, making it vulnerable to exploits which obtain illegal read access to arbitrary files. It would be better (but harder) to arrange for the MAC key to be obtained dynamically by the application through some local communication protocol (the application contacts a local server, which gives the key only to the application); that way, the key would only exist in the RAM of the application, not as a file readable with the access rights of the application. It would not be absolute protection (if your server gets thoroughly hacked, well, that's it) but it would be stronger in practice. I see that you include the hashed password in the data which is MACed. This is a bit weird; you already have the MAC as authentication: the MAC proves that the cookie data is genuine, thus there is no need for further authentication. Blowfish is not a hash function; it is a block cipher (or a type of fish) and, as such, cannot be used for hashing unless it is considerably modified, which would mean homemade cryptography, and that's not a good idea. If you are offloading state on the client, you might want to offload state which the client himself should not know. This means that you may also need encryption. Combining encryption and MAC securely is not as easy as it seems; there are modes for that. I recommend EAX. Be warned that not maintaining state makes you inherently weak against replay attacks. That's unavoidable. You can minimize the damage by using short validity ranges (e.g. a cookie expires within 15 minutes).
0.666667
How to store a MAC on a client?
awk - Group by and sum column values
I have command to list system process by memory usage: ps -A --sort -rss -o comm,pmem Which list a table like COMMAND %MEM firefox 28.2 chrome 5.4 compiz 4.8 atom 2.5 chrome 2.3 Xorg 2.3 skype 2.2 chrome 2.0 chrome 1.9 atom 1.9 nautilus 1.8 hud-service 1.5 evince 1.3 I would like to get total memory share per programs instead of per process of same programs. So I could get output like COMMAND %MEM firefox 28.2 chrome 11.6 compiz 4.8 atom 4.4 Xorg 2.3 skype 2.2 nautilus 1.8 hud-service 1.5 evince 1.3 I thought about using awk, which I don't know much. Ended up with something like: ps -A --sort -rss -o comm,pmem | awk -F "\t" ' {processes[$0] += $1;} {End for(i in processes) { print i,"\t",processes[i]; } }' But it didn't work. How can I correct this?
cuonglm answer solves your typo, to get the values in ascending order (as asked in your comment), pipe the output through sort -n -k 2 (sort as numbers (-n, on second field (-k 2), after changing the print statement to output the floats as in your example: $ ps -A --sort -rss -o comm,pmem | awk ' NR == 1 { print; next } { a[$1] += $2 } END { for (i in a) { printf "%-15s\t%.1f\n", i, a[i]; } } ' | sed 's/%MEM/-1MEM/' | sort -n -k 2 | sed 's/-1MEM/%MEM/' Output (using your table as input instead of doing ps on my system): COMMAND %MEM evince 1.3 hud-service 1.5 nautilus 1.8 skype 2.2 Xorg 2.3 atom 4.4 compiz 4.8 chrome 11.6 firefox 28.2 Alternatively you can pipe the output through this python program (if you want descending sort (as in your example), change the reverse=False into reverse=True: #! /usr/bin/env python # coding: utf-8 import sys import operator d = {} for line in sys.stdin: try: name, val = line.split() val = float(val) d.setdefault(name, [0.0])[0] += val except ValueError: print line, for x in sorted(d.items(), reverse=False, key=operator.itemgetter(1)): print "{:16s}{:>4}".format(x[0], x[1][0])
0.888889
Pipe the output through sort -n -k 2
What are the uses for a roasting pan? Do I really need a roasting pan?
We registered for a roasting pan and it has been sitting around taking up a lot of space. Do I really need this or is this a "one-tasker" as Alton Brown would say? I understand that the roasting rack allows the juices to drip down. I've had lots of success roasting chickens just in a baking pan with 2" high sides.
I use my roasting pan (either with or without a rack) at least once a week to roast vegetables - either for salads, for sides, or (for instance with pumpkin for soup) to get a slightly different and more concentrated flavour before blending the veges. I find the vegetables cook more evenly in a roasting pan than a baking pan - perhaps the higher sides help to create a kind of microclimate around the veges?? Not sure about that one. When making roast vege salads, you can take the pan straight out of the oven and take advantage of the high sides to mix your other ingredients in (pasta, greens, dressing etc) then serve from there if no one is looking at your serving dish! I also use it as a water bath when cooking souffles, puddings etc.
1
Roast vegetables in a roasting pan?
How to reverse the direction of marquee of a TextView
I want to reverse the direction of marquee in the TextView. By default, the text moves from Right to Left, I want it to move from Left to Right. How can I do this?
Here is the solution : Set this in layout file : <TextView android:id="@+id/textId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#337700" android:textSize="20px" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:singleLine="true" android:textStyle="bold" android:text="Download Form for Different Vehiecle Purposes ....!!!"> </TextView> And set this in activity : tv = (TextView) findViewById(R.id.textId); tv.setSelected(true); In My case this is moving text from right to left.
1
Set this in activity : tv
Where are the fishing spots surrounded by rocks etc, and do they actually increase the chances of catching fish?
While talking to the fisher guy in the fishing hut he told me the best place to fish was in small places surrounded be rocks or wall. Is this true? If so, where are theses places in the game? Is there anything else that helps to catch more fish? For example, I have noticed that fishing next to a fisherman seems to have a higher chance of catching something. is this correct, and what else helps with fishing?
Yes, fishing in a small tile of water walled off by shore and/or rocks on three of the 4 sides decreases the chance of "Nothing seems to be biting..." message. This does not reduce the chances of not catching anything to 0, but it is considerably better than it is otherwise. However, if you are chain-fishing for shiny Pokemon, your best bet is is to have your lead Pokemon have the ability Suction Cups or Sticky Hold. If the Pokemon you've chosen for the task is under-leveled compared to what you are fishing, having it hold something like a smoke ball will allow you to flee from the hordes of non-shinies without fail. For more information on how chain-fishing works (specifically what will and will not break the chain) see this question/answer; How does chain fishing work?
0.888889
How does chain-fishing work?
Using video ports 'backwards'
If I want to connect my laptop, which has a VGA output, to a monitor, I plug a VGA cable into both ends. The output being my laptop, and the input the monitor VGA output sockets are the same as VGA input sockets however, so what if I want to use my laptop as the monitor, with the video being outputted from somewhere else? As I said, VGA's output is the same as input, so in theory, I have the hardware in my laptop to do this. But presumably I need some software. So can I use the VGA port on a laptop as a video input? (And also, can this be done with HDMI?)
Your video adapter is an output device. just because the ports are the same/similar doesn't automatically mean they are wired, or work the same. If you want video in, you need a video capture adapter.
1
Video capture adapter is output device
Character values bounded away from zero
Character values for a finite group are sums of nth roots of unity. I'm wondering if there are any results bounding nonzero values of irreducible characters away from zero. Or if not are there examples of natural sequences of groups where entries in the character table can be made arbitrarily close zero. I don't see anything like this in Isaacs book for example. Added: Thanks for the answers below, I of course should have figured out the direct product once you have one of norm <1. I guess the problem is more interesting for simple groups, for example the alternating groups the nonzero values are bounded away from zero.
The dihedral group $D_{2n}$ has two dimensional irreducible representations for which the character values (on the cyclic group of order $n$) are $2\cos(2\pi k/n)$ for $1\le k\le n$. Clearly these values get arbitrarily close to zero for large $n$ and $k$ close to $n/4$. See for example http://groupprops.subwiki.org/wiki/Linear_representation_theory_of_dihedral_groups .
0.666667
The dihedral group $D_2n$ has two dimensional irreducible representations for which the character values are
hadoop complains about attempting to overwrite nonempty destination directory
I'm following Rasesh Mori's instructions to install Hadoop on a multinode cluster, and have gotten to the point where jps shows the various nodes are up and running. I can copy files into hdfs; I did so with $HADOOP_HOME/bin/hdfs dfs -put ~/in /in and then tried to run the wordcount example program on it with $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.0.jar wordcount /in /out but I get the error 15/06/16 00:59:53 INFO mapreduce.Job: Task Id : attempt_1434414924941_0004_m_000000_0, Status : FAILED Rename cannot overwrite non empty destination directory /home/hduser/hadoop-2.6.0/nm-local-dir/usercache/hduser/appcache/application_1434414924941_0004/filecache/10 java.io.IOException: Rename cannot overwrite non empty destination directory /home/hduser/hadoop-2.6.0/nm-local-dir/usercache/hduser/appcache/application_1434414924941_0004/filecache/10 at org.apache.hadoop.fs.AbstractFileSystem.renameInternal(AbstractFileSystem.java:716) at org.apache.hadoop.fs.FilterFs.renameInternal(FilterFs.java:228) at org.apache.hadoop.fs.AbstractFileSystem.rename(AbstractFileSystem.java:659) at org.apache.hadoop.fs.FileContext.rename(FileContext.java:909) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:364) at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:60) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) How can I fix this?
This is a bug in Hadoop 2.6.0. It's been marked as fixed but it still happens occasionally (see: https://issues.apache.org/jira/browse/YARN-2624). Clearing out the appcache directory and restarting the YARN daemons should most likely fix this.
0.777778
This bug in Hadoop 2.6.0
How can I reliably make myself a cup of coffee in my hotel room that doesn't suck?
Like most people, I have a habit, and that habit is Coffee. Unfortunately, this can be an expensive habit. There are plenty of methods of making it less expensive, but in my experience, most of them are pretty bulky and not conducive to being carried around the country. Others are more portable, but taste dire (looking at you instant coffee, cheap cup from a gas station, etc...) Assuming the coffee maker in a given hotel room isn't capable of doing anything besides producing hot water competently, how can I make myself a decent cuppa, easily, cheaply, and effectively? What sort of equipment would I want to look into buying or using to do this? Cost effectiveness and ease of use is as important as portability/quality here. I'm open to cold-brew solutions, though hot coffee is definitely preferred. As far as resources that can be assumed: Hot water and tap water is 90% of what can be relied upon. A fridge or microwave is occasionally present, but I wouldn't count on either.
You can buy an electric moka which only requires some current and fresh water: The coffee from mokas is stronger than coffee people usually drink in USA (or other countries outside EU/Latin America), since it passes through the ground coffee at higher pressure (about 1.5 atmospheres I believe). You can read more information on the wikipedia page. They come with different sizes, the smallest one would be about 15 cm tall with a base of about 10x12 cm (at least, from the electric mokas I've seen/used). Depending on the space you have available it might be too big or small enough to pack. The price depends a lot on the dimensions, the brand etc. but I have seen some at about €30 to €40 on Amazon/eBay and other websites.
1
Electric mokas are stronger than coffee people drink in USA (or other countries outside EU/Latin America)
Find cron jobs that run between given times
Is it possible to find all entries in a crontab that run between time X and time Y without having to parse the cron time entries myself? I'm mainly concerned with time hour and minute, not so much the other 3 time fields.
You can use the Ruby 1.8.7 gem "crontab-parser" to parse a crontab, and then iterate through each minute between the two timestamps, calling should_run? on every crontab entry: require 'rubygems' require 'crontab-parser' start_time = Time.parse(ARGV[0]) end_time = Time.parse(ARGV[1]) # CrontabParser barfs on env variable setting in a crontab, so just skip them cron_data = File.readlines(ARGV[2]).select {|line| line =~ /^[0-9*]/} cron = CrontabParser.new(cron_data.join("\n")) (start_time..end_time).each do |timestamp| next unless timestamp.sec.to_i == 0 cron.each do |cron_entry| if cron_entry.should_run?(timestamp) puts "#{timestamp}\t#{cron_entry.cmd}" end end end So, if you have a crontab.txt that looks like this: * * * * * foo 18 15 * * * bar Then call the script with output from date or similar and a file containing a crontab: ruby cron_report.rb "Sat Mar 3 02:07:32 UTC 2012" "Sat Mar 3 02:21:32 UTC 2012" crontab.txt You'll get output like this: Sat Mar 03 15:17:00 UTC 2012 * * * * * foo Sat Mar 03 15:18:00 UTC 2012 * * * * * foo Sat Mar 03 15:18:00 UTC 2012 18 15 * * * bar Sat Mar 03 15:19:00 UTC 2012 * * * * * foo Sat Mar 03 15:20:00 UTC 2012 * * * * * foo
0.888889
Ruby 1.8.7 gem "crontab-parser" parse a crontab
Reading own metadata within a Qt plugin class
I am currently writing my own Qt plugin to be used in a Qt program. To identify the plugin version information, I use the metadata as stored in the JSON file like the following: { "type" : "communication", "name" : "USB-LIN-IB", "longname" : "USB-LIN Communication", "version" : "1.1", "dependencies" : [] } To access these metadata information from outside the plugin classes (within the Qt program world), I fall back on them as I have defined the JSON file like this: Q_PLUGIN_METADATA(IID "org.plugins.communications.1" FILE "USBLINCommunication.json") Is it possible to use a standardized and convenient way to access exactly the same metadata from within the plugin member (e.g. the plugin constructor)? Of course, I could either use the QPluginLoader (for which I have to know the plugin file path) or a file readAll from a JSON Object. However, both methods rely on knowing the exact path of the plugin and the JSON file. This is not very reliable for me. I thought there is another more standardized way?
You do not need to know the absolute plugin file path for QPluginLoader, so you would be safe. You can just pass the plugin name, and it will work fine. It will also return the fully-qualified file name of the plugin, including the full path to the plugin if you are reading the file name back with the corresponding method. It will be clear for the class based on the information that can be obtained from QCoreApplication::libraryPaths(). Here is the corresponding part of the documentation: When loading the plugin, QPluginLoader searches in the current directory and in all plugin locations specified by QCoreApplication::libraryPaths(), unless the file name has an absolute path. After loading the plugin successfully, fileName() returns the fully-qualified file name of the plugin, including the full path to the plugin if one was given in the constructor or passed to setFileName(). Therefore, what you could do basically is this: myPluginLoader.metaData().value("MetaData").toObject().value("foo").toString() where foo can be either of your aforementioned keys.
1
QPluginLoader searches in the current directory and in all plugin locations specified by QCoreApplication::libraryPa
Why isn't jQuery selector returning an object instead of an element?
Please help me understand why the following jquery select is returning an element rather than the expected object. Thanks. <div class="partner-tab partner-tab-opaque remove4" id="tab-5"> <a href="#"> <img class="blink" src="../skin/images/logo_endicia.png"> </a> </div> code $("<a href=\"#\" />") .on("click", { "partnerId": pid }, function (e) { return showPartnerSettings(e); }) .appendTo("#footer #tab-" + pid); // $("<a href=\"#\" />")[ < a href = ​"#" > ​ < /a> ] Error: Uncaught TypeError: Object[object Object] has no method 'on' Here's the whole function: $(document).ready(function () { showPartnerTabs = function (flashUSPS) { $.post("<?=$this->baseUrl('partner/ajaxgetactive')?>", {}, function (data) { var partner = data.partners; //alert((data.partners).length); /* $("#footer .partner-tab").remove();*/ var remove = 1; var doc = $(document); for (var id in data.partners) { if (partner[id].toggle_value == "on") { remove++; logo = partner[id].logo_file; var pid = parseInt(id) + 1; $("<div class=\"partner-tab partner-tab-opaque remove" + remove + "\" id=\"tab-" + pid + "\" />") .appendTo("#footer"); $("<a href=\"#\" />") .on("click", { "partnerId": pid }, function (e) { return showPartnerSettings(e); }) .appendTo("#footer #tab-" + pid); var logochck = "tab-" + pid; //alert(logochck); if (flashUSPS && logochck == 'tab-5') { $("<img class='blink' src='../skin/images/" + logo + "' />") .appendTo("#footer #tab-" + pid + " a"); } else { $("<img src='../skin/images/" + logo + "' />") .appendTo("#footer #tab-" + pid + " a"); } //$("</div>").appendTo("#footer"); } /* else { $("<div class=\"partner-tab partner-tab-opaque remove" + remove + "\" id=\"tab-" + pid + "\" />") .appendTo("#footer"); $("<a href=\"#\" />") .on("click", { "partnerId": pid }, function(e){ return showPartnerSettings(e); }) .appendTo("#footer #tab-" + pid); $("<img src='../skin/images/" + logo + "' />") .appendTo("#footer #tab-" + pid + " a"); //$("</div>").appendTo("#footer"); } */ } //alert($(".remove2").length); if ($(".remove2").length > 1) { $($(".remove2")[0]).remove(); $($(".remove3")[0]).remove(); $($(".remove4")[0]).remove(); } }, "json"); } $(".Partnerconnection ul li .controls .toggle-switch").on("click", null, function () { $(this).showPartnerTabs(); }); showPartnerTabs(<?=$flash?>); }); As I mentioned in a comment, this function worked fine until I changed the function declaration from '$.fn.showPartnerTabs()...' to 'showPartnerTabs()...'. Does this help?
Because $("<a href=\"#\" />") is NOT a selector You are creating a new anchor element Other than that, your code seems to be correct. See jsFiddle Update Unfortunately, I am unable to reproduce the error Uncaught TypeError: Object[object Object] has no method 'on' But if you have changed $.fn.showPartnerTabs() to showPartnerTabs(), the this line $(this).showPartnerTabs(); will throw this error Object [object Object] has no method 'showPartnerTabs' Please make sure the following is true $ is actually jQuery and not any other library i.e. console.log($("<a href=\"#\" />") instanceof $) prints true or console.log($==jQuery) prints true You are using jQuery 1.7+ because earlier versions have no support for .on
0.833333
jsFiddle Update
Enclosure for whole house water filter
I plan to install a whole house water filter system. I will buy the cartridges separately and have a plumber hook it up. I don't want to trench from one end of the house to the other to put them on the garage wall, so I plan to just have it installed outside in the bushes where the water line comes in from the street. I will have 3 cylinder cartridges that are about 7" diameter and 24" tall. For reference, 3 of these: http://www.purewaterproducts.com/whole-house-filters-compact (Style C + Style B). One particulate filter + 2 carbon filters in parallel. Any ideas on enclosures I can use to protect them from the weather?
You need to think this through more carefully. First of all, Ft. Worth freezes every winter and some winters it gets really cold at night. Just last night it was below 15F. So, if you were to install your imaginary system it would have frozen solid and been destroyed (water expands when it freezes and it will rupture every single cannister, fitting, line and valve in the system when it does this). Secondly, what do you mean by "filtration"? Are you just talking carbon filtration to remove a little sediment, large-scale microbial filtration, osmotic water purification? There is a wide range of levels of filtration depending on how small the objects are that you want to remove. Anything less than an osmotic purifier is pretty much useless because they will pass through all dissolved solids and most pathogens (like e. coli etc). If you just want to get rid of some rust/dirt, then carbon is correct, but if you want to purify the water to any degree you will need osmosis. Thirdly any filter reduces the water flow a LOT and takes pressure down to about zero. So that means that if you want to, say, take a shower, you will have to repressurize the water after you filter it. So, the filter puts the water in a large tank, then you have to have a high-power pump that will repressurize the water coming out of that tank. For a typical home you will need a tank at least as big as a water heater, and even then you will run dry more often than you think. I would probably have AT LEAST one water-heater-sized tank FOR EVERY PERSON in the household. If you have a 4-person household, that is a big tank, 200 gallons or more. Finally, your filtration system has to produce water faster than you use it. A typical family uses about 400 gallons per day. As osmotic system capable of producing 400 gallons per day costs about $10,000 to $25,000 and is the size of an SUV. Starting to get the picture?
0.888889
What do you mean by "filtration"?
Can I substitute a stainless steel pot for the traditional iron dutch oven?
I have very limited options in my kitchen, and while the dutch oven is the preferred method for getting an 'oven spring' while baking sourdough, I do not have a cast iron pot to do it. IF stainless steel is a good substitute, should I consider extra precautions?
I have been using a Tramontina Triply DO (stainless/aluminum/stainless sandwich). This is a fairly substantial construction but no where near cast iron thickness. The lid is single layer stainless and the handles are solid stainless. Plastic handles will suffer in a 450 to 500 oven. I always preheat the oven, but have tried both a hot and a cold start for the DO. Both methods work very nicely with similar oven spring. The cold start allows the dough to spread to the edges of the DO, producing a round, domed loaf with nice crust. The hot start "freezes" the dough in "rustic" irregular shapes and the crust seems a bit crispier. I adjust lid-off bake time to achieve 200-210F on an instant read thermometer.
1
Tramontina Triply DO
Without using dowels, how do I join 2x4s edge to edge to be 1.5" x 7"?
I am trying to join a 2x4 supporting a workbench tabletop to another to make a backsplash of sorts. Any ideas how to do this without dowels? (No, I can't use 2x8)
I would definitely use Pocket-hole joinery My brother got me a jig that is very easy to use, and the joints are incredibly strong even without wood glue; also if you use glue the joins are "self clamping". Basically this allows you to edge-join, or do 45 degree angles, etc. just by drilling a couple of perfectly angled holes and screwing the pieces together such that the screw doesn't protrude from your work. Obviously, I wouldn't get a jig for just one project, but I have totally stopped using dowels, biscuits, and other fancy techniques in favor of pocket holes. Hope this helps!
1
Pocket-hole joinery
Piezo as a switch to flash an led when disturbed
An LED embedded in a small translucent item (say half the size of a pack of cards) that would flash on briefly if the object was disturbed or tipped over. I immediately responded that a piezoelectric sensor/generator inside the object wired to an LED would do it. However, when I tried to demonstrate this concept using a piezo buzzer I liberated from an old phone, I could only get the LED to register a dim blip when I smashed the piezo buzzer with a blunt object. How would I ensure that a piezo sensor/generator would actually light up the LED adequately without the application of blunt force trauma. As I mentioned, space would be an issue so no large parts, breadboards, or really complex circuitry. I'm just trying to figure out the easiest and smallest way to accomplish this simple task. Thanks a lot for any help you can give me!
The trick is to get some feedback oscillation. I once built one of these using a trusty spring from a mechanical pencil. Attach the spring to a pager motor inside a grounded aluminum housing. When the spring hits the foil it will cause a vibration that will last for an random, but short period of time. The challenge is calibrating the pager motor so that the spring gets a little extra kit; but shuts off most of time.
0.777778
The trick is to get feedback oscillation
-ic -ous nomenclature
I recently came across a practice problem in my textbook asking me to name a few compounds using -ic and -ous endings. The exact wording is: Write the name of each of the following ionic substances, using -ous and -ic endings to indicate the charge of the cation. The first one was CoCl2. However, cobalt has more than just two oxidization states (3, 2, 0, and -1). So if it is one of the states in the middle, how do I decide whether to use -ous or -ic
Cobalt may possibly have all those other oxidation states (and others too) for this nomenclature system, we only care about the two most common oxidation states in ionic compounds: $\ce{Co^{2+}}$ and $\ce{Co^{3+}}$. Cobalt(II) compounds would thus be named cobaltous and cobalt(III) compounds would be cobaltic. Which is yours?
1
Cobalt(II) compounds would be named cobaltous
GIS Software Choice for a small university research centre
I need to choose a GIS system for a small university research centre. We are handling a broad range of data, (for example, numerical tidal analyses, weather data, poverty, isolated economic activity, skills availability and renewable energy resource availability) and operate primarily in countries with relatively poor existing data sets. We interact with other groups, some of which use ARCGIS. Do I have to wade through every GIS software descriptor on the web, or can someone please give an indication of likely candidates?
Based on your requirements, you may need a GIS stack: server, database, presentation, and then the analysis tools. I'd recommend GeoServer (http://www.geoserver.org) for server, PostgreSQL with PostGIS extension for database (http://postgis.net). This combination can enable easy distributed authoring/analysis and publishing using WFS, WPS, and WMS, which are OGC standards. You can use the tools mentioned above for analysis. In addition to QGIS, you can also use uDig (http://udig.refractions.net) for editing. For presentation, you may use OpenLayers or GeoExt.
0.888889
GIS stack: server, database, presentation, and analysis tools
Search predictions broken in Chrome - reinstall didn't solve the problem
I recently changed the default search engine to a custom google search URL (using baseUrl) with some additional parameters and removed all the rest of the search engines, and since then, the search predictions stopped working. I even tried to reinstall Chrome but as soon as I resync, the problem is back! Search predictions are just gone without option to fix!! In IE changing the search provider allows specifying a prediction (suggestion) provider, In chrome, once you change the default search engine, you'll never be able to have predictions again!! This is a terrible bug, I mean WTF!!! Is there any workaround to that? I posted a bug report a while ago but it seems no one looks at it. I'm about to give up on Chrome and go back to IE, the only good thing about Chrome is the Extension market and the AdBlocker (which I can find in IE as well). The perfrormance changes don't matter to me too much. Thanks
After trying @ZacB's suggestion, it still didn't work. Removing all Chromium's settings and rebooting the computer also didn't work, so I concluded that the Chromium version I was running must be buggy. Updating Chromium fixed it for me.
0.777778
Removing Chromium settings and rebooting the computer
Is there a difference between pulling the plug and holding power for 5 seconds on a PC?
This is in the context of data not being flushed from the disk cache during a power interruption. If I power down a PC by holding the power button, will any disk caches flush themselves since there is still power? Or does ACPI make it function as if the power was immediately cut?
Holding the power button forces a main supply cutoff, but leaves standby power on. Since drives do not have access to standby power, the result is the same.
1
Holding the power button forces a main supply cutoff
"Hundreds of applicants" vs "hundreds of resumes"
When I am referring to a number of job applicants, I might say, "I've got a hundred qualified applicants in this folder"; when what I mean is, "I've got RESUMES from a hundred qualified applicants in this folder". Although most English speakers would understand what I meant, it is not proper English. Is there a name for this grammatical shortcut/faux pas? Although the Web has powerful search capabilities; unless you KNOW the name of something, it is hard to search for it. I am very grateful for all the StackExchange sites.
"A hundred qualified applicants in this folder" is perfectly grammatical, and a reasonable turn of phrase; it is an example of metonymy:- a figure of speech in which a thing or concept is called not by its own name but rather by the name of something associated with that thing or concept
0.888889
"A hundred qualified applicants in this folder" is perfectly grammatical, and a reasonable turn of phrase
My server is up. Now where do I go from here?
I finally got my server up and when I goto local host in a browser i get the "It works!" page. That's wonderful! I have my web page put together on my windows7 machine as an HTML/CSS document. question: How do I get it over and into my server to be displayed for all the world to see? I mean, I get it about files and stuff. but I'm not sure of the procedure to cause all this to happen in my Ubuntu box? Go easy on me folks! I'm a noob at this. But I am clever so just throw me a clue of "where to go" "what to see" and "what to do" and stuff.
You install SSH. sudo apt-get install ssh Then you use it for administering the server from your Windows box (one popular SSH client is PuTTY), as well as for transferring files to and from via SFTP (not FTP). One SFTP client that I have used is FileZilla, there are many others.
0.777778
Install SSH. sudo apt-get install ssh
AngularUI-Bootstrap's Typeahead Can't Read `length` Property of `undefined`
I am getting the following error when I attempt to get a typeahead values from AngularUI-Bootstrap, using a promise. TypeError: Cannot read property 'length' of undefined at http://localhost:8000/static/js/ui-bootstrap-tpls-0.6.0.min.js:1:37982 at i (http://localhost:8000/static/js/angular.min.js:79:437) at i (http://localhost:8000/static/js/angular.min.js:79:437) at http://localhost:8000/static/js/angular.min.js:80:485 at Object.e.$eval (http://localhost:8000/static/js/angular.min.js:92:272) at Object.e.$digest (http://localhost:8000/static/js/angular.min.js:90:142) at Object.e.$apply (http://localhost:8000/static/js/angular.min.js:92:431) at HTMLInputElement.Va.i (http://localhost:8000/static/js/angular.min.js:120:156) at HTMLInputElement.x.event.dispatch (http://localhost:8000/static/js/jquery-1.10.2.min.js:5:14129) at HTMLInputElement.v.handle (http://localhost:8000/static/js/jquery-1.10.2.min.js:5:10866) My HTML tag is: <input type="text" class="form-control" id="guestName" ng-model="name" typeahead="name for name in getTypeaheadValues($viewValue)"> With my getTypeaheadValues function doing the following: $scope.getTypeaheadValues = function($viewValue) { // return ['1','2','3','4']; $http({ method: 'GET', url: 'api/v1/person?name__icontains=' + $viewValue }).error(function ($data) { console.log("failed to fetch typeahead data"); }).success(function ($data) { var output = []; $data.objects.forEach(function (person) { output.push(person.name); }); console.log(output); return output; }); } I do not understand what AngularUI-Bootstrap is complaining about as being undefined. If I remove the comment on the top-most return the values show up fine. The console.log output in the success also return all the values I'm expecting in an array. What am I missing that would cause AngularUI-Bootstrap not see the returned array?
This problem was two fold. The first is that I was not returning the promise event (the $http call). The lack of a return statement (as @tobo points out) is what was causing the error directly. I needed to be returning the promise though, not the array. The second is that I need to be using .then rather than .success for AngularUI-Bootstrap to pick up the results. I ran across the following question: How to tie angular-ui's typeahead with a server via $http for server side optimization? Which updated my function call to the below: $scope.getTypeaheadValues = function($viewValue) { return $http({ method: 'GET', url: 'api/v1/person?name__icontains=' + $viewValue }).then(function ($response) { var output = []; console.log($data); $response.data.objects.forEach(function (person) { output.push(person.name); }); console.log(output); return output; }); }
0.777778
How to tie angular-ui's typeahead with a server via $http
What is the difference between unicast, anycast, broadcast and multicast traffic?
I have never had the privilege of working in an environment that required complicated routing or if it did require it, it was handled upstream of me. I've always used very simple static routing configurations and never needed to do any multipath routing -- hence my general confusion regarding this subject. I would like to understand multicasting and anycasting better. What is the difference between unicast, anycast, broadcast and multicast traffic? What situations are they generally used in and why (e.g., what applications use which method)? How do you calculate how much broadcast traffic is too much for a given network segment or broadcast domain? What are the security implications of allowing broadcast and multicast traffic?
Simply put: ------------------------------------------------------------ | TYPE | ASSOCIATIONS | SCOPE | EXAMPLE | ------------------------------------------------------------ | Unicast | 1 to 1 | Whole network | HTTP | ------------------------------------------------------------ | Broadcast | 1 to Many | Subnet | ARP | ------------------------------------------------------------ | Multicast | One/Many to Many | Defined horizon | SLP | ------------------------------------------------------------ | Anycast | Many to Few | Whole network | 6to4 | ------------------------------------------------------------ Unicast is used when two network nodes need to talk to each other. This is pretty straight forward, so I'm not going to spend much time on it. TCP by definition is a Unicast protocol, except when there is Anycast involved (more on that below). When you need to have more than two nodes see the traffic, you have options. If all of the nodes are on the same subnet, then broadcast becomes a viable solution. All nodes on the subnet will see all traffic. There is no TCP-like connection state maintained. Broadcast is a layer 2 feature in the Ethernet protocol, and also a layer 3 feature in IPv4. Multicast is like a broadcast that can cross subnets, but unlike broadcast does not touch all nodes. Nodes have to subscribe to a multicast group to receive information. Multicast protocols are usually UDP protocols, since by definition no connection-state can be maintained. Nodes transmitting data to a multicast group do not know what nodes are receiving. By default, Internet routers do not pass Multicast traffic. For internal use, though, it is perfectly allowed; thus, "Defined horizon" in the above chart. Multicast is a layer 3 feature of IPv4 & IPv6. To use anycast you advertise the same network in multiple spots of the Internet, and rely on shortest-path calculations to funnel clients to your multiple locations. As far the network nodes themselves are concerned, they're using a unicast connection to talk to your anycasted nodes. For more on Anycast, try: What is "anycast" and how is it helpful?. Anycast is also a layer 3 feature, but is a function of how route-coalescing happens. Examples Some examples of how the non-Unicast methods are used in the real Internet. BroadcastARP is a broadcast protocol, and is used by TCP/IP stacks to determine how to send traffic to other nodes on the network. If the destination is on the same subnet, ARP is used to figure out the MAC address that goes to the stated IP address. This is a Level 2 (Ethernet) broadcast, to the reserved FF:FF:FF:FF:FF:FF MAC address. Also, Microsoft's machine browsing protocol is famously broadcast based. Work-arounds like WINS were created to allow cross-subnet browsing. This involves a Level 3 (IP) broadcast, which is an IP packet with the Destination address listed as the broadcast address of the subnet (in 192.168.101.0/24, the broadcast address would be 192.168.101.255). The NTP protocol allows a broadcast method for announcing time sources. MulticastInside a corporate network, Multicast can deliver live video to multiple nodes without having to have massive bandwidth on the part of the server delivering the video feed. This way you can have a video server feeding a 720p stream on only a 100Mb connection, and yet still serve that feed to 3000 clients. When Novell moved away from IPX and to IP, they had to pick a service-advertising protocol to replace the SAP protocol in IPX. In IPX, the Service Advertising Protocol, did a network-wide announcement every time it announced a service was available. As TCP/IP lacked such a global announcement protocol, Novell chose to use a Multicast based protocol instead: the Service Location Protocol. New servers announce their services on the SLP multicast group. Clients looking for specific types of services announce their need to the multicast group and listen for unicasted replies. HP printers announce their presence on a multicast group by default. With the right tools, it makes it real easy to learn what printers are available on your network. The NTP protocol also allows a multicast method (IP 224.0.1.1) for announcing time sources to areas beyond just the one subnet. Anycast Anycast is a bit special since Unicast layers on top of it. Anycast is announcing the same network in different parts of the network, in order to decrease the network hops needed to get to that network. The 6to4 IPv6 transition protocol uses Anycast. 6to4 gateways announce their presence on a specific IP, 192.88.99.1. Clients looking to use a 6to4 gateway send traffic to 192.88.99.1 and trust the network to deliver the connection request to a 6to4 router. NTP services for especially popular NTP hosts may very well be anycasted, but I don't have proof of this. There is nothing in the protocol to prevent it. Other services use Anycast to improve data locality to end users. Google does Anycast with its search pages in some places (and geo-IP in others). The Root DNS servers use Anycast for similar reasons. ServerFault itself just might go there, they do have datacenters in New York and Oregon, but hasn't gone there yet. Network concerns Excessive broadcast traffic can rob all nodes in that subnet of bandwidth. This is less of a concern these days with full-duplex GigE ports, but back in the half-duplex 10Mb days a broadcast storm could bring a network to a halt real fast. Those half-duplex networks with one big collision domain across all nodes were especially vulnerable to broadcast storms, which is why networking books, especially older ones, say to keep an eye on broadcast traffic. Switched/Full-Duplex networks are a lot harder to bring to a halt with a broadcast storm, but it can still happen. Broadcast is required for correct functioning of IP networks. Multicast has the same possibility for abuse. If one node on the multicast group starts sending huge amounts of traffic to that group, all subscribed nodes will see all of that traffic. As with broadcast, excessive Mcast traffic can increase the possibilities of collisions on such connections where that is a problem. Multicast is an optional feature with IPv4, but required for IPv6. The IPv4 broadcast is replaced by multicast in IPv6 (See also: Why can't IPv6 send broadcasts?). It is frequently turned off on IPv4 networks. Not coincidentally, enabling multicast is one of the many reasons network-engineers are leery of moving to IPv6 before they have to do it. Calculating how much traffic is too much traffic depends on a few things Half vs Full Duplex: Half-duplex networks have much lower tolerances for bcast/mcast traffic. Speed of network ports: The faster your network, the less of an issue this becomes. In the 10Mb ethernet days 5-10% of traffic on a port could be bcast traffic, if not more, but on GigE less than 1% (probably way less) is more likely. Number of nodes on the network: The more nodes you have, the more unavoidable broadcast traffic you'll incur (ARP). If you have broadcast specific protocols in use, Windows browsing or other things like cluster heartbeats, where problems start will change. Network technology: Wired Ethernet is fast enough that so long as you have modern gear driving it, bcast/mcast isn't likely to cause you problems. Wireless, on the other hand, can suffer from excessive broadcast traffic as it is a shared medium amongst all nodes and therefore in a single collision domain. In the end, Bcast and Mcast traffic rob ports of bandwidth off the top. When you start to worry is highly dependent on your individual network and tolerance for variable performance. In general, network-node counts haven't scaled as fast as network speeds so the overall broadcast percentage-as-traffic number has been dropping over time. Some networks disallow Multicast for specific reasons, and others have never taken the time to set it up. There are some multicast protocols that can reveal interesting information (SLP is one such) to anyone listening for the right things. Personally, I don't mind minor multicast traffic as the biggest annoyance I've seen with it is polluted network captures when I'm doing some network analysis; and for that there are filters.
1
Multicast is a layer 3 feature of IPv4 & IPv6
Does the a gasoline or diesel engine appy fuel at high speeds when not pressing the pedal and more
Let say I directly connect a small engine to my bicycle, and that I'm superman who can overcome any force. Then I start cycling (using my legs...) - the engine starts to rotate, even though I haven't "started it" using the switch. Does it mean that if I press the pedal (or whatever) of the engine, it will apply force? Either on a diesel or a gasoline engine. Another question: Lets say I'm driving down a hill in a relatively high speed in a car, and I'm not pressing the gas pedal at all. Does the engine burn fuel at all, in both diesel and gas? If I (while in gear) turn off the engine, will something actually happen? If I would press the pedal after turning it off (while it still rotates) - will it apply force? (in both diesel and gas). If, while driving, I disconnected the idler (i.e the engine won't apply any force if I'm not pressing the pedal at any RPM and pressing the clutch will take it to zero RPM) and press the brake until I get to a complete stop, will the engine "stall"? If I'm doing it in a hill facing down, after releasing the brakes I'd accelerate and the engine would gain RPMs, will it be able to continue applying force? Finally: What's the difference between a "running engine" and one thats not running, assuming both are rotating? I'm sorry if I'm asking too much so if you would at least explain the principle I'd be very happy. Thank you!
All EFI engines shut off the fuel injectors when the accelerator is released above a certain RPM or speed (varies by manufacturer). It's easier to detect on newer model cars with a digital instant fuel economy gauge where when cruising at 55 MPH and the accelerator pedal is released, the economy readout will shoot from 30 MPG to the highest number or the readout goes blank. On an automatic transmission when the gear selector is placed in neutral at highway speed, the engine computer will allow the fuel injectors to fire again and actually raises the RPMs in anticipation of it being thrown into gear again. On a manual transmission when pressing in the clutch or placing gear selector in neutral, the engine RPMs will fall to idle where the engine computer will fire the injectors to maintain idle speed. If you turn off the engine (with the key) while moving, the car will still keep moving, but you won't accelerate or maintain speed. If the engine is off, pressing the accelerator does nothing.
0.888889
All EFI engines shut off fuel injectors when the accelerator is released above a certain RPM or speed (varies by manufacturer)
How can I remove an element whose ID starts with "A" and ends with "Z"?
I have the following script <script type="text/javascript"> $(document).ready(function(){ if ($("input[id^='ABCD']").$("input[id$='Z']")) { $("input[id^='ABCD']").$("input[id$='Z']").remove(); } }) </script> And I want to remove the elements whose ID starts with "ABCD" and ends with "Z". How can I do that?
You can combine those to match elements that both starts with ABCD and ends with Z $(document).ready(function(){ $("input[id^='ABCD'][id$='Z']").remove(); }); this removes something like <div id="ABCD_something_Z" ... To remove elements starting with ABCD AND elements ending with Z $(document).ready(function(){ $("input[id^='ABCD'], input[id$='Z']").remove(); }); this removes <div id="ABCDEF"> and <div id="crapZZZ">
1
Add elements starting with ABCD and ending with Z $(document).ready(function() $(input[id='
50v capacitor in a 40v circuit
I am Making a Power Supply, There is a 40v rail that needs a 10000uf cap, I was wondering if it is safe to use a 50v rated cap, Should i be worried that it is close to the Limit? The Brand of the capacitor is Elna.
Under full load you're close to 40V peak- you need to allow for high mains voltage and transformer regulation (voltage will rise under light load). 50V should just be okay if transformer regulation is good (usually is for larger transformers). Elna is a good brand.
1
Elna is a good brand for high mains and transformer regulation
Replace multiline string in files
I have a number of files I want to update by replacing one multi-line string with another multi-line string. Something along the lines of: * Some text, * something else * another thing And I want to replace it with: * This is completely * different text The result would be that after the replacement the file containing the first block of text, will now contain the second string (the rest of the file is unchanged). Part of the problem is that I have to find the list of files to be updated in the file system, I guess I can use grep for that (though again that's not as easy to do with multiline strings) then pipe it in sed maybe? Is there an easy way to do this? Sed is an option but it's awkward because I have to add \n etc. Is there a way to say "take the input from this file, match it in those files, then replace it with teh content of this other file" ? I can use python if need be, but I want something quick and simple, so if there is an utility available, I rather use that than write my own script (which I know how to do).
Substitute "Some...\n...Thing" by the contents of file "new" in one or more input files perl -i -p0e 's/Some.*?thing\n/`cat new`/se' input.txt ... -i to change input.txt directly -p0 slurp input file file and print it in the end s/regexp/.../s in regexp . is .|\n s/.../exp/e replace by eval(exp) new -- a file containing the replacement text (This is completely...different text) if useful you can expand the original text s/Some text\n...\n...thing\n/...
0.888889
Substitute "Some...n...Thing" by the contents of file "new"
Noise canceling headphones make strange sound when I touch my MacBook Pro
I've got headphones plugged into my desktop, and a laptop nearby that I use for work as well. Whenever I touch my MacBook Pro with the noise-canceling on my headphones turned on, it makes my headphones go nuts, creating a lot of buzzing, crackling, and popping. I assume this has something to do with conduction between my hands and the computer, but is there any way to get around this?
I have a similar issue with my MacBook Pro and an old Pioneer amp. Whenever I plugin the laptop into a power socket the amp (plugged into the same wall socket) starts to buzz and make popping sounds. This is called a ground loop and to get rid of this loop needs to be "broken". I have found two ways to do this: Connect an external display to the MacBook Pro. It gets rid of the hum. Get a ground loop isolator and connect your headphones through it. Ensure your Mac power adapter connects with three conductors to a properly grounded outlet and check for a stuck pin in the MagSafe connector in case the break in grounding is there.
1
Connect an external display to the MacBook Pro
How did Adam and Eve win at Hide and Seek?
I began reading the KJV a couple months ago, and one question that keeps plaguing my mind is, "How did Adam and Eve successfully hide from God?" Genesis Chapter 3: 8 And they heard the voice of the LORD God walking in the garden in the cool of the day: and Adam and his wife hid themselves from the presence of the LORD God amongst the trees of the garden. 9 And the LORD God called unto Adam, and said unto him, Where [art] thou? 10 And he said, I heard thy voice in the garden, and I was afraid, because I [was] naked; and I hid myself.
Good question because that scripture screams that question every time it is read. I don't believe that Adam and Eve successfully hid from God. How could they if God is omniscient? Hebrews 4:13 And there is no creature hidden from His sight, but all things are naked and open to the eyes of Him to whom we must give account. Psalm 139:4 Even before a word is on my tongue, behold, O Lord, you know it altogether. So if God knows all, then the question becomes why did God ask the question, because it wasn't because he didn't know. So if the question wasn't for God's benefit, then it must have been for Adam's If we process the whole scene, Adam and Eve had been in perfect relationship and fellowship with God until they disobeyed and sinned against God. Then all of the sudden Adam and Eve are trying to avoid God. When God asks the question, even in Adam's hearing of the question, he has to realize that something isn't right. God has never had to ask this question before, because Adam had never hidden from God before. So for God to ask, let's Adam know even before he answers, that God knows something is wrong. Even in the same scripture God continues to ask questions. God could've just came in and said "Adam and Eve you sinned and the serpent tempted you, here are your curses, see you later", but instead He questions them. Then for Adam to answer he can begin to understand and process "where" he is in relationship to God versus where he was. Adam's position has changed, and he is not in the same place physically or spiritually. God does this throughout scripture where He asks a question he already knows the answer to, but it is to the benefit of the hearer that he asked the question. There are many scriptures where God asks questions, but indeed already knows the answer. Here are a few: Genesis 4:6 NKJV So the Lord said to Cain, “Why are you angry? And why has your countenance fallen? Genesis 4:9-10 NKJV 9 Then the Lord said to Cain, “Where is Abel your brother?” He said, “I do not know. Am I my brother’s keeper?” 10 And He said, “What have you done? The voice of your brother’s blood cries out to Me from the ground. 1 Kings 19:9-10 NKJV 9 And there he went into a cave, and spent the night in that place; and behold, the word of the Lord came to him, and He said to him, “What are you doing here, Elijah?” 10 So he said, “I have been very zealous for the Lord God of hosts; for the children of Israel have forsaken Your covenant, torn down Your altars, and killed Your prophets with the sword. I alone am left; and they seek to take my life.” After Elijah's final answer God corrects him and gives him an assignment to go anoint Elisha Hopefully this helps.
0.888889
How could they if God is omniscient?
How to make extra crispy and crunchy breading like KFC?
I'm wondering how I would go about making extra crispy chicken breading like they do at many places like KFC and the like. Is there a certain ingredient that makes the breading like that? Any assistance would be very much appreciated, and feel free to share any of your own recipes for crispy chicken breading if you have them. I'll be sure to put them to good use! Thanks!
You only need to add your favorite seasonings to a bowl of rice flour. Then you coat the chicken with the rice flour, fry and eat it.
1
Seasonings to a bowl of rice flour
iOS: Change Device Volume
Is there a way to change the volume of the device? I've seen several apps do it. I have a desktop version of the iOS app and the device will be able to be controlled to some extent over the network. One of the things I want to allow the user to do is change the device volume and then play a sound. This can help if you loose your iPhone in a crack in your couch again, but can't find it. Is there any way that you can do this without Apple getting angry?
Using iPodMusicPlayer would affect the actual iPod volume setting as well. If you want to avoid that, use this: #import <MediaPlayer/MediaPlayer.h> // ... MPMusicPlayerController *musicPlayer = [MPMusicPlayerController applicationMusicPlayer]; musicPlayer.volume = 1.0f; As the user holex correctly mentioned the property volume in MPMusicPlayerController is deprecated in iOS 7.
0.888889
Using iPodMusicPlayer
Decompiler Bytecode and Obfuscators
Can we completely reverse-engineer the source code from java bytecode ? Why this feature is allowed in Java and How successful are java decompilers against obfuscators.?
you can get source code from binary these days. Although the source code obtained by Java's bytecode is more readable, obfuscating will make it slightly unreadable. Its not that only Java can be reverse engineered to code. Even C/C++ these days (with Hexrays plugin for IDA Pro) can be decompiled to source. Obfuscaters will make it hard to read but not impossible. There is nothing that can save your program from an intelligent and capable reverse engineer. :). Good luck.
1
obfuscaters can be reverse engineered to code
Can monsters make multiple attacks in a single action?
In the bestiary for the new D&D Next playtest packets, some creatures look as though they get multiple attacks per round. e.g.: An owl bear gets Melee Attack: Claws +5/+5 (etc.) and Bite +5 (etc.) along with a special power says that if both claw attacks hit, then extra damage is done. However, the basic rules don't seem to cover this situation. I can't tell if the owlbear is able to use both claws AND bite in one action, or if it can only use one claw OR a bite, or 2 claws OR A bite. So, do monsters get multiple attacks per action? And what are the rules for the owl bear, or other monsters that have a +x/+x description for an attack? One possible way to answer this question would be to explain how this worked in earlier editions of D&D. If you can tell from the rules test how this is supposed to work, that would be a better answer.
In the final rules it's pretty clear: a monster can make multiple attacks only if it has the "Multiattack" action, which always specifies which attacks can be made. In the case of the Owlbear, it has a Beak and a Claws attack (Claws counts as only one attack). It also has a Multiattack action saying "The owlbear makes two attacks: one with its beak and one with its claws." If a creature has different attacks but doesn't have Multiattack it has to choose which one to use at each turn.
1
a monster can make multiple attacks only if it has the Multiattack action .
Can I use the word "library" to refer to collections of things other than books or software?
It makes sense to say "library of books". Is it legitimate to use the word "library" in other contexts. For example, could one have a "library of hedgehogs" or a "library of apples"?
A place set apart to contain books, periodicals, and other material for reading, viewing, listening, study, or reference, as a room, set of rooms, or building where books may be read or borrowed. A collection of any materials for study and enjoyment http://dictionary.reference.com/browse/library The word library is often used for categorical collections. It could be a collection of refrence materials. Books or other forms of media like audio cd's, DVD's and magazines are forms of reference and entertainment. You could simply say you have a 'collection of hedgehogs' or use a thesaurus to find synonyms.
1
A place set apart to contain books, periodicals, and other material for reading, viewing, listening, study, or reference
Looking up for an item in a list and different table styles in iOS
I have a settings view with a grouped table. One of the cells of such table is intended to show a very long list of items from where I want the user to select one. Due to the length of the list, I need to provide a way to make easier to find a certain item. One of the options I think there are, is to show letters of alphabet as indexes at the right side of a plain table. Since my first table is a grouped one, my navigation hierarchy would be then like this: Would it be inconsistent to navigate from a grouped table to a plain table? If so, could somebody give an existing example? I didn't find anything related to this in iOS Human Interface Guidelines, maybe it is described somewhere else and this navigation pattern breaks the guidelines. Another option could be having a search bar. Can a search bar be used in both a plain table and a grouped table? The existing example of such bar I found is in Contacts app and it is a plain table. In a plain table, could both an alphabet index and a search bar be shown?
Users a tend to remember list structure, so it is not a good idea to reorder it. I would say the following: long lists are not that good search field is a bad idea (usually the user doesn't know what to search) complex components (list withing a cell of the treetable) do not usually work well Please check Miller columns and this topic. I will also add list of options from my other answer:
1
How to reorder list structure
Show tooltip on invalid input in edit control
I have subclassed edit control to accept only floating numbers. I would like to pop a tooltip when user makes an invalid input. The behavior I target is like the one edit control with ES_NUMBER has : So far I was able to implement tracking tooltip and display it when user makes invalid input. However, the tooltip is misplaced. I have tried to use ScreenToClient and ClientToScreen to fix this but have failed. Here are the instructions for creating SCCE : 1) Create default Win32 project in Visual Studio. 2) Add the following includes in your stdafx.h, just under #include <windows.h> : #include <windowsx.h> #include <commctrl.h> #pragma comment( lib, "comctl32.lib") #pragma comment(linker, \ "\"/manifestdependency:type='Win32' "\ "name='Microsoft.Windows.Common-Controls' "\ "version='6.0.0.0' "\ "processorArchitecture='*' "\ "publicKeyToken='6595b64144ccf1df' "\ "language='*'\"") 3) Add these global variables: HWND g_hwndTT; TOOLINFO g_ti; 4) Here is a simple subclass procedure for edit controls ( just for testing purposes ) : LRESULT CALLBACK EditSubProc ( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { switch (message) { case WM_CHAR: { POINT pt; if( ! isdigit( wParam ) ) // if not a number pop a tooltip! { if (GetCaretPos(&pt)) // here comes the problem { // coordinates are not good, so tooltip is misplaced ClientToScreen( hwnd, &pt ); /************************** EDIT #1 ****************************/ /******* If I delete this line x-coordinate is OK *************/ /*** y-coordinate should be little lower, but it is still OK **/ /**************************************************************/ ScreenToClient( GetParent(hwnd), &pt ); /************************* Edit #2 ****************************/ // this adjusts the y-coordinate, see the second edit RECT rcClientRect; Edit_GetRect( hwnd, &rcClientRect ); pt.y = rcClientRect.bottom; /**************************************************************/ SendMessage(g_hwndTT, TTM_TRACKACTIVATE, TRUE, (LPARAM)&g_ti); SendMessage(g_hwndTT, TTM_TRACKPOSITION, 0, MAKELPARAM(pt.x, pt.y)); } return FALSE; } else { SendMessage(g_hwndTT, TTM_TRACKACTIVATE, FALSE, (LPARAM)&g_ti); return ::DefSubclassProc( hwnd, message, wParam, lParam ); } } break; case WM_NCDESTROY: ::RemoveWindowSubclass( hwnd, EditSubProc, 0 ); return DefSubclassProc( hwnd, message, wParam, lParam); break; } return DefSubclassProc( hwnd, message, wParam, lParam); } 5) Add the following WM_CREATE handler : case WM_CREATE: { HWND hEdit = CreateWindowEx( 0, L"EDIT", L"edit", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_CENTER, 150, 150, 100, 30, hWnd, (HMENU)1000, hInst, 0 ); // try with tooltip g_hwndTT = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP | TTS_BALLOON, 0, 0, 0, 0, hWnd, NULL, hInst, NULL); if( !g_hwndTT ) MessageBeep(0); // just to signal error somehow g_ti.cbSize = sizeof(TOOLINFO); g_ti.uFlags = TTF_TRACK | TTF_ABSOLUTE; g_ti.hwnd = hWnd; g_ti.hinst = hInst; g_ti.lpszText = TEXT("Hi there"); if( ! SendMessage(g_hwndTT, TTM_ADDTOOL, 0, (LPARAM)&g_ti) ) MessageBeep(0); // just to have some error signal // subclass edit control SetWindowSubclass( hEdit, EditSubProc, 0, 0 ); } return 0L; 6) Initialize common controls in MyRegisterClass ( before return statement ) : // initialize common controls INITCOMMONCONTROLSEX iccex; iccex.dwSize = sizeof(INITCOMMONCONTROLSEX); iccex.dwICC = ICC_BAR_CLASSES | ICC_WIN95_CLASSES | ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_STANDARD_CLASSES ; if( !InitCommonControlsEx(&iccex) ) MessageBeep(0); // signal error That's it, for the SSCCE. My questions are following : How can I properly position tooltip in my main window? How should I manipulate with caret coordinates? Is there a way for tooltip handle and toolinfo structure to not be global? Thank you for your time. Best regards. EDIT #1: I have managed to achieve quite an improvement by deleting ScreenToClient call in the subclass procedure. The x-coordinate is good, y-coordinate could be slightly lower. I still would like to remove global variables somehow... EDIT #2: I was able to adjust y-coordinate by using EM_GETRECT message and setting y-coordinate to the bottom of the formatting rectangle: RECT rcClientRect; Edit_GetRect( hwnd, &rcClientRect ); pt.y = rcClient.bottom; Now the end-result is much better. All that is left is to remove global variables... EDIT #3: It seems that I have cracked it! The solution is in EM_SHOWBALLOONTIP and EM_HIDEBALLOONTIP messages! Tooltip is placed at the caret position, ballon shape is the same as the one on the picture, and it auto-dismisses itself properly. And the best thing is that I do not need global variables! Here is my subclass procedure snippet: case WM_CHAR: { // whatever... This condition is for testing purpose only if( ! IsCharAlpha( wParam ) && IsCharAlphaNumeric( wParam ) ) { SendMessage(hwnd, EM_HIDEBALLOONTIP, 0, 0); return ::DefSubclassProc( hwnd, message, wParam, lParam ); } else { EDITBALLOONTIP ebt; ebt.cbStruct = sizeof( EDITBALLOONTIP ); ebt.pszText = L" Tooltip text! "; ebt.pszTitle = L" Tooltip title!!! "; ebt.ttiIcon = TTI_ERROR_LARGE; // tooltip icon SendMessage(hwnd, EM_SHOWBALLOONTIP, 0, (LPARAM)&ebt); return FALSE; } } break;
As a follow-up to comments regarding the use of the SetProp function to remove the need to hold onto a pair of globals for the tool-tip data, I present the following solution. Note: By error-checking on calls to GetProp, I've designed a WndProc for the subclassed edit control that would function regardless of whether or not it was desired to make use of tool-tips. If the property isn't found, I simply omit any tool-tip handling code. Note 2: One downside to all of the available approaches to making the tooltip info non-global is that it introduces coupling between the subclassed WndProc and the parent window's wndProc. By using dwRefData, one must check that it holds a non-NULL pointer. By using SetWindowLongPtr, one must remember an index into the user-data. By using SetProp, one must remember a textual property name. I find this easier. Removing the call to SetProp removes the tool-tip functionality. I.e you could use the same subclassed wndProc for edit controls whether they took advantage of tooltips or not. Anyhoo, on with the (Code::Blocks) code. #define _WIN32_IE 0x0500 #define _WIN32_WINNT 0x0501 #if defined(UNICODE) && !defined(_UNICODE) #define _UNICODE #elif defined(_UNICODE) && !defined(UNICODE) #define UNICODE #endif #include <tchar.h> #include <windows.h> #include <windowsx.h> #include <commctrl.h> #include <ctype.h> #include <cstdio> /* Declare Windows procedure */ LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM); /* Make the class name into a global variable */ TCHAR szClassName[ ] = _T("CodeBlocksWindowsApp"); HWND g_hwndTT; TOOLINFO g_ti; typedef struct mToolTipInfo { HWND hwnd; TOOLINFO tInfo; } * p_mToolTipInfo; LRESULT CALLBACK EditSubProc ( HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData ) { p_mToolTipInfo tmp = (p_mToolTipInfo)GetProp(hwnd, _T("tipData")); switch (message) { case WM_CHAR: { POINT pt; if( ! isdigit( wParam ) ) // if not a number pop a tooltip! { if (GetCaretPos(&pt)) // here comes the problem { // coordinates are not good, so tooltip is misplaced ClientToScreen( hwnd, &pt ); RECT lastCharRect; lastCharRect.left = lastCharRect.top = 0; lastCharRect.right = lastCharRect.bottom = 32; HDC editHdc; char lastChar; int charHeight, charWidth; lastChar = (char)wParam; editHdc = GetDC(hwnd); charHeight = DrawText(editHdc, &lastChar, 1, &lastCharRect, DT_CALCRECT); charWidth = lastCharRect.right; ReleaseDC(hwnd, editHdc); //pt.x += xOfs + charWidth; // invalid char isn't drawn, so no need to advance xPos to reflect width of last char pt.y += charHeight; if (tmp) { SendMessage(tmp->hwnd, TTM_TRACKACTIVATE, TRUE, (LPARAM)&tmp->tInfo); SendMessage(tmp->hwnd, TTM_TRACKPOSITION, 0, MAKELPARAM(pt.x, pt.y)); } } return FALSE; } else { if (tmp) SendMessage(tmp->hwnd, TTM_TRACKACTIVATE, FALSE, (LPARAM)&tmp->tInfo ); return ::DefSubclassProc( hwnd, message, wParam, lParam ); } } break; case WM_DESTROY: { p_mToolTipInfo tmp = (p_mToolTipInfo)GetProp(hwnd, _T("tipData")); if (tmp) { delete(tmp); RemoveProp(hwnd, _T("tipData")); } } return 0; case WM_NCDESTROY: ::RemoveWindowSubclass( hwnd, EditSubProc, 0 ); return DefSubclassProc( hwnd, message, wParam, lParam); break; } return DefSubclassProc( hwnd, message, wParam, lParam); } HINSTANCE hInst; int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) { HWND hwnd; /* This is the handle for our window */ MSG messages; /* Here messages to the application are saved */ WNDCLASSEX wincl; /* Data structure for the windowclass */ /* The Window structure */ wincl.hInstance = hThisInstance; wincl.lpszClassName = szClassName; wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */ wincl.style = CS_DBLCLKS; /* Catch double-clicks */ wincl.cbSize = sizeof (WNDCLASSEX); /* Use default icon and mouse-pointer */ wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION); wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION); wincl.hCursor = LoadCursor (NULL, IDC_ARROW); wincl.lpszMenuName = NULL; /* No menu */ wincl.cbClsExtra = 0; /* No extra bytes after the window class */ wincl.cbWndExtra = 0; /* structure or the window instance */ /* Use Windows's default colour as the background of the window */ wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND; /* Register the window class, and if it fails quit the program */ if (!RegisterClassEx (&wincl)) return 0; /* The class is registered, let's create the program*/ hwnd = CreateWindowEx ( 0, /* Extended possibilites for variation */ szClassName, /* Classname */ _T("Code::Blocks Template Windows App"), /* Title Text */ WS_OVERLAPPEDWINDOW, /* default window */ CW_USEDEFAULT, /* Windows decides the position */ CW_USEDEFAULT, /* where the window ends up on the screen */ 544, /* The programs width */ 375, /* and height in pixels */ HWND_DESKTOP, /* The window is a child-window to desktop */ NULL, /* No menu */ hThisInstance, /* Program Instance handler */ NULL /* No Window Creation data */ ); /* Make the window visible on the screen */ ShowWindow (hwnd, nCmdShow); /* Run the message loop. It will run until GetMessage() returns 0 */ while (GetMessage (&messages, NULL, 0, 0)) { /* Translate virtual-key messages into character messages */ TranslateMessage(&messages); /* Send message to WindowProcedure */ DispatchMessage(&messages); } /* The program return-value is 0 - The value that PostQuitMessage() gave */ return messages.wParam; } /* This function is called by the Windows function DispatchMessage() */ LRESULT CALLBACK WindowProcedure (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) /* handle the messages */ { case WM_CREATE: { HWND hEdit = CreateWindowEx( 0, _T("EDIT"), _T("edit"), WS_CHILD | WS_VISIBLE | WS_BORDER | ES_CENTER, 150, 150, 100, 30, hWnd, (HMENU)1000, hInst, 0 ); p_mToolTipInfo tmp = new mToolTipInfo; SetProp(hEdit, _T("tipData"), tmp); // try with tooltip //g_hwndTT = CreateWindow(TOOLTIPS_CLASS, NULL, tmp->hwnd = CreateWindow(TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP | TTS_BALLOON, 0, 0, 0, 0, hWnd, NULL, hInst, NULL); //if( !g_hwndTT ) if( !tmp->hwnd ) MessageBeep(0); // just to signal error somehow // g_ti.cbSize = sizeof(TOOLINFO); // g_ti.uFlags = TTF_TRACK | TTF_ABSOLUTE; // g_ti.hwnd = hWnd; // g_ti.hinst = hInst; // g_ti.lpszText = _T("Hi there"); tmp->tInfo.cbSize = sizeof(TOOLINFO); tmp->tInfo.uFlags = TTF_TRACK | TTF_ABSOLUTE; tmp->tInfo.hwnd = hWnd; tmp->tInfo.hinst = hInst; tmp->tInfo.lpszText = _T("Hi there"); // if( ! SendMessage(g_hwndTT, TTM_ADDTOOL, 0, (LPARAM)&g_ti) ) if( ! SendMessage(tmp->hwnd, TTM_ADDTOOL, 0, (LPARAM)&tmp->tInfo) ) MessageBeep(0); // just to have some error signal // subclass edit control SetWindowSubclass( hEdit, EditSubProc, 0, 0 ); } return 0L; case WM_DESTROY: PostQuitMessage (0); /* send a WM_QUIT to the message queue */ break; default: /* for messages that we don't deal with */ return DefWindowProc (hWnd, message, wParam, lParam); } return 0; }
0.777778
Using SetProp to remove the need to hold onto a pair of globals
Intangibility in Marvel Heroic Roleplaying
I am playing the Breakout event, as Spiderman (stop reading if you don't want spoilers!). We just met Zzzax, and I decided to attack him by web-throwing a huge metal pipe through him. I managed a Total 28, effect d10 action and aimed for Physical Stress. The Watcher did a Reaction Roll, and got a Total 2, Effect d4 Reaction (yes, it is possible, only one die not an opportunity). But the Watcher activated its "Grounded" Limit: Zzzax ignored all Stress, and became grounded through the pipe. And here is the disagreement: His point of view: Since Zzzax has Intangibility d10, he ignores all physical attacks, the only way to defeat him is to activate his Limit and then over-complicate him. He activated the Limit because my roll was so high that it should have a result. He still has Intangibility even though his Power Set is shut down. My point of view: Activating a Limit doesn't allow you to randomly ignore an attack. I can't ignore an attack and become Exhausted instead. Intangibility is just a die to add to Reaction rolls, not an automatic effect that allows you to ignore everything, that requires an SFX like Immunity(Physical attacks). I went with his interpretation (and built a Faraday cage through web and pipes), but I still think that it was not right. So how does Intangibility work? Is it an automatic effect, even without Immunity/Invulnerability SFXs, or is it just a resistance, allowing you to be attacked normally?
Here's is my take on this problem. Mechanically, I agree with your statement "intangibility is just a die to add to Reaction rolls, not an automatic effect that allows you to ignore everything, that requires SFX." But, in the Marvel RPG, the narrative is king. What that means to me is that you still have to come up with a reason that makes sense (in the story) to explain why you can stress Zzzax when he is intangible. This will be easier to come up with for certain types of heroes and harder for others. But comic book writers do this all the time. I think this is the part of this system that most gamers have trouble with.
1
How can you stress Zzzax when he is intangible?
Link_to Routing Issue With Nested Resources
I have two models Jobs and Questions. A job has many questions and questions belong to a job. I've set up the resources in the model, as well as the routes. I am having an issue trying to link_to the Show method of the questions controller on the questions#index page. My rake routes say that the path should be job_question_path with the two necessary :id's being :job_id and :id , so I tried: <td><%= link_to 'Show', job_question_path(@job, question) %></td> and got the error: No route matches {:action=>"show", :controller=>"questions", :job_id=>nil, :id=>#<Question id: 1, job_id: 1, question1: "sfsdfssfs", question2: "sfsdfs", question3: "sfsdf", question4: "sfsdfsf", question5: "sfsfsfs", created_at: "2011-06-21 03:25:12", updated_at: "2011-06-21 03:25:12">} I've tried multiple other combos and nothing is seeming to work, I keep getting: No route matches {:action=>"show", :controller=>"questions", :job_id=>nil } or some combination of that. The part I don't get is that I can put in the url /jobs/1/questions/1 and it takes me to the show page, so I am assuming that my questions#show methods are ok. See below for the rest of my code. Questions#index view <% @questions.each do |question| %> <tr> <td><%= question.question1 %></td> <td><%= question.question2 %></td> <td><%= question.question3 %></td> <td><%= question.question4 %></td> <td><%= question.question5 %></td> <td><%= link_to 'Show', job_question_path(@job, question) %></td> </tr> <% end %> Questions Controller def index @questions = Question.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @questions } end end def show @job = Job.find(params[:job_id]) @question = @job.questions.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @question } end end Models class Job < ActiveRecord::Base has_many :questions class Question < ActiveRecord::Base belongs_to :job Routes.rb root :to => "pages#home" resources :jobs do resources :questions end get "pages/home" get "pages/about" get "pages/contact" See this https://gist.github.com/1032734 for my rake routes. Thanks for any help in advance, i've been at this for a while now and just can't figure out the solution. Please let me know if you need any more info.
may be so? Questions#index view <% @questions.each do |question| %> <tr> <td><%= question.question1 %></td> <td><%= question.question2 %></td> <td><%= question.question3 %></td> <td><%= question.question4 %></td> <td><%= question.question5 %></td> <%= link_to 'Show', job_question_path(question.job_id, question.id) %> </tr> It have to work. Or haven't you 'job_id' field in Questions table ?
0.666667
'job_id' field in Questions
How do I receive the Rannoch: Admiral Koris mission?
I'm looking for the "Rannoch: Admiral Koris" mission. Who or what do I need to interact with to receive this mission? I know it's possible to permanently miss certain missions by not accessing them before completing other missions. Is this the case with "Rannoch: Admiral Koris", or am I just not wandering around in the right places?
You get this from the admiral in the War Room after the Geth Dreadnaught mission. Here is a G4 walk through of the mission.
0.777778
G4 walk through Geth Dreadnaught mission
How do I receive the Rannoch: Admiral Koris mission?
I'm looking for the "Rannoch: Admiral Koris" mission. Who or what do I need to interact with to receive this mission? I know it's possible to permanently miss certain missions by not accessing them before completing other missions. Is this the case with "Rannoch: Admiral Koris", or am I just not wandering around in the right places?
You'll get this mission at the same time you get Rannoch: Geth Fighters. If you haven't advanced the plot to this point, you won't have this mission. This happens after you've assaulted the Geth Dreadnought. Note that it is important to play the Admiral Koris mission, and the other side mission on Rannoch (Geth Fighters) before completing Priority: Rannoch, as it's possible that the outcome of Priority: Rannoch will be influenced by whether or not you've completed these two missions. Completing either of these two missions will unlock access to Priority: Rannoch.
1
Priority: Rannoch: Geth Fighters
Can you talk on the iPhone and use Siri with Monster beats headphones?
I want a set of Beats by Dre headphones and have seen that they come with a control on the cord. Does this have a Mic? and can it be used with Siri in the same way the official Apple ones can? I have looked at online reviews etc, but little is mentioned with iPhone voice compatibility.
Yes. You should be okay. The beats headphones mic is simply an extension of the built-in mic. Additionally, the hardware to filter out background noise is inside of your iPhone and so the mic won't make much of a difference. Can you do same thing with your standard Apple headphones, right? It's the same thing. I personally use Klipsch ONE headphones with my iPhone 4. It works well with voice commands. I used my Apple earbuds with the new iPad before. Dictation works like a charm. So, yes, you can.
1
Beats headphones mic is an extension of the built-in mic
Why is my fuse board buzzing when I'm using the shower?
I have used an electric shower for years no problems, but all of a sudden my fuse board started buzzing when I use the shower. I replaced the shower with the same size unit and it still makes a buzzing noise. I have checked all the wires and they are tight and well connected. I changed the old cartridge fuse for an mcb 40amp fuse, and still it makes a buzzing noise. Is this a sign that my wylex fuse board needs changing?
It could be a loose connection behind the board. Also, wylex boards used to have a din rail in the board to mount door bell transformers at the end - the rail or door bell transformer could be vibrating.
1
wylex boards used to have din rail in board to mount door bell transformers
C# & VS error: "make sure that the maximum index on a list is less than the list size"
I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with: public static double LaskeMiidi(double[] luvut) { double ka = Keskiarvo(luvut); double miidi = luvut[0]; for (int i = 0; i < luvut.Length; i++) { if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to! { miidi = luvut[i]; } else { miidi = luvut[i + 1]; } } return miidi; } So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.
End your loop earlier: for (int i = 0; i < luvut.Length - 1; i++) This stops the loop ever getting to the point where an index would be invalid.
0.888889
End your loop earlier: for
Using pstool with beamer
I would like to use pstool with beamer to create a presentation in pdflatex with figures processed by psfrag. However, as the simple example below shows, the figures are processed using the beamer documentclass, so that they each have a full beamer "frame" around them. Is there a way around this? \documentclass{beamer} \usepackage{lmodern} \usepackage{graphicx} \usepackage[process=all,crop=pdfcrop]{pstool} \begin{document} \begin{frame} \frametitle{Circle} \begin{figure} \psfragfig[width=0.3\textwidth]{figures/circle} { \psfrag{1}{\(s\)} } \end{figure} \end{frame} \end{document} I suspect that if it's possible to override the documentclass used by pstool to process the figures, that would be a solution, but I haven't found how to do this. Thanks.
The key to solving this is to realise that a "regular" compilation process sends your document through pdfLaTeX in PDF mode, and in order to do the psfrag replacements the graphic is sent through pdfLaTeX in DVI mode. Therefore, conditional commands for either the main document only or each graphic only can simply use \ifpdf: \ifpdf % setup for the main document only \else % setup for pstool images only \fi And so in your case: \ifpdf\else \setbeamertemplate{navigation symbols}{} \fi This is entirely unmentioned in the documentation, so I'll go fix that up now.
1
a "regular" compilation process sends your document through pdfLaTeX in PDF mode
How do you make a binary image in Photoshop?
I am trying to make a binary image. I want more than just the look of the image to be black/white, but I want the actual file to be a binary file. Every pixel should be either black, or white. I don't just want a monochrome image. I can't have varying shades of gray, every pixel needs to be black or white. Is this possible? I looked under Image > Mode but nothing there seems to indiciate a binary style image.
You can try this: 1 - change the image mode to Grayscale (top menu Image > Mode > Grayscale) 2 - open Image > Adjustments > Threshold. That will allow you to adjust which parts of the grayscale will be converted to black or to white, making your image truly binary. From the Adobe help: The Threshold filter converts grayscale or color images into high-contrast, black-and-white images. You can specify a certain level as a threshold. All pixels lighter than the threshold are converted to white; and all pixels darker are converted to black. The Threshold command is useful for determining the lightest and darkest areas of an image.
0.888889
The Threshold filter converts grayscale or color images into high-contrast, black and white images
Postfix or exim: Automated/Programmatic and forwarded email setup
I'm looking to replace our current use of an external smtp provider with an in-house installation. It should handle the following situations: Certain addresses should be forwarded to gmail addresses; we'd like to continue to use gmail as our primary email interface. Other addresses should be available as pop/imap mailboxes. Other addresses will be handled programmatically: they'll kick off various tasks, get logged, etc. These addresses should either kick off a process to the handle the email addresses, or should store in an easily processable format. It should also be fairly easily configurable with domain keys, spf, and anything else it takes to allow email deliverability. I've used sendmail in the distant past. It seems postfix and exim are the recommended options these days. My main question is: what's the best choice and setup for the forwarding of the addresses to gmail, and for the programmatic access? Is procmail still the way to go or are there better options these days? We're using linux/ubuntu servers.
Postfix is solid, well-supported and easy to configure. All the stuff you describe is fairly routine. Forwarding: use virtual_alias maps POP/IMAP mailboxes: local delivery, use something like Dovecot for your POP/IMAP server Programmatic stuff: if you mean you feed the mail to a script, that's done from /etc/aliases. For "easily processable", you've got mbox and Maildir format, it's all standard stuff. Domain keys/SPF: SPF is done in DNS. Domain-keys is easy enough to setup as a milter or SMTP proxy.
0.777778
Postfix is solid, well-supported and easy to configure
Capture all queries that use hints
How can I capture or list all queries that use hints and have executed since the last instance restart? I am using SQL Server 2005 Standard Edition.
Using the sys.dm_exec_query_plan statement you can get the information you are looking for.
1
Using sys.dm_exec_query_plan
Where to install SSL Cert
I have Bluehost hosting my landing page and a few subdomains. One of the subdomains has a A-Record that points to an Amazon EC2 instance running tomcat. I would like the tomcat application to be hosted over HTTPS. Where do I need to install the certificate? On Bluehost or in tomcat on my EC2 instance?
You install the certificate On Tomcat. See here. In general terms you run the certificate on the device you want to handle HTTPS, which is the web server hosting the subdomain. This is fairly intuitive as an SSL cert [usually] specifices a single domain, unless you get a wildcard cert or an SNI cert, in which case you would use it in both places.
0.888889
Installing the certificate On Tomcat
Excel VBA App stops spontaneously with message "Code execution has been halted"
From what I can see on the web, this is a fairly common complaint, but answers seem to be rarer. The problem is this: We have a number of Excel VBA apps which work perfectly on a number of users' machines. However on one machine they stop on certain lines of code. It is always the same lines, but those lines seem to have nothing in common with one another. If you press F5 (run) after the halt, the app continues, so it's almost like a break point has been added. We've tried selecting 'remove all breaks' from the menu and even adding a break and removing it again. We've had this issue with single apps before and we've 'bodged' it by cutting code out of modules, compiling and then pasting it back in etc. The problem now seems to relate to Excel itself rather than a single .xls, so we're a little unsure how to manage this. Any help would be gratefully received :) Thanks, Philip Whittington
One solution is here: The solution for this problem is to add the line of code “Application.EnableCancelKey = xlDisabled” in the first line of your macro.. This will fix the problem and you will be able to execute the macro successfully without getting the error message “Code execution has been interrupted”. But, after I inserted this line of code, I was not able to use Ctrl+Break any more. So it works but not greatly.
0.777778
Adding the line of code in the first line of your macro
How do I set up multiple printing defaults for one printer?
I have a printer capable of printing high res photos on photo paper, and duplex documents on plain A4. I have set the printer up twice (i.e. two separate printers pointing to the same URI) using the CUPS interface at http://localhost:631, once called Documents, once called Photos. For each of these instances I have set up the appropriate defaults (media type, size, print quality, duplex...). CUPS seems to remember these fine but applications (e.g. LibreOffice, EOG, firefox ... under Gnome Shell FWIW) seem to have some weird other default that bears no resemblance to either the defaults I set up, nor the last settings I used with any particular application. It's a problem because there are so many settings to change that it adds a couple of minutes to each and every print job. Inevitably I forget one or two and end up having to reprint the job. Seems there must be somewhere that these defaults get stored? Anyone shed any light on it?
I have three CUPS print queues configured with the same printer URI. Queue "deskjet" is configured with my local standard paper, queue "Legal" is configured with "Legal" size paper, and queue "Envelopes" is configured for #10 Envelopes. "Legal" and "Envelopes" queues are stopped (via cupsdisable). First, add the queue in CUPS (http://localhost:631), then use Administration->Modify Printer to change the paper type and other characteristics. I use my setup like this: # print to the Envelope queue ( select Envelope queue in your app) envelope .envelope/addresses/Friend4 | lpr -PEnvelope cupsdisable deskjet # remove regular paper, load envelopes cupsenable Envelope # wait until envelope is printed, then cupsdisable Envelope cupsenable deskjet
1
Queue "deskjet" and "Envelopes" queues are stopped
Should FPS exceed ticks/second?
I was once told that you should never re-draw a frame if the game logic has not changed since the last draw. Assuming game logic is updated once every tick, and assuming a game runs at 40 FPS @ 20 ticks/second, does that mean that every two consecutive frames will be exactly the same? If so, is there any visual difference between a game running at 40 FPS @ 20 ticks/second versus a game running at 20 FPS @ 20 ticks/second? Perhaps I don't understand game loops that well, but it seems to me that ticks/second is a limiting factor of FPS.
Your engine and your game must be super flexible to allow the possibility of drawing two times with no state change. A usual game loop ties very closely all updates in a sequential fashion. One thread, one loop, one point to flush events, one point to execute processing updates (entity/component processors, or simply manager's updates), and finally one render call which triggers the whole engine 1-frame render. Whole engine 1 frame render can be made in two fashions, extrospective (intrusive), by accessing (with visitors) the state of the drwable objects of the game, and create the rendering states, passes and commands that go with it. Or it could be fully retained, and the state of the engine was set BY the processors during the logic update, and it holds sufficient information per se to draw a frame in isolation. This is a classical game loop. It uses a delta_time variable that is given to all managers during update. If you have a physical manager, usually there is another loop within the Update itself, that will use a fixed dt and iterate as many time to fill the lagging-time to reach delta_time. And store the remainder for the next frame's refresh, to execute as part of the first loop next time. Now, its possible to have a more advanced game loop by separating event treatments, by using a thread specific system event queue, preparing a pool of timestamped events, and when the main thread is in the event treatment update, it pulls this queue. Its hardly possible to completely asychronize managers updates and frame rendering. Many engine state updates are not atomic. Even a fully retained engine will have limitations. DirectX11 introduces isolated command lists (deferred devices, in their parlance), which can help to design such an engine. But if you have such basic doubts about your own render loop, I suppose you don't use such things, yet. Since you are in java, and you talk about ticks, I imagine you must have plugged your refresh function to a periodic timer. Of course this is sub-par as a game loop design, even from the most basic loop design described above. This is not how real time systems are designed, doing this, you rely on a framework, that depends on operating system native kernel tick rate, and java's virtual machine to relay you the wakening events (and scheduling) to fire up your frame routine. This will incur bad sampling rates (aliasing) and randomness from various sources. You will have to suffer from potentially long sleep times that are not controlled, in the thread ready queue, or kernel timer tick rounding issues. This will all misalign with your framerate presentation, and result in stutterings, and if the event queue is not fully depleted at each refresh, you will also have input lag, and potentially, building up with time. Worse, since you are event based, your events I fear, are consumed by event treatment, therefore your processing time will vary according to input, and delay your frame rendering. Potentially totally masking it out. This is like a security flaw, lots of input could overflow the game and make it unresponsive. Event based systems are not made for real time applications, they are made for basically idling applications. Now, back to your question, it should not be a problem to fraw at 40FPS when your game updates at 20. Also be careful, in a timer based system, 20 FPS = 50ms, it will likely round up to 60ms (4*15 ; 15=typical kernel), therefore you'll get 16FPS. Use some precise chronometers to display frame update time on screen, and another one to display display rate. (use a counter around the Present call. Or framebuffer Swap (OpenGL term), or simply install Fraps.) This will give you some statistics. The people advocating that high display rates are bad probably refer to useless loss of resource, resulting in machine heating up, or the useless frame taking time to finish, the GPU is not ready to render the next frame when its ready, that is to say, likely right in the middle of the useless redraw. Which is why, no redraw = better responsiveness, leaving the GPU available right away when the next frame is ready. Also tearing, is an argument often heard. Tearing is caused by swappings (presentations) frequencies that are non multiples of the screen frequency. the VSynch is the feature that helps that, by using hardware support, the VGA/DVI/HDMI cable transports a tick signal that says "I flipped!", the graphic cards receives it, signal it to the CPU with an interrupt (most likely), and the driver gets it and communicate it to the currently waiting OpenGL/DirectX presenting threads. This unleash a fast back-to-front copy, which executes in much less that the 60Hz timeframe, and then when the screen next flips, a full image is presented, this avoids perfectly the tearing. The best is to respect this presentation rate, it is a tempo given by hardware, and the whole game/engine thread is put to sleep by the graphics API itself inside of the Swap/Present call, which allows to rest the CPU, allowing it to cool down, and allows perfect frame/game synchronization if using a linear loop like mentioned above. Provided your game can update faster than 60Hz. Otherwise, it will fallback immediately to 30Fps naturally, then 20, then 15, by plateaus. This is a natural response.
0.888889
a game loop that triggers the entire engine 1-frame render
Evaluating an integrals by appropriate substitution
i can't understand how to solve this issue: using an appropriate substitution, evaluate this integral: $$ \int \frac{1+x²}{\sqrt{1+x}}\mathrm{d}x $$ can any one solve this so i can understand how to do this.
Let $u^2=1+x$. Then $2u\,du =dx$. Using the fact that $x=u^2-1$, we find that $x^2+1=u^4-2u^2+2$. Substituting, we find that our integral is $$\int \frac{(u^4-2u^2+2)(2u)}{u}\,du.$$ There is cancellation, and we have reached $$\int (2u^4-4u^2+4)\,du$$ which is $$\frac{2}{5}u^5 -\frac{4}{3}u^3+4u+C.$$ Now replace $u$ by $(x+1)^{1/2}$.
0.888889
Let $u2=1+x$; then $2u,du =dx$.
How can I get a UIWebView's UIScrollView delegate methods called from within a standard UIViewController?
So I just have a standard UIViewController with a UIWebView in it that displays a pdf. For the app functionality, I have need to be able to respond to the UIWebView's nested UIScrollView events like scrollViewWillBeginDragging, scrollViewDidScroll, etc. The only way I can get access to the scrollView is to (it seems like a hack) go in and get it by the subviews array: for (id subview in webView.subviews){ if ([[subview class] isSubclassOfClass: [UIScrollView class]]) { UIScrollView * s = (UIScrollView*)subview; s.delegate = self; s.tag = 1; scrollView = s; } } But that seems to introduce more problems than it's worth, because I lose native UIScrollView stuff like zooming. So to sum up what I'm needing: What is the best way to set my UIViewController class as the delegate of the UIScrollView inside of the UIWebView? Is there something I need to do with subclassing my own UIWebView so that it handles events from it's built in UIWebView a certain way and then pass it along somehow to the UIViewController? How does that passing thing work anyway? Please advise! Thank you!
Have you checked there is only one UIScrollView subclass in the subviews? Bung in a log in your loop to see. If there is more than one, then you'll only pick up the last one using your code. If there is just one UIScrollView subclass, you could try saving a reference to its delegate and then in your own delegate methods passing messages on after you have done your business. So, in your loop, something like originalDelegate = s.delegate And then for the delegate methods, something like: - (void) scrollViewDidScroll: (UIScrollView*) scrollView; { // do your stuff [originalDelegate scrollViewDidScroll: scrollView]; } You might need to check whether originalDelegate responds to the selector before calling it, i.e. if ([originalDelegate respondsToSelector: @selector(scrollViewDidScroll:)) etc. If it were me, I'd start by implementing all twelve delegate methods defined in the UIScrollView delegate protocol. Not tested this, so will be interested to know if it can be made to work. Do note, the docs explicitly say that UIWebView "should not be subclassed"
1
UIWebView should not be subclassed
How do I make a query for if value exists in row add a value to another field?
I have a database on access and I want to add a value to a column at the end of each row based on which hospital they are in. This is a separate value. For example - the hospital called "St. James Hospital" has the id of "3" in a separate field. How do I do this using a query rather than manually going through a whole database? example here
After examining your ACCDB file, I suggest you consider setting up the tables differently. Table Health_Professionals: ID First Name Second Name Position hospital_id 1 John Doe PI 2 2 Joe Smith Co-PI 1 3 Sarah Johnson Nurse 3 Table Hospitals: hospital_id Hospital 1 Beaumont 2 St James 3 Letterkenny Hosptial A key point is to avoid storing both the hospital ID and name in the Health_Professionals table. Store only the ID. When you need to see the name, use the hospital ID to join with the Hospitals table and get the name from there. A useful side effect of this design is that if anyone ever misspells a hospital name, eg "Hosptial", you need correct that error in only one place. Same holds true whenever a hospital is intentionally renamed. Based on those tables, the query below returns this result set. ID Second Name First Name Position hospital_id Hospital 1 Doe John PI 2 St James 3 Johnson Sarah Nurse 3 Letterkenny Hosptial 2 Smith Joe Co-PI 1 Beaumont SELECT hp.ID, hp.[Second Name], hp.[First Name], hp.Position, hp.hospital_id, h.Hospital FROM Health_Professionals AS hp INNER JOIN Hospitals AS h ON hp.hospital_id = h.hospital_id ORDER BY hp.[Second Name], hp.[First Name];
1
ID First Name First Name Position Hospitals
Why don't spinning tops fall over?
One topic which was covered in university, but which I never understood, is how a spinning top "magically" resists the force of gravity. The conservation of energy explanations make sense, but I don't believe that they provide as much insight as a mechanical explanation would. The hyperphysics link Cedric provided looks similar to a diagram that I saw in my physics textbook. This diagram illustrates precession nicely, but doesn't explain why the top doesn't fall. Since the angular acceleration is always tangential, I would expect that the top should spiral outwards until it falls to the ground. However, the diagram seems to indicate that the top should be precessing in a circle, not a spiral. Another reason I am not satisfied with this explanation is that the calculation is apparently limited to situations where: "the spin angular velocity $\omega$ is much greater than the precession angular velocity $\omega_P$". The calculation gives no explanation of why this is not the case.
All the explanations given involve conservation of angular momentum, which is perfectly correct, but I feel that people with no thorough background in physics and mathematics will be left unsatisfied with this. Is there a way to explain conservation of angular momentum in terms which would be understandable to the layman? It's a pedagogical problem I have given a lot of thought and I have yet to find a satisfactory answer. Surely, you need to start from something, some basic axiom that the person will be willing to accept at face value. I thought about using either the law of action and reaction or conservation of momentum. I think these are relatively easy to describe "pictorially". But going from these to angular momentum using a vector product, is a mathematical procedure I'm not sure I can explain to someone who doesn't know anything about math. So, this should be circumvented in some way by a nice visual example again to make things clearer and I haven't found one. Anybody having ideas?
0.666667
Is there a way to explain conservation of angular momentum in terms which would be understandable?
hard self collision: make particles occupy space
By default, Blender's particles don't have any spatial extension. This is fine as long as particles are rendered as halos. But if you give them a size and an appearance as object, it becomes obvious that they're able to go through each other. What tricks can be pulled off to fix that problem? For example, if you want to fill an area with houses, toss some leaves onto the floor, or just want charged balls to stick to each other. I'm aware that a precise solution of this problem is very challenging -- but already some kind of approximation would do in most cases.
There is an add on called Molecular. http://pyroevil.com/molecular-script-download/. It makes the particles act as rigid bodies. The particles can be linked to each other as well. Here is a little teaser trailer the creator made: https://www.youtube.com/watch?v=_5QkPnPDcfc. I hope this helps!
1
Molecular is an add on called Molecular
Comment form json?
Just out of curiosity, is it possible to have a native comment-form return json instead of redirecting? Thanks! Steven
With a custom extension, you could. Just use the insert_comment_end hook, then do something like this: if(ee()->input->is_ajax_request()) { ee()->extensions->end_script = TRUE; $data['comment_id'] = $comment_id; $data['moderated'] = $comment_moderate; echo json_encode($data); }
0.666667
Using insert_comment_end hook
Can I remove the labels from ICs?
In another question I asked about ways one might obfuscate the design of a system, to prevent unauthorized cloning. One suggestion was that IC manufacturers are often willing to put custom labels on their chips. The idea is interesting, but my quantities are low enough that this would not be cost-effective. How might one remove or otherwise render unreadable the labels on ICs?
Google the phrase "ic remarking" to find many suppliers of this service.
1
Google the phrase "ic remarking"
How do Future Bill & Ted know Rufus' name?
In Bill and Ted's Excellent Adventure, we never see Rufus introduce himself to Bill and Ted. Instead, Future Bill says to Present Bill and Present Ted: "Listen to this dude, Rufus. He knows what he's talking about." How did Future Bill know what Rufus's name was? Did he read it in the history books? This has been on my mind for a while.
Bill and Ted call Rufus by his name when they meet up with their original self, thereby allowing the original self to know the name of Rufus, so that when the ones from the movie timeline arrive back to meet their current self in their timeline, they can say hello to Rufus. Confused yet? The "Rufus!" comes from the Bill and Ted from their future timeline, thus creating a Stable time loop, as Rufus does not introduce himself.
1
The "Rufus!" comes from the Bill and Ted from their future timeline
Can a Floating Action Button morph be reverted?
There are two specific examples in the Android Floating Action Button guidelines that explain how the button can morph into either new buttons, or a toolbar. If the hallmark of the app is adding file types, a floating action button can morph into related actions after it is first touched. If a floating action button morphs into a toolbar, that toolbar should contain related actions. In this example, the button lets the user select the media type to add. After the button has morphed, how does the user revert back to the previous single button mode? As I understand it, the rest of the UI is not blocked after these buttons have morphed, so it's not clear how the user can hide the new buttons or revert the morphed shape if they decide not to go through with the new action. Update This is more commentary than anything else: I just took a look at Drive to find implementation examples and found an Bottom sheet instead of a FAB morph.
Yes it can While the Material Design guidelines don't specify how morphing items are reversed: There are implemented examples of reversing animations. For example, this demo shows a reversible menu button which could be used in a floating button or fixed navbar. Reversible interactions which comport with Material Design physics. A morphing button might open a slide-up bottom sheet, a slide down paper element, or a fold-down item....the morphed button could reverse that effect using the same material physics and it would comport with the principles of Material Design.
0.888889
Reversible interactions which comport with Material Design physics
How to stop HTTPS requests for non-ssl-enabled virtual hosts from going to the first ssl-enabled virtualhost (Apache-SNI)
I hope that title is clear. How do I prevent HTTPS requests for non-ssl-enabled virtual hosts from going to the first ssl-enabled virtualhost (setup is Apache-SNI). For example, using my abbreviated config below, requests for https://example.com (a non-ssl vhost) are being served by Apache at the ssl-enabled vhost https://example.org. I'd like to disable that behavior and possibly reply with the appropriate HTTP response code (unsure of what that is). It may not even be possible, but I thought I'd ask. # I actually have a SNI setup, but it's not demonstrated here. # I don't think it's relevant in this situation. NameVirtualHost *:80 NameVirtualHost *:443 <VirtualHost *:80> ServerName example.org </VirtualHost> <VirtualHost *:443> ServerName example.org </VirtualHost> <VirtualHost *:80> ServerName example.com </VirtualHost> EDIT: Maybe a mod_rewrite rule in the first ssl-vhost?
As the Apache docs say, when no ServerName matches the hostname give in the web request, the first VirtualHost matching the given IP/port combination will be used. Thus, you merely need to give a default virtual host that serves no content, or content of your choosing, and it must be the first one parsed by Apache when it loads its configuration. If you don't want specific hosts to be accessible via https at all, place them on a separate IP address, on which you have configured Apache not to Listen on port 443.
0.888889
When no ServerName matches the hostname give in web request, the first VirtualHost matching the given IP/port combination will be used
No navigation links on 404 pages Drupal 7
When I visit a page that does not exist, I expect to still see the primary and secondary links as on any other page, but what I get is no navigation links in the 404 page. See also No navigation links on 404 pages. I have found a solution, but I am happy if something else can fix this (possibly without using extra modules).
You can do it by defining a page in a custom module. Create a page for the category "Page not found" using hook_menu(). function MODULE_menu() { $items['page-not-found'] = array( 'title' => '', 'page callback' => 'MODULE_page_not_found', 'access callback' => TRUE, ); return $items; } function MODULE_page_not_found() { drupal_set_title('Page not found'); $cust_err = ""; $cust_err = $cust_err . "The requested page " . current_path() . " could not be found"; return $cust_err; } The page callback uses current_path() to return the path of the page causing the 404 error. Go to Admin > Config > System > Site-information, and enter page-not-found (same name as defined in hook_menu) under Default 404 (not found) page. Now the error page appears like in the following screenshot. It is clear that it contains all the navigation links, and also the page URL producing the error (very similar to the original page not found). And the module mentioned in the answer above by @Nikhil will output "The requested page could not be found." but does not contain the URL of the page causing the error.
0.777778
Create a page for the category "Page not found"
INSERT multiple values via join
I have three tables, representing two entities and a connection relationship. Each of the entity relations has an artificial surrogate key used for foreign key constraints in place of natural keys. CREATE TABLE Person ( person_id SERIAL PRIMARY KEY, username VARCHAR NOT NULL UNIQUE ); CREATE TABLE Group ( group_id SERIAL PRIMARY KEY, group_name VARCHAR NOT NULL UNIQUE ); CREATE TABLE GroupMember ( person_id INTEGER REFERENCES Person, group_id INTEGER REFERENCES Group, PRIMARY KEY (person_id, group_id) ); I would like to insert multiple entries into the relationship relation GroupMember, but using the natural keys of the associated entities. Something along the lines of: INSERT INTO GroupMember (person_id,group_id) SELECT person_id,group_id FROM Person P, Group G, ( ('alice','girls'), ('bob','boys'), ('alice','coolkids'), ('bob','coolkids') ) AS X WHERE P.username = X.1 AND G.group_name = X.2; Obviously the above syntax isn't valid, but hopefully conveys the idea. Is there a way to do this in PostgreSQL?
Use a VALUES expression to generate an ad-hoc table and join to the other tables to get the respective IDs. INSERT INTO groupmember (person_id, group_id) SELECT p.person_id, g.group_id FROM ( VALUES ('alice'::varchar, 'girls'::varchar) , ('bob','boys', , ('alice','coolkids') , ('bob','coolkids') ) x (username, group_name) JOIN person p USING (username) JOIN "group" g USING (group_name); Aside: don't use the reserved word group as table name.
1
Use a VALUES expression to generate an ad-hoc table
Facebook Batch Request recognizing access token as user for page admin
I am developing an app to post multiple post messages in one time. Say I have 5 fan pages and 10 groups. It will post them all. I have used graph api method and its working well when using for loop and executing one at a time. But I came to know about facebook batch request. Now the problem is when I to fan pages using fan page access token from (https://graph.facebook.com/100000598120816/accounts) its working fine $param = array( 'message' => "Demo test " , 'access_token' => "<fan page access token>"); try { $posted = $facebook->api('/425355934226513/feed/', 'post', $param); if (strlen($posted["id"]) > 0 ) $success = TRUE; } catch (FacebookApiException $e) { $errMsg = $e->getMessage(); $error = TRUE; } But when I try to do the same using batch request, It post as the USER, not as PAGE ADMIN. $arr1[] = array( "method"=>"POST", 'relative_url' => '<fan page id>/feed',"body" => "message=Apps testing..Please ignore this message for page." , 'access_token' => "<FAN PAGE TOKEN>"); $arr1[] = array( "method"=>"POST", 'relative_url' => '<my group id>/feed',"body" => "message=Apps testing..Please ignore this message for page." , 'access_token' => "<USER PAGE TOKEN>"); try { $posted = $facebook->api("/?batch=".urlencode(json_encode($arr1)), 'post'); $success = TRUE; } catch (FacebookApiException $e) { $errMsg = $e->getMessage(); $error = TRUE; } P.S Both the above code runs successfully. But in fan page its showing as the USER not PAGE ADMIN. Thanks in Advance.
You should try specifying a "fallback" Access Token as described in https://developers.facebook.com/docs/graph-api/making-multiple-requests/#differentaccesstokens This Access Token should be an App Access Token. Also, I'm not sure if you're not overwriting your $arr1[] variable...
0.777778
Configuring a "fallback" Access Token
Applications of recoil principle in classical physics
Are there any interesting, important or (for the non physicist) astonishing examples where the recoil principle (as special case of conservation of linear momentum) is applied beside rockets and guns? I am teaching physics in high school and was just wondering if there are any more interesting examples than the two textbook standard examples above. I am not interested in examples which are not in the domain of macroscopic, classical physics like Mößbauer-effect or something like that.
Yarkovsky effect (almost like a photon rocket, I think). Non-uniform thermal radiation (because 'day' is hotter than 'night') of a celestial object can give a net recoil. More spoiler: http://en.wikipedia.org/wiki/Yarkovsky_effect
1
Non-uniform thermal radiation of a celestial object
How do I keep drawer knobs from loosening over time?
I see knobs like this on cabinets, dressers, and closet doors. They are held in place with a single wood screw. Very often they are loose. I guess when we grab them we often impart a slight twist. Also, temperature and humidity changes cause the wood to swell and shrink. The system is biased towards unscrewing, so over time they loosen up. My DIY instinct says that this is bad. That the screw will strip out the knob, or it will ream out the hole in the door. Well, it seems sloppy. When I notice one, I give it a twist to tighten. Sometimes I put my finger over the screw head to hold it still. When it's really stiff, I might get out the multitool. Sometimes, in my enthusiasm, I strip out the knob. Doh! What's the best way to deal with these things? For example: Use handles that take two screws. Put a washer under the head to distribute the load, then make them really tight. Keep them all tight according to a schedule. Only use knobs made of strong wood, and keep them tight. Use knobs that take a machine screw instead of a wood screw. Put wood glue in the screw hole. Use door designs that don't need a handle.
I'd recommend going with a metal knob that's held in place by a machine screw. They're going to cost more, but they won't get damaged from everyday use, and you don't have to worry about them stripping out. Most of the knobs in my house are metal and take machine screws. I do have to periodically re-tighten them though. Some Blue Loctite might take care of it, but I've never taken the time to address the issue.
1
Metal knobs are held in place by a machine screw
Rails undefined method `model_name' for NilClass:Class When trying to render simple_form in a view
I've searched through the questions and couldn't find an answer that would work for me and I'm new to Rails and am stuck. I'm trying to render a simple_form I use to post statuses into a view for user profiles. But every time I load the profile page I get the following error: undefined method `model_name' for NilClass:Class Extracted source (around line #1): 1: <%= simple_form_for(@status) do |f| %> I don't know why because it renders fine in two other views I have, only difference they are located in the same folder as the form. The profile is not. This is what I used to render the form: <%= render partial: "statuses/form", locals: { status: @status} %> and here's what my controller looks like: class StatusesController < ApplicationController before_filter :authenticate_member!, only: [:new, :create, :edit, :update] # GET /statuses # GET /statuses.json def index @statuses = Status.all respond_to do |format| format.html # index.html.erb format.json { render json: @statuses } end end # GET /statuses/1 # GET /statuses/1.json def show @status = Status.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @status } end end # GET /statuses/new # GET /statuses/new.json def new @status = Status.new respond_to do |format| format.html # new.html.erb format.json { render json: @status } end end # GET /statuses/1/edit def edit @status = Status.find(params[:id]) end # POST /statuses # POST /statuses.json def create @status = current_member.statuses.new(params[:status]) respond_to do |format| if @status.save format.html { redirect_to @status, notice: 'Status was successfully created.' } format.json { render json: @status, status: :created, location: @status } else format.html { render action: "new" } format.json { render json: @status.errors, status: :unprocessable_entity } end end end # PUT /statuses/1 # PUT /statuses/1.json def update @status = current_member.statuses.find(params[:id]) if params[:status] && params[:status].has_key?(:user_id) params[:status].delete(:user_id) end respond_to do |format| if @status.update_attributes(params[:status]) format.html { redirect_to @status, notice: 'Status was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @status.errors, status: :unprocessable_entity } end end end # DELETE /statuses/1 # DELETE /statuses/1.json def destroy @status = Status.find(params[:id]) @status.destroy respond_to do |format| format.html { redirect_to statuses_url } format.json { head :no_content } end end end What am I missing here?
Ok I finally figured this one out. Instead of trying to render it I just added to form directly to view like so: <%= simple_form_for(@status) do |f| %> <%= f.input :content, label: false, input_html: { class: 'forms', id: 'update_box', tabindex: '1', rows: '1' } %> <span class="actions"> <%= f.submit "Post to Stream", :class => 'reg_button btn btn-info' %> </span> <% end %> and added @status = Status.new to my show method in my Profiles Controller so that it posts correctly: class ProfilesController < ApplicationController def show @status = Status.new @member = Member.find_by_user_name(params[:id]) if @member @statuses = @member.statuses.all render action: :show else render file: 'public/404', status: 404, formats: [:html] end end end Hope this helps someone else out.
0.777778
Adding to form to view like so
Is it possible to disable XSS filtering on Cartthrob?
I'm looking for some hidden configuration settings that will allow me to disable XSS filtering when using Cartthrob. The global EE config item is ignored. Is this possible?
It absolutely is. You can find information on how to disable XSS filtering on this thread Are PDFs still an XSS problem with EE uploads?
1
How to disable XSS filtering?
How do I find which elements in one array aren't in another?
I am new to programming and hence I am stuck on a basic level problem. Following is code I wrote for comparison. But the result I get does not make sense to me. I would appreciate if someone could tell me what is going wrong. There are two arrays: @array1 , @array2 of unequal length. I wish to compare both and list down values not present in @array1. my %temp = map {$_,$_}@array2; for (@array1){ next if exists $temp{$_}; open (FILE, ">>/filename") or die "$!"; print FILE "$_\n"; close(FILE); }
If you're doing this for a test, which I assume you are I would highly suggest is_deeply in the newer versions of Test::More You'll have to update Test::More cpanp install Test::More or if you're on perl 5.5 cpan Test::More Then you'll have use it use Test::More; tests => 1 is_deeply ( \@arr1, \@arr2, 'test failed' ); If you're not doing this for testing, but you're doing this for introspective purposes and the arrays are small, I'd suggest using XXX: cpanp install http://search.cpan.org/CPAN/authors/id/I/IN/INGY/XXX-0.12.tar.gz Then you'll have use it use XXX; YYY [ \@arr1, \@arr2 ];
1
If you're doing this for a test, I'd highly suggest using XXX: cpanp install
Is it possible to add house numbers using the Mapbox Street Vector Tiles source in Tilemill2?
Title says it all. Does anyony know if the house number is included in Mapbox’ vector tiles, and if so how to access it for styling? Thanks for any advice!
Version 5 of the Mapbox Streets vector tiles includes the house number in a new layer. I used the following to add them to the starting style: #housenum_label { text-name: '[house_num]'; text-face-name: @sans; text-fill: darken(#cde, 20%); text-size: 9; }
1
Mapbox Streets vector tiles include house number in new layer
k-center algorithm in one-dimensional space
I'm aware of the general k-center approximation algorithm, but my professor (this is a question from a CS class) says that in a one-dimensional space, the problem can be solved (optimal solution found, not an approximation) in O(n^2) polynomial time without depending on k or using dynamic programming. A general description of the k-center problem: Given a set of nodes in an n-dimensional space, cluster them into k clusters such that the "radius" of each cluster (distance from furthest node to its center node) is minimized. A more formal and detailed description can be found at http://en.wikipedia.org/wiki/Metric_k-center As you might expect, I can't figure out how this is possible. The part currently causing me problems is how the runtime can not rely on k. The nature of the problem causes me to try to step through the nodes on a sort of number line and try to find points to put boundaries, marking off the edges of each cluster that way. But this would require a runtime based on k. The O(n^2) runtime though makes me think it might involve filling out an nxn array with the distance between two nodes in each entry. Any explanation on how this is works or tips on how to figure it out would be very helpful.
First, There exist optimal solutions in which each cluster consists of a contiguous sequence of points in the real line. Any other optimal solutions can be transformed into the cases above. In the following, we focus on the optimal solutions of the kind above. The complexity of the following "dynamic programming" algorithm is $O(n^2 k) = O(n^3)$. The case for $k=1$ is easy. Denote the optimal solution to $k=1$ in $n$ points by $R_{n,1}$. Let $R(n,k)$ be the optimal solution for the problem of $k$-center in the first $n$ points. For convenience, define $R(n,k) = 0$ if $k \ge n$ (This is reasonable because we can choose each point as the center of the cluster consisting of only itself). For general $k > 1$, we consider all the cases according to the number (denoted $m$) of points that are assigned to the last cluster (that is, the last cluster contains a contiguous sequence of the rightmost $m$ points). $$R(n,k) = \min_{0 \le m \le n} \{ R(n-m, k-1) + R_{m,1} \}$$ The complexity of the "dynamic programming" algorithm is $O(n^2 k) = O(n^3)$. Note: This paper [1] gives an $O(n \log n)$ time algorithm. [1] Efficient Algorithms for the One-Dimensional $k$-Center Problem. arXiv, 2014.
0.666667
The complexity of the following "dynamic programming" algorithm is $O(n2 k) = O (n3)$
Mixed number fractions class
I'm looking for bugs. I tried to test all functionality in a variety of ways. #by JB0x2D1 from decimal import Decimal import math import numbers import operator from fractions import Fraction class Mixed(Fraction): """This class implements Fraction, which implements rational numbers.""" # We're immutable, so use __new__ not __init__ def __new__(cls, whole=0, numerator=None, denominator=None): """Constructs a Rational. Takes a string like '-1 2/3' or '1.5', another Rational instance, a numerator/denominator pair, a float, or a whole number/numerator/ denominator set. If one or more non-zero arguments is negative, all are treated as negative and the result is negative. General behavior: whole number + (numerator / denominator) Examples -------- >>> Mixed(Mixed(-1,1,2), Mixed(0,1,2), Mixed(0,1,2)) Mixed(-2, 1, 2) Note: The above call is similar to: >>> Fraction(-3,2) + Fraction(Fraction(-1,2), Fraction(1,2)) Fraction(-5, 2) >>> Mixed('-1 2/3') Mixed(-1, 2, 3) >>> Mixed(10,-8) Mixed(-1, 1, 4) >>> Mixed(Fraction(1,7), 5) Mixed(0, 1, 35) >>> Mixed(Mixed(1, 7), Fraction(2, 3)) Mixed(0, 3, 14) >>> Mixed(Mixed(0, 3, 2), Fraction(2, 3), 2) Mixed(1, 5, 6) >>> Mixed('314') Mixed(314, 0, 1) >>> Mixed('-35/4') Mixed(-8, 3, 4) >>> Mixed('3.1415') Mixed(3, 283, 2000) >>> Mixed('-47e-2') Mixed(0, -47, 100) >>> Mixed(1.47) Mixed(1, 2116691824864133, 4503599627370496) >>> Mixed(2.25) Mixed(2, 1, 4) >>> Mixed(Decimal('1.47')) Mixed(1, 47, 100) """ self = super(Fraction, cls).__new__(cls) if (numerator is None) and (denominator is None): #single argument if isinstance(whole, numbers.Rational) or \ isinstance(whole, float) or \ isinstance(whole, Decimal): if type(whole) == Mixed: return whole f = Fraction(whole) whole = 0 elif isinstance(whole, str): # Handle construction from strings. arg = whole fail = False try: f = Fraction(whole) whole = 0 except ValueError: n = whole.split() if (len(n) == 2): try: whole = Fraction(n[0]) f = Fraction(n[1]) except ValueError: fail = True else: fail = True if fail: raise ValueError('Invalid literal for Mixed: %r' % arg) else: raise TypeError("argument should be a string " "or a Rational instance") elif (isinstance(numerator, numbers.Rational) and #two arguments isinstance(whole, numbers.Rational) and (denominator is None)): #here whole is treated as numerator and numerator as denominator if numerator == 0: raise ZeroDivisionError('Mixed(%s, 0)' % whole) f = Fraction(whole, numerator) whole = 0 elif (isinstance(whole, numbers.Rational) and #three arguments isinstance(numerator, numbers.Rational) and isinstance(denominator, numbers.Rational)): if denominator == 0: raise ZeroDivisionError('Mixed(%s, %s, 0)' % whole, numerator) whole = Fraction(whole) f = Fraction(numerator, denominator) else: raise TypeError("all three arguments should be " "Rational instances") #handle negative values and convert improper to mixed number fraction if (whole < 0) and (f > 0): f = -f + whole elif (whole > 0) and (f < 0): f += -whole else: f += whole numerator = f.numerator denominator = f.denominator if numerator < 0: whole = -(-numerator // denominator) numerator = -numerator % denominator else: whole = numerator // denominator numerator %= denominator self._whole = whole self._numerator = numerator self._denominator = denominator return self def __repr__(self): """repr(self)""" return ('Mixed(%s, %s, %s)' % (self._whole, self._numerator, self._denominator)) def __str__(self): """str(self)""" if self._numerator == 0: return str(self._whole) elif self._whole != 0: return '%s %s/%s' % (self._whole, self._numerator, self._denominator) else: return '%s/%s' % (self._numerator, self._denominator) def to_fraction(self): n = self._numerator if self._whole != 0: if self._whole < 0: n *= -1 n += self._whole * self._denominator return Fraction(n, self._denominator) def limit_denominator(self, max_denominator=1000000): """Closest Fraction to self with denominator at most max_denominator. >>> Mixed('3.141592653589793').limit_denominator(10) Mixed(3, 1, 7) >>> Mixed('3.141592653589793').limit_denominator(100) Mixed(3, 14, 99) >>> Mixed(4321, 8765).limit_denominator(10000) Mixed(0, 4321, 8765) """ return Mixed(self.to_fraction().limit_denominator(max_denominator)) @property def numerator(a): return a.to_fraction().numerator @property def denominator(a): return a._denominator @property def whole(a): """returns the whole number only (a % 1) >>> Mixed(10,3).whole 3 """ return a._whole @property def fnumerator(a): """ returns the fractional portion's numerator. >>> Mixed('1 3/4').fnumerator 3 """ return a._numerator def _add(a, b): """a + b""" return Mixed(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator) __add__, __radd__ = Fraction._operator_fallbacks(_add, operator.add) def _sub(a, b): """a - b""" return Mixed(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator) __sub__, __rsub__ = Fraction._operator_fallbacks(_sub, operator.sub) def _mul(a, b): """a * b""" return Mixed(a.numerator * b.numerator, a.denominator * b.denominator) __mul__, __rmul__ = Fraction._operator_fallbacks(_mul, operator.mul) def _div(a, b): """a / b""" return Mixed(a.numerator * b.denominator, a.denominator * b.numerator) __truediv__, __rtruediv__ = Fraction._operator_fallbacks(_div, operator.truediv) def __pow__(a, b): """a ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the result will be rational. """ if isinstance(b, numbers.Rational): if b.denominator == 1: return Mixed(Fraction(a) ** b) else: # A fractional power will generally produce an # irrational number. return float(a) ** float(b) else: return float(a) ** b def __rpow__(b, a): """a ** b""" if b._denominator == 1 and b._numerator >= 0: # If a is an int, keep it that way if possible. return a ** b.numerator if isinstance(a, numbers.Rational): return Mixed(a.numerator, a.denominator) ** b if b._denominator == 1: return a ** b.numerator return a ** float(b) def __pos__(a): """+a: Coerces a subclass instance to Fraction""" return Mixed(a.numerator, a.denominator) def __neg__(a): """-a""" return Mixed(-a.numerator, a.denominator) def __abs__(a): """abs(a)""" return Mixed(abs(a.numerator), a.denominator) def __trunc__(a): """trunc(a)""" if a.numerator < 0: return -(-a.numerator // a.denominator) else: return a.numerator // a.denominator def __hash__(self): """hash(self)""" return self.to_fraction().__hash__() def __eq__(a, b): """a == b""" return Fraction(a) == b def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ return self.to_fraction()._richcmp(other, op) def __reduce__(self): return (self.__class__, (str(self),)) def __copy__(self): if type(self) == Mixed: return self # I'm immutable; therefore I am my own clone return self.__class__(self.numerator, self.denominator) def __deepcopy__(self, memo): if type(self) == Mixed: return self # My components are also immutable return self.__class__(self.numerator, self.denominator) Latest version download here.
1. Bugs Your doctests do not pass: $ python3.3 -mdoctest cr35274.py ********************************************************************** File "./cr35274.py", line 76, in cr35274.Mixed.__new__ Failed example: Mixed(Mixed(-1,1,2), Mixed(0,1,2), Mixed(0,1,2)) Expected: Mixed(-2, 1, 2) Note: The above call is similar to: Got: Mixed(-2, 1, 2) ********************************************************************** File "./cr35274.py", line 97, in cr35274.Mixed.__new__ Failed example: Mixed('-47e-2') Expected: Mixed(0, -47, 100) Got: Mixed(0, 47, 100) ********************************************************************** 1 items had failures: 2 of 14 in cr35274.Mixed.__new__ ***Test Failed*** 2 failures. 2. Commentary As far as I can see, there are really only two things that you are trying to achieve: To create the mixed fraction a b/c from the string "a b/c". But instead of implementing a whole new class, why not just write a function to parse the string and return a Fraction? import re from fractions import Fraction _MIXED_FORMAT = re.compile(r""" \A\s* # optional whitespace at the start, then (?P<sign>[-+]?) # an optional sign, then (?P<whole>\d+) # integer part \s+ # whitespace (?P<num>\d+) # numerator /(?P<denom>\d+) # denominator \s*\Z # and optional whitespace to finish """, re.VERBOSE) def mixed(s): """Parse the string s as a (possibly mixed) fraction. >>> mixed('1 2/3') Fraction(5, 3) >>> mixed(' -1 2/3 ') Fraction(-5, 3) >>> mixed('-0 12/15') Fraction(-4, 5) >>> mixed('+45/15') Fraction(3, 1) """ m = _MIXED_FORMAT.match(s) if not m: return Fraction(s) d = m.groupdict() result = int(d['whole']) + Fraction(int(d['num']), int(d['denom'])) if d['sign'] == '-': return -result else: return result To format a fraction in mixed notation. But why not just write this as a function: def format_mixed(f): """Format the fraction f as a (possibly) mixed fraction. >>> all(format_mixed(mixed(f)) == f for f in ['1 2/3', '-3 4/5', '7/8']) True """ if abs(f) <= 1 or f.denominator == 1: return str(f) return '{0} {1.numerator}/{1.denominator}'.format(int(f), abs(f - int(f))) The rest of your code seems unnecessary and complicated.
0.888889
Why not just write a function to parse the string and return a Fraction?
What would be the best way to design a real time clock for the MSP430?
Basically that. The way I am doing it now is with the TimerA set to 1 second interrupts. But I think that it's very annoying. Are there any other ways to do it? I want to basically set timers on that clock, like, shutdown until 40 seconds have passed...
It's not perfectly clear to whether you want a real-time clock or a stopwatch (the 40 seconds you mention). You could use an RTC IC (Real-Time Clock), like the NXP PCF8563. This one is available in several packages, including both the old DIL and a very small DFN. But you probably don't need a separate RTC IC. It's typically used because it consumes very little power, and the rest of the circuit can power down while the RTC keeps running of a battery or supercap. The MSP430, however, is also a low-power device, and it has a low-frequency oscillator which can run on the same 32.768kHz crystal you would use for the RTC. In one project I had the MSP430 running continuously on a 32kHz crystal, and yet it consumed less than 5\$\mu\$A. That's more than an RTC (the PCF8563 only needs 250nA), but it will be acceptable for many applications. What's your problem with the 1s interrupt? If you want to make a real-time clock you'll need a time-cue anyhow, whether generated internally or coming from an external RTC. Upon interrupt you can perform required updates of seconds, minutes and hour counters, and wait for the next interrupt. You even could work with 10ths of a second, although with the 32.768kHz this will have a minor deviation. You would have four tenths of a second or 3277 clock ticks, followed by one tenth of 3278 ticks, to get exactly 1/2 second, so repeat this pattern a second time to complete one second.
1
What's your problem with the 1s interrupt?
Can Noether's theorem be understood intuitively?
Noether's theorem is one of those surprisingly clear results of mathematical calculations, for which I am inclined to think that some kind of intuitive understanding should or must be possible. However I don't know of any, do you? Independence of time <=> energy conservation. Independence of position <=> momentum conservation. Independence of direction <=> angular momentum conservation. I know that the mathematics leads in the direction of Lie-algebra and such but I would like to discuss whether this theorem can be understood from a non-mathematical point of view also.
It's intuitively clear that the energy most accurately describes how much the state of the system is changing with time. So if the laws of physics don't depend on time, then the amount how much the state of the system changes with time has to be conserved because it's still changing in the same way. In the same way, and perhaps even more intuitively, if the laws don't depend on position, you may hit the objects, and hit them a little bit more, and so on. The momentum measures how much the objects depend on space, so if the laws themselves don't depend on the position on space, the momentum has to be conserved. The angular momentum with respect to an axis is determining how much the state changes if you rotate it around the axis - how much it depends on the angle (therefore "angular" in the name). So the symmetry is linked to the conservation law once again. If your intuition doesn't find the comments intuitive enough, maybe you should train your intuition because your current intuition apparently misses the most important properties of time, space, angles, energy, momentum, and angular momentum. ;-)
0.888889
How much the state of the system changes with time?
Can excited electrons fall back to their ground state without the emission of photons?
In gas discharge lamps, for example, a current composed of ionized atoms excites the electrons of the atoms of the gas, and when they fall back to their ground state photons are emitted. Why is the reverse process (energy transfer of an excited electron to a free electron) never mentioned? Is it not possible or is the characteristic time involved too low for the electron to "wait" for an electron to pass? I have read about losing excitation energy as heat in chemistry oriented articles, but they don't go too deep. Here is an example.
Two thoughts for you in addition to dmckee's answer. 1) Andrew Murray's research group in Manchester has done some experiments on superelastic collisions of electrons with excited atoms, see for example here. In these collisions free electrons hit excited atoms and gain energy from the excitation energy of the atom. This is a difficult experiment - you need a nice laser system to make a large enough population of excited atoms to make it possible. 2) You mention losing energy as 'heat'. Energy loss to heat is particularly relevant to systems where the excited atoms (or molecules) are in liquid or solid. Effectively the excitation energy is converted by collisions with neighbouring atoms (or molecules) into vibrational / rotational motion, which goes into heat. This is relevant to Kasha's rule in classical photochemistry. Kasha's rule applies to molecules in liquids (or solids). So in the case of the discharge lamp you are thinking of the excited atoms are in a gas phase environment and the likelihood of losing excitation energy to heat will depend on the rate of collisions and, hence, the gas pressure.
0.666667
dmckee's answer to superelastic collisions of electrons with excited atoms
Counting vowels with consonants
I have made a program to count the number of vowels and consonants in an inputted string: Scanner in = new Scanner(System.in); System.out.print("Enter a string "); String phrase = in.nextLine(); int i, length, vowels = 0; int consonants = 0; boolean y = false; String j; length = phrase.length(); for (i = 0; i < length; i++) { j = "" + phrase.charAt(i); boolean isAVowel = "aeiou".contains(j.toLowerCase()); boolean y = "y".contains(j.toLowerCase()); if(isAVowel){ vowels++; }else if(isAVowel && y){ vowels++; consonants++; //}else if(y && !(isAVowel)){ // vowels++; }else{ consonants++; } System.out.println("The number of vowels in \"" +phrase+"\" is "+ vowels+".\n\nThe number of consonants is "+consonants+".\n\n"); When "y" is by itself it says its a consonant, it should be a vowel. Where do I state this?
Maybe you should simply use regex String phrase = in.nextLine(); int consonants = phrase.replaceAll("a|e|o|u|i", "").length(); int vowels = phrase.replaceAll("[^a|e|o|u|i|y]", "").length();
1
regex String phrase = in.nextLine
Potential PHP problems with EE 1.13 or CE 1.8
My client is on an old server running PHP 5.2.17, should I encourage him to upgrade to 5.3 or will it be ok?
I suggest to try with PHP 5.4. If it is EE installation please talk to support first as 5.4 is not officially supported yet (not fully tested) but works correctly since 1.13/1.8 based on the feedback i got.
0.888889
PHP 5.4 is not officially supported yet (not fully tested) but works correctly since 1.13/1.8
Prepare SD card for Wifi on Headless Pi
I need to SSH my Pi over wifi but because it is a model A board (using a usb hub is not possible - ever) and I have no ethernet, i can't configure the Pi to connect to my secured wifi network. I want to have the SD card plugged into my laptop and I want to edit a file with the wifi configuration information in it so my Pi will connect to my network automatically at start-up so I can then SSH it to get control. I know how to enable SSH on a headless system thanks to this answer. Edit. Ive been searching around and I'm wondering if I'm able to just edit the file /etc/network/interfaces while the SD card is in my PC and put in all the network ssid, psk and wlan0 stuff in it. Will this work? Thanks
Some specific Instructions: Contents of /etc/network/interfaces: auto lo iface lo inet loopback allow-hotplug eth0 iface eth0 inet dhcp allow-hotplug wlan0 iface wlan0 inet manual wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf post-up ifdown eth0 iface default inet dhcp Contents of /etc/wpa_supplicant/wpa_supplicant.conf: ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 network={ ssid="YOUR_SSID_HERE" psk="YOUR_SECRET_PASSPHRASE_HERE" id_str="SOME_DESCRIPTIVE_NAME" } Honest. Those two files, with given contents are what I use on all my pi's. They boot and immediately connect to my wireless router. DHCP negotiation provides an address, and my router resolves the hostname to the proper IP address. Make sure to name each PI appropriately via /etc/hostname. The weirdness in the 'interfaces' file in the trailing 'iface default...' is needed, otherwise the wireless wpa connection won't come up. The wpa_supplicant.conf file can have multiple 'network={' entries too, I used to take my pi to work... plug it in and voila, it connected automagically there too, work's configuration was a bit more convoluted though. Included here as an example, add/replace the following in the wpa_supplicant.conf file: network={ ssid="THE_OFFICE" scan_ssid=1 key_mgmt=WPA-EAP eap=PEAP identity="WORK_USERNAME" password="WORK_PASSWORD" phase1="peaplabel=0" phase2="auth=MSCHAPV2" id_str="SOME_DESCRIPTIVE_NAME" } Essentially, it scans the wpa_supplicant.conf file and connects to the first network it finds that matches. Very handy. It's possible to make it connect to any 'open' network automatically this way too. Not the smartest thing to do, but do-able.
0.777778
'interfaces' file in trailing 'iface default' is needed .
Java - Not being able to get data from Text Field
I have built this application and I tried to run it but I could not get the data from a JTextField. I don't know what's wrong... Here is the code that is relevant... Construct the JTextFeild: (File Main.java) public class Constructor extends javax.swing.JFrame { public Constructor() { initComponents(); } private void initComponents() { refernce = new javax.swing.JTextField(); /*Some other code in here*/ } private javax.swing.JTextField refernce; /*Some other code in here*/ } Get the data from the Text Field: (File Save.java) public class Save { /*Some other code in here*/ private javax.swing.JTextField refernce; String refernceText = refernce.toString(); } Error Report: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at Save.<init>(Save.java:79) at Constructor.saveMouseClicked(Constructor.java:444) at Constructor.access$200(Constructor.java:15) at Constructor$3.mouseClicked(Constructor.java:210) at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270) ... (it carry on(ask if you need it)) So where have I gone wrong??? Also there are no syntax errors etc...
It looks like you declared reference (which by the way is a terrible name for a variable) of type JTextField in the class Save, but you never initialized it. That is why you are getting a NullPointerException. You new it in the Constructor class. After you have newed the JTextField in the constructor class, you need to pass the JTextField variable as an argument to either the constructor of the Save class, or to a method of the Save the class, and use that to get the text from the text field. Also, you don't want to call toString on the JTextField. toString will not get you the data in the textfield. You want getText().
0.888889
JTextField in Save class
Natty freezes constantly after install
I've just installed 11.04 and now at random everything freezes. The keyboard responds but the only thing that seems to unlock it is a reisub. I never had this problem before and I've had this computer for almost a year. I'm using gnome 3 but it also happens when I'm using unity. Even if I don't have any programs running soon or later it freezes. I've seen some similar questions here like this and this but no solution.
Sounds like a sync issue (which I thought they'd already patched). Try this and see if it helps: Grab the compiz settings manager like so: sudo apt-get install compizconfig-settings-manager Open it up and browse to the openGL plug-in. Look for the "Sync to VBlank" option and uncheck it.
0.888889
Install compizconfig-settings manager