source
list
text
stringlengths
99
98.5k
[ "pets.stackexchange", "0000002911.txt" ]
Q: Can trancing a rabbit have cumulative negative effects? Trancing a rabbit (See How do I trance my rabbit?) is used as a method for controlling the pet while doing some grooming to scent glands and toenails. I have received some questions about possible, long term cumulative negative effects, and I am looking for answers that document long term negative impacts to the rabbit. A: Trancing is, for those unaware, the use of the natural fear state of prey animals to go into a near death-like state in order to convince predators that they are dead and should stop being attacked. This is called tonic immobility or TI for short. The immediate side-effects of coming out of TI include things like increased respiration, heart rate, and plasma corticosterone (a steroid found in many animals). So, if you consider that that basic situation is that the rabbit has been put into a state of extreme fear and that the response after release is to escape and hide which, after all, is the purpose of TI in the first place, then the significant impact would be to its trust in humans and its willingness to engage in their surroundings. The impact would only get worse the more frequently the rabbit is tranced and when tranced for long periods of time. In effect, the long term negative is to make the rabbit generally regular feel fear and anxiety in an environment that they can't get out of. The health impacts of that can include: Sudden death as a result of increased arterial hypertension, hypotension, and heart failure from increased adrenaline in the system. Basically, the rabbit might not actually trance at some point, they might actually die. Essentially scared to death. Exertional myopathy which is basically a muscle disease that can become acute through repeated stress and fear. There's a lot of potential problems that can result as a consequence of that as the linked abstract discusses. Immediate injury as a result of escaping from the situation post trance. The rabbit is in fear, its reactions will not be normal. In general, I would resort to trancing in only absolute necessity and avoid using it in a regular fashion if it all possible.
[ "stackoverflow", "0006766190.txt" ]
Q: java: How to add Transparent Gradient Background to JFrame java: I want to use the Gradient style Transparent Background to JFrame. On the top the transparency should be 100% but when going down it should go on decreasing and at the bottom it should be 20% I know i can use the images already having such effect but i want to provide the themes facility and allowing user to use their favorite images but allow transparency at the run time. A: Sun added support for translucent backgrounds to java in 6u10 but it is not formally described in the API. In Java 7 the functionality was formally added to the API via the setBackground(), setOpacity(), and setShape() methods of the Window class. The behavior is described by Oracle here Towards the bottom there is a code example for the gradient effect. The technique will only work if the underlying OS window manager supports it. X11 (Linux) requires a compositing window manager to be installed and configured correctly. This is documented in the known issues of the Java 7 release notes and in this bug.
[ "stackoverflow", "0050683759.txt" ]
Q: Using a global with Ng-Packagr in an Angular library Given that we're trying to reference Lodash in an Angular project to be built using ng-packagr, we're getting the following error: error TS2686: '_' refers to a UMD global, but the current file is a module. Consider adding an import instead. This suggests to me that it's not correctly picking up the typescript definitions file we have set up. The error only occurs when using ng-packagr to build. When using ng-serve to test the demo app it works fine. typings.d.ts /* SystemJS module definition */ declare var module: NodeModule; interface NodeModule { id: string; } // lodash global typing - begin declare namespace _ { } // lodash global typing - end I've seen various issues on ng-packagr's github page talking about using externals or embedded, but the documentation is pretty sparse and experimentation in this area hasn't yielded any leads for me to follow. I've seen this snippet pop up a few times, which appears to accurately reference the correct path. ng-package.json ... "externals": { "lodash": "./node_modules/lodash/index.js" }, ... Anyone got any ideas how I might debug and investigate this? A: I've found a workaround for this problem but I'm unsatisfied with the solution. In the following link, ng-packagr's author recommends using a triple slash reference to reference the .d.ts. https://github.com/dherges/ng-packagr/issues/908
[ "stackoverflow", "0046224203.txt" ]
Q: exponential backoff implementation in python I have two lists 'start' and 'end'. They are of the same length (4 million each): for i in xrange(0,len(start)): print start[i], end[i] 3000027 3000162 3000162 3000186 3000186 3000187 3000187 3005000 3005000 3005020 3005020 3005090 3007000 3007186 3007186 3009000 3009000 3009500 ....... My problem is that I want to iterate the two lists, starting at the same point, but but progressively iterate along the 'end list' until I find a value where the difference between 'start[i]' and 'end[i+x]' is greater than 1000. I have made my best attempt at doing this where I use an endless loop to iterate the 'end list' until the difference with start exceeds 1000 and then start from that point and perform the same operation from there... NOTE: old content omitted Ultimately the output that I am looking for is (taking the illustrative figure above as an example): print density [4, 2, 1 ...........] Can anyone help me with this? UPDATE While the previous answer to this question does indeed work: density=[] i_s = 0 while i_s < len(start): i_e = i_s while i_e < len(end): if end[i_e] - start[i_s] > 1000: density.append(i_e - i_s + 1) i_s = i_e break i_e += 1 i_s += 1 print sum(density)/float(len(density)) print max(density) print min(density) I am afraid that the code is extremely slow as I am updating the extension of 'i_e' by adding 1 to it with each iteration of the inner while loop... To solve this I wanted to create a 'counter' variable that will extend the 'i_e' variable dynamically. This will be done with recursion whereby the i_e variable will be increased exponentially up until the point where half the desired distance is reached and then will be exponentially decreased until the desired distance is reached. Strategy illustration My attempt at this is as follows: I created a recursive a function to update a variable 'counter' counter=1 ##### initialise counter with value of 1 def exponentially_increase_decrease(start, end, counter): distance=end-start if distance<=500: ###500 is half the desired distance counter=exponentially_increase_decrease(start, end, counter*2) else: counter=-exponentially_increase_decrease(start, end, counter/2) print counter return counter Calling the function within the original code: density=[] i_s = 0 while i_s < len(start): i_e = i_s while i_e < len(end): if end[i_e] - start[i_s] > 1000: density.append(i_e - i_s + 1) i_s = i_e break counter=counter=exponentially_increase_decrease(i_s, i_e, counter) i_e += counter i_s += 1 I get the following error: (Printed thousands of times) counter=exponentially_increase_decrease(start, end, counter*2) RuntimeError: maximum recursion depth exceeded I am not experienced with this kind of problem and am not sure if I am approaching it correctly... can anyone help? A: This is one of the few cases where I find while loops to be more straight-forward, since i_e and i_s depend on each other. You could use two range iterators, and advance the former by how much you've consumed from the latter, but that seems overly complicated. >>> start [3000027, 3000162, 3000186, 3000187, 3005000, 3005020, 3007000, 3007186, 3009000] >>> end [3000162, 3000186, 3000187, 3005000, 3005020, 3005090, 3007186, 3009000, 3009500] >>> i_s = 0 >>> while i_s < len(start): ... i_e = i_s ... while i_e < len(end): ... if end[i_e] - start[i_s] > 1000: ... print(i_e - i_s + 1) ... i_s = i_e ... break ... i_e += 1 ... i_s += 1 ... 4 3 1
[ "askubuntu", "0000218836.txt" ]
Q: How to open multiple instances of the bash Terminal? Under Ubuntu 10 I could easily open as many Terminal instances as I needed, and I often need 6 or more. How can I do that in Ubuntu 12? When are they going to fix the bug that restricts me to only one? A: There is absolutely nothing in Ubuntu that restricts you to opening only one terminal window. At the moment I have anout 30 terminal windows open :) A: Difference between Gnome 2 and the "new" Unity I think you are referring to the behavior of the panel on the left side of screen which is now similar to a mac. When you click on an icon, the application is started. If, however, the application is running already, you will switch to its window. For users of good old Gnome 2, this may be irritating. There, starters were for starting applications. No matter how often you click them and no matter what is already running, they start a new window. Switching between windows was done via a separate panel which lists all running application. In Unity, the panel takes over both tasks. Launching and switching to applications. It assumes that the typical use case is to have one instance of an application open and maybe use its built-in tab support. Multiple Windows in Unity However, there is a possibility to open multiple windows by using just the mouse. Just right click on the element and select New Terminal. A more convenient way involving also the keyboard is holding Shift and left clicking on the application icon. A third possibility to start the terminal (which is the one I prefer) is using the shorcut Ctrl+Alt+T. Choose what you like most. As you can see, its not a bug, its just a big change on the user interface.
[ "stackoverflow", "0055576502.txt" ]
Q: How to perform a LINQ where clause with a dynamic column I am attempting to use System.Linq.Dynamic.Core (https://github.com/StefH/System.Linq.Dynamic.Core) in order to create dynamic queries. Following the example given on the github page, I have tried the following lstContacts = lstContacts.Where("@0 == true", "active"); However I get the following result: 'active is not a valid value for Boolean A: Reference this library: using System.Linq.Dynamic; And make your query like that: string columnName = "active"; var lstContacts = lstContacts.Where(columnName + " == true"); Here is a working example: using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic; public class Program { public static void Main() { var lstContacts = new List<Contact>{ new Contact{Id = 1, Active = true, Name = "Chris"}, new Contact{Id = 2, Active = true, Name = "Scott"}, new Contact{Id = 3, Active = true, Name = "Mark"}, new Contact{Id = 4, Active = false, Name = "Alan"}}; string columnName = "Active"; List<Contact> results = lstContacts.Where(String.Format("{0} == true", columnName)).ToList(); foreach (var item in results) { Console.WriteLine(item.Id.ToString() + " - " + item.Name.ToString()); } } } public class Contact { public int Id { get; set; } public bool Active { get; set; } public string Name { get; set; } } You can experiment with this .net-fiddle-here
[ "serverfault", "0000265883.txt" ]
Q: Can Apache deny access if REMOTE_USER doesn't match the subdomain? I'd like to deny access if the REMOTE_USER does not match SUBDOMAIN.example.com. The site is protected by Require valid-user (as usual). Currently anybody can access all areas so long as she's logged in. The intended behavior is this: alice can access alice.example.com and nothing else bob can access bob.example.com and nothing else bonus points for granting all-access to admin Sound too easy? Here's the catch: Subdomains/usernames are dynamic, so any hard-coded "alice" or "bob" strings do not count! Is there any way I can do that with Apache? Thanks! A: As the apps I'm trying to authorize are all Rack apps, I've ended up implementing this as a Rack middleware, released as the Portarius gem.
[ "stackoverflow", "0045200002.txt" ]
Q: Convert csv to double list with c# with the following code Im trying to read a csv file that contains double values and convert it into a list. If I want to print that list The output just contains "system.collections.generic.list1 system.string". What is wrong in my code? var filePath = @"C:\Users\amuenal\Desktop\Uni\test.csv"; var contents = File.ReadAllText(filePath).Split(';'); var csv = from line in contents select line.Split(';').ToList(); foreach (var i in csv) { Console.WriteLine(i); } A: You got a couple things wrong with your code. First, you should most likely be using ReadAllLines() instead of ReadAllText(). Secondly, your LINQ query was returning a List<List<string>> which I imagine is not what you wanted. I would try something like this: var filePath = @"C:\Users\amuenal\Desktop\Uni\test.csv"; //iterate through all the rows foreach (var row in File.ReadAllLines(filePath)) { //iterate through each column in each row foreach(var col in row.Split(';')) { Console.WriteLine(col); } }
[ "stackoverflow", "0021393684.txt" ]
Q: Populate Select element with LINQ and WebForms Here is my select list. <div class="field"> <select name="position" id="position" class="grayed" onclick="this.className=this.options[this.selectedIndex].className"> <option value="" disabled="disabled" selected="selected" class="disabled">Applicant's position</option> </select> <div id="arrow-select"></div> <svg id="arrow-select-svg"></svg> <span class="entypo-book icon"></span> <span class="slick-tip left">Choose Position</span> </div> Here is my LINQ: from v in Jobs select new { ID = v.Id, Title = v.Title } How do I combine the two so the select list is populated with what is returned from the LINQ query? It has to be a select element not the asp:dropdown. A: Add runat="server" into your select html tag In your code behind, use the ID of your select: var data = from v in Jobs select new { ID = v.Id, Title = v.Title }; position.DataSource = data.ToList(); position.DataTextField = "Title"; position.DataValueField = "ID"; position.DataBind(); position.Items.Insert(0, new ListItem("Applicant's position", ""));
[ "unix.stackexchange", "0000124437.txt" ]
Q: Reboot when there is a hardware failure without physical access to machine? I'm getting this error message whathever I do: $ sudo reboot bash: /usr/bin/sudo: Input/output error $ reboot bash: /sbin/reboot: Input/output error It's a hardware failure according to this question. Is there anyway that I can reboot the machine without physically pull the the plug. The machine is not close to me. I can SSH into the machine. ls, pwd, echo, cat and some other apps are working. Things like ps, vim and killall are not working. A: If you have root access, you can try to do this: # echo b > /proc/sysrq-trigger (that will immediately reboot the system without syncing or unmounting your disks.) Unfortunately, I do not think there is a way to reboot without root privileges.
[ "stackoverflow", "0026871000.txt" ]
Q: Cannot login properly in Grails I've a grails application using Grails 2.3.9, and the Spring security plugin. When I login to my page, the request is redirected to /[context]/grails-errorhandler, with the text: Sorry, you're not authorized to view this page. But when I access manually to /[context]/ , I can access to the website without problems! The log says this: intercept.FilterSecurityInterceptor Previously Authenticated: <my authentication token>@20870684 hierarchicalroles.RoleHierarchyImpl getReachableGrantedAuthorities() - From the roles [<many roles>] one can reach <same roles>] in zero or more steps. support.XmlWebApplicationContext Publishing event in Root WebApplicationContext: org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: URL: /grails-errorhandler] access.ExceptionTranslationFilter Access is denied (user is not anonymous); delegating to AccessDeniedHandler <more stacktrace> Did you know what kind of problem is this? A: I found the problem, but I don't know why this happens... In the UrlMappings, I added the next rule: "404"(controller:'error', action:'notFound') (I have an "ErrorController"). But I don't know why this change causes the problem with spring security, but if I remove it, the application works without problems. Thanks! Specially to getbuckts for the comment :)
[ "stackoverflow", "0031494231.txt" ]
Q: with trackId in AVMutableVideoComposition so I am working on this video editor project and I faced a problem with getting the trackID I searched every where I know and all I can found was some objective-c code which I couldn't transform it to swift I get the error in this line : layer?.trackID = videoAsset?.tracksWithMediaType(AVMediaTypeVideo) The Error is Cannot assign to the result of this expression This is my code: import UIKit import MobileCoreServices import AVFoundation import AVKit class VideoMakerViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIVideoEditorControllerDelegate { var videoAsset: AVAsset? = nil var videoEditor: AVMutableVideoComposition? = nil var videoEditorInstroctions: AVVideoCompositionInstruction? = nil var layer: AVVideoCompositionLayerInstruction? = nil override func viewDidLoad() { super.viewDidLoad() } @IBAction func chooseVideo(sender: AnyObject) { var videoPicker = UIImagePickerController() videoPicker.delegate = self videoPicker.sourceType = .PhotoLibrary videoPicker.mediaTypes = [kUTTypeMovie] videoPicker.allowsEditing = false presentViewController(videoPicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { dismissViewControllerAnimated(true, completion: nil) let url = info[UIImagePickerControllerReferenceURL] as! NSURL let videoName = url.path!.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String let localPath = documentDirectory.stringByAppendingPathComponent(videoName) println(videoName) videoAsset = AVURLAsset(URL: url, options: nil) videoEditorInstroctions?.backgroundColor = UIColor.blueColor().CGColor layer?.trackID = videoAsset?.tracksWithMediaType(AVMediaTypeVideo) videoEditor = AVMutableVideoComposition(propertiesOfAsset: videoAsset) videoEditor?.frameDuration = CMTimeMake(60, 30) videoEditor?.renderSize = CGSize(width: 600, height: 1000) videoEditor?.renderScale = Float(1) println(videoAsset?.duration) } } A: First: trackID is read-only. To be able to assign anything to it, you have to use AVMutableVideoCompositionLayerInstruction instead of AVVideoCompositionLayerInstruction. Second: tracksWithMediaType returns An array of AVAssetTrack objects of the asset that present media of mediaType. while trackID is of type CMPersistentTrackID. Therefore you cannot assign one to the other. You can however / have to retrieve the ID your are looking for from any of the objects in the returned array: layer?.trackID = (videoAsset?.tracksWithMediaType(AVMediaTypeVideo)[0].trackID)! or layer?.trackID = videoAsset!.tracksWithMediaType(AVMediaTypeVideo)[0].trackID
[ "stackoverflow", "0039619121.txt" ]
Q: Why am I getting 'Terminated due to timeout' error here? I'm solving this problem on Hackerrank. John Watson performs an operation called a right circular rotation on an array of integers, [a[0],a[ 1]......a[n]].After performing one right circular rotation operation, the array is transformed from [a[0],a[ 1]......a[n]] to [a[n- 1],a[0]......a[n-2]]. Watson performs this operation 'k' times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks 'q' queries, where each query consists of a single integer, 'm', for which you must print the element at index in the rotated array (i.e., the value of a[m] ). Input Format The first line contains 3 space-separated integers,'n' ,'k' , and , 'q' respectively. The second line contains 'n' space-separated integers, where each integer 'i' describes array element a[n] (where 0<=i Output Format For each query, print the value of the element at index 'm' of the rotated array on a new line. #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n,k,q,temp; cin>>n>>k>>q; //Input of n,k,q; int arr[n],qur[q]; for(int i=0;i<n;i++) //Input of array { cin>>arr[i]; } for(int i=0;i<q;i++) //Input of query numbers { cin>>qur[i]; } for(int z=0;z<k;z++) { temp = arr[n-1]; for(int i=n-1;i>0;i--) { arr[i]=arr[i-1]; } arr[0]=temp; } for(int i=0;i<q;i++) { cout<<arr[qur[i]]<<endl; } return 0; } The code's logic seems to be flawless. I'm a newbie.Thanks in advance. A: The reason is that you don't really need to perform the rotation, you can use The Ancient Power of Mathematics. (Performing the rotation can require 10 billion arr[i]=arr[i-1]s, and doing that 500 times would take a while.) If you start with the sequence Element: | 12 | 34 | ... | 56 | 78 | (1) Index: 0 1 ... k-1 k and right-rotate by one, you get Element: | 78 | 12 | 34 | ... | 56 | (2) Index: 0 1 2 ... k or, changing the viewpoint just a little bit: Element: | 12 | 34 | ... | 56 | 78 | (3) Index: 1 2 ... k 0 There's a fairly simple relationship between the indices of the elements in (1) and (3), and you only need some arithmetic to get from one to the other. Discovering the relationship and performing the arithmetic left as an exercise.
[ "scifi.stackexchange", "0000144239.txt" ]
Q: Old SF story about the need to destroy an out-of-control passenger ship with a nuke before it crashes? I'm trying to pin down a memory of a short story which I first read sometime in the early-to-mid 1980s (in an anthology I found in a school library, I think). I later found it again in another book, in another library, sometime in the 1990s. I remember the general plot, but not who wrote it. I have the impression that the story was already pretty old before I first ran across it. Here's the plot outline: As the story begins, a spaceship containing hundreds (or even more?) of passengers is returning to Earth from some other planet. Something goes terribly wrong, and they lose the main engine. (Which may have been the only engine -- I'm not sure of the technical details.) I don't recall if it was accident, sabotage, a meteor strike, or what, but their main means of propulsion is gone, with no hope of fixing it any time soon. The timing is terrible. The ship is still on a trajectory that has it approaching Earth at high speed, and it badly needs to decelerate if there's to be any hope of touching down safely instead of slamming into the planet so hard that it will inevitably kill everyone aboard. But now the ship can't decelerate (nor change course to miss Earth entirely, which could have bought them valuable time), and there's only a matter of some hours left before the projected time of impact. Some political and military leaders meet on Earth for an emergency conference to discuss their options. What it comes down to is that a) there is no way to save the passengers and crew of the ship, no matter what they do, but b) if they do nothing at all, this will also mean the tragic deaths of millions of other civilians in the region which the ship will crash into. Not so much because of the shock of impact, but because of the sound in the minute or so before that. My memory gets blurred on the physical details of what makes the sound so bad . . . but I think the general idea may have been that such a huge metallic mass, moving so incredibly fast as it comes down toward the Eastern Seaboard of North America (or perhaps some other densely populated bit of the globe?), will be "screaming" in such a way that the vibrations racing through the air will shatter zillions of pieces of glass and/or otherwise cause huge numbers of fatalities down on the ground, even before the ship strikes whatever bit of the Earth's surface it is projected to strike. The final decision is that the lesser of two evils is to send up a missile (nuclear warhead, I think?) to vaporize the ship before it comes plummeting through the air near an urban area. I think that the officers aboard the ship either already knew, or very strongly suspected, that everyone aboard was doomed after the main engine had dropped dead. But the Captain and his loyal subordinates do their best to maintain a stiff upper lip in order to prevent mass hysteria from breaking out among the passengers. There's one bit where it is announced that a rescue ship is coming up from Earth to pull alongside the falling ship and then they'll transfer the passengers to safety. I believe the Captain knows darn well that the laws of physics do not make such a maneuver possible at this late date, and thus "a rescue mission" cannot be the intended function of the fast-moving blip on the radar screen that is headed straight for his ship, but he sees nothing to be gained by telling everyone the truth. So most of them die in blissful ignorance. A: It's the novelette "Sound Decision" by Robert Silverberg and Randall Garrett. You can read it here. It was adapted to radio (drastically abridged) as an episode of Exploring Tomorrow which you can listen to here. Here are some excerpts to show how the story fits your description. The spaceship is coming in from Mars: The Martian Queen was a luxury liner of some five hundred metric tons, belonging to Barr Spaceways. She was, at the time, making a "short-run” orbit from Mars to Earth, carrying a hundred and fifty passengers and a crew of thirty, including stewards. The cause of the mishap is unknown: Just exactly what went wrong with the drivers isn't known or knowable; the four men who might have known were dead within seconds after it happened. There are several things that could have caused the disaster—an accident which, except for the level-thinking of one man, might have caused the deaths of many more than the mere handful who died in a sudden blaze of light. The passengers are told a comforting lie which is literally true: "Your attention please! Your attention please! The ship is falling out of control, but there is absolutely no danger of our hitting Earth. A rocket from the spaceport will be here in two minutes. Repeat: a rocket from the spaceport will be here in two minutes. Please wait quietly, and be ready for it when it comes.” The danger to people on the ground is from the shock wave: "But its actual impact with Earth’s surface isn't going to be the thing that will do the damage. It won’t matter whether it comes down in Long Island Sound or in Times Square—it’s the impact with the atmosphere that will cause about twenty million deaths.” No one said anything. The five men in the screen looked at him in blank-faced horror. "You know what happens when a jet plane goes over a city too low?" Stanley said. "A supersonic jet can break windows. What sort of sound wave do you think a five-hundred-metric-ton spaceship will cause at—seventy-two thousand miles an hour? "I’ll tell you. It would flatten every structure for miles around. If that ship hits Long Island Sound, New York City will be toppling in ruins before it ever arrives! Every town on Long Island is going to be pancaked. From Newark, New Jersey, to Hartford, Connecticut, that shock wave will knock over everything standing. This isn’t a matter of a few people in a ship dying; it's a matter of millions!” The spaceship is nuked: "Oh, it won’t land,” said Stanley. His voice sounded old and tired. "There won’t be any crash. I sent up an XV-19 under robot control several minutes before you gentlemen got together. It was loaded with a thermo nuclear warhead. Captain Deering will—or I should say has—guided it in. The Martian Queen was vaporized over a minute ago. It was the only thing to do.”
[ "stackoverflow", "0025486674.txt" ]
Q: Vaadin Add new column to existing table I'm having some problems to add new column to my table that is generated from one JPAContainer. The question is... I can add a new column to my existing table if my fields are inserted from JPAContainer? My code looks like... persons = JPAContainerFactory.make(Users.class, PERSISTENCE_UNIT); persons.sort(new String[]{"niu"}, new boolean[]{true}); table_1.setWidth("100%"); table_1.setSelectable(true); // Hacemos que se puedan seleccionar las filas del Grid. table_1.setMultiSelect(false);// Selección de múltiples filas del Grid. table_1.setContainerDataSource(persons); table_1.addContainerProperty("admin_vis", String.class, null); for (Iterator i = table_1.getItemIds().iterator(); i.hasNext();) { Object itemIdentifier = i.next(); Item item = table_1.getItem(itemIdentifier); String admin = (String) item.getItemProperty("admin").getValue(); Item item1 = ((Container) table_1.getContainerProperty(String.class, "admin_vis")).addItem("row"+i); if(admin.equals("Y")) { Property property = item1.getItemProperty("admin_vis"); property.setValue("true"); } else { Property property = item1.getItemProperty("admin_vis"); property.setValue("false"); } } table_1.setVisibleColumns(new Object[] { "niu", "nom", "mail", "admin_vis" }); table_1.setColumnHeaders(new String[] { "Niu", "Nom", "Mail", "Admin", }) table_1.setPageLength(15); table_1.setImmediate(true); The error that I'm having is: Caused by: java.lang.UnsupportedOperationException at com.vaadin.addon.jpacontainer.JPAContainer.addContainerProperty(JPAContainer.java:666) at com.vaadin.ui.AbstractSelect.addContainerProperty(AbstractSelect.java:772) at com.vaadin.ui.Table.addContainerProperty(Table.java:4099) Hope someone can help me. Thanks for advice! A: I answer to my own, the better solution that I find to this problem is next... table_1.addGeneratedColumn("mycolumn", new ColumnGenerator() { public Object generateCell(Table source, Object itemId, Object columnId) { Item item = source.getItem(itemId); String admin = (String) item.getItemProperty("admin").getValue(); return admin.equals("Y") ? "true" : "false"; } }); With this form all correctly works, thanks for reading. Greetings
[ "stackoverflow", "0008756048.txt" ]
Q: Can't seem to get a response from my SoapClient I'm just getting started with soap communication through php. I have access to a webservice that returns a true or false dependant on three attributes 'username', 'password' and 'domain' Here's my anonymised request code: //VARS $username = 'example'; $password = 'example'; $domain = 'example'; $client = new SoapClient("https://www.example.com/example.wsdl"); try { $client->authenticate(array($email, $password, $domain)); echo $client->__getLastResponse(); } catch (SoapFault $e) { echo $e->getMessage(); } die(); Now, as I mentioned, I'm new to this so I'm not sure that what I've written is even correct, please help! Here are the relevant parts of the wsdl (again, anonymised): //MESSAGE <message name="AuthenticateRequest"> <part type="xsd:string" name="username"/> <part type="xsd:string" name="password"/> <part type="xsd:string" name="domain"/> </message> <message name="AuthenticateResponse"> <part type="xsd:boolean" name="authenticationResponse"/> </message> //OPERATION <portType name="LDAPPortType"> <operation name="authenticate"> <documentation> Connects to the LDAP server with the parameters provided. If successful, this function then attempts to bind to the LDAP directory with the user's credentials. The function returns TRUE on success or FALSE on failure. </documentation> <input message="tns:AuthenticateRequest"/> <output message="tns:AuthenticateResponse"/> </operation> </portType> Have I missed anything crucial? Thanks for your help, it's greatly appreciated! A: I think you are going to need $username instead of $email in this line $client->authenticate(array($email, $password, $domain)); ^ Also try to specify parameter names in array as: $client->authenticate(array("username"=>$username, "password"=>$password, "domain"=>$domain));
[ "stackoverflow", "0020103882.txt" ]
Q: link for max characters in javascript not working Ive got a js that runs to see if a maximum amount of characters is reached. Its got text along with href, but when the max amount of characters is reached, the link doesnt work and converts it to just text. When the limit of less then 580 characters, link works. When it does reach the limit, the read more link does work. Any advice or help please and thanks $(document).ready(function () { var stylistText = $('#stylistText'); var stylistText2 = document.getElementById("stylistText").innerHTML; var countActualText = stylistText2.valueOf().length; var maxLength = 580; var aElement = document.createElement('a'); var linkText = document.createTextNode(" ...Read more"); aElement.appendChild(linkText); aElement.href = "#"; if (countActualText > maxLength) { stylistText.text(stylistText.text().substring(0, 580)); stylistText.append(aElement); } }); here is the html <div class="stylistInfo"> <img id="stylistPhoto" src="images/Test.jpg" alt="peekaboo beans stylist" /> <p id="stylistText"> <a href="sdf">This is supposed to be a link</a> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet. </p> </div> A: Change stylistText.text(stylistText.text().substring(0, 580)); to stylistText.html(stylistText.html().substring(0, 580)); However, truncating a block of text that contains HTML may cause other problems, especially if the truncation occurs in the middle of an element. I would recommend rethinking your whole strategy on this.
[ "sharepoint.stackexchange", "0000104675.txt" ]
Q: Access personal views in a list with PowerShell I am trying to first access and then edit Personal Views for a SharePoint List using PowerShell. However only the public views are returned. In the example below the list called List1 has two views - 1 public and 1 personal created by a regular user account (contoso\user1). I run the script below via an admin account (contoso\spadmin) - $url= "http://portal.contoso.com/sites/TEST" $web = Get-SPWeb $url $list = $web.Lists["List1"] Write-Output "Count = $($list.views.count)" $list.views| % {Write-Output "Title = $($_.title)"} Result - Count = 1 Title = All Items I tried the following as well but that did not return the personal views. [Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges( { $web = Get-SPWeb $url $list = $web.Lists["List1"] Write-Host "Count = $($list.views.count)" $list.views| % {Write-Host "Title = $($_.title)"} } ) How do I access the personal views for a list with PowerShell? A: If you want to access the user's personal view you need to create the SPSite object with that particular user's Token. Below is the sample code which shows how to access the personal views in C# code. You can create equivalent powershell code. This code gives you idea how to get the personal views. static void GetViews(SPSite site) { SPWeb spweb = site.OpenWeb(); foreach(SPUser oUser in spweb.AllUsers) { SPSecurity.RunWithElevatedPrivileges(delegate() { try { SPSite oElevSite = new SPSite(site.ID, oUser.UserToken); SPWeb oElevWeb = oElevSite.RootWeb; SPList splist = oElevWeb.Lists["CustomStatusList"]; SPViewCollection views = splist.Views; foreach (SPView view in views) { if (view.PersonalView) { Console.WriteLine(oUser.Name +":"+ view.Title); } } oElevWeb.Dispose(); oElevSite.Dispose(); } catch { } }); } } In powershell you can use usertoken as: $user=$web.AllUsers.GetByID(1073741823) $token = $user.UserToken; $impWebObj= New-Object Microsoft.SharePoint.SPSite($web.Url, $token);
[ "stackoverflow", "0021287919.txt" ]
Q: Is initWithNibName method useless In the case we are setting up the the viewcontroller from storyboard then creating a viewcontroller class and attaching it the class to storyboard view. It seems this method is pointless, am I correct? Or are there some cases where this maybe useful? - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } A: What if you're storyboard is going to have many view elements and you don't want to add them programmatically, nor do you want to clutter your storyboard but you'd still rather use IB? That's at least one scenario. Basically it depends on how your app grows, and how you intend to refactor it. Perhaps at the moment you don't find a need to use it, but what about later? Using it, or having the option to use it, is just another tool in your toolbox. -- Update @trojanfoe has a good point as well. Programmatically creating your VCs and getting their views from a NIB
[ "codegolf.stackexchange", "0000026407.txt" ]
Q: Circle Maze Checker You know those wooden toys with little ball bearings where the object is to move around the maze? This is kinda like that. Given a maze and a series of moves, determine where the ball ends up. The board is held vertically, and the ball moves only by gravity when the board is rotated. Each "move" is a rotation (in radians). The maze is simply concentric circular walls, with each wall having exactly one opening into the outer corridor, similar to this (assume those walls are circles and not pointed): As you can see, the ball starts in the middle and is trying to get out. The ball will instantly fall through as soon as the correct orientation is achieved, even if it's midway through a rotation. A single rotation may cause the ball to fall through multiple openings. For instance, a rotation >= n * 2 * pi is enough to escape any maze. For the purposes of the game, a ball located within 0.001 radians of the opening is considered a "fit", and will drop through to the next corridor. Input: Input is in two parts: The maze is given by an integer n representing how many walls/openings are in the maze. This is followed by n lines, with one number on each, representing where the passage to the next corridor is. The moves are given as an integer m representing how many moves were taken, followed (again on separate lines) by m clockwise rotations of the board in radians (negative is anticlockwise). All passage positions are given as 0 rad = up, with positive radians going clockwise. For the sample image above, the input may look like this: 7 // 7 openings 0 0.785398163 3.14159265 1.74532925 4.71238898 4.01425728 0 3 // 3 moves -3.92699082 3.14159265 0.81245687 Output: Output the corridor number that the ball ends in. Corridors are zero-indexed, starting from the center, so you start in 0. If you pass through one opening, you're in corridor 1. If you escape the entire maze, output any integer >= n For the sample input, there are three moves. The first will cause the ball to fall through two openings. The second doesn't find an opening, and the third finds one. The ball is now in corridor 3, so expected output is: 3 Behavior is undefined for invalid input. Valid input is well-formed, with n >= 1 and m >= 0. Scoring is standard code golf, lowest number of bytes wins. Standard loopholes are forbidden. Input must not be hard-coded, but can be taken from standard input, arguments, console, etc. Output can be to console, file, whatever, just make it output somewhere visible. A: JavaScript 200 function f(i){with(Math)for(m=i.split('\n'),o=m.slice(1,t=+m[0]+1),m=m.slice(t+1),c=PI,p=2*c,r=0,s=1e-3;m.length;c%=p)abs(c-o[r])<s?r++:abs(t=m[0])<s?m.shift(c+=t):(b=t<0?-s:s,c+=p-b,m[0]-=b);return r} EDIT : Here is an animated example proving that this solver works : http://jsfiddle.net/F74AP/4/ The function must be called passing the input string. Here is the call of the example given by the OP : f("7\n0\n0.785398163\n3.14159265\n1.74532925\n4.71238898\n4.01425728\n0\n3\n-3.92699082\n3.14159265\n0.81245687"); It returns 3 as intended. A: Perl, 211 191 With newlines and indentation for readability: $p=atan2 0,-1; @n=map~~<>,1..<>; <>; while(<>){ $_=atan2(sin,cos)for@n; $y=abs($n[$-]+$_)<$p-.001 ?$_ :($_<=>0)*$p-$n[$-]; $_+=$y for@n; $p-.001<abs$n[$-]&&++$-==@n&&last; $_-=$y; .001<abs&&redo } print$- Number of moves in the input is discarded, stdin's eof indicates end of moves.
[ "stackoverflow", "0043307582.txt" ]
Q: How to access hadoop cluster which is Kerberos enabled programmatically? I have this piece of code which can fetch a file from a Hadoop filesystem. I setup hadoop on a single node and from my local machine ran this code to see if it would be able to fetch file from HDFS setup on that node. It worked. package com.hdfs.test.hdfs_util; /* Copy file from hdfs to local disk without hadoop installation * * params are something like * hdfs://node01.sindice.net:8020 /user/bob/file.zip file.zip * */ import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class HDFSdownloader{ public static void main(String[] args) throws Exception { System.getProperty("java.classpath"); if (args.length != 3) { System.out.println("use: HDFSdownloader hdfs src dst"); System.exit(1); } System.out.println(HDFSdownloader.class.getName()); HDFSdownloader dw = new HDFSdownloader(); dw.copy2local(args[0], args[1], args[2]); } private void copy2local(String hdfs, String src, String dst) throws IOException { System.out.println("!! Entering function !!"); Configuration conf = new Configuration(); conf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); conf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); conf.set("fs.default.name", hdfs); FileSystem.get(conf).copyToLocalFile(new Path(src), new Path(dst)); System.out.println("!! copytoLocalFile Reached!!"); } } Now I took the same code, bundled it in a jar and tried to run it on another node(say B). This time the code had to fetch a file from a proper distributed Hadoop cluster. That cluster has Kerberos enabled in it. The code ran but gave an exception : Exception in thread "main" org.apache.hadoop.security.AccessControlException: SIMPLE authentication is not enabled. Available:[TOKEN, KERBEROS] at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106) at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:73) at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:2115) at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1305) at org.apache.hadoop.hdfs.DistributedFileSystem$22.doCall(DistributedFileSystem.java:1301) at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81) at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1317) at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:337) at org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:289) at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:2030) at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:1999) at org.apache.hadoop.fs.FileSystem.copyToLocalFile(FileSystem.java:1975) at com.hdfs.test.hdfs_util.HDFSdownloader.copy2local(HDFSdownloader.java:49) at com.hdfs.test.hdfs_util.HDFSdownloader.main(HDFSdownloader.java:35) Is there a way to programatically make this code run. For some reason, I can't install kinit on the source node. A: Here's a code snippet to work in the scenario you have described above i.e. programatically access a kerberos enabled cluster. Important points to note are Provide keytab file location in UserGroupInformation Provide kerberos realm details in JVM arguments - krb5.conf file Define hadoop security authentication mode as kerberos import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.UserGroupInformation; public class KerberosHDFSIO { public static void main(String[] args) throws IOException { Configuration conf = new Configuration(); //The following property is enough for a non-kerberized setup // conf.set("fs.defaultFS", "localhost:9000"); //need following set of properties to access a kerberized cluster conf.set("fs.defaultFS", "hdfs://devha:8020"); conf.set("hadoop.security.authentication", "kerberos"); //The location of krb5.conf file needs to be provided in the VM arguments for the JVM //-Djava.security.krb5.conf=/Users/user/Desktop/utils/cluster/dev/krb5.conf UserGroupInformation.setConfiguration(conf); UserGroupInformation.loginUserFromKeytab("user@HADOOP_DEV.ABC.COM", "/Users/user/Desktop/utils/cluster/dev/.user.keytab"); try (FileSystem fs = FileSystem.get(conf);) { FileStatus[] fileStatuses = fs.listStatus(new Path("/user/username/dropoff")); for (FileStatus fileStatus : fileStatuses) { System.out.println(fileStatus.getPath().getName()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[ "stackoverflow", "0000278112.txt" ]
Q: Webcam library for C on Linux? Is there any c library to get a video from the webcam on linux? A: A lot of us use OpenCV (cross-platform Computer Vision library, currently on v2.1) The following snippet grabs frames from camera, converts them to grayscale and displays them on the screen: #include <stdio.h> #include "cv.h" #include "highgui.h" typedef IplImage* (*callback_prototype)(IplImage*); /* * make_it_gray: custom callback to convert a colored frame to its grayscale version. * Remember that you must deallocate the returned IplImage* yourself after calling this function. */ IplImage* make_it_gray(IplImage* frame) { // Allocate space for a new image IplImage* gray_frame = 0; gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, 1); if (!gray_frame) { fprintf(stderr, "!!! cvCreateImage failed!\n" ); return NULL; } cvCvtColor(frame, gray_frame, CV_RGB2GRAY); return gray_frame; } /* * process_video: retrieves frames from camera and executes a callback to do individual frame processing. * Keep in mind that if your callback takes too much time to execute, you might loose a few frames from * the camera. */ void process_video(callback_prototype custom_cb) { // Initialize camera CvCapture *capture = 0; capture = cvCaptureFromCAM(-1); if (!capture) { fprintf(stderr, "!!! Cannot open initialize webcam!\n" ); return; } // Create a window for the video cvNamedWindow("result", CV_WINDOW_AUTOSIZE); IplImage* frame = 0; char key = 0; while (key != 27) // ESC { frame = cvQueryFrame(capture); if(!frame) { fprintf( stderr, "!!! cvQueryFrame failed!\n" ); break; } // Execute callback on each frame IplImage* processed_frame = (*custom_cb)(frame); // Display processed frame cvShowImage("result", processed_frame); // Release resources cvReleaseImage(&processed_frame); // Exit when user press ESC key = cvWaitKey(10); } // Free memory cvDestroyWindow("result"); cvReleaseCapture(&capture); } int main( int argc, char **argv ) { process_video(make_it_gray); return 0; } A: v4l2 official examples What you get: ./v4l2grab: capture a few snapshots to files outNNN.ppm ./v4l2gl: show video live on a window using an OpenGL texture (immediate rendering, hey!) and raw X11 windowing (plus GLUT's gluLookAt for good measure). How to get it on Ubuntu 16.04: sudo apt-get install libv4l-dev sudo apt-get build-dep libv4l-dev git clone git://linuxtv.org/v4l-utils.git cd v4l-utils # Matching the installed version of dpkg -s libv4l-dev git checkout v4l-utils-1.10.0 ./bootstrap.sh ./configure make # TODO: fails halfway, but it does not matter for us now. cd contrib/tests make It is also easy to use those examples outside of the Git tree, just copy them out, make relative includes "" absolute <>, and remove config.h. I've done that for you at: https://github.com/cirosantilli/cpp-cheat/tree/09fe73d248f7da2e9c9f3eff2520a143c259f4a6/v4l2 Minimal example from docs The docs 4.9.0 contain what appears to be a minimal version of ./v4l2grab at https://linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/v4l2grab-example.html. I needed to patch it minimally and I've sent the patch to http://www.spinics.net/lists/linux-media/ (their docs live in the Linux kernel tree as rst, neat), where it was dully ignored. Usage: gcc v4l2grab.c -lv4l2 ./a.out Patched code: /* V4L2 video picture grabber Copyright (C) 2009 Mauro Carvalho Chehab <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/time.h> #include <sys/mman.h> #include <linux/videodev2.h> #include <libv4l2.h> #define CLEAR(x) memset(&(x), 0, sizeof(x)) struct buffer { void *start; size_t length; }; static void xioctl(int fh, int request, void *arg) { int r; do { r = v4l2_ioctl(fh, request, arg); } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN))); if (r == -1) { fprintf(stderr, "error %d, %s\\n", errno, strerror(errno)); exit(EXIT_FAILURE); } } int main(int argc, char **argv) { struct v4l2_format fmt; struct v4l2_buffer buf; struct v4l2_requestbuffers req; enum v4l2_buf_type type; fd_set fds; struct timeval tv; int r, fd = -1; unsigned int i, n_buffers; char *dev_name = "/dev/video0"; char out_name[256]; FILE *fout; struct buffer *buffers; fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0); if (fd < 0) { perror("Cannot open device"); exit(EXIT_FAILURE); } CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.width = 640; fmt.fmt.pix.height = 480; fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24; fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; xioctl(fd, VIDIOC_S_FMT, &fmt); if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_RGB24) { printf("Libv4l didn't accept RGB24 format. Can't proceed.\\n"); exit(EXIT_FAILURE); } if ((fmt.fmt.pix.width != 640) || (fmt.fmt.pix.height != 480)) printf("Warning: driver is sending image at %dx%d\\n", fmt.fmt.pix.width, fmt.fmt.pix.height); CLEAR(req); req.count = 2; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; xioctl(fd, VIDIOC_REQBUFS, &req); buffers = calloc(req.count, sizeof(*buffers)); for (n_buffers = 0; n_buffers < req.count; ++n_buffers) { CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers; xioctl(fd, VIDIOC_QUERYBUF, &buf); buffers[n_buffers].length = buf.length; buffers[n_buffers].start = v4l2_mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset); if (MAP_FAILED == buffers[n_buffers].start) { perror("mmap"); exit(EXIT_FAILURE); } } for (i = 0; i < n_buffers; ++i) { CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = i; xioctl(fd, VIDIOC_QBUF, &buf); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; xioctl(fd, VIDIOC_STREAMON, &type); for (i = 0; i < 20; i++) { do { FD_ZERO(&fds); FD_SET(fd, &fds); /* Timeout. */ tv.tv_sec = 2; tv.tv_usec = 0; r = select(fd + 1, &fds, NULL, NULL, &tv); } while ((r == -1 && (errno = EINTR))); if (r == -1) { perror("select"); return errno; } CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; xioctl(fd, VIDIOC_DQBUF, &buf); sprintf(out_name, "out%03d.ppm", i); fout = fopen(out_name, "w"); if (!fout) { perror("Cannot open image"); exit(EXIT_FAILURE); } fprintf(fout, "P6\n%d %d 255\n", fmt.fmt.pix.width, fmt.fmt.pix.height); fwrite(buffers[buf.index].start, buf.bytesused, 1, fout); fclose(fout); xioctl(fd, VIDIOC_QBUF, &buf); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; xioctl(fd, VIDIOC_STREAMOFF, &type); for (i = 0; i < n_buffers; ++i) v4l2_munmap(buffers[i].start, buffers[i].length); v4l2_close(fd); return 0; } Header only object oriented version for reuse Extracted from the example in the docs, but in a form that makes it super easy to reuse. common_v4l2.h: #ifndef COMMON_V4L2_H #define COMMON_V4L2_H #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/time.h> #include <sys/types.h> #include <libv4l2.h> #include <linux/videodev2.h> #define COMMON_V4L2_CLEAR(x) memset(&(x), 0, sizeof(x)) typedef struct { void *start; size_t length; } CommonV4l2_Buffer; typedef struct { int fd; CommonV4l2_Buffer *buffers; struct v4l2_buffer buf; unsigned int n_buffers; } CommonV4l2; void CommonV4l2_xioctl(int fh, unsigned long int request, void *arg) { int r; do { r = v4l2_ioctl(fh, request, arg); } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN))); if (r == -1) { fprintf(stderr, "error %d, %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } } void CommonV4l2_init(CommonV4l2 *this, char *dev_name, unsigned int x_res, unsigned int y_res) { enum v4l2_buf_type type; struct v4l2_format fmt; struct v4l2_requestbuffers req; unsigned int i; this->fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0); if (this->fd < 0) { perror("Cannot open device"); exit(EXIT_FAILURE); } COMMON_V4L2_CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; fmt.fmt.pix.width = x_res; fmt.fmt.pix.height = y_res; fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24; fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; CommonV4l2_xioctl(this->fd, VIDIOC_S_FMT, &fmt); if ((fmt.fmt.pix.width != x_res) || (fmt.fmt.pix.height != y_res)) printf("Warning: driver is sending image at %dx%d\n", fmt.fmt.pix.width, fmt.fmt.pix.height); COMMON_V4L2_CLEAR(req); req.count = 2; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; CommonV4l2_xioctl(this->fd, VIDIOC_REQBUFS, &req); this->buffers = calloc(req.count, sizeof(*this->buffers)); for (this->n_buffers = 0; this->n_buffers < req.count; ++this->n_buffers) { COMMON_V4L2_CLEAR(this->buf); this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; this->buf.memory = V4L2_MEMORY_MMAP; this->buf.index = this->n_buffers; CommonV4l2_xioctl(this->fd, VIDIOC_QUERYBUF, &this->buf); this->buffers[this->n_buffers].length = this->buf.length; this->buffers[this->n_buffers].start = v4l2_mmap(NULL, this->buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, this->buf.m.offset); if (MAP_FAILED == this->buffers[this->n_buffers].start) { perror("mmap"); exit(EXIT_FAILURE); } } for (i = 0; i < this->n_buffers; ++i) { COMMON_V4L2_CLEAR(this->buf); this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; this->buf.memory = V4L2_MEMORY_MMAP; this->buf.index = i; CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; CommonV4l2_xioctl(this->fd, VIDIOC_STREAMON, &type); } void CommonV4l2_update_image(CommonV4l2 *this) { fd_set fds; int r; struct timeval tv; do { FD_ZERO(&fds); FD_SET(this->fd, &fds); /* Timeout. */ tv.tv_sec = 2; tv.tv_usec = 0; r = select(this->fd + 1, &fds, NULL, NULL, &tv); } while ((r == -1 && (errno == EINTR))); if (r == -1) { perror("select"); exit(EXIT_FAILURE); } COMMON_V4L2_CLEAR(this->buf); this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; this->buf.memory = V4L2_MEMORY_MMAP; CommonV4l2_xioctl(this->fd, VIDIOC_DQBUF, &this->buf); CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf); } char * CommonV4l2_get_image(CommonV4l2 *this) { return ((char *)this->buffers[this->buf.index].start); } size_t CommonV4l2_get_image_size(CommonV4l2 *this) { return this->buffers[this->buf.index].length; } void CommonV4l2_deinit(CommonV4l2 *this) { unsigned int i; enum v4l2_buf_type type; type = V4L2_BUF_TYPE_VIDEO_CAPTURE; CommonV4l2_xioctl(this->fd, VIDIOC_STREAMOFF, &type); for (i = 0; i < this->n_buffers; ++i) v4l2_munmap(this->buffers[i].start, this->buffers[i].length); v4l2_close(this->fd); free(this->buffers); } #endif main.c: #include <stdio.h> #include <stdlib.h> #include "common_v4l2.h" static void save_ppm( unsigned int i, unsigned int x_res, unsigned int y_res, size_t data_lenght, char *data ) { FILE *fout; char out_name[256]; sprintf(out_name, "out%03d.ppm", i); fout = fopen(out_name, "w"); if (!fout) { perror("error: fopen"); exit(EXIT_FAILURE); } fprintf(fout, "P6\n%d %d 255\n", x_res, y_res); fwrite(data, data_lenght, 1, fout); fclose(fout); } int main(void) { CommonV4l2 common_v4l2; char *dev_name = "/dev/video0"; struct buffer *buffers; unsigned int i, x_res = 640, y_res = 480 ; CommonV4l2_init(&common_v4l2, dev_name, x_res, y_res); for (i = 0; i < 20; i++) { CommonV4l2_update_image(&common_v4l2); save_ppm( i, x_res, y_res, CommonV4l2_get_image_size(&common_v4l2), CommonV4l2_get_image(&common_v4l2) ); } CommonV4l2_deinit(&common_v4l2); return EXIT_SUCCESS; } Upstream: https://github.com/cirosantilli/cpp-cheat/blob/be5d6444bddab93e95949b3388d92007b5ca916f/v4l2/common_v4l2.h SDL Video capture is in their roadmap: https://wiki.libsdl.org/Roadmap and I bet it will wrap v4l on Linux. It will be sweet when we get that portability layer, with less bloat than OpenCV. A: Your best bet is probably: video4linux (V4L) It's easy to use, and powerful.
[ "mathoverflow", "0000364019.txt" ]
Q: Concavity of entropy difference Suppose that $\mathrm{A}$ is a $n\times n$ random matrix with a given distribution. Suppose that $\mathrm{U}$ is a diagonal unitary random matrix, defined as \begin{align*} \begin{bmatrix} \exp(i\theta_1)&0&\cdots&0\\ 0&\exp(i\theta_2)&\cdots&0\\ 0&0&\ddots&0\\ 0&0&\cdots&\exp(i\theta_n) \end{bmatrix}, \end{align*} where $\theta_i$ are i.i.d. Uniform random variable over $[0,2\pi]$, independent of $\mathrm{A}$, and $i$ is the imaginary number. I need to show that the following function is concave w.r.t. the input distribution: \begin{align*} F(p(\mathbf{x}))\triangleq H(\mathrm{A}\mathbf{X})- H(\mathrm{A} \mathrm{U}\mathbf{X}), \end{align*} where $\mathbf{X}$ is a continuous random vector of size $n$, with probability distribution $p(\mathbf{x})$, and $H(\cdot)$ is the Shannon entropy. This means that we need to show that for any $0 \leq \lambda \leq 1$, $p_1(\mathbf{x})$ and $p_2(\mathbf{x})$ \begin{align*} \lambda F(p_1(\mathbf{x}))+ (1-\lambda) F(p_2(\mathbf{x})) \leq F(p(\mathbf{x})), \end{align*} where $p(\mathbf{x})=\lambda p_1(\mathbf{x})+ (1-\lambda) p_2(\mathbf{x}) $. P.S. Some extra assumptions on $\mathrm{A}$ might be needed. A: Without further assumptions, I think $F$ is not necessarily concave. Let $\mathbf{X}_1\sim p_1$, $\mathbf{X}_2\sim p_2$ and $B\sim\textrm{Bernoulli}(\lambda)$ be independent, and let \begin{align*} \mathbf{X} &:= \begin{cases} \mathbf{X}_1 & \text{if $B=1$,} \\ \mathbf{X}_2 & \text{if $B=0$.} \end{cases} \end{align*} Then, $\mathbf{X}\sim p=\lambda p_1 + (1-\lambda) p_2$. In general, for two random variables $Z$ and $C$, where $Z$ is continuous and $C$ is discrete, we have \begin{align*} h(Z) + H(C\,|\,Z) &= H(C) + h(Z\,|\,C) \;, \end{align*} where $H(\cdot)$ denotes the ordinary (discrete) entropy and $h(\cdot)$ is the differential entropy. It follows that \begin{align*} & \overbrace{h(\mathrm{A}\mathbf{X}) - h(\mathrm{A}\mathrm{U}\mathbf{X})}^{F(p)} + \overbrace{H(B\,|\,\mathrm{A}\mathbf{X}) - H(B\,|\,\mathrm{A}\mathrm{U}\mathbf{X})}^{\displaystyle(\sharp)} \\ &= h(\mathrm{A}\mathbf{X}\,|\,B) - h(\mathrm{A}\mathrm{U}\mathbf{X}\,|\,B) + H(B) - H(B) \\ &= \lambda\big(\underbrace{h(\mathrm{A}\mathbf{X}_1) - h(\mathrm{A}\mathrm{U}\mathbf{X}_1)}_{F(p_1)}\big) + (1-\lambda)\big(\underbrace{h(\mathrm{A}\mathbf{X}_2) - h(\mathrm{A}\mathrm{U}\mathbf{X}_2)}_{F(p_2)}\big) \end{align*} provided that $p_1$ and $p_2$ are absolutely continuous w.r.t. the three-dimensional Lebesgue and $\mathrm{A}$ is almost surely non-singular. (Otherwise, the differential entropies become $-\infty$ and $F$ would not be well-defined.) Therefore, in order for $F$ to be concave, we must have \begin{align*} (\sharp) = H(B\,|\,\mathrm{A}\mathbf{X}) - H(B\,|\,\mathrm{A}\mathrm{U}\mathbf{X}) &\leq 0 \tag{?} \end{align*} whenever $p_1$ and $p_2$ are absolutely continuous and $\mathrm{A}$ is almost surely non-singular. [Update: The original example was not valid because it disregarded the requirement that $p_1$ and $p_2$ have to be absolutely continuous and $\mathrm{A}$ non-singular. The following sketch is meant to circumvent that issue.] Fix $0<\lambda<1$. Let \begin{align*} \hat{\mathrm{A}} &:= \begin{bmatrix} 1 & 1/2 & 1/2 \\ 0 & -1/2 & 1/2 \\ 0 & -1/2 & 1/2 \end{bmatrix} & \hat{\mathbf{X}}_1 &:= \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix} & \hat{\mathbf{X}}_2 &:= \begin{bmatrix} 0 \\ 1 \\ 1 \end{bmatrix} \end{align*} Let $\mathrm{A}$ be a non-singular (deterministic or random) matrix which is very close to $\hat{\mathrm{A}}$, and let $\mathbf{X}_1=\hat{\mathbf{X}}+\sigma\mathbf{Z}_1$ and $\mathbf{X}_2=\hat{\mathbf{X}}+\sigma\mathbf{Z}_2$, where $\mathbf{Z}_1$ and $\mathbf{Z}_2$ are two independent standard normal vectors and $\sigma$ is very small. Assume that $\mathbf{Z}_1$, $\mathbf{Z}_2$, $\mathrm{U}$ and $\mathrm{A}$ are all independent. Note that both $\mathrm{A}\mathbf{X}_1$ and $\mathrm{A}\mathbf{X}_2$ are highly concentrated around a vector very close to $\hat{\mathbf{X}}_1$. By chooseing $\mathrm{A}$ close enough to $\hat{\mathrm{A}}$, we can make sure that $\mathrm{A}\mathbf{X}_1$ and $\mathrm{A}\mathbf{X}_2$ are hardly distinguishable. Hence, $\mathrm{A}\mathbf{X}$ would hardly have any information about $B$, and as a result \begin{align*} H(B\,|\,\mathrm{A}\mathbf{X}) &\approx H(B) = H(\lambda) \;. \end{align*} On the other hand, $\mathrm{A}\mathrm{U}\mathbf{X}_1$ and $\mathrm{A}\mathrm{U}\mathbf{X}_2$ will be distinguishable, with $\mathrm{A}\mathrm{U}\mathbf{X}_1$ still being close to the linear span of $\hat{\mathbf{X}}_1$ and $\mathrm{A}\mathrm{U}\mathbf{X}_2$ typically far from it. In particular, $\mathrm{A}\mathrm{U}\mathbf{X}$ has significant information about $B$ and hence \begin{align*} H(B\,|\,\mathrm{A}\mathrm{U}\mathbf{X}) &\ll H(B) = H(\lambda) \;. \end{align*} Therefore, in this example, $(\sharp)>0$ contrary to the claim.
[ "unix.stackexchange", "0000469333.txt" ]
Q: rsync - specify negative exclusion (not inclusion) I'm trying to tell rsync to ONLY include .org (or better yet, .org AND .py files). However, I have to do this through the --exclude= option, not the --include= option. Reason: I'm using BackInTime and want to make a backup config that only include Org and Py files. That interface lets me specify exclusion options, but not inclusion options. Is there a way to exclude everything but one (or two) specific extensions? A: BackInTime has an option to pass any parameters to rsync that you want. In this case you could use --include and --exclude directly (or even --filter). See the Expert Options pane, last option.
[ "unix.stackexchange", "0000147916.txt" ]
Q: Getting the process-id out of command launched with "su -c" I am running a java program inside a shell and writing the process-id to a text file. So when I do this: nohup java app.Main > /dev/null 2>&1 & echo $! > /var/run/app.pid It works. But I really want to run it as another user su - appuser -c "nohup java app.Main > /dev/null 2>&1 &" echo $! > /var/run/app.pid This doesn't work. Is there any way of getting the process-id of the command launched with the -c option? A: You can do: su - appuser -c 'nohup java app.Main > /dev/null 2>&1 & echo "$!"' > /var/run/app.pid (that assumes the login shell of appuser is Bourne-like). su - resets the environment, so if you want to have variables expanded in the command line, it has to be done by your shell (not the login shell of the remote user) like: su - appuser -c "nohup '$JAVA_BIN' '$JAVA_CLASS' > /dev/null 2>&1 &"' echo "$!"' > /var/run/app.pid (that assumes those variables don't contain single quote characters). You want the redirection to be performed by your shell (running as root), not appuser's shell (which probably doesn't have write permission to /var/run).
[ "math.stackexchange", "0001388863.txt" ]
Q: If $ \arcsin x+ \arcsin y=\frac{\pi}{2}$, prove that $ x^2+y^2=1$. If $ \arcsin x+ \arcsin y=\frac{\pi}{2}$, prove that $$ x^2+y^2=1$$ I tried taking sine of both the sides, I only come to this result: $$x^2 + y^2 -2x^2y^2 + 2xy\sqrt{(1-y^2)(1+x^2)}=1.$$ A: $\arcsin x=\dfrac\pi2-\arcsin y=\arccos y$ $\arcsin x=\arccos y=A$ (say) $\implies x=\sin A,y=\cos A$ Hope you can take it from here! A: Take the sine of both sides for a direct demonstration. $$\sin (\arcsin x+\arcsin y)=1$$ Then $$\sin (\arcsin x)\cos(\arcsin y)+\cos(\arcsin x)+\sin (\arcsin y)=1$$ Now note that $\arcsin y=\frac \pi 2-\arcsin x$ from the original equation and also $\cos \left(\frac \pi2-\theta\right)=\sin \theta$ to obtain $$x \sin(\arcsin x)+y \sin (\arcsin y)=x^2+y^2=1$$ A: Another way to prove it, which might give a little more insight on why this is true, is to look at this triangle: from Wikimedia Commons By definition, $\theta$ is equal to the arcsin of $x$; the other sharp angle is $\pi/2 - \theta$ (because the angles of a triangle sum up to $\pi$) and its arcsin is $y = \sqrt{1-x^2}$ (by Pythagoras). Now, arcsin $x$ + arcsin $y$ = $\theta + \pi/2 - \theta$ = $\pi/2$, and you can verify that $x^2 + y^2 = 1$.
[ "stackoverflow", "0004425107.txt" ]
Q: mapkit multiple points display with different images This should be fairly easy to figure out I think... I have a working mapview which drops a series of numbered pin markers onto the map. I'm calling the image for the pin from a plist however, when the pins drop they all have the same number that of the last pin. (instead of 1,2,3..) The offending code is below, i just am not sure how to fix it... thanks. NSString *path = [[NSBundle mainBundle] pathForResource:[route objectForKey:NAME_KEY] ofType:@"plist"]; NSMutableArray* array = [[NSMutableArray alloc] initWithContentsOfFile:path]; points = array; for (NSDictionary *routeDict in points){ AllAnnotations *Annotation = [[AllAnnotations alloc] initWithDictionary:routeDict]; [mapView addAnnotation:Annotation]; [Annotation release]; } for (NSDictionary *routeDict in points){ NSString *first = [routeDict objectForKey: POINT_KEY]; NSString *getNum = [routeDict objectForKey: COLOR_KEY]; NSString *again = [getNum stringByAppendingString:first]; NSString *imgValue = [again stringByAppendingString:@".png"]; annotationView.image = [UIImage imageNamed:imgValue]; } annotationView.canShowCallout = YES; AllAnnotations.m ------------------------------------------------------------------------------------------ - (id) initWithDictionary:(NSDictionary *) dict { self = [super init]; if (self != nil) { coordinate.latitude = [[dict objectForKey:@"latitude"] doubleValue]; coordinate.longitude = [[dict objectForKey:@"longitude"] doubleValue]; self.title = [dict objectForKey:@"name"]; self.subtitle = [dict objectForKey:@"subname"]; } return self; } A: The second loop goes through all the points (annotations) and the current annotation view ends up with the image for the last point. The annotationView object is not changing inside that loop. I assume that second loop and the last line are in the viewForAnnotation method. Instead of looping through all points, you should get the routeDict from the current annotation object only and set the annotationView's image once. Assuming you've added routeDict as a property in the AllAnnotations class, you would do something like this: NSDictionary *routeDict = ((AllAnnotations *)annotation).routeDict; NSString *first = [routeDict objectForKey: POINT_KEY]; NSString *getNum = [routeDict objectForKey: COLOR_KEY]; NSString *again = [getNum stringByAppendingString:first]; NSString *imgValue = [again stringByAppendingString:@".png"]; annotationView.image = [UIImage imageNamed:imgValue]; Edit: Based on the updated code in your question and comments, here are the changes you need to make. In AllAnnotations.h, add an ivar to store the image file name for the annotation: @interface AllAnnotations : NSObject <MKAnnotation> { //existing ivars here NSString *imageFileName; } //existing properties here @property (copy) NSString *imageFileName; //existing method headers here @end In AllAnnotations.m, add the synthesize for the new ivar and update the initWithDictionary and dealloc methods: @synthesize imageFileName; - (id) initWithDictionary:(NSDictionary *) dict { self = [super init]; if (self != nil) { coordinate.latitude = [[dict objectForKey:@"latitude"] doubleValue]; coordinate.longitude = [[dict objectForKey:@"longitude"] doubleValue]; self.title = [dict objectForKey:@"name"]; self.subtitle = [dict objectForKey:@"subname"]; //set this annotation's image file name... NSString *first = [dict objectForKey: POINT_KEY]; NSString *getNum = [dict objectForKey: COLOR_KEY]; NSString *again = [getNum stringByAppendingString:first]; self.imageFileName = [again stringByAppendingString:@".png"]; } return self; } - (void) dealloc { [title release]; [subtitle release]; [imageFileName release]; [super dealloc]; } Alternatively, you could store the values of the POINT_KEY and COLOR_KEY objects in the annotation and generate the filename in the viewForAnnotation method. By the way, "AllAnnotations" is not a good name for this class which represents a single annotation. Perhaps "RouteAnnotation" would be better. Finally, the viewForAnnotation method should look like this: - (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { MKAnnotationView * annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"annot"]; if (!annotationView) { annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annot"] autorelease]; annotationView.canShowCallout = YES; } else { annotationView.annotation = annotation; } AllAnnotations *routeAnnotation = (AllAnnotations *)annotation; annotationView.image = [UIImage imageNamed:routeAnnotation.imageFileName]; return annotationView; }
[ "stackoverflow", "0002253756.txt" ]
Q: Scrolling a div with overflow without javascript I have a div with a static height, with content clipped using overflow: auto. On regular desktop browsers I use javascript to scroll to the bottom of the content. However, I need to do the same on mobile browsers, or browsers without javascript. Not in real time, but to output html+css in such a way so as the browser renders the bottom of the content. Tools at my disposal: HTML, CSS, PHP. Is this possible? A: There is in fact a trick to achieve this without JavaScript. You can put an anchor tag at the bottom of your scrollable div, and then use the meta refresh header in your HTML page to request a redirect to this anchor. The browser should not trigger a real page refresh in this case, because only the hash part will change. It should simply scroll to the anchor at the bottom of the div. The following works in Google Chrome 4.0, Firefox 3.5.7, Safari 4.0.4, IE 7 and IE 8: <html> <head> <meta http-equiv="refresh" content="0; url=#anchor-bottom" /> </head> <body> <div style="overflow: scroll; height: 100px; width: 150px;"> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo iriure dolor in hendrerit in vulputate velit esse molestie consequat, nulla facilisis at vero eros et accumsan et iusto odio dignissim qui zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber eleifend option congue nihil imperdiet doming id quod mazim.</p> <p>Typi non habent claritatem insitam; est usus legentis in iis Investigationes demonstraverunt lectores legere me lius quod ii processus dynamicus, qui sequitur mutationem consuetudium lectorum. gothica, quam nunc putamus parum claram, anteposuerit litterarum seacula quarta decima et quinta decima. Eodem modo typi, qui nunc fiant sollemnes in futurum. Lorem ipsum dolor sit amet, consectetuer nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat veniam, quis nostrud exerci tation ullamcorper suscipit lobortis consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate claritatem. Investigationes demonstraverunt lectores legere me.</p> <a name="anchor-bottom"></a> <p>Mirum est notare quam littera gothica, quam nunc putamus parum humanitatis per seacula quarta decima et quinta decima. Eodem modo clari, fiant sollemnes in futurum.</p> </div> </body> </html> While testing the above in Opera 10.0, I found a slight issue with the the meta refresh, which apparently interprets the 0 as an infinite loop, unlike the other browsers. A similar problem seemed to happen in IE for Windows Mobile 6. I'm sure this can be tackled in some way. One option would be to supply the URL complete with the anchor tag. I also tested the above on the iPhone with Safari, and it appears to work fine. Nevertheless I have to say that it may be a better idea to render the full div content without any internal scrolling in mobile browsers. Multiple scrollbars in mobile browsers do not seem very useable.
[ "stackoverflow", "0020182865.txt" ]
Q: RegEx extract positinal values in simular character group Javascript. I need to extract second positive number value in "inset" groups: Exampple string: "box-shadow: inset 3px 4px 0px #444, inset -1px -2px 0px #444,5px 6px 0px #444, inset 1px 1px 0px #444" so I need to extract 4 and 1 from example string. don't get how to do this. A: This regex should do the trick: /inset -?\d+px (\d+)px/g However, as you will need to use the global modifier to catch all the occurrences, you should use the exec method in a while instead of using match, otherwise you won't get the captured groups. var match, regex = /inset -?\d+px (\d+)px/g, str = "box-shadow: inset 3px 4px 0px #444, inset -1px -2px 0px #444,5px 6px 0px #444, inset 1px 1px 0px #444"; while (match = regex.exec(str)) { console.log(match[1]) } If you want to join the matches in an array, you could use: var matches = []; while (match = regex.exec(str)) { matches.push(match[1]); } console.log(matches); // ["4", "1"]
[ "sustainability.stackexchange", "0000006259.txt" ]
Q: To what extent (if any) are electric vehicle batteries recyclable? Are there any existing procedures for the recycling of electric vehicle car batteries, and if so what are they? In particular I'm interested in those used in the Volkswagen E-Golf, though general information is appreciated too. A: Li-Ion batteries are worth recycling just for the lithium in them. This material can be re-refined, and made into new batteries. In this use they should show similar cost savings to recycled vs new aluminum. There is also the prospect of repurposing a worn battery for stationary use. E.g. It stores 30 kWh in your car for 3 years, then stores 10 kWh in your house for the next 3-10 years. One source I read proposed that the used battery market would help older EV's hold value. Edit: I'm wrong. See https://waste-management-world.com/a/1-the-lithium-battery-recycling-challenge Summary: At present recycling lithium from batteries costs about 5 times the cost of mined lithium. However the cost of the lithium is only about 3% of the cost of the battery. So the price of lithium rising by a factor of 5 would make recycled Li economical, and would raise the price of making batteries by about 12%
[ "stackoverflow", "0051534205.txt" ]
Q: Flutter / Android - moving focus from a TextField to a DropdownButton I have a textfield and a dropdownbutton on a screen. When I move from the textfield to choose an item and then back to the textfield I find this a little bit awkward. Type in text field Select dropdown by tapping it twice My problem is that you have to tap twice, once to exit the textfield and the second to access the dropdown - is there a way to exit the textfield and open the dropdownlist in one tap? Is this built into Android or the Flutter controls? Here is some flutter code that displays a dropdown and a textbox... class _TextAndDropdownState extends State<TextAndDropdown> { int selectedDropdown; String selectedText; final textController = new TextEditingController(); @override void initState() { super.initState(); selectedDropdown = 1; textController.addListener(() => print('')); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Text and dropdown'), ), body: Container( child: Column( children: [ Padding( padding: EdgeInsets.all(10.0), ), DropdownButton(value: selectedDropdown, onChanged: _dropdownChange, items: [ DropdownMenuItem( child: Text('First'), value: 1, ), DropdownMenuItem(child: Text('Seconds')), ]), TextField(controller: textController), ], ), ), ); } void _dropdownChange(val) { setState(() { selectedDropdown = val; }); } } A: Sorry for the late Answer... I'm also finding the solution for this. now i get it. Only you have to add this FocusScope.of(context).requestFocus(new FocusNode()); in your _dropdownChange(val) method void _dropdownChange(val) { setState(() { FocusScope.of(context).requestFocus(new FocusNode());///It will clear all focus of the textfield selectedDropdown = val; }); }
[ "stackoverflow", "0038317320.txt" ]
Q: Nativescript Loading Images Here is my scenario: On my main view I am loading a list of items. Each item has an imageURL property. I am binding an Image component to the ImageURL property. Everything works well, but the image takes an extra second or two to load during which time the Image component is collapsed. Once the image is loaded, the Image component is displayed properly. This creates an undesirable shift on the page as the image is rendered. The same images are going to be rendered on 2 other views. What is the best practice to handle this scenario? I tried loading the base 64 string instead of the image url, which worked, but it slowed down the loading of the initial view significantly. How can I pre-fetch the images and reuse them as I navigate between the views? I was looking at the image-cache module which seems to be addressing the exact scenario, but the documentation is very vague and the only example I found (https://github.com/telerik/nativescript-sample-cuteness/blob/master/nativescript-sample-cuteness/app/reddit-app-view-model.js) did not really address the same scenario. If I understood the code correctly, this is more about the virtual scrolling. In my case, I will have only 2-3 items, so the scrolling is not really a concern. I would appreciate any advise. Thank you. A: Have you tried this? https://github.com/VideoSpike/nativescript-web-image-cache You will likely want to use a community plugin for this. You can also take a look at this: https://docs.nativescript.org/cookbook/ui/image-cache A: So after some research I came up with a solution that works for me. Here is what I did: When the app start I created a global variable that contained a list of observable objects then I made the http call to get all the objects and load them into the global variable In the view I displayed the image as (the image is part of a Repeater item template): <Image loaded="imageLoaded" /> in the js file I handled the imageLoaded events as: var imageSource = require("image-source"); function imageLoaded(args) { var img = args.object; var bc = img.bindingContext; if (bc.Loaded) { img.imageSource = bc.ImageSource; } else { imageSource.fromUrl(bc.ImageURL).then(function (iSource) { img.imageSource = iSource; bc.set('ImageSource', iSource); bc.set('Loaded', true); }); } } So, after the initial load I am saving the imageSource as part of the global variable and on every other page I am getting it from there with the fallback of loading it from the URL is the image source is not available for this item. I know this may raise some concerns about the amount of memory I am using to store the images, but since in my case, I am talking about no more than 2-3 images, I thought that this approach would not cause any memory issues. I would love to hear any feedback on how to make this approach more efficient or if there is a better approach altogether.
[ "stackoverflow", "0056120273.txt" ]
Q: Quicker way to implement numpy.isin followed by sum I am performing data analysis using a python script and learned from profiling that more than 95 % of the computation time is taken by the line which performs the following operation np.sum(C[np.isin(A, b)]), where A, C are 2D NumPy arrays of equal dimension m x n, and b is a 1D array of variable length. I am wondering if not a dedicated NumPy function, is there a way to accelerate such computation? Typical sizes of A (int64), C (float64): 10M x 100 Typical size of b (int64): 1000 A: As your labels are from a small integer range you should get a sizeable speedup from using np.bincount (pp) below. Alternatively, you can speedup lookup by creating a mask (p2). This---as does your original code---allows for replacing np.sum with math.fsum which guarantees an exact within machine precision result (p3). Alternatively, we can pythranize it for another 40% speedup (p4). On my rig the numba soln (mx) is about as fast as pp but maybe I'm not doing it right. import numpy as np import math from subsum import pflat MAXIND = 120_000 def OP(): return sum(C[np.isin(A, b)]) def pp(): return np.bincount(A.reshape(-1), C.reshape(-1), MAXIND)[np.unique(b)].sum() def p2(): grid = np.zeros(MAXIND, bool) grid[b] = True return C[grid[A]].sum() def p3(): grid = np.zeros(MAXIND, bool) grid[b] = True return math.fsum(C[grid[A]]) def p4(): return pflat(A.ravel(), C.ravel(), b, MAXIND) import numba as nb @nb.njit(parallel=True,fastmath=True) def nb_ss(A,C,b): s=set(b) sum=0. for i in nb.prange(A.shape[0]): for j in range(A.shape[1]): if A[i,j] in s: sum+=C[i,j] return sum def mx(): return nb_ss(A,C,b) sh = 100_000, 100 A = np.random.randint(0, MAXIND, sh) C = np.random.random(sh) b = np.random.randint(0, MAXIND, 1000) print(OP(), pp(), p2(), p3(), p4(), mx()) from timeit import timeit print("OP", timeit(OP, number=4)*250) print("pp", timeit(pp, number=10)*100) print("p2", timeit(p2, number=10)*100) print("p3", timeit(p3, number=10)*100) print("p4", timeit(p4, number=10)*100) print("mx", timeit(mx, number=10)*100) The code for the pythran module: [subsum.py] import numpy as np #pythran export pflat(int[:], float[:], int[:], int) def pflat(A, C, b, MAXIND): grid = np.zeros(MAXIND, bool) grid[b] = True return C[grid[A]].sum() Compilation is as simple as pythran subsum.py Sample run: 41330.15849965791 41330.15849965748 41330.15849965747 41330.158499657475 41330.15849965791 41330.158499657446 OP 1963.3807722493657 pp 53.23419079941232 p2 21.8758742994396 p3 26.829131800332107 p4 12.988955597393215 mx 52.37018179905135
[ "stackoverflow", "0005188211.txt" ]
Q: persisting variables in sinatra Suppose I have a Sinatra app that simply prints out random numbers from 0-9: get '/' do rand(10) end I want to make sure that the app does not print out the same number as last time (so it's not really random -- this is just a toy example, in any case): # I want to do something like this... This code doesn't work. prev_rand = nil get '/' do curr_rand = rand(10) while prev_rand and curr_rand == prev_rand curr_rand = rand(10) end prev_rand = curr_rand curr_rand end How would I do this? Using the above example doesn't quite work, as the prev_rand inside the get '/' block is a local variable (not the same as the one outside the block), so changing its value doesn't persist. (I don't quite understand Sinatra scope.) A: You could store "prev_rand" as a setting, which is an application-level variable that's accessible within the request context via the "settings" object: configure do set :prev_rand, nil end get '/' do begin curr_rand = rand(10) end while curr_rand == settings.prev_rand set :prev_rand, curr_rand curr_rand end For more info: http://www.sinatrarb.com/configuration.html
[ "math.stackexchange", "0001917480.txt" ]
Q: Calculate $\lim_{n\to\infty}\frac{e^\frac{1}{n}+e^\frac{2}{n}+\ldots+e}{n}$ Calculate $$\lim_{n\to\infty}\frac{e^\frac{1}{n}+e^\frac{2}{n}+\ldots+e^\frac{n-1}{n}+e}{n}$$by expressing this limit as a definite integral of some continuous function and then using calculus methods. I've worked this out with a friend and we've come to the conclusion that this is equivalent to $\int e^\frac{x}{n}\,dx$. However, we would like a confirmation that this is what the above evaluates to. A: If $f(x)=e^x$ then the expression is $\frac{1}{n}\sum_{k=1}^nf(\frac{k}{n})$, which is a right Riemann sum for $\int_0^1f(x)\;dx$. Therefore the limit is $\int_0^1e^x\;dx=e-1$. A: If you do not use the integral (as commented by @carmichael561), you coud write $$S_n=\frac{e^\frac{1}{n}+e^\frac{2}{n}+\ldots+e^\frac{n-1}{n}+e}{n}=\frac{\sum_{i=1}^n e^{\frac in} }n=\frac{\sum_{i=1}^n x^i }n$$ using $x= e^{\frac 1n}$. Hence $$S_n=\frac{x \left(1-x^n\right)}{n(1-x)}=\frac{(e-1) e^{\frac{1}{n}}}{\left(e^{\frac{1}{n}}-1\right) n}$$ Now, for large values of $n$, you could use Taylor expansion $$e^{\frac{1}{n}}=1+\frac{1}{n}+\frac{1}{2 n^2}+O\left(\frac{1}{n^3}\right)$$ which makes $$S_n=\frac{e-1}n \times\frac {1+\frac{1}{n}+\frac{1}{2 n^2}+O\left(\frac{1}{n^3}\right)}{\frac{1}{n}+\frac{1}{2 n^2}+O\left(\frac{1}{n^3}\right)}=\frac{e-1}n \times\left( n+\frac{1}{2}+O\left(\frac{1}{n}\right)\right)$$ $$=(e-1)+\frac{(e-1)}{2 n}+O\left(\frac{1}{n^2}\right)$$ which shows the limit and how it is approched,
[ "stackoverflow", "0012774297.txt" ]
Q: Char length in Arduino sketch I have the following char inside an Arduino sketch: char inData[80]; When I print to the serial console: Serial.print(strlen(inData) - 1); I'm expecting to see: 79 instead I see: 655356553501234567 Can someone shed some light as to why this is happening? A: strlen is looking for a terminating nul. Calling it on an uninitialized array or pointer results in undefined behavior. You want sizeof(inData) instead.
[ "scifi.stackexchange", "0000024201.txt" ]
Q: Why did Spider-man have a six legged spider emblem on his costume? I saw a funny panel Slytherincess posted in chat. It has a six legged emblem on Spideys costume. Is this a Stan Lee sanctioned version of the webslinger? Is there a back story? A: That's from the 1967 Spider-Man cartoon series, which included Stan Lee as a "Creative Consultant". The 1967 cartoon series has given rise to an internet meme involving taking screenshots from the series and adding "witty" text to it. So while it is a product approved by Stan Lee, like most cartoons, complex designs must be simplified. It's the same reason that most cartoon people have 3 or 4 fingers and not 5 like a real person would have. Thus, an 8 legged spider now has 6 legs, making it look like a tick instead.
[ "stackoverflow", "0058438371.txt" ]
Q: chaining query trees w/o "Rendered more hooks than during the previous render" This is an apollo client using the rest link. I have 2 APIs I need to hit, 1 with the value and the id of the record and another api that gives me more information about the record. I then stitch the info together for the content I'm rendering. nope... no gql backend, just trying to get a foot forward and hooking up the client. The way I'm trying to do this is with hooks like const {data: recordsById = {}, loading: loading1} = useQuery(firstQuery, {variables: {sectionId}}) const records = Object.keys(recordsById).map((recordId) => { const {data} = useQuery(secondQuery, {skip: loading1, variables: {sectionId, recordId}}) return { id: recordId, value: recordsById[recordId], info: data, } }) Obviously when the firstQuery responds with an object like {fooId: 'something', barId: 'else'} there are more useQuery effects in the next render. What's the proper way of doing a sequential query like this w/ apollo? A: React fails because in internals it binds each call of hook to component and order of how it called, it means that in each component hooks call order and number of hooks called should be constant, in your component you should get rid of using hooks in any kind of loops, e.g. with splitting it into separate components
[ "stackoverflow", "0003109709.txt" ]
Q: Flex HTML component to bitmap I'm creating a HTML Component in Flex, loading a URL and then capturing that element and converting it to a bitmap to try and replicate a sort of automatic screenshot saving process. However the bitmaps that it is producing do not contain any flash elements from the HTML. Anyone have any ideas why this is? A: I've figured this out I was setting my HTML elements visbility to false when taking the snapshot of that component, it need to be visible when taking the screenshot. :)
[ "stackoverflow", "0025528952.txt" ]
Q: Polymorphism unexpected results On my quest to understand Polymorphism more, i have constructed a little test and it's returning unexpected results. So the idea was to override the base class method with virtual/override keywords but it seems i don't need those ? public class Employee { public Employee() { this.firstName = "Terry"; this.lastName = "Wingfield"; } public string firstName { get; set; } public string lastName { get; set; } public void writeName() { Console.WriteLine(this.firstName + " " + this.lastName); Console.ReadLine(); } } public class PartTimeEmployee : Employee { public void writeName() { Console.WriteLine("John" + " " + "Doe"); Console.ReadLine(); } } public class FullTimeEmployee : Employee { public void writeName() { Console.WriteLine("Jane" + " " + "Doe"); Console.ReadLine(); } } static void Main(string[] args) { Employee employee = new Employee(); PartTimeEmployee partTimeEmployee = new PartTimeEmployee(); FullTimeEmployee fullTimeEmployee = new FullTimeEmployee(); employee.writeName(); partTimeEmployee.writeName(); fullTimeEmployee.writeName(); } } With the code above i was expecting results like so: Terry Wignfield Terry Wingfield Terry Wingfield But instead the below was written to the console: Terry Wingfield John Doe Jane Doe I assumed the latter would not work because it would of needed the ovrride keyword. So the question is why am i seeing the latter names without the appropriate keywords? I hope this is clear enough to read. Regards, A: There is no polymorphism in play in the code you showed. Change it to: Employee employee = new Employee(); Employee partTimeEmployee = new PartTimeEmployee(); Employee fullTimeEmployee = new FullTimeEmployee(); and you will get your expected result. Update: The concept of "polymorphism" (many forms) in OOP means that the code deals with references of certain type (base class or interface) while there may be instances of different types (descendants, implementations) behind these references. For polymorphism to "kick in" there must be inheritance and virtual methods (different terms in the case of interface implementation, but let's use terms relevant to your code example). You have inheritance, but no virtual methods. For regular (non-virtual) methods, method calls are resolved at compile-time based on the type of objects whose methods are called. For code: PartTimeEmployee partTimeEmployee = ...; partTimeEmployee.writeName(); it is clear to the compiler what method writeName to call, and it is PartTimeEmployee.writeName. Similarly, for code: Employee partTimeEmployee = ...; partTimeEmployee.writeName(); the method to call is Employee.writeName. A: This is called method hiding. You are simply hiding the base class method in your derived classes. You should be getting a warning for that but it's completely legal. For more information see the documentation. You might also want to take a look at this question
[ "stackoverflow", "0038833765.txt" ]
Q: Add a subsequent row to get consecutive IDs I have some data that looks like this. DESCTV DT HR show1 2016-05-10 0 show2 2016-05-10 2 show3 2016-05-10 4 show4 2016-05-10 6 But I want it to look like this. DESCTV DT HR show1 2016-05-10 0 show1 2016-05-10 1 show2 2016-05-10 2 show2 2016-05-10 3 show3 2016-05-10 4 show3 2016-05-10 5 show4 2016-05-10 6 show4 2016-05-10 7 I guess I'm wanting to create an empty row after each hour change and then copy the preceding row down but give the next hour number. A: You can use data.table, i.e. # Load data d<- fread("DESCTV DT HR show1 2016-05-10 0 show2 2016-05-10 2 show3 2016-05-10 4 show4 2016-05-10 6") # 2 steps: (1) add rows (2) fill with specified values d.out <- setDT(d)[, .SD[1:(.N+1)], by=list(DESCTV, DT) ][, HR:=ifelse(is.na(HR), as.integer((shift(HR)+1)), HR), by=list(DESCTV, DT)] d.out looks like that: # > d.out # DESCTV DT HR # 1: show1 2016-05-10 0 # 2: show1 2016-05-10 1 # 3: show2 2016-05-10 2 # 4: show2 2016-05-10 3 # 5: show3 2016-05-10 4 # 6: show3 2016-05-10 5 # 7: show4 2016-05-10 6 # 8: show4 2016-05-10 7
[ "stackoverflow", "0012761040.txt" ]
Q: indexPath Value of UICollectionView When using a UICollectionView, I am perplexed with getting the indexPath value of the didSelectItemAtIndexPath method. I'm using the following line of code in the didSelectItemAtIndexPath method: //FileList is an NSArray of files from the Documents Folder within my app. //This line gets the indexPath of the selected item and finds the same index in the Array NSString *selectedItem = [NSString stringWithFormat:@"%@",[FileList objectAtIndex:indexPath.item]]; //Now the selected file name is displayed using NSLog NSLog(@"Selected File: %@", selectedItem); The problem is that the indexPath always returns 0 (see below code) and as a result only the first item in the FileList NSArray is ever selected. I've tried different parameters such as indexPath.row indexPath.item and just plain indexPath ALL of these return a value of 0 in the following NSLog statement: NSLog(@"index path: %d", indexPath.item); //I also tried indexPath.row here Maybe I'm just formatting the NSString improperly, however I don't think this is the case as there are no warnings and I've tried formatting it differently in other places. Why does the indexPath always return 0? Any help would be appreciated! Thanks! A: At the risk of stating the obvious, make sure your code is in the didSelectItemAtIndexPath method rather than didDeselectItemAtIndexPath. You will get very different indexPath values for a given touch event in the latter method and it's quite easy to insert the wrong one with Xcode's code completion.
[ "stackoverflow", "0006969082.txt" ]
Q: Android GL ARGB image with GL_BLEND off When I try to draw an image with alpha channel using OpenGL ES on Android with GL_BLEND disabled, the area that should be transparent is drawn in black... Who can I choose the color that is used to draw the area that should be transparent A: The color will most likely depend on how the original image is encoded. If your transparent pixels are encoded as rgba(0,0,0,0) you will get black. If you those pixels are encoded as rgba(1,0,0,0) you would get red.
[ "superuser", "0000697625.txt" ]
Q: Increasing virtual hard drive capacity in vbox I am using Virtual Box. I have a virtual hard drive storage 8GB (dynamic allocated). Later on, that drive is full. I don't know how to increase the capacity. Therefore, I decide to add the second hard drive. But the problem is not solved. (low disc space message in my Ubuntu virtual machine) (the second virtual hard drive probably does not been detected by my Ubuntu virtual machine) Can anybody give me a suggestion? Thanks A: You'll need to first resize your Virtual Box disk image, then launch your VM and resize the parition on your VM. The 2nd VDI was probably recognized by the VM (and the guest OS) but merely having a 2nd hard drive in a machine does not automagically free up the disk space on offending drive, you would have to clean up the drive yourself (delete/move files). Hope that can help.
[ "stackoverflow", "0006818595.txt" ]
Q: Access Textbox content that is inside a detailsView cell Hi I need to access the contents of a textbox that is inside a details view: <asp:TemplateField HeaderText="Transaction Name:" > <InsertItemTemplate> <asp:TextBox ID="txtTransactionName" runat="server" /> </InsertItemTemplate> </asp:TemplateField> Tried string v = ((TextBox)detailsNew.FindControl("txtTransactionName")).Text; but it returned "" when I checked. EDIT: I'm trying the above in detailsNew_ItemInserting(...) A: Found the problem. Leaving this here to help someone else who might have the same problem. I cannot use the sender object to get the DetailsView. So the correct way: TextBox txt = (TextBox)DETAILSVIEW_ID.FindControl("TEXTBOX_ID") as TextBox; string tmp = txt.Text; DETAILSVIEW_IDis the ID of the DetailsView and TEXTBOX_ID the ID of the TextBox crated inside the DetailsView.
[ "es.stackoverflow", "0000128837.txt" ]
Q: Falta cadena conexión en Control de usuario c# hola tengo un problema que al agregar algunos controles de usuario a mi formulario la vista de diseño de este se rompe, pero a pesar de ello compila el proyecto y los controles se muestran en el formulario, permitiendo operar con estos e interactuar con la BD. Esta linea del Main.Designer.cs es la que rompe la vista de diseño this.Controls.Add(this.panel_contenido); //contiene los controles de usuario Mensaje de error: No se encuentra ninguna cadena de conexión denominada 'SistemaPacientesEntities' en el archivo de configuración de la aplicación. Mi duda es ¿por qué dice que no encuentra la cadena conexión y cuando compila, a pesar de este problema, trabaja perfectamente con los datos de la BD (todas las operaciones de un ABM básico las realiza correctamente) a través de los controles mencionados? A: El problema fue solucionado haciendo uso de un truco, lo que ocurría era que se quería conectar a la BD en tiempos de diseño y no encontraba la cadena conexión es por eso que hago uso de esto: private void UserControl_Load(object sender, EventArgs e) { if (!this.DesignMode) { //codigo } } Aclaración: Esto no funciona para UserControl anidados, es decir si se pone un User Control dentro de otro este planteo no va a funcionar
[ "stackoverflow", "0035784493.txt" ]
Q: How to move the cursor down a line in 16-bit code? Here is the code i wrote I'm trying to write on assembly 8086 like on a regular keyboard but every time i press on enter it goes down a line and writes the second letter in the RAM how do i fix it without resetting the ram lets the user write from the keyboard. data segment ; add your data here! msg db ? nxtline db 10,13,'$' ends stack segment dw 128 dup(0) ends code segment start: ; set segment registers: mov ax, data mov ds, ax mov es, ax ; add your code here xor ax,ax mov ah,1 xor bx,bx mov bx,offset msg ifpressed: ;pusha mov ah,1 int 21h cmp al,0Dh ;check when enter is pressed jz nextline mov [bx],al add bx,2 ;popa jmp ifpressed nextline: lea dx, nxtline mov ah, 9 int 21h jmp ifpressed reapet: mov ax, 4c00h ; exit to operating system. int 21h ends end start ; set entry point and stop the assembler. ` A: ...but every time i press on enter it goes down a line... That's exactly what the program was created for. If you don't want this to happen then either remove the next 2 lines from your program: cmp al,0Dh ;check when enter is pressed jz nextline or keep these 2 lines but alter the definition of nxtline (remove the 13): nxtline db 10,'$'
[ "stackoverflow", "0025736828.txt" ]
Q: Passing multiple onClick parameters using div.innerHTML I want to pass multiple parameters to a function that is called via onClick. Here is the code: div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form,divName + '\')" />'; function homeForm(form,divName){ //do something } This works with one parameter but not two: div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\'' + form + '\')" />'; Could someone post a working method for this, or perhaps a cleaner way? A: So in the end this code was the only one that worked for me. I'm posting it here in case someone else needs it: div.innerHTML += '<input type="button" name="back" id="back" value="Back" onClick="homeForm(\''+myForm+'\',\''+divName+'\')" />';
[ "askubuntu", "0000614941.txt" ]
Q: Need a script to find files modified in the last three days and exclude all backup folders I'm trying to set a script to let me know what WordPress files have been modified in the last 3 days, but I get a huge list of every site's backups when I just run: find /var/websites -mtime -1 How do I exclude all directories with the word backup in them? An example of a path that I'd like to exclude is /var/websites/com.site1/backup and all of its subdirectories. A: Use find in this way: find /var/websites -type f -mtime -3 -not -path '*/backup/*' -not -path '*/backup/*' will cause find to ignore the files that have /backup/ in their path. The trailing / in /backup/ is to ensure that this will only consider backup as directory names. Also note that to get precise result regarding time you should use -mmin instead of -mtime. Check man find to get more idea on this.
[ "stackoverflow", "0046909389.txt" ]
Q: Using JMSCorrelationId as selector while receiving Jms message from queue How can I get JMSCorrelationID with CitrusFramework. Any headers we add with header() are dropped by application so I would like to use JMSCorrelationID as selector while receiving message from queue. A: As given in the reference documentation Citrus uses special JMS header names for reserved JMS headers such as JMSCorrelationID (http://www.citrusframework.org/reference/html/index.html#jms-message-headers) You should use citrus_jms_correlationId header name when setting/getting the header. This header name should also work in message selectors in Citrus.
[ "stackoverflow", "0004978791.txt" ]
Q: What is wrong with locking non-static fields? What is the correct way to lock a particular instance? Why is it considered bad practice to lock non-static fields? And, if I am not locking non-static fields, then how do I lock an instance method without locking the method on all other instances of the same or derived class? I wrote an example to make my question more clear. public abstract class BaseClass { private readonly object NonStaticLockObject = new object(); private static readonly object StaticLockObject = new object(); protected void DoThreadSafeAction<T>(Action<T> action) where T: BaseClass { var derived = this as T; if(derived == null) { throw new Exception(); } lock(NonStaticLockObject) { action(derived); } } } public class DerivedClass :BaseClass { private readonly Queue<object> _queue; public void Enqueue(object obj) { DoThreadSafeAction<DerivedClass>(x=>x._queue.Enqueue(obj)); } } If I make the lock on the StaticLockObject, then the DoThreadSafeAction method will be locked for all instances of all classes that derive from BaseClass and that is not what I want. I want to make sure that no other threads can call a method on a particular instance of an object while it is locked. Update Thank you all for your help : I have posted a another question as a follow up to some of the information you all provided. Since you seem to be well versed in this area, I have posted the link: What is wrong with this solution to locking and managing locked exceptions? A: It's not about it being bad-practice, it's about what is your purpose. Static fields are accessed (or, "common to") all the instances of that type. So locking such an static field enables you to control concurrency between all the instances of that type, or, the scope of concurrency control achieved is all the instances of that type. However, if you lock a non-static field, the lock will only be active for that instance, so you control concurrency only within that instance, or, the scope of concurrency control achieved is the instance. Now, whenever locking an object I go like this. What is the resource that I'm concurring for? Maybe it's database, maybe it's a bunch of instance fields that can't be changed while I doing a certain processing, etc. Once I know what is I'm locking myself out of, I check it's scope. If it's an entity outside my application, then it's application scope. Everything must be locked out simultaneously. If it's a bunch of instance fields, then it's instance scope. If it's a bunch of static fields, then it's type scope. So, for 1 and 3, use a static field. For 2, use a instance field. Now, another thing: usually, for 1, you will have a single class that wraps around that resource. And, usually you will design that class as a singleton. Now, with singletons, this is funny: you are guaranteed, by design, to have only a single instance, so it doesn't matter whether you are locking a instance or static field. PS.: If you are using a lock to protect the instantiation of the singleton, of course it should be static. (why?) A: You are locking an object that is used as a lock. The difference therefor is where the lock is contained (or its accessibility). If you have it as a static member, it is accessible to all the objects of the same class. So you get a single lock, that will lock them all. If you have it as member of the class (non static) then it is only accessible to that object. So you will get a single lock per object instance. There's no good-bad practice in this case. It's just a question of what you want to achieve. Just remember to avoid locking this in an object.
[ "stackoverflow", "0046839294.txt" ]
Q: scaleQuantile function doesn't output what I expect I'm using d3.scaleQuantile() to get some specific output of numbers, the range of the d3.scaleQuantile() is an array of 8 numbers. I console.log() a number in the middle position of the range, it returns the first one of that range. The code looks like this var sortMass = d3.scaleQuantile() .domain([minMass, maxMass]) .range([2000,4000,6000,8000,100000,120000]) console.log(sortMass(6500)) // here shows 2000 If it returns either 6000 or 8000, that makes more sense. But I can't figure out why the output is 2000. I read over the D3 documentation, but I'm still confused. Anyone can explain how the d3.scaleQuantile() function works? A: There is a misunderstanding here: in a D3 scale, any kind of scale, you don't pass a value within the range to the scale. Instead of that, you pass a value within the domain. So, given your scale... var sortMass = d3.scaleQuantile() .domain([minMass, maxMass]) .range([2000, 4000, 6000, 8000, 100000, 120000]); ... if you pass the scale a value between minMass and maxMass, it will return the correspondent value in the range. Here is a basic demo, where I'm setting minMass to 0 and maxMass to 100: var minMass = 0, maxMass = 100; var sortMass = d3.scaleQuantile() .domain([minMass, maxMass]) .range([2000, 4000, 6000, 8000, 100000, 120000]); d3.range(0, 110, 10).forEach(function(d) { console.log("for the value " + d + ", the output is:" + sortMass(d)) }) <script src="https://d3js.org/d3.v4.min.js"></script> I suspect that you're using the limits of the range as minMass and maxMass. If that is the case indeed, it won't work: the domain is divided in equal segments. Let's prove it: var sortMass = d3.scaleQuantile() .domain([2000,120000]) .range([2000, 4000, 6000, 8000, 100000, 120000]); console.log(sortMass(6500)) <script src="https://d3js.org/d3.v4.min.js"></script> And that 2000 in the output is proper expected. Therefore, if my assumption above is correct, you should use a threshold scale instead: var thresholds = [2000, 4000, 6000, 8000, 100000, 120000]; var sortMass = d3.scaleThreshold() .domain(thresholds) .range(thresholds); console.log(sortMass(6500)) <script src="https://d3js.org/d3.v4.min.js"></script> Conclusion: So, to answer your question: Can anyone explain how the d3.scaleQuantile() function works? For any D3 scale, you pass a value according to the domain, and the scale will return a value according to the range. Remember: Domain → is the input. Range → is the output.
[ "electronics.stackexchange", "0000258957.txt" ]
Q: When using NOW in ModelSim in VHDL simulation, what determines the time resolution or its unit? The value returned by now could be in ps or ns or some other unit. How do I know what the unit if the returned value is and what in modelsim or VHDL is used to control this unit or resolution of time? A: Modelsim SE User Manual 10.4c Chapter 6 VHDL Simulation, Usage Characteristics and and Requirements, Simulator Resolution Limit for VHDL: Simulator Resolution Limit for VHDL The simulator internally represents time as a 64-bit integer in units equivalent to the smallest unit of simulation time, also known as the simulator resolution limit. The default resolution limit is set to the value specified by the Resolution variable in the modelsim.ini file. You can view the current resolution by invoking the report command with the simulator state argument. So the simulation time units are whatever the resolution limit is. Also see IEEE Std 1076-2008 5.7 String representations: For a value of a physical type, when forming the string representation for a TO_STRING operation, the abstract literal is a decimal literal that is an integer literal, there is no exponent, and there is a single SPACE character between the abstract literal and the unit name. If the physical type is TIME, the unit name is the simple name of the resolution limit (see 5.2.4.2); otherwise, the unit name is the simple name of the primary unit of the physical type. When forming the string representation for the WRITE procedure for type TIME, the physical literal is as described in 16.4. The function now defined in library standard returns a value of type TIME, and anything that converts that to text will report the resolution limit. (The elective bit on Modelsim's part is whether or not to 'scale' units to the resolution limit, which isn't dictated by the VHDL standard).
[ "stackoverflow", "0019454295.txt" ]
Q: Understanding Pythons int method I have a string, "stringify". Doing: int("stringify",36) returns: 81323539083358 Is there a way to convert that number back to "stringify"? A: There is not a built-in way to encode this number back to base 36, but there is a Python implementation on Wikipedia: http://en.wikipedia.org/wiki/Base_36#Python_implementation Here is a slightly modified version of that code (just changed the uppercase letters to lowercase): def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): """Converts an integer to a base36 string.""" if not isinstance(number, (int, long)): raise TypeError('number must be an integer') base36 = '' sign = '' if number < 0: sign = '-' number = -number if 0 <= number < len(alphabet): return sign + alphabet[number] while number != 0: number, i = divmod(number, len(alphabet)) base36 = alphabet[i] + base36 return sign + base36 >>> base36encode(81323539083358) 'stringify'
[ "stackoverflow", "0012779834.txt" ]
Q: What does this mysterious code do? My code: public void mysterious() { int x = 1; x = x++ / ++x; System.out.println(x); } whats the answer? A: int x = 1; x = x++ / ++x; System.out.println(x); Evaluation is done left-to-right: - First x++ is evaluated.. So, it will be 1 Then x will be incremented by 1.. For Post Increment.. Then ++x is evaluated.. Which will be 3 (As x was incremented after x++) So, basically, your above code is equivalent to: - int x = 1; int a = x++; // a = 1, x = 2 int b = ++x; // b = 3, x = 3 x = a / b; // x = 1 / 3 System.out.println(x); // Prints 0
[ "stackoverflow", "0049541115.txt" ]
Q: Powershell text search - multiple matches I have a group of .txt files that contain one or two of the following strings. "red", "blue", "green", "orange", "purple", .... many more (50+) possibilities in the list. If it helps, I can tell if the .txt file contains one or two items, but don't know which one/ones they are. The string patterns are always on their own line. I'd like the script to tell me specifically which one or two string matches (from the master list) it found, and the order in which it found them. (Which one was first) Since I have a lot of text files to search, I'd like to write the output results to a CSV file as I search. FILENAME1,first_match,second_match file1.txt,blue,red file2.txt,red, blue file3.txt,orange, file4.txt,purple,red file5.txt,purple, ... I've tried using many individual Select-Strings returning Boolean results to set variables with any matches found, but with the number of possible strings it gets ugly real fast. My search results for this issue has provided me with no new ideas to try. (I'm sure I'm not asking in the correct way) Do I need to loop through each line of text in each file? Am I stuck with the process of elimination method by checking for the existence of each search string? I'm looking for a more elegant approach to this problem. (if one exists) A: Not very intuïtive but elegant... Following switch statement $regex = "(purple|blue|red)" Get-ChildItem $env:TEMP\test\*.txt | Foreach-Object{ $result = $_.FullName switch -Regex -File $_ { $regex {$result = "$($result),$($matches[1])"} } $result } returns C:\Users\Lieven Keersmaekers\AppData\Local\Temp\test\file1.txt,blue,red C:\Users\Lieven Keersmaekers\AppData\Local\Temp\test\file2.txt,red,blue where file1 contains first blue, then red file2 contains first red, then blue
[ "askubuntu", "0000491385.txt" ]
Q: how to change to next page when clicked on button hi guys I'm new in qml programming and i was just wondering how can i switch to an other page when the user clicks on my button. by the way how can i make a new page in the ubuntu sdk so that when the user clicks on the button goes to there. Thanks A: The following code is heavily inspired by the one provided by the official SDK documentation. I only changed the default control to be Button instead of ListItem: import QtQuick 2.0 import Ubuntu.Components 0.1 MainView { width: units.gu(48) height: units.gu(60) PageStack { id: pageStack Component.onCompleted: push(page0) Page { id: page0 title: i18n.tr("Root page") visible: false Column { anchors.margins: units.gu(3) spacing: units.gu(3) anchors.fill: parent Button { anchors.horizontalCenter: parent.horizontalCenter text: i18n.tr("Page one") onClicked: pageStack.push(page1, {color: UbuntuColors.orange}) } Button { anchors.horizontalCenter: parent.horizontalCenter text: i18n.tr("External page") onClicked: pageStack.push(Qt.resolvedUrl("MyCustomPage.qml")) } } } Page { title: "Rectangle" id: page1 visible: false property alias color: rectangle.color Rectangle { id: rectangle anchors { fill: parent margins: units.gu(5) } } } } } To switch or create a new page, you just need to call the push method. The pushed page may be an Item, Component or URL.
[ "math.stackexchange", "0000161016.txt" ]
Q: Doubt on displacement of a parabola Find the equation which is an displacement of $x² - 3x + 4$ and passes though point $(-3, 3)$ and $(2, 8)$ I've already mounted an simple system of equations which looks obvious $$\begin{align} 8 &= 4a + 2b + c \\ 3 &= 9a - 3b + c \end{align}$$ but I'm stuck here, does someone know where to go now ? thanks in advance. A: We could think that since the new parabola is only a displacement of the first one, it must have the same leading coefficient, i.e., $a=1$ (otherwise we'd also be stretching, shrinking or reflecting it). Then we can solve the resulting system of two equations in two unknowns: $\begin{cases} 8 =4 + 2b +c \\ 3 = 9 - 3b + c \end{cases} \Longleftrightarrow \begin{cases} 4 = 2b +c \\ -6 = - 3b + c \end{cases} $ We could try subtracting the last two equations to get $10 = 5b$, then $b=2$ and replacing anywhere we get $c=0$. So the equation of the desired parabola would be $y= x^2 +2x$.
[ "stackoverflow", "0033910263.txt" ]
Q: Laravel 5 One-to-many relationship master and parent data CRUD I have a purchase table with date and comments and a purchasedetail table with purchaseId as a foreign key of purchase table. Have the relation in both model table is : Purchase model:- use Illuminate\Database\Eloquent\Model; class Purchase extends Model { public function purchasedetails() { return $this->hasMany('App\Models\Purchasedetail', 'PurchaseId', 'Id'); } } and the Purchasedetail model :- use Illuminate\Database\Eloquent\Model; class Purchasedetail extends Model { public function purchase() { return $this->belongsTo('App\Models\Purchase', 'PurchaseId', 'Id'); } } How can I create, update and delete both table data with relations? My main problem is when I send data to controller and try to create, master page data is created but it can not create parent table data or update it. I am using Laravel 5. Some code of my controller: $purchase = new Purchase(); $purchase->Date = Input::get('Date'); $purchase->Comment = Input::get('Comment'); $purchase->purchasedetails = Input::get('Purchasedetail'); $purchase-> save(); if (count($purchase->purchasedetails) != 0) { foreach ($purchase->purchasedetails as $v) { $purchasedetail = new Purchasedetail(); $purchasedetail->ItemId = $v->ItemId; return $v->ItemId; } } $purchase-> Purchasedetail()->save($purchasedetail); I get this error in return: ErrorException in helpers.php line 703: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array. That means $purchase->save() can not possible. Here i get an array list from Input::get('Purchasedetail'). So what can I do now? A: Try the following: $purchase = new Purchase(); $purchase->Date = Input::get('Date'); $purchase->Comment = Input::get('Comment'); $purchase-> save(); $purchase->purchasedetails = Input::get('Purchasedetail'); foreach ($purchase->purchasedetails as $row) { $purchasedetail = new Purchasedetail(); $purchasedetail->ItemId = $row['ItemId']; $purchasedetail->GradeId = $row['GradeId']; $purchasedetail->Quantity = $row['Quantity']; $purchase->purchasedetails()->save($purchasedetail); }
[ "stackoverflow", "0054836514.txt" ]
Q: Disable password toggle ImageButton when TextInputEditText is disabled When a TextInputLayout's app:passwordToggleEnabled attribute is set to true and a TextInputEditText's android:enabled attribute is set to false, how can one prevent the password toggle ImageButton from being clickable? <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="24dp" android:hint="@string/password" app:hintAnimationEnabled="true" app:passwordToggleEnabled="true"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:maxLength="32" android:maxLines="1" android:enabled="false"/> </com.google.android.material.textfield.TextInputLayout> Is this a bug or expected behavior? A: Like I mentioned in the comments, a simple solution to your problem would be to setEnabled of the TextInputLayout to false rather than the TextInputEditText. Since the TextInputLayout houses the TextInputEditText, the entire layout would be disabled by this. Here's a little demo: TextInputLayout textInputLayout = findViewById(R.id.textInputLayout); if(someCondition){ textInputLayout.setEnabled(false); } I hope this helps.. Merry coding!
[ "stackoverflow", "0009900753.txt" ]
Q: How I can add more than 12 tabs to my facebook fan page I am having a facebook fan page with more than 12 tabs added but only admin can see all of them, the normal user only see 12 tabs. How can I make my users see all of tabs? A: You can't make them see more than that limit. You need to prioritize. As this limit is trying to point out, users aren't going to scroll through many apps to find something. Focus on making some apps really well suited to your page.
[ "superuser", "0000113696.txt" ]
Q: Strange symbols while executing win command file Every time I create .cmd file and execute it windows finds strange symbols at start of file: ie: REM ping ping localhost leads to C:\>я╗┐REM ping 'я╗┐' is not recognized as an internal or external command, operable program or batch file. ... I've checked encoding of .cmd file and it seems to be fine. Even HEX editor didn't show any strange in file. A: It looks like a BOM, a Byte Order Mark, although I do not recognize for which encoding. Make sure you save the file with ASCII or ANSI encoding. If it's not a BOM (because it should normally show up in a hex editor), maybe it's a problem with the Command Prompt. Have you tried using .bat instead of .cmd ?
[ "ell.stackexchange", "0000022665.txt" ]
Q: Using 'fluctuation' in a bar chart I am wondering, can 'fluctuation' be mentioned in a bar chart like this: the bar chart depicts the fluctuation of the number of pets per certain category. A: Whether or not fluctuation is a good word to use depends on two factors: What is on the X-axis of the bar chart? How is the data behaving? First, consider this bar chart: I wouldn't consider this fluctuation, because the graph is merely depicting the condition of a pet store at a particular moment in time. Nothing is really fluctuating; the graph simply shows that there were more puppies than kittens at the pet store at the time this data was collected. Now, consider this bar chart: This comes closer to fluctuation, but I think a better word would be growth. NOAD defines fluctuation as: fluctuation (n.) rise and fall irregularly in number or amount In the second graph, the sales numbers are rising, but not falling; therefore, the pet store has had steady growth in feline sales since 2011, not fluctuating sales since 2011. Finally, let's consider this graph: Now we have some fluctuation. The data has been collected over a period of time, and, during this time span, there were times when sales were increasing (2010 through 2012), and times when sales were decreasing (2012 through 2013). Therefore, sales have been fluctuating during the time depicted on the graph.
[ "photo.stackexchange", "0000025820.txt" ]
Q: Why are my recovered images only 160x120 pixels? I am trying to recover some lost images, and with all the programs I've tried, some of the photos resulted to be in a 160x120 pixel resolution. What does this mean, and is there any possibility to recover photos in original dimensions? Any help is appreciated. A: What you have there is the thumbnail stored inside a normal EXIF JPEG file. The size 160×120 is a significant clue that this is where these thumbnails come in, because although I don't think the standard mandates a particular size, 160×120 is incredibly common. (My DSLR saves thumbnails that size, and in fact "letterboxes" the 3:2 images with black bars to fit the aspect ratio.) It must have seemed like a good idea at the time the EXIF standard was written, but these tiny thumbnails are so low quality and so small that they are rarely actually used for anything — yet most JPEG files still contain them. Recovery software works by scanning your data disk block by disk block (or even byte by byte) regardless of any filesystem structure, looking for blocks of data which appear JPEG-like. The thumbnails are perfectly normal JPEG files themselves, so recovery software will pick them up. If that's all you're getting, it's likely that the filesystem you're trying to recover from is so messed up that the big files can't be reconstructed, but the tiny internal thumbnails will sometimes fit in a single disk block (or maybe two together), so they're more likely to be intact. Logically, this symptom is more common when trying to recover from a highly-fragmented drive.
[ "stackoverflow", "0029039429.txt" ]
Q: how to convert html template in to squarespace theme? I have a simple HTML template. I would like to convert it into a squarespace theme, I couldn't find any help. Please guide me to convert this. A: http://base-template.squarespace.com/ Follow above mentioned link it is guiding to create template from scratch.
[ "stackoverflow", "0040000747.txt" ]
Q: Component's overlay doesn't disappear even after state changes in react native Below is my code: // Styling for the common loader const loader = StyleSheet.create({ centering: { flex: 1, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, padding: 8, zIndex: 1005, backgroundColor: '#fff', opacity: 0.8 }, }); // State this.state = { animating: false }; // Component { this.state.animating ? <ActivityIndicator animating={this.state.animating} color="#8bcb43" style={loader.centering} size="large" /> : null } I have attached the screenshot of how the loader looks when this.state.animating is true and when it is false. I am surprised as to why the component doesn't disappear when this.state.animating is false. I am not sure what am I doing wrong. A: I faced this problem nine months ago when I was using React Native 0.35.0 and this is what I did back then as I didn't find any appropriate solution: import React, { Component } from 'react'; import { StyleSheet, ActivityIndicator } from 'react-native'; // Styling for the common loader const loader = StyleSheet.create({ centering: { flex: 1, position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, zIndex: 5, backgroundColor: '#fff', opacity: 0.8 }, hideIndicator: { position: 'absolute', top: -100, opacity: 0 } }); export default class Loader extends Component { render() { /* The reason for adding another activity indicator was to hide the first one */ /* At the time of development, ActivityIndicator had a bug of not getting hidden */ return ( <ActivityIndicator animating={ this.props.animating } color="#8bcb43" style={ this.props.animating ? loader.centering : loader.hideIndicator } size="large" /> ); } } I toggle the style for the loading states. style={ this.props.animating ? loader.centering : loader.hideIndicator } I am not sure if this problem still persists, but if you're facing the same issue then I hope this answer helps.
[ "stackoverflow", "0032981678.txt" ]
Q: Comparator fails with given test data - Why? I have a problem with a comparator. It works most of the time. I have created a test where it fails but I cannot see why it fails or what is wrong. It fails with the error of: java.lang.IllegalArgumentException: Comparison method violates its general contract! The general situation is a list of fields from a PDF that are being sorted by page then by the Y position and then by the X position. I hope someone can point me in the right direction as to why this is failing with the given test data. import junit.framework.TestCase; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class DateUtilsTest extends TestCase { public void testForDerrick() { String fields = "null\t\t27.5118\t\t496.989\n" + "null\t\t121.96\t\t192.52\n" + "0\t\t79.5814\t\t301.597\n" + "0\t\t79.5814\t\t264.662\n" + "0\t\t196.29\t\t429.681\n" + "0\t\t195.955\t\t314.32\n" + "0\t\t196.868\t\t277.982\n" + "0\t\t210.99\t\t429.681\n" + "0\t\t210.82\t\t277.982\n" + "0\t\t225.552\t\t429.681\n" + "0\t\t224.029\t\t277.982\n" + "0\t\t218.91\t\t198.61\n" + "0\t\t267.12\t\t340.05\n" + "0\t\t298.85\t\t346.5\n" + "0\t\t372.16\t\t384.81\n" + "null\t\t349.16\t\t346.5\n" + "0\t\t549.35\t\t188.459\n" + "0\t\t626.48\t\t457.041\n" + "0\t\t649.28\t\t511.764\n" + "0\t\t647.456\t\t503.618\n" + "0\t\t647.456\t\t477.432\n" + "0\t\t658.659\t\t539.6\n" + "0\t\t658.659\t\t477.432\n" + "0\t\t701.73\t\t474.041\n" + "0\t\t712.98\t\t474.041\n" + "0\t\t626.48\t\t121.0\n" + "0\t\t626.48\t\t41.0\n" + "0\t\t662.44\t\t117.0\n" + "0\t\t673.611\t\t117.0\n" + "0\t\t687.52\t\t117.0\n" + "0\t\t700.73\t\t117.0\n" + "0\t\t712.98\t\t117.0\n" + "0\t\t787.169\t\t150.654\n" + "null\t\t123.57\t\t532.77\n" + "1\t\t35.6173\t\t92.42\n" + "1\t\t47.83\t\t515.0\n" + "1\t\t47.83\t\t369.25\n" + "1\t\t76.5\t\t441.88\n" + "1\t\t76.5\t\t368.85\n" + "null\t\t123.57\t\t417.02\n" + "1\t\t99.03\t\t515.0\n" + "1\t\t99.03\t\t441.88\n" + "1\t\t99.03\t\t369.25\n" + "1\t\t99.03\t\t53.2\n" + "1\t\t109.29\t\t515.0\n" + "1\t\t109.29\t\t441.88\n" + "1\t\t109.29\t\t369.25\n" + "1\t\t109.29\t\t53.2\n" + "1\t\t119.56\t\t515.0\n" + "1\t\t119.56\t\t441.88\n" + "1\t\t119.56\t\t369.25\n" + "1\t\t119.56\t\t53.2\n" + "1\t\t129.83\t\t515.0\n" + "1\t\t129.83\t\t441.88\n" + "1\t\t129.83\t\t369.25\n" + "1\t\t129.83\t\t53.2\n" + "1\t\t140.09\t\t515.0\n" + "1\t\t140.09\t\t441.88\n" + "1\t\t140.09\t\t369.25\n" + "1\t\t140.09\t\t53.2\n" + "1\t\t150.36\t\t515.0\n" + "1\t\t150.36\t\t441.88\n" + "1\t\t150.36\t\t369.25\n" + "1\t\t150.36\t\t53.2\n" + "1\t\t160.62\t\t515.0\n" + "1\t\t160.62\t\t441.88\n" + "1\t\t160.62\t\t369.25\n" + "1\t\t160.62\t\t53.2\n" + "1\t\t171.319\t\t515.0\n" + "1\t\t171.319\t\t441.88\n" + "1\t\t171.319\t\t369.25\n" + "1\t\t171.319\t\t53.2\n" + "1\t\t180.464\t\t401.15\n" + "1\t\t192.194\t\t514.83\n" + "1\t\t192.194\t\t441.71\n" + "1\t\t192.194\t\t369.08\n" + "1\t\t202.464\t\t514.83\n" + "1\t\t202.464\t\t441.71\n" + "1\t\t202.464\t\t369.08\n" + "1\t\t202.464\t\t53.0295\n" + "1\t\t212.724\t\t514.83\n" + "1\t\t212.724\t\t441.71\n" + "1\t\t212.724\t\t369.08\n" + "1\t\t212.724\t\t53.0295\n" + "1\t\t222.994\t\t514.83\n" + "1\t\t222.994\t\t441.71\n" + "1\t\t222.994\t\t369.08\n" + "1\t\t222.994\t\t53.0295\n" + "1\t\t233.254\t\t514.83\n" + "1\t\t233.254\t\t441.71\n" + "1\t\t233.254\t\t369.08\n" + "1\t\t233.254\t\t53.0295\n" + "1\t\t243.564\t\t514.83\n" + "1\t\t243.564\t\t441.71\n" + "1\t\t243.564\t\t369.08\n" + "1\t\t243.564\t\t242.83\n" + "1\t\t243.564\t\t136.83\n" + "1\t\t253.874\t\t514.83\n" + "1\t\t253.874\t\t441.71\n" + "1\t\t253.874\t\t369.08\n" + "1\t\t253.874\t\t242.83\n" + "1\t\t253.874\t\t136.83\n" + "1\t\t264.264\t\t514.83\n" + "1\t\t264.264\t\t441.71\n" + "1\t\t264.264\t\t369.08\n" + "1\t\t264.264\t\t242.83\n" + "1\t\t264.264\t\t136.83\n" + "1\t\t274.154\t\t400.98\n" + "1\t\t285.485\t\t515.0\n" + "1\t\t285.485\t\t441.444\n" + "1\t\t285.485\t\t369.25\n" + "1\t\t285.485\t\t53.2\n" + "1\t\t295.802\t\t515.0\n" + "1\t\t295.802\t\t441.444\n" + "1\t\t295.802\t\t369.25\n" + "1\t\t295.802\t\t149.84\n" + "1\t\t295.802\t\t104.36\n" + "1\t\t305.576\t\t515.0\n" + "1\t\t305.576\t\t441.444\n" + "1\t\t305.576\t\t369.25\n" + "1\t\t305.576\t\t242.29\n" + "1\t\t305.576\t\t189.18\n" + "1\t\t305.576\t\t107.88\n" + "1\t\t316.153\t\t515.0\n" + "1\t\t316.153\t\t441.444\n" + "1\t\t316.153\t\t369.25\n" + "1\t\t316.153\t\t198.06\n" + "1\t\t316.153\t\t151.58\n" + "1\t\t326.675\t\t515.0\n" + "1\t\t326.675\t\t441.444\n" + "1\t\t326.675\t\t369.25\n" + "1\t\t326.675\t\t211.5\n" + "1\t\t326.675\t\t165.02\n" + "1\t\t336.47\t\t401.15\n" + "1\t\t347.74\t\t515.0\n" + "1\t\t347.74\t\t441.88\n" + "1\t\t347.74\t\t369.25\n" + "1\t\t347.74\t\t53.2\n" + "1\t\t358.13\t\t515.0\n" + "1\t\t358.13\t\t441.88\n" + "1\t\t358.13\t\t369.25\n" + "1\t\t358.13\t\t247.9\n" + "1\t\t358.13\t\t153.0\n" + "1\t\t368.02\t\t401.15\n" + "1\t\t400.19\t\t442.787\n" + "1\t\t400.19\t\t368.25\n" + "null\t\t123.57\t\t306.57\n" + "1\t\t423.977\t\t516.463\n" + "1\t\t423.977\t\t443.343\n" + "1\t\t423.977\t\t369.713\n" + "1\t\t423.977\t\t54.6625\n" + "1\t\t434.237\t\t516.463\n" + "1\t\t434.237\t\t443.343\n" + "1\t\t434.237\t\t369.713\n" + "1\t\t434.237\t\t54.6625\n" + "1\t\t444.507\t\t516.463\n" + "1\t\t444.507\t\t443.343\n" + "1\t\t444.507\t\t369.713\n" + "1\t\t444.507\t\t54.6625\n" + "1\t\t454.777\t\t516.463\n" + "1\t\t454.777\t\t443.343\n" + "1\t\t454.777\t\t369.713\n" + "1\t\t454.777\t\t54.6625\n" + "1\t\t465.037\t\t516.463\n" + "1\t\t465.037\t\t443.343\n" + "1\t\t465.037\t\t369.713\n" + "1\t\t465.037\t\t54.6625\n" + "1\t\t475.307\t\t516.463\n" + "1\t\t475.307\t\t443.343\n" + "1\t\t475.307\t\t369.713\n" + "1\t\t475.307\t\t54.6625\n" + "1\t\t485.567\t\t516.463\n" + "1\t\t485.567\t\t443.343\n" + "1\t\t485.567\t\t369.713\n" + "1\t\t485.567\t\t54.6625\n" + "1\t\t495.837\t\t516.463\n" + "1\t\t495.957\t\t443.343\n" + "1\t\t495.957\t\t369.713\n" + "1\t\t495.957\t\t54.6625\n" + "1\t\t506.847\t\t402.613\n" + "1\t\t517.117\t\t516.463\n" + "1\t\t517.117\t\t443.343\n" + "1\t\t517.117\t\t369.713\n" + "1\t\t517.117\t\t54.6625\n" + "1\t\t527.387\t\t516.463\n" + "1\t\t527.387\t\t443.343\n" + "1\t\t527.387\t\t369.713\n" + "1\t\t527.387\t\t54.6625\n" + "1\t\t537.647\t\t516.463\n" + "1\t\t537.647\t\t443.343\n" + "1\t\t537.647\t\t369.713\n" + "1\t\t537.647\t\t54.6625\n" + "1\t\t547.917\t\t516.463\n" + "1\t\t547.917\t\t443.343\n" + "1\t\t547.917\t\t369.713\n" + "1\t\t547.917\t\t54.6625\n" + "1\t\t558.177\t\t516.463\n" + "1\t\t558.177\t\t443.343\n" + "1\t\t558.177\t\t369.713\n" + "1\t\t558.177\t\t54.6625\n" + "1\t\t568.447\t\t516.463\n" + "1\t\t568.447\t\t443.343\n" + "1\t\t568.447\t\t369.713\n" + "1\t\t568.447\t\t54.6625\n" + "1\t\t578.707\t\t516.463\n" + "1\t\t578.707\t\t443.343\n" + "1\t\t578.707\t\t369.713\n" + "1\t\t578.707\t\t54.6625\n" + "1\t\t588.977\t\t516.463\n" + "1\t\t588.977\t\t443.343\n" + "1\t\t588.977\t\t369.713\n" + "1\t\t588.977\t\t54.6625\n" + "1\t\t599.237\t\t516.463\n" + "1\t\t599.237\t\t443.343\n" + "1\t\t599.237\t\t369.713\n" + "1\t\t599.237\t\t54.6625\n" + "1\t\t609.507\t\t516.463\n" + "1\t\t609.637\t\t443.343\n" + "1\t\t609.637\t\t369.713\n" + "1\t\t609.637\t\t54.6625\n" + "1\t\t620.527\t\t402.613\n" + "1\t\t630.787\t\t516.463\n" + "1\t\t630.787\t\t443.343\n" + "1\t\t630.787\t\t369.713\n" + "1\t\t630.787\t\t54.6625\n" + "1\t\t641.057\t\t516.463\n" + "1\t\t641.057\t\t443.343\n" + "1\t\t641.057\t\t369.713\n" + "1\t\t641.057\t\t54.6625\n" + "1\t\t651.317\t\t516.463\n" + "1\t\t651.317\t\t443.343\n" + "1\t\t651.317\t\t369.713\n" + "1\t\t651.317\t\t54.6625\n" + "1\t\t661.587\t\t516.463\n" + "1\t\t661.587\t\t443.343\n" + "1\t\t661.587\t\t369.713\n" + "1\t\t661.587\t\t54.6625\n" + "1\t\t671.847\t\t516.463\n" + "1\t\t671.847\t\t443.343\n" + "1\t\t671.847\t\t369.713\n" + "1\t\t671.847\t\t54.6625\n" + "1\t\t682.117\t\t516.463\n" + "1\t\t682.117\t\t443.343\n" + "1\t\t682.117\t\t369.713\n" + "1\t\t682.117\t\t54.6625\n" + "1\t\t692.387\t\t516.463\n" + "1\t\t692.387\t\t443.343\n" + "1\t\t692.387\t\t369.713\n" + "1\t\t692.387\t\t54.6625\n" + "1\t\t702.777\t\t516.463\n" + "1\t\t702.777\t\t443.343\n" + "1\t\t702.777\t\t369.713\n" + "1\t\t702.777\t\t54.6625\n" + "1\t\t712.667\t\t402.613\n" + "2\t\t131.82\t\t494.835\n" + "2\t\t166.95\t\t334.15\n" + "2\t\t166.95\t\t311.9\n" + "2\t\t180.85\t\t334.15\n" + "2\t\t180.85\t\t311.9\n" + "2\t\t193.091\t\t334.15\n" + "2\t\t204.861\t\t334.15\n" + "2\t\t198.31\t\t311.9\n" + "2\t\t216.78\t\t334.15\n" + "2\t\t216.78\t\t311.9\n" + "2\t\t140.206\t\t286.44\n" + "2\t\t140.206\t\t250.77\n" + "null\t\t90.11\t\t192.52\n" + "null\t\t47.83\t\t440.17\n" + "null\t\t572.54\t\t197.55\n" + "2\t\t140.206\t\t224.243\n" + "2\t\t140.206\t\t188.434\n" + "2\t\t152.411\t\t190.822\n" + "2\t\t166.95\t\t191.0\n" + "2\t\t198.31\t\t191.0\n" + "2\t\t216.78\t\t191.0\n" + "null\t\t166.95\t\t254.0\n" + "2\t\t313.6\t\t501.8\n" + "2\t\t313.6\t\t57.8\n" + "2\t\t342.27\t\t501.8\n" + "2\t\t342.27\t\t57.8\n" + "2\t\t371.07\t\t501.8\n" + "2\t\t371.07\t\t57.8\n" + "2\t\t399.87\t\t501.8\n" + "2\t\t399.87\t\t57.8\n" + "2\t\t428.67\t\t501.8\n" + "2\t\t428.67\t\t57.8\n" + "2\t\t457.47\t\t501.8\n" + "2\t\t457.47\t\t57.8\n" + "2\t\t486.27\t\t501.8\n" + "2\t\t486.27\t\t57.8\n" + "2\t\t515.07\t\t501.8\n" + "2\t\t515.07\t\t57.8\n" + "2\t\t543.87\t\t501.8\n" + "2\t\t543.87\t\t57.8\n" + "2\t\t572.67\t\t501.8\n" + "2\t\t572.67\t\t57.8\n" + "2\t\t601.47\t\t501.8\n" + "2\t\t601.47\t\t57.8\n" + "2\t\t630.27\t\t501.8\n" + "2\t\t630.27\t\t57.8\n" + "2\t\t659.07\t\t501.8\n" + "2\t\t659.07\t\t57.8\n" + "2\t\t687.87\t\t501.8\n" + "2\t\t687.87\t\t57.8\n" + "2\t\t715.92\t\t501.8\n" + "2\t\t715.92\t\t57.8\n" + "3\t\t359.57\t\t394.05\n" + "3\t\t390.22\t\t394.05\n" + "3\t\t458.086\t\t545.206\n" + "3\t\t458.086\t\t478.15\n" + "3\t\t458.086\t\t317.306\n" + "3\t\t488.85\t\t394.05\n" + "3\t\t518.65\t\t394.05\n" + "3\t\t538.809\t\t435.303\n" + "3\t\t550.477\t\t435.303\n" + "3\t\t568.55\t\t394.05\n" + "3\t\t581.219\t\t436.03\n" + "3\t\t590.989\t\t436.03\n" + "3\t\t603.112\t\t436.03\n" + "3\t\t620.3\t\t394.05\n" + "3\t\t687.503\t\t317.306\n" + "null\t\t639.63\t\t117.0\n" + "null\t\t650.984\t\t117.0\n" + "3\t\t314.184\t\t39.7711\n" + "3\t\t336.086\t\t39.7711\n" + "3\t\t358.272\t\t39.7711\n" + "3\t\t571.296\t\t40.0028\n" + "3\t\t599.766\t\t39.8304\n" + "3\t\t621.736\t\t39.8304\n" + "3\t\t665.499\t\t39.8304\n" + "3\t\t687.859\t\t39.8304\n" + "4\t\t115.997\t\t503.877\n" + "4\t\t115.62\t\t324.0\n" + "4\t\t115.62\t\t40.5\n" + "4\t\t121.715\t\t215.873\n" + "4\t\t188.51\t\t432.749\n" + "4\t\t200.49\t\t432.75\n" + "4\t\t220.99\t\t432.75\n" + "4\t\t233.98\t\t432.75\n" + "4\t\t244.96\t\t432.75\n" + "4\t\t255.95\t\t432.75\n" + "4\t\t266.94\t\t432.75\n" + "4\t\t278.92\t\t432.75\n" + "4\t\t288.55\t\t432.75\n" + "4\t\t299.294\t\t432.749\n" + "4\t\t312.88\t\t432.75\n" + "4\t\t321.887\t\t432.75\n" + "4\t\t188.51\t\t288.75\n" + "4\t\t200.49\t\t288.75\n" + "4\t\t220.99\t\t288.75\n" + "4\t\t233.98\t\t288.75\n" + "4\t\t244.96\t\t288.75\n" + "4\t\t255.95\t\t288.75\n" ; List<TestSort> testSortList = new ArrayList<TestSort>(); String[] fieldList = fields.split("\n"); for (String field : fieldList) { String[] threeVals = field.split("\t\t"); TestSort df = new TestSort(); df.setPage(!"null".equals(threeVals[0]) ? Integer.valueOf(threeVals[0]) : null); df.setTopLeftY(Double.valueOf(threeVals[1])); df.setTopLeftX(Double.valueOf(threeVals[2])); df.setFormField(""); testSortList.add(df); } Collections.sort(testSortList, new Comparator<TestSort>() { @Override public int compare(TestSort o1, TestSort o2) { if (o1.getPage() == null || o2.getPage() == null || o1.getPage().equals(o2.getPage())) { if (o1.getTopLeftY() == null || o2.getTopLeftY() == null || o1.getTopLeftY().equals(o2.getTopLeftY())) { if (o1.getTopLeftX() == null || o2.getTopLeftX() == null || o1.getTopLeftX().equals(o2.getTopLeftX())) { return o1.getFormField().compareTo(o2.getFormField()); } else { return o1.getTopLeftX().compareTo(o2.getTopLeftX()); } } else { return o1.getTopLeftY().compareTo(o2.getTopLeftY()); } } else { return o1.getPage().compareTo(o2.getPage()); } } }); } public class TestSort { private Integer page; private Double topLeftY; private Double topLeftX; private String formField; public String getFormField() { return formField; } public void setFormField(String formField) { this.formField = formField; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Double getTopLeftY() { return topLeftY; } public void setTopLeftY(Double topLeftY) { this.topLeftY = topLeftY; } public Double getTopLeftX() { return topLeftX; } public void setTopLeftX(Double topLeftX) { this.topLeftX = topLeftX; } } } A: The exception is indicating that this is a non-transitive comparison. I have to agree with Dave Newton's comment that it's hard to reason about this comparator. All the null-checking is confusing, but it seems like the order that things get compared in is not consistent. See Effective Java, Item 12 (Consider Implementing Comparable): If a class has multiple significant fields, the order in which you compare them is critical. You must start with the most significant field and work your way down. If a comparison results in anything other than zero (which represents equality), you’re done; just return the result. If the most significant fields are equal, go on to compare the next-most-significant fields, and so on. If all fields are equal, the objects are equal; return zero. Specifically, if you're comparing a null field to a non-null field your code is trying to go on and compare the next most significant field, that means you're taking a case where one field is null and the other isn't, so one ought to sort higher than the other, and you're treating them as if they are equivalent, yet you're going forward with comparing the next most significant fields. Here's a comparator written to comply with Bloch's advice, that tries to clean up the null-checking; nulls get replaced with a low-sorting value so the ordering will be consistent: class TestSortComparator implements Comparator<TestSort> { Double defaultIfNull(Double d) { return d == null ? Double.NEGATIVE_INFINITY : d; } Integer defaultIfNull(Integer i) { return i == null ? Integer.MIN_VALUE : i; } String defaultIfNull(String s) { return s == null ? "" : s; } @Override public int compare(TestSort o1, TestSort o2) { int pageComp = defaultIfNull(o1.getPage()) .compareTo(defaultIfNull(o2.getPage())); if (pageComp != 0) return pageComp; int yComp = defaultIfNull(o1.getTopLeftY()) .compareTo(defaultIfNull(o2.getTopLeftY())); if (yComp != 0) return yComp; int xComp = defaultIfNull(o1.getTopLeftX()) .compareTo(defaultIfNull(o2.getTopLeftX())); if (xComp != 0) return xComp; return defaultIfNull(o1.getFormField()) .compareTo(defaultIfNull(o2.getFormField())); } }
[ "stackoverflow", "0009198282.txt" ]
Q: Play Framework: case-insensitive matching in play.libs.XPath The Play Framework provides a great XPath object for processing XML documents. For example, to select foobar nodes from an xml document you could use List<Node> nodes = XPath.selectNodes(".//foobar", xmlDocument); However, this is case sensitive (as expected), so if you were to run the same query on an xml document that had the elements named fooBar instead, then no nodes would be found. Through my google searches I found that "case-insensitive" searching can be achieved by making the node name lower case: .//[lower-case(@foobar)] Does anyone know how I would apply that to work with the Play Framework's XPath lib? A: I don't know what Play, specifically, supports, but you have a couple options. First, if Play supports XPath 2.0, then use lower-case: //*[lower-case(local-name())='foo'] If lower-case is not supported, then use the XPath 1.0 translate function to imitate it: //*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='foo']
[ "stackoverflow", "0006023031.txt" ]
Q: Display strokes on an InkCanvas, but do not capture events I am developing a touch screen application and allow users to add touch-based markup to an overlay over content using an ink canvas. I have reached a point where the view behind the overlay has an element that needs the user should be allowed to interact with, but events are captured by the InkCanvas and not by the underlying control. Is there a way to display strokes, but still allow controls behind the InkCanvas to capture events? A: You can set InkCanvas.IsHitTestVisible = false and it will still display but you will not be able to interact with it and all events will go to elements lower in the z-order, which sounds like exactly what you want.
[ "stackoverflow", "0028655897.txt" ]
Q: Bind parameter doesn't work with like in Firebird 2.0. Is there a workaround? If I use a bind parameter with like it restricts the length of the parameter. for example: select * from rdb$database where :x like '%N'; If the x parameter is longer than 2 I get a string truncation exception. I'm using Firebird 2.0. Is there a way around it or bind parameters won't work with like? A: In Firebird bind parameters are restricted to the same type and length as the field, column or value they are compared to. In this case you are comparing to a literal of two characters and it is considered a CHAR(2) by Firebird, so the bind parameter is also a CHAR(2). This doesn't just apply to like, but to all comparison operations. This means you cannot use a value longer than two characters for the parameter. There are two workarounds I know of: Cast the value, eg: WHERE ? LIKE CAST('%N' AS VARCHAR(256)) Cast the parameter, eg: WHERE CAST(? AS VARCHAR(256)) LIKE '%N'
[ "mathematica.stackexchange", "0000077441.txt" ]
Q: Creating a random make matrix with a particular rank Does Mathematica have a built-in function that will return a random mxn matrix with rank r?l A: For square matrices: You can try this: RandomMatrix[rank_, m_] := Sum[TensorProduct @@ RandomReal[{-1, 1}, {2, m}], {i, rank}]; It returns a pseudorandom m-by-m matrix with rank rank. Example usage: MatrixRank@RandomMatrix[5, 10] (*5*) Rectangular matrices For rectangular matrices, try this: RandomMatrix[rank_, m_, n_] := Sum[RandomReal[{-1, 1}, m]\[TensorProduct]RandomReal[{-1, 1}, n], {i, rank}]; Example usage: Dimensions[RandomMatrix[3, 4, 5]] MatrixRank[RandomMatrix[3, 4, 5]] (*{4, 5}*) (*3*)
[ "stackoverflow", "0062466195.txt" ]
Q: How can I import a certificate into the iOS keychain? I tried the following code but I keep getting "The specified attribute does not exist" error. kSecValueRef was checked and is not nil let attributes: [String: Any] = [kSecClass as String : kSecClassCertificate, kSecValueRef as String : certificateRef!, kSecAttrApplicationTag as String : tag] let osStatus = SecItemAdd(attributes as CFDictionary, nil) A: You can find the resource describing available attributes for the kSecClassCertificate type here. You should change kSecAttrApplicationTag to kSecAttrLabel, that should solve the issue for you. The application tag is not a valid parameter for a certificate. p.s. There is a document describing each of these attributes per class on the Apple developer documentation page, or you could also look at the source code.
[ "stackoverflow", "0030935575.txt" ]
Q: Speech recognizing in a loop I am trying to write a speech recognition code which takes voice from the microphone and process till a "Stop" is said. The code works for the first voice but then it gives an error. The code which I wrote is below: import speech_recognition as sr import webbrowser r = sr.Recognizer() with sr.Microphone() as source: while True: audio = r.listen(source) print("You said " + r.recognize(audio)) if r.recognize(audio)=="Facebook": webbrowser.open('https://www.facebook.com') if r.recognize(audio)=="Google": webbrowser.open('https://www.google.co.uk') if r.recognize(audio)=="Stop": break The error which I am getting is : You said Facebook Traceback (most recent call last): File "C:/Work/Scripts/SpeechRecognition/Speech.py", line 9, in <module> print("You said " + r.recognize(audio)) # listen for the first phrase and extract it into audio data File "C:\Users\roradhak.NDS-UK\AppData\Roaming\Python\Python27\site-packages\speech_recognition\__init__.py", line 324, in recognize raise LookupError("Speech is unintelligible") LookupError: Speech is unintelligible Process finished with exit code 1 A: You need to catch the exception: def recognize(audio): try: return r.recognize(audio) except LookupError, e: print e return '' Then: with sr.Microphone() as source: while True: audio = r.listen(source) words = recognize(audio) print("You said " + words) if words == "Facebook": webbrowser.open('https://www.facebook.com') elif words =="Google": webbrowser.open('https://www.google.co.uk') elif words == "Stop": break
[ "stackoverflow", "0000120075.txt" ]
Q: Problem with Asp.Net RequireFieldValidator and Javascript WYSIWYG I am using the open source Javascript WYSIWYG from OpenWebWare and Asp.Net RequiredFieldValidator on the TextBox which I am calling the WYSIWYG for. Everything works fine, but the first time I try to submit the form, I get the server-side RFV ErrorMessage "Required", but if I submit a second time, it goes through. Am I missing something? I would like to have the client-side validation... how can I get the text to register as not empty? A: I think the reason for this behavior is that validation code runs earlier than the code that updates underlying TextBox from value of WYSIWYG. So the first time you get the error, then the field is updated and the second time you don't get it. Try removing all the content the second time and I bet you wont get validation error (since the value for validator at the moment is what you actually submitted the first time). The solution would be to find a JavaScript API call for your WYSIWYG which would force the update of the underlying text box field and call it onclick (client-side) of your submit button or whatever you use for that.
[ "stackoverflow", "0005656602.txt" ]
Q: Windows Form not getting updates from my database? Ive only recently starting fiddling with Visual Basic Express and Sql Databases. Ive managed to get a database up and running, and can query information from it. I have even created a form that can add a new entry to the table im using. The first form has a ComboBox that list the PlayerNames in my table. Form2 allows you to add a new name to the table, but anything I add isnt immediately updated in Form1. I have to relaunch the program to see the new entries. Even then, these new entries dont seem to be permanent as they eventually dissappear. The code I have for Form1: Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim db = New PlayerTestDataContextDataContext() Dim PlayerList = From List In db.Players Select List.PlayerName For Each PName In PlayerList cbPList.Items.Add(PName) Next End Sub Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click frmNewPlayer.Show() End Sub End Class The code for Form2: Private Sub btnCPlayer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCPlayer.Click Dim db = New PlayerTestDataContextDataContext() If txtNewPlayer.Text = "" Then lbWarning.Text = "Please enter a name!" Else Dim Plyr As New Player With { .PlayerName = txtNewPlayer.Text} db.Players.InsertOnSubmit(Plyr) db.SubmitChanges() Me.Close() End If End Sub Not sure what is going wrong here...any help is appreciated. If I have overlooked an obvious answer around here forgive me, Im not sure what I need to be looking for. A: That should do the trick. But you need to do some reading ... Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click if frmNewPlayer.ShowDailog() == DialogResult.Ok Dim db = New PlayerTestDataContextDataContext() Dim PlayerList = From List In db.Players Select List.PlayerName ' cbpList.Items.Clear() ' For Each PName In PlayerList cbPList.Items.Add(PName) Next end if End Sub
[ "puzzling.stackexchange", "0000065279.txt" ]
Q: As Stack Exchange does You may call me fake, but with great power I make, and I keep you awake. From a Stack Exchange site, my name I use. Be careful with your commands, don't abuse! What am I? A: I want to say this is: Reputation points. You may call me fake People call it Meaningless/Fake Internet Points. but with great power I make Higher reputation gives you higher privileges, i.e. more power in a site. and I keep you awake Higher rep also means you are/were a regular contributor to a site and that's one way to be kept awake(?) TITLE: Stack Exchange awards us reputation. A: My guess is News You may call me fake By now, the term 'fake news' is pretty common. but with great power I make News has great power over people, influencing society in many ways. News is also made by people with great power, and can make positions of great power i.e. Donald Trump's presidential campaign was made partially by the news media. and I keep you awake News has become intrusive in our lives, with current events being a click away Title Not too sure about this, but my guess is that this has something to do with Stack Exchange making the news. A: I am: Bitcoin You may call me fake, Many people consider Bitcoin to be a fake currency. but with great power I make, It takes a lot of power to mine Bitcoin. and I keep you awake. The volatility of Bitcoin is certainly enough to "keep you up at night". Title: As Stack Exchange does: Well, there's this: https://bitcoin.stackexchange.com/
[ "stackoverflow", "0053980050.txt" ]
Q: Unable to populate my RecyclerView with the conversation from the user and DialogFlow(api.ai) I am trying to build an android chat bot application using FirebaseDatabase and DialogFlow(api.ai) and I am using RecyclerView to Load the messages into the app. But I am unable to load messages into the app, every time it shows blank screen when I run the app. I have tried all the suggested answers on StackOverflow but still I am unable to load messages into the app. MainActivity import ai.api.AIConfiguration; import ai.api.AIListener; import ai.api.AIServiceException; import ai.api.android.AIDataService; import ai.api.android.AIService; import ai.api.model.AIError; import ai.api.model.AIRequest; import ai.api.model.AIResponse; import ai.api.model.Result; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.annotation.SuppressLint; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.RelativeLayout; import com.firebase.ui.database.FirebaseRecyclerAdapter; import com.firebase.ui.database.FirebaseRecyclerOptions; import com.firebase.ui.database.SnapshotParser; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.List; import java.util.Objects; public class MainActivity extends AppCompatActivity implements AIListener{ RecyclerView recyclerView; EditText editText; RelativeLayout addBtn; DatabaseReference ref; private AIService aiService; private Context context; FirebaseRecyclerAdapter<ChatMessage, chat_rec>adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.RecyclerView); editText = findViewById(R.id.TEXT); addBtn = findViewById(R.id.addBtn); context = getApplicationContext(); recyclerView.setHasFixedSize(true); final ai.api.android.AIConfiguration configuration = new ai.api.android.AIConfiguration("8c9665a53fba45d9a3015e0ba7330417", AIConfiguration.SupportedLanguages.English, ai.api.android.AIConfiguration.RecognitionEngine.System); aiService = AIService.getService(this, configuration); aiService.setListener(this); final AIRequest aiRequest = new AIRequest(); final AIDataService aiDataService = new AIDataService(context, configuration); final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setStackFromEnd(true); ref = FirebaseDatabase.getInstance().getReference(); ref.keepSynced(true); addBtn.setOnClickListener(new View.OnClickListener() { @SuppressLint("StaticFieldLeak") @Override public void onClick(View v) { recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setHasFixedSize(true); String message = editText.getText().toString().trim(); if (!message.equals("")) { ref = FirebaseDatabase.getInstance().getReference().child("chat").push(); ChatMessage chatMessage = new ChatMessage(message, "user"); ref.child("chat").push().setValue(chatMessage); ChatMessage model1 = new ChatMessage(); model1.setMessageUser(chatMessage.toString()); new AsyncTask<AIRequest, Void, AIResponse>() { @Override protected AIResponse doInBackground(AIRequest... aiRequests) { final AIRequest request = aiRequests[0]; try { final AIResponse response = aiDataService.request(aiRequest); } catch (AIServiceException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(AIResponse response) { if (response != null) { Result result = response.getResult(); String reply = result.getFulfillment().getSpeech(); ChatMessage chatMessage = new ChatMessage(reply, "bot"); ref.child("chat").push().setValue(chatMessage); } } }.execute(aiRequest); } else { aiService.startListening(); } editText.setText(""); } }); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); FirebaseRecyclerOptions<ChatMessage>options = new FirebaseRecyclerOptions.Builder<ChatMessage>() .setQuery(ref, ChatMessage.class) .build(); adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(options) { @Override protected void onBindViewHolder(@NonNull final chat_rec holder, int i, @NonNull final ChatMessage model) { ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(Objects.requireNonNull(dataSnapshot.child("chat").getValue()).equals( model.getMessageUser())) { holder.rightText.setText(model.getMessageText()); holder.rightText.setVisibility(View.VISIBLE); } else { holder.leftText.setText(model.getMessageText()); holder.leftText.setVisibility(View.VISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @NonNull @Override public chat_rec onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.messagelist, parent, false); return new chat_rec(view); } }; adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int msgCount = adapter.getItemCount(); int lastVisiblePosition = linearLayoutManager.findLastCompletelyVisibleItemPosition(); if (lastVisiblePosition == -1 || (positionStart >= (msgCount - 1) && lastVisiblePosition == (positionStart - 1))) { recyclerView.scrollToPosition(positionStart); } } }); recyclerView.setAdapter(adapter); } @Override protected void onStart() { super.onStart(); adapter.startListening(); } @Override public void onResult(AIResponse result) { Result result1 = result.getResult(); String message = result1.getResolvedQuery(); ChatMessage chatMessage = new ChatMessage(message, "user"); ref.child("chat").push().setValue(chatMessage); String reply = result1.getFulfillment().getSpeech(); ChatMessage chatMessage1 = new ChatMessage(reply,"bot"); ref.child("chat").push().setValue(chatMessage1); } @Override public void onError(AIError error) { } @Override public void onAudioLevel(float level) { } @Override public void onListeningStarted() { } @Override public void onListeningCanceled() { } @Override public void onListeningFinished() { } } Can somebody please let me know what changes I should make, so that I can make this thing work. A: I found an alternative solution to this problem. Instead of populating the RecyclerView. One can create two different xml layouts - Bot Layout and User Layout. Bot message layout <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp" android:paddingBottom="0dp"> <LinearLayout android:id="@+id/botMsgLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="start|center_vertical" android:layout_marginTop="4dp" android:layout_marginBottom="4dp" android:layout_marginEnd="16dp" android:layout_marginStart="8dp" android:background="@drawable/bot_bg_bubble" android:gravity="start|center_vertical" android:orientation="vertical"> <TextView android:id="@+id/chatMsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:fontFamily="@font/adamina" android:lineSpacingExtra="1sp" android:padding="12dp" android:text="Hello There!" android:textAlignment="viewStart" android:textAllCaps="false" android:textSize="18sp" android:typeface="normal" /> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> </FrameLayout> </LinearLayout> </FrameLayout> User message layout <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp"> <LinearLayout android:id="@+id/userMsgLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|center_vertical" android:layout_marginTop="4dp" android:layout_marginBottom="4dp" android:layout_marginEnd="16dp" android:layout_marginStart="8dp" android:background="@drawable/user_bg_bubble" android:gravity="end|center_vertical" android:orientation="vertical"> <TextView android:id="@+id/chatMsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:padding="12dp" android:text="Hello!" android:textSize="18sp" /> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp"> </FrameLayout> </LinearLayout> </FrameLayout> Now, in MainActivity inflate the above layouts using a switch case according to the required needs.
[ "writers.stackexchange", "0000040198.txt" ]
Q: Comic Cruelty - Examples In the movie Inglourious Basterds, there are many scenes employing what I can only describe as "comic cruelty". Acts of barbarity that yet somehow inspire glee and revelry in the audience. Anyone who's watched the movie knows what I'm talking about. Is this an official trope or a writing style? Does it have a name and are there other examples in books and film that you can think of? I would really like to study this form of comedy, but so far only have had exposure from one movie. A: This is typically called black humor (based on an essay by Andre Breton). Personally, I dislike the term, because it sounds racial when it isn't, but it is commonly used and well-understood ("bleak" humor is a soundalike alternative). It isn't always about cruelty, but it deals with grotesque, obscene, taboo or otherwise usually unfunny subjects. The most well-known subgenre of this type of humor is "gallows humor," which is specifically about death. Physical comedy involving pain, cruelty and violence, but as played for lighthearted uncomplicated laughs, is called slapstick. In contrast to black humor, however, slapstick is usually cartoonishly unreal, and completely consequence free. If you combine the two, you end up with what is variously called a bleak, black, or tragic farce. Death at at Funeral, The Ladykillers, Heathers, Accidental Death of an Anarchist, Movie 43, and Tropic Thunder are a few examples that come readily to mind, or, for something more reminiscent of Tarantino, Once Upon a Time in Mexico.
[ "stackoverflow", "0001711483.txt" ]
Q: Python web hosting: Why are server restarts necessary? We currently run a small shared hosting service for a couple of hundred small PHP sites on our servers. We'd like to offer Python support too, but from our initial research at least, a server restart seems to be required after each source code change. Is this really the case? If so, we're just not going to be able to offer Python hosting support. Giving our clients the ability to upload files is easy, but we can't have them restart the (shared) server process! PHP is easy -- you upload a new version of a file, the new version is run. I've a lot of respect for the Python language and community, so find it hard to believe that it really requires such a crazy process to update a site's code. Please tell me I'm wrong! :-) A: Python is a compiled language; the compiled byte code is cached by the Python process for later use, to improve performance. PHP, by default, is interpreted. It's a tradeoff between usability and speed. If you're using a standard WSGI module, such as Apache's mod_wsgi, then you don't have to restart the server -- just touch the .wsgi file and the code will be reloaded. If you're using some weird server which doesn't support WSGI, you're sort of on your own usability-wise. A: Depends on how you deploy the Python application. If it is as a pure Python CGI script, no restarts are necessary (not advised at all though, because it will be super slow). If you are using modwsgi in Apache, there are valid ways of reloading the source. modpython apparently has some support and accompanying issues for module reloading. There are ways other than Apache to host Python application, including the CherryPy server, Paste Server, Zope, Twisted, and Tornado. However, unless you have a specific reason not to use it (an since you are coming from presumably an Apache/PHP shop), I would highly recommed mod_wsgi on Apache. I know that Django recommends modwsgi on Apache and most of the other major Python frameworks will work on modwsgi. A: Is this really the case? It Depends. Code reloading is highly specific to the hosting solution. Most servers provide some way to automatically reload the WSGI script itself, but there's no standardisation; indeed, the question of how a WSGI Application object is connected to a web server at all differs widely across varying hosting environments. (You can just about make a single script file that works as deployment glue for CGI, mod_wsgi, passenger and ISAPI_WSGI, but it's not wholly trivial.) What Python really struggles with, though, is module reloading. Which is problematic for WSGI applications because any non-trivial webapp will be encapsulating its functionality into modules and packages rather than simple standalone scripts. It turns out reloading modules is quite tricky, because if you reload() them one by one they can easily end up with bad references to old versions. Ideally the way forward would be to reload the whole Python interpreter when any file is updated, but in practice it seems some C extensions seem not to like this so it isn't generally done. There are workarounds to reload a group of modules at once which can reliably update an application when one of its modules is touched. I use a deployment module that does this (which I haven't got around to publishing, but can chuck you a copy if you're interested) and it works great for my own webapps. But you do need a little discipline to make sure you don't accidentally start leaving references to your old modules' objects in other modules you aren't reloading; if you're talking loads of sites written by third parties whose code may be leaky, this might not be ideal. In that case you might want to look at something like running mod_wsgi in daemon mode with an application group for each party and process-level reloading, and touch the WSGI script file when you've updated any of the modules. You're right to complain; this (and many other WSGI deployment issues) could do with some standardisation help.
[ "stackoverflow", "0013900441.txt" ]
Q: C# - Read .txt file into TextBox I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help? private void button_LoadSource_Click(object sender, EventArgs e) { Stream myStream = null; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { // Insert code to read the stream here. } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } A: if you just need the complete text, you should use the function File.ReadAllText - pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName). to load for example the content into a textbox, you can write: textbox1.Text = File.ReadAllText(openFileDialog1.FileName); opening and using streams is a little bit more complicated, for that you should look up the using - statement
[ "stackoverflow", "0017799110.txt" ]
Q: How to compare two date values using SQL How to compare two dates the first column table one 2013-04-04 05:47:52.000 the second one from other table 2010-01-01 00:00:00.000. I want to compare just yy/month/day; if they are equal, I get second id table. A: For Sql Server you can do this: CAST(table1date AS DATE) = CAST(table2date AS DATE) Example of how it could be used: declare @dateTime1 as datetime = '2013-04-04 05:47:52.000' declare @dateTime2 as datetime = '2013-04-04 00:00:00.000' if CAST(@dateTime1 AS DATE) = CAST(@dateTime2 AS DATE) print 'yy mm dd is the same' else print 'not the same' Or using tables: declare @dateTime1 as datetime = '2013-04-04 05:47:52.000' declare @dateTime2 as datetime = '2011-04-04 00:00:00.000' declare @table1 table (id1 int, dt1 datetime) declare @table2 table (id2 int, dt2 datetime, table1id int) insert into @table1 values (1, @dateTime1) insert into @table2 values (2, @dateTime2, 1) select case when CAST(@dateTime1 AS DATE) = CAST(@dateTime2 AS DATE) then t2.id2 else t2.table1id end as id from @table1 t1 join @table2 t2 on t1.id1 = t2.table1id A: IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE) A: By compare you mean to find the difference? How about DATEDIFF(datepart,startdate,enddate) http://www.w3schools.com/sql/func_datediff.asp
[ "stackoverflow", "0056751796.txt" ]
Q: strange behavior of unsigned long long int in loop While was solving this problem on hackerrank, I noticed a strange thing in the for loop. First, let me show an example code: #include <bits/stdc++.h> using namespace std; #define modVal 1000000007; int main() { for(long long int i=2;i>=0;--i){ cout<<"here: "<<i<<endl; } } input: 123 output: here: 2 here: 1 here: 0 164 Now, when I change long long int to unsigned long long int in for loop for the initialization of variable i. The variable i gets initialized with 18446744073709551615. Why is this happening? A: When the variable is unsigned, i >= 0 is always true. So your loop never ends. When i gets to 0, the next -- makes i 0xFFFFFFFFFFFFFFFF (decimal 18446744073709551615). A: Because unsigned types can't be negative, attempting to set them to a negative value will make them wrap around and instead hold std::numeric_limits<T>::max() - abs(value) + 1 where T is the type and value the value below 0. In your loop once i reaches 0 the condition i >= 0 is still met and thus it would get decremented to -1 but that is impossible for unsigned types as explained above and thus the loop will never exit. A: The unsigned numbers as the name suggests don't take signed values. So when i = -1 it is actually 0xFFFFFFFFFFFFFFFF(18446744073709551615 in decimal). You can see that yourself with the modified program. #include <bits/stdc++.h> using namespace std; #define modVal 1000000007; int main() { for(unsigned long long int i=2;i>=0;--i){ cout<<"here: "<<i<<endl; if(i > 3) return 0; } }
[ "stackoverflow", "0041005125.txt" ]
Q: How to translate SQL queries to cypher in the optimal way? I am new in neo4j using version 3.0. I have a huge transactional dataset that I converted to a graph model. I need to translate the below SQL query into cypher. create table calc_base as select a.ticket_id ticket_id, b.product_id, b.product_desc, a.promotion_flag promo_flag, sum(quantity) sum_units, sum(sales) sum_sales from fact a inner join dimproduct b on a.product_id = b.product_id where store_id in (select store_id from dimstore) and b.product_id in (select product_id from fact group by 1 order by count(distinct ticket_id) desc limit 5000) group by 1,2,3,4; Here is my ER diagram and corresponding graph model . My relationships for this query are: MATCH (a:PRODUCT) MATCH (b:FACT {PRODUCT_ID: a.PRODUCT_ID}) CREATE (b)-[:HAS_PRODUCT]->(a); MATCH (a:STORE) MATCH (b:FACT {STORE_ID: a.STORE_ID}) CREATE (b)-[:HAS_STORE]->(a); My cypher translation for this query is : PROFILE MATCH (b:PRODUCT) MATCH (a:FACT) MATCH (c:STORE) CREATE (d:CALC_BASE {TICKET_ID: a.TICKET_ID, PRODUCT_ID: a.PRODUCT_ID, PRODUCT_DESC: b.PRODUCT_DESC, PROMO_FLAG: a.PROMOTION_FLAG, KPI_UNITS: SUM(a.QUANTITY_ABS), KPI_SALES: SUM(a.SALES_ABS) }) Q = (MATCH (e:FACT) WITH count(PRODUCT_ID) AS PRO_ID_NUM , COUNT(DISTINCT TICKET_ID) AS TICKET_ID_NUM ORDER BY TICKET_ID_NUM DESC) WHERE b.PRODUCT_ID = Q ORDER BY TICKET_ID, PRODUCT_ID, PRODUCT_DESC, PROMO_FLAG My main problem is defining group by and sub queries in cypher. How can I write this query into cypher in an optimal way? A: For one, there is no GROUP BY in Cypher, as the grouping columns are implicitly the non-aggregation columns in each row. I'm assuming you have constraints and indexes set up? You'll need these set up correctly for performant queries. A major red flag I'm seeing is that there are no relationships at all in these queries and likely in your entire data model. Graph databases are made to model relationships between things, and these tend to replace the concept of foreign keys in relational dbs. I'll speak more on better ways to model your data at the end. That said, I'll take a stab at translating this with your current data model. My approach is to go from the inside out. First let's get collections for allowed store_id and b.product_id values. // first collect allowed STORE_IDs MATCH (s:STORE) WITH COLLECT(s.STORE_ID) as STORE_IDs MATCH (e:FACT) // now get PRODUCT_IDs with the most associated TICKET_IDs WITH STORE_IDs, e.PRODUCT_ID, COUNT(DISTICT e.TICKET_ID) as TICKET_ID_CNT ORDER BY TICKET_ID_CNT DESC LIMIT 5000 WITH STORE_IDs, COLLECT(e.PRODUCT_ID) as PRODUCT_IDs // we now have 1 row with both collections, and will do membership checking with them later // next get only PRODUCT nodes with PRODUCT_ID in the collection of allowed PRODUCT_IDs MATCH (b:PRODUCT) WHERE b.PRODUCT_ID in PRODUCT_IDs WITH b, STORE_IDs // now get FACT nodes with STORE_ID in the collection of allowed STORE_IDs // and associated with PRODUCT nodes by PRODUCT_ID MATCH (a:FACT) WHERE a.STORE_ID in STORE_IDs AND a.PRODUCT_ID = b.PRODUCT_ID WITH a, b // grouping is implicit, the non-aggregation columns are the grouping key WITH a.TICKET_ID as TICKET_ID, b.PRODUCT_ID as PRODUCT_ID, b.PRODUCT_DESC as PRODUCT_DESC, a.PROMOTION_FLAG as PROMOTION_FLAG, SUM(a.QUANTITY) as SUM_UNITS, SUM(a.SALES) as SUM_SALES CREATE (:CALC_BASE {TICKET_ID:TICKET_ID, PRODUCT_ID:PRODUCT_ID, PRODUCT_DESC:PRODUCT_DESC, PROMO_FLAG:PROMOTION_FLAG, SUM_UNITS:SUM_UNITS, SUM_SALES:SUM_SALES}) That should get you what you want. And now back to the major problem with all this...you're using a graph db for non-graph data and queries. You're using foreign keys and attempting to join nodes rather than modeling these as relationships. You're also using abbreviated names, which makes it hard to figure out the meaning of your data and how it's supposed to relate to each other. My advice to you is to rethink your data model, especially on how your data connects together. Look for where you're using foreign key joining, and instead think about how to replace that with relationships between your nodes, complete with the nature of those relationships. Data modeled in a more graph-oriented way with relationships lends itself to more graph-oriented and performant queries, as well as a data model that is easier to understand and communicate to others. EDIT Now that you have relationships between different types of nodes, we can simplify the query a bit. The approach will be similar, we will still go from the inside out rather than some inner subquery (though with Neo4j 3.1, pattern comprehension can be used like an inner query in various cases). // first get products with the most tickets (top 5k) MATCH (f:FACT) WITH f.PRODUCT_ID as productID, COUNT(DISTICT f.TICKET_ID) as ticketIDCnt ORDER BY ticketIDCnt DESC LIMIT 5000 MATCH (p:PRODUCT) WHERE p.PRODUCT_ID = productID WITH p // with those products, get related facts (graph equivalent of a join) MATCH (p)<-[:HAS_PRODUCT]-(f:FACT) // ensure the fact has a related store. // if ALL facts have a related store, you don't need this WHERE clause WHERE (f)-[:HAS_STORE]->(:STORE) WITH f.TICKET_ID as TICKET_ID, p.PRODUCT_ID as PRODUCT_ID, p.PRODUCT_DESC as PRODUCT_DESC, f.PROMOTION_FLAG as PROMOTION_FLAG, SUM(f.QUANTITY) as SUM_UNITS, SUM(f.SALES) as SUM_SALES CREATE (:CALC_BASE {TICKET_ID:TICKET_ID, PRODUCT_ID:PRODUCT_ID, PRODUCT_DESC:PRODUCT_DESC, PROMO_FLAG:PROMOTION_FLAG, SUM_UNITS:SUM_UNITS, SUM_SALES:SUM_SALES}) Again, you'll want to make sure there are indexes and unique constraints where appropriate in your data model to speed up your matches. There are still several areas where you might want to think about modifying your data model (where it makes sense, of course). There is a concept of ticket IDs, but no :Ticket nodes. You have created :CALC_BASE nodes, but have not related them to to :Products or tickets. In general, it's useful to see where you're still using the concept of foreign keys, and seeing if it would be better to model these as relationships to other nodes. And again on GROUP BY, this is handled for you in Cypher. Your rows are made up of non-aggregation columns, and aggregation columns. The non-aggregation columns are automatically used by Cypher as the grouping key (the equivalent of grouping by those columns). Since SUM_UNITS and SUM_SALES are the result of SUM() operations, which are aggregation functions, all the other columns are automatically used as the grouping key.
[ "stackoverflow", "0025259202.txt" ]
Q: hdfs log file is too huge after a lot of read and write operation to the hdfs , (i don't know the exact operation that cause this problem). these two files : dncp_block_verification.log.curr , dncp_block_verification.log.prev are more than 200 000 000 000 byte each. what operation to hdfs may cause these file grow fast? from the internet I know that I could shotdown the hdfs and delete the log,but it is not the good solution. how to avoid this problem? thank you very much A: The block scanner is what is causing the files to grow. Here's a link to an article explaining the behavior: http://aosabook.org/en/hdfs.html (Section 8.3.5). The bug which causes this has been fixed in HDFS 2.6.0
[ "stackoverflow", "0057429226.txt" ]
Q: How to set up multiple email targets for Post-commit notification in VisualSVNServer? I am trying to set up multiple email targets for post-commit email notification. I have tried comma separated emails including quotes and with separate quotes as below. "%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" ^ commit-notification "%1" -r %2 ^ --from "[email protected]" --to "[email protected]","[email protected]" ^ --smtp-server javamail.abcd.com Email notification should be sent to multiple email ids on commit. A: Resolved. Turns out that mailing server I'm using will send emails only to mails with same domain name.
[ "stackoverflow", "0034223811.txt" ]
Q: Permission - android.permission.WRITE_EXTERNAL_STORAGE PlayStore I would like to know, if this 'permission:android.permission.WRITE_EXTERNAL_STORAGE' is written in the manifest, what will be written in the permission details on the play store ? It's when i click on "View Details" under "Permission" on an app page on the google play store. A: In this page they describe in a public question the listing of permisions: https://android.stackexchange.com/questions/71802/help-understanding-whatsapps-permissions and they quote for external storage permision description: Photos/Media/Files modify or delete the contents of your USB storage test access to protected storage
[ "stackoverflow", "0035453076.txt" ]
Q: Swift array: How to add multiple values in an index I'm trying to create a simple data model in Swift. The model is a list, in which it will have items such as name, size, colour and store. struct List{ var list: [String] var name: String var size: String var colour: String var store: String init(var list:[String], name: String, size: String, colour: String, store: String){ self.list = list self.name = name self.size = size self.colour = colour self.store = store list = [name, size, colour, store] } If I were to put list = [name, size, colour, store] at index 0, only name is there. How do I store multiple values for one index such that Index 0: name1, size1, colour1, store1 Index 1: name2, size2, colour2, store2 A: You need to define a model to represent the elements of your list struct Element { let name: String let size: String let colour: String let store: String } Creating the list var list = [Element]() Adding elements let elm = Element(name: "name0", size: "size0", colour: "colour0", store: "store0") list.append(elm) let anotherElm = Element(name: "name1", size: "size1", colour: "colour1", store: "store1") list.append(anotherElm) Extracting an element let firstElm = list[0] // "name0", "size0", "colour0", "store0"
[ "stackoverflow", "0036180297.txt" ]
Q: Javascript - Making Array Index toLowerCase() not working I'm trying to make all array indexes lowercase strings, but it's not working. I looked at other answers on here and tried their solutions like using toString() before adding toLowerCase but it doesn't work, which is weird. I created a jsfiddle of the problem here. JS: $(colorArr).each(function(i, item) // loop thru each of elements in colorArr and make lowercase + trim { if(colorArr[i] !== undefined) // check if colorArr index undefined { colorArr[i].toString().toLowerCase().trim(); // FIX HERE /* TRIED - DIDN'T WORK! colorArr[i].toLowerCase().trim(); */ } }); A: i updated your fiddle https://jsfiddle.net/af91r2cq/6/ colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE your way was really close ;)
[ "stackoverflow", "0038885850.txt" ]
Q: Strange output in Ruby Longest Palindrome substring function I am trying to develop a function which will return the longest palindrome substring of an entered string. I am right now working on breaking up the string so that each subsection could then be analyzed to see if it is a palindromeThe code is as follows: def longest_palindrome(s) place = 0 array = s.chars output = [] while place < s.length output << (array[0]..array[place]).to_a place += 1 end return output end if given string "ababa" I would expect the resulting array to look like this: [["a"],["a","b"],["a","b","a"],["a","b","a","b"],["a","b","a","b","a"]] However, when i return the output array this is what is stored inside: [["a"], ["a", "b"], ["a"], ["a", "b"], ["a"], ["a", "b"]] What about my function is causing this to happen? Edit: Not sure if I should start another topic for this. My code is now as follows: def longest_palindrome(s) array = s.chars start = 0 place = 1 output = [] while start < s.length - 1 while place < s.length output << array[start..place] place += 1 end start += 1 end return output end My logic is that this will start at index 0, then progressively capture one character more of the string until the whole string is complete. Then it will start on index 1 and do the same until it has gotten all possible substrings within the string. However, it only returns: [["a"],["a","b"],["a","b","a"],["a","b","a","b"],["a","b","a","b","a"]] Where is the flaw in my logic? A: You're misusing the range operator to produce ranges like 'a'..'a', which is just 'a'. You have two completely independent array indexing operations, each of which return a single element (character) from the array to be used in a range. You're getting array[0], which is always a, and array[place] which alternates between a and b, and producing the ranges 'a'..'a' and 'a'..'b' over and over, which have nothing to do with the arrays the characters originally came from. You can't build the ranges after extracting the elements from the array and expect the ranges to be produced from the array. The correct sub-array is produced by using the range as the index of the array: array[0..place]. This returns the sub-array from 0 to place, inclusive.
[ "stackoverflow", "0018360914.txt" ]
Q: JSON and Cygwin - how to parse, get fields, etc I'm getting a JSON based output when sending GET requests to an API online, using Cygwin. I know how to manage JSON files over PHP and JS, but in this I wish to keep using Cygwin. Is there any way to "handle" those files, getting fields' value, etc? I know I can "create" something manually with sed, grep, awk and such - but I'm looking, first of all, for something which is "ready-to-use". Example: { "campaign": { "name": "my campaign", "id": 1434, "creatives": [ { "id": 4162, "state": "active" } ], } } A: A great option is to use 'jq'. It is a command line JSON query tool. There is a source tarball available for Linux/Cygwin etc that you can build and use to query JSON directly as well as pipe it into other tools. https://stedolan.github.io/jq/download/
[ "superuser", "0000387504.txt" ]
Q: Unable to connect to Facebook Chat Via Python, using xmpppy library I am trying to write a script in python to connect to facebook chat. I am just not able to. Here is the code: import xmpp FACEBOOK_ID = "[email protected]" PASS = "password" jid=xmpp.protocol.JID(FACEBOOK_ID) C=xmpp.Client(jid.getDomain(),debug=['always']) if not C.connect(("chat.facebook.com",5222)): raise IOError('Can not connect to server.') if not C.auth(jid.getNode(),PASS): raise IOError('Can not auth with server.') C.send(xmpp.protocol.Message("[email protected]","Hello world from script",)) This is the error I get: An error occurred while looking up _xmpp-client._tcp.chat.facebook.com And this is the debugger output here. Which shows that I do get authenticated (Line 136) , but still the message is not sent somehow. I am really stuck at this for days now. A: As @grawity pointed out, you need to get the JIDs which you can get by adding following code to your script. In your code after authenticating with server you can ask the server for the list of contacts. In your code add this, C.sendInitPresence(requestRoster=1) rosterobject = C.getRoster() If you want to just check/print the JIDs, you can do this with following loop. for i in rosterobject.getItems(): print i In roster object you should have contacts aka JIDs, Now use that JID in the next statement, C.send(xmpp.Message("[email protected]","Hello world from script",)) I hope this solves your problem.
[ "stackoverflow", "0014377220.txt" ]
Q: Fonts change while Scrolling a listview with individual item font I have a ListView setup with custom array adapter I want to change the font of each individual list items the getVIew() method code below does change the font but the fonts change as I scroll UP and down public View getView(int position, View convertView, ViewGroup parent){ View v = convertView; //View row = null; if (v == null) { LayoutInflater inflater = Main.this.getLayoutInflater(); v = inflater.inflate(R.layout.genre_list, parent, false); TextView item = (TextView)v.findViewById(R.id.txtListText); switch(position) { case 0: tf = Typeface.createFromAsset(getAssets(),"fonts/font (1).ttf");item.setTypeface(tf); break; case 1: tf = Typeface.createFromAsset(getAssets(),"fonts/font (2).ttf"); item.setTypeface(tf); break; case 2: tf = Typeface.createFromAsset(getAssets(),"fonts/font (3).ttf"); item.setTypeface(tf); break; case 3: tf = Typeface.createFromAsset(getAssets(),"fonts/font (4).ttf"); item.setTypeface(tf); break; case 4: tf = Typeface.createFromAsset(getAssets(),"fonts/font (5).ttf"); item.setTypeface(tf); break; case 5: tf = Typeface.createFromAsset(getAssets(),"fonts/font (6).ttf"); item.setTypeface(tf); break; case 6: tf = Typeface.createFromAsset(getAssets(),"fonts/font (7).ttf"); item.setTypeface(tf); break; case 7: tf = Typeface.createFromAsset(getAssets(),"fonts/font (8).ttf"); item.setTypeface(tf); break; case 8: tf = Typeface.createFromAsset(getAssets(),"fonts/font (9).ttf"); item.setTypeface(tf); break; case 9: tf = Typeface.createFromAsset(getAssets(),"fonts/font (10).ttf"); item.setTypeface(tf); break; default: tf = Typeface.createFromAsset(getAssets(),"fonts/font (10).ttf"); item.setTypeface(tf); } } TextView item = (TextView)v.findViewById(R.id.txtListText); item.setText(Genres[position]); // Declare and define the TextView, "icon." This is where // the icon in each row will appear. return v; } A: String[] typefaceArr = new String[] {"fonts/font (1).ttf", "fonts/font (2).ttf", "fonts/font (3).ttf", "fonts/font (4).ttf", "fonts/font (5).ttf", "fonts/font (6).ttf", "fonts/font (7).ttf", "fonts/font (8).ttf", "fonts/font (9).ttf", "fonts/font (10).ttf", "fonts/font (10).ttf"}; public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; //View row = null; if (v == null) { LayoutInflater inflater = Main.this.getLayoutInflater(); v = inflater.inflate(R.layout.genre_list, parent, false); TextView item = (TextView)v.findViewById(R.id.txtListText); /*switch(position) { case 0: tf = Typeface.createFromAsset(getAssets(),"fonts/font (1).ttf");item.setTypeface(tf); break; case 1: tf = Typeface.createFromAsset(getAssets(),"fonts/font (2).ttf"); item.setTypeface(tf); break; case 2: tf = Typeface.createFromAsset(getAssets(),"fonts/font (3).ttf"); item.setTypeface(tf); break; case 3: tf = Typeface.createFromAsset(getAssets(),"fonts/font (4).ttf"); item.setTypeface(tf); break; case 4: tf = Typeface.createFromAsset(getAssets(),"fonts/font (5).ttf"); item.setTypeface(tf); break; case 5: tf = Typeface.createFromAsset(getAssets(),"fonts/font (6).ttf"); item.setTypeface(tf); break; case 6: tf = Typeface.createFromAsset(getAssets(),"fonts/font (7).ttf"); item.setTypeface(tf); break; case 7: tf = Typeface.createFromAsset(getAssets(),"fonts/font (8).ttf"); item.setTypeface(tf); break; case 8: tf = Typeface.createFromAsset(getAssets(),"fonts/font (9).ttf"); item.setTypeface(tf); break; case 9: tf = Typeface.createFromAsset(getAssets(),"fonts/font (10).ttf"); item.setTypeface(tf); break; default: tf = Typeface.createFromAsset(getAssets(),"fonts/font (10).ttf"); item.setTypeface(tf); }*/ } TextView item = (TextView)v.findViewById(R.id.txtListText); item.setText(Genres[position]); tf = Typeface.createFromAsset(getAssets(),typefaceArr[position]); item.setTypeface(tf); // Declare and define the TextView, "icon." This is where // the icon in each row will appear. return v; }
[ "stackoverflow", "0050031932.txt" ]
Q: Need help on Excel VBA loop code that creates new worksheets using cells in range My code below attempts to create a worksheet for each cell value in Column D and then do work in each worksheet 1 at a time (i.e., paste values and run 2 formulas). It errors out on the selection.copy command and the activesheet.name command. I am looking to create 1 worksheet at a time, run formulas in that worksheet, and repeat instead of adding all of the worksheets at once and then renaming them using the cell values in column D. I apologize in advance for the lengthiness, I'm a VBA beginner and most of this code came from using the record function. Sub Macro2() Dim x As Integer NumRows = Range("D1", Range("D1").End(xlDown)).Rows.Count Range("D1").Select For x = 1 To NumRows Selection.Copy Sheets.Add After:=ActiveSheet ActiveSheet.Select ActiveSheet.Name = Selection.Paste ActiveSheet.Paste Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Sheets("Sheet1").Select Range("H2:H5").Select Application.CutCopyMode = False Selection.Copy Sheets(Selection.Paste).Select Range("A2").Select ActiveSheet.Paste Range("A5").Select Application.CutCopyMode = False Range("B6").Select ActiveCell.FormulaR1C1 = "=BDH(R[-5]C[-1],R[-2]C[-1],R[-4]C[-1],R[-3]C[-1],)" Range("D6").Select ActiveCell.FormulaR1C1 = "=BDH(R[-5]C[-3],R[-1]C[-3],R[-4]C[-3],R[-3]C[-3],)" Range("D6").Select Sheets(Selection.Paste).Select Next End Sub Sheet1 Thanks in advance! A: Whatever that “BDH” in your formula may be, you may try this: Sub Macro2() Dim valuesRng As Range, hRng As Range, cell As Range With Sheet1 Set valuesRng = .Range("D1", .Range("D1").End(xlDown)) Set hRng = .Range("H2:H5") End with For Each cell in valuesRng With Sheets.Add(After:=Sheets(Sheets.Count)) .Name = cell.Value .Range("A1").Value= cell.Value .Range("A2:A5").Value= hRng.Value .Range("B6").FormulaR1C1 = "=BDH(R[-5]C[-1],R[-2]C[-1],R[-4]C[-1],R[-3]C[-1],)" .Range("D6").FormulaR1C1 = "=BDH(R[-5]C[-3],R[-1]C[-3],R[-4]C[-3],R[-3]C[-3],)" End with Next End Sub
[ "sound.stackexchange", "0000027454.txt" ]
Q: Real time low-cut and noise reduction software Is there anyone that's aware of a software that acts a bit like an audio console? I would like to adjust the frequencies of my microphone for ambient noise reduction etc in real time. Thanks, A: Not quite in what you may mean by "real time": such processing requires conversion from analogue to digital and back, which necessarily introduces some latency: you need to read data into some buffer, then it can be processed, and then sent to the output. The buffer needs to be at least one sample. It's still called real time, because you can have just this constant delay, but continuously following signal without interruptions. Obviously, this is just what digital mixing consoles do. These nowadays have similarly versatile EQs, dynamics etc. as those built into all DAWs, but they use dedicated DSP chips rather than the CPU where also the complete operating system has to run on, so they can achieve lower latency at the same processing power. CPU-based processing needs quite big buffers to run stable, when you try getting the latency below something like 5 ms you may get drop-outs. But if you're ok with that, what you need is A good audio interface, with decent drivers for your platform of choice. Few devices have well-working ALSA drivers, so with Linux it's always a bit difficult; on Windows, the professional standard is ASIO, on Mac it's Core audio – almost any interface supports those. A clean OS, that won't start expensive background operations when you need the power to maintain the low-latency audio connection. Here, GNU/Linux with lightwight window managers clearly wins, Windows XP is also quite stable, but provided you don't have too much junk installed (popping up messenger services etc.), newer Windowses and OSX will also do the job, given a sufficiently fast machine. A live-suited DAW. There are plenty. I like Reaper, which is easy to route for such stuff, lightweight, has powerful plugins capabilities, and isn't free but quite close to. Make sure you actually use the right drivers; for instance with Windows sound system drivers you'll never get anything you could call low-latency. Once you have it all running, your opportunities are quite unlimited. Arm some tracks in you DAW, switch on their monitoring, and put in whatever plugins you want.
[ "stackoverflow", "0003693902.txt" ]
Q: What is the best way to play an animation frame by frame? I draw some GIS data dynamically, based on user's control, into CGImageRef. But how to play these frame like an animation efficiently in an UIImageView? After searching and surveying, the way to play an animation in UIImageView is preloading all images you need,and invoking the startanimating method,like this: myImageView.animationimages=[NSArray arrayWithObjects:1uiimage,2uiimage,....,nil]; [myImageView startAnimating]; But the waiting time is too long if i preload all UIImages, because i have more than 400 frames each time. I want to play the animation like a stream,real time stream, how to do that? Deeply appreciating if you could give me any idea or an example. :) A: Use CADisplayLink to get notified on each screen refresh. Change myImageView.image in the callback. (You might have to do something more clever if you want to limit the framerate.)
[ "stackoverflow", "0043596920.txt" ]
Q: Value of type 'SCNVector3' has no member 'length' So I've made a testgame with Scenekit and used the default game template to do it. In my code i set the ball speed to a constant velocity of 1.0 so that there is control over the physical behavior like so: var ballNode: SCNNode! ... ballNode = gameScene.rootNode.childNode(withName: "Ball", recursively: true)! ... ballNode.physicsBody?.velocity.length = 1.0 This worked out perfectly, however, when I created a new game template from xcode with a 'single page application' template, and recreated the exact same code with additional transitions between scenes, I'm not able to access the velocity.length. error given: Value of type 'SCNVector3' has no member 'length' how I want it to be: screenshot how it is: screenshot So what am I missing ? the only difference in code I can think of is the different template I used to create the game. A: Based on your screenshot, it looks like you might have this .swift file copied into your project https://github.com/wesmatlock/MarbleMazer/blob/master/MarbleMaze/GameUtils/SCNVector3%2BExtensions.swift It's the only one I could find where length was a settable var, not a function, and other functions seem to match.
[ "stackoverflow", "0013624772.txt" ]
Q: Ternary operator not working as expected I am using this code for displaying result as even or odd instead of true and false here: Console.WriteLine(" is " + result == true ? "even" : "odd"); Therefore i am using ternary operator , but it is throwing error, some syntax problem is here but i am unable to catching it . Thanks in Advance using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplicationForTesting { delegate int Increment(int val); delegate bool IsEven(int v); class lambdaExpressions { static void Main(string[] args) { Increment Incr = count => count + 1; IsEven isEven = n => n % 2 == 0; Console.WriteLine("Use incr lambda expression:"); int x = -10; while (x <= 0) { Console.Write(x + " "); bool result = isEven(x); Console.WriteLine(" is " + result == true ? "even" : "odd"); x = Incr(x); } A: Look at the error you are getting: Operator '==' cannot be applied to operands of type 'string' and 'bool' That is because of the missing parentheses. It is concatenating string and bool value, which results in a string value, and you can't compare it against a bool. To fix it do: Console.WriteLine(" is " + (result == true ? "even" : "odd")); Further clarification. bool result = true; string strTemp = " is " + result; The above statement is a valid statement and results in a string, is True, so your statement currently looks like: Console.WriteLine(" is True" == true ? "even" : "odd"); The above comparison between a string and bool is invalid, hence you get the error. A: You need parentheses. " is " + (result ? "even" : "odd" ); The ternary operator has a lower precendence then the concententation (see the precendence table at MSDN). Your original code says combine " is " + result and then compare to true. A: Operator + has higher priority than ==. To fix it, simply put parenthesis around the ternary expresion: Console.WriteLine(" is " + (result == true ? "even" : "odd"));
[ "codereview.stackexchange", "0000082984.txt" ]
Q: Multiple Wordpress metaboxes in fewer different functions Is it possible to call multiple metaboxes in Wordpress with less duplicate functions? For instance, these are my current metaboxes (3 of them, one is a checkbox and two others are text input fields): /* * STICKY POSTS * */ function add_sticky_metabox(){ add_meta_box( 'sticky_post_metabox', 'Sticky Post', 'output_sticky_metabox', 'post' ); } add_action('add_meta_boxes', 'add_sticky_metabox'); // Make a post sticky function output_sticky_metabox($post){ /** Grab the current 'my_sticky_post' option value */ $sp = intval(get_option('sticky_post')); /** Check to see if the 'my_sticky_post' option should be disabled or checked for the current Post */ $checked = checked($sp, $post->ID, false); if($sp > 0) : $disabled = (!disabled($sp, $post->ID, false)) ? 'disabled="true"' : ''; else : $disabled = ''; endif; /** Add a nonce field */ wp_nonce_field('sticky_post_metabox', 'sticky_post_metabox_nonce'); /** Add a hidden field to check against in case it is unchecked before save */ $value = ($checked) ? '1' : '0'; echo '<input type="hidden" name="was_checked" value="' . $value . '" />'; /** Output the checkbox and label */ echo '<label for="sticky_post">'; echo '<input type="checkbox" id="sticky_post" name="sticky_post" value="' . $post->ID . '" ' . $checked . $disabled . '>'; echo 'Maak van dit bericht de highlight?</label>'; /** Let the user know which Post is currently sticky */ switch($sp) : case 0: $message = 'Er is momenteel geen highlight.'; break; case $post->ID: $message = 'Dit bericht is de highlight!'; break; default: $message = '<a href="' . get_edit_post_link($sp) . '" title="' . the_title_attribute('before=Bewerk bericht \'&after=\'&echo=0') . '">' . get_the_title($sp) . '</a> is momenteel de highlight'; $message.= '<br />Je moet de highlight status van dat bericht verwijderen voor je deze kan highlighten. Dat is gedaan zodat er geen meerdere highlights kunnen zijn.'; endswitch; echo '<p><em>' . $message .'</em></p>'; } function save_sticky_metabox($post_id){ /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ /** Ensure that a nonce is set */ if(!isset($_POST['sticky_post_metabox_nonce'])) : return; endif; /** Ensure that the nonce is valid */ if(!wp_verify_nonce( $_POST['sticky_post_metabox_nonce'], 'sticky_post_metabox')) : return; endif; /** Ensure that an AUTOSAVE is not taking place */ if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) : return; endif; /** Ensure that the user has permission to update this option */ if(!current_user_can('edit_post', $post_id)) : return; endif; /** * Everything is valid, now the option can be updated */ /** Check to see if the 'my_sticky_post' option was checked */ if(isset($_POST['sticky_post'])) : // It was... update_option('sticky_post', $_POST['sticky_post']); // Update the option else : // It was not... /** Check to see if the option was checked prior to the options being updated */ if(isset($_POST['was_checked'])) : // It was... update_option('sticky_post', 0); // Set the option to '0' endif; endif; } add_action('save_post', 'save_sticky_metabox'); /* * Source * */ function add_source_metabox(){ add_meta_box( 'source_post_metabox', 'Bron', 'output_source_metabox', 'post' ); } add_action('add_meta_boxes', 'add_source_metabox'); function output_source_metabox($post){ wp_nonce_field('source_post_metabox', 'source_post_metabox_nonce'); $post_source = $post->post_source; echo '<label for="source_post">'; echo '<input type="text" id="source_post" name="source_post" value="'.$post_source.'" style="width: 80%;max-width: 720px;">'; echo ' Voer hier de bron van je bericht in.</label>'; echo '<p>Bv. <em>http://tweakers.net/nieuws/101372/ing-belgie-wil-betalingsgedrag-van-klanten-meer-gebruiken-voor-dienstverlening.html</em></p>'; } function save_source_metabox($post_id){ /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ /** Ensure that a nonce is set */ if(!isset($_POST['source_post_metabox_nonce'])) : return; endif; /** Ensure that the nonce is valid */ if(!wp_verify_nonce( $_POST['source_post_metabox_nonce'], 'source_post_metabox')) : return; endif; /** Ensure that an AUTOSAVE is not taking place */ if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) : return; endif; /** Ensure that the user has permission to update this option */ if(!current_user_can('edit_post', $post_id)) : return; endif; // Update and save the field so it can be used in our template if ( isset( $_POST['source_post'] ) ) { $data = sanitize_text_field( $_POST['source_post'] ); update_post_meta( $post_id, 'post_source', $data ); } } add_action('save_post', 'save_source_metabox'); /* * Reviews name field * */ function add_review_metabox(){ add_meta_box( 'review_post_metabox', 'Review', 'output_review_metabox', 'post' ); } add_action('add_meta_boxes', 'add_review_metabox'); function output_review_metabox($post){ wp_nonce_field('review_post_metabox', 'review_post_metabox_nonce'); $post_review = $post->post_review; echo '<label for="review_post">'; echo '<input type="text" id="review_post" name="review_post" value="'.$post_review.'" style="width: 80%;max-width: 720px;">'; echo ' Voer hier de naam van het gereviewde apparaat in, zo kort mogelijk.</label>'; echo '<p>Bv. <em>Lumia 930</em></p>'; } function save_review_metabox($post_id){ /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ /** Ensure that a nonce is set */ if(!isset($_POST['review_post_metabox_nonce'])) : return; endif; /** Ensure that the nonce is valid */ if(!wp_verify_nonce( $_POST['review_post_metabox_nonce'], 'review_post_metabox')) : return; endif; /** Ensure that an AUTOSAVE is not taking place */ if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) : return; endif; /** Ensure that the user has permission to update this option */ if(!current_user_can('edit_post', $post_id)) : return; endif; // Update and save the field so it can be used in our template if ( isset( $_POST['review_post'] ) ) { $data = sanitize_text_field( $_POST['review_post'] ); update_post_meta( $post_id, 'post_review', $data ); } } add_action('save_post', 'save_review_metabox'); As you can see there is a lot of duplication, especially in the save functions. However, I'm not sure that this can be put together, because if you do, won't that affect how things are saved? How would I go about putting less load on the server by running as few functions as possible, but with the same functionality? A: As we've already discussed, you can call all 3 metaboxes from the same add_meta_boxes callback, but you can also use just one save_post callback to validate/update if you wish. Add the metaboxes add_action('add_meta_boxes', 'add_post_metaboxes'); function add_post_metaboxes(){ add_meta_box('sticky_post_metabox', 'Sticky Post', 'output_sticky_metabox', 'post'); add_meta_box('source_post_metabox', 'Bron', 'output_source_metabox', 'post'); add_meta_box('review_post_metabox', 'Review', 'output_review_metabox', 'post'); } Populate the metaboxes For this, to the best of my knowledge, you have to use a separate callback for each matabox. If you were able to pass the name of the option to the funciton, you could then use a switch statement, but as far as I can tell you can't. It's no biggy thoough, it's probably easier to manage this way. Save the metabox data Note in this case that the choice is yours. There is nothing wrong with doing it the way you currently are, but this is anouther option. Your validation is simple enough though, so I'd suggest you don't need to use separate callbacks for each piece of data, but the choice is yours... function save_metabox_data($post_id){ /* * We need to verify this came from our screen and with proper authorization, * because the save_post action can be triggered at other times. */ /** Ensure that a nonce is set */ if( !isset($_POST['review_post_metabox_nonce']) || !isset($_POST['source_post_metabox_nonce']) || !isset($_POST['sticky_post_metabox_nonce']) ) : return; endif; /** Ensure that the nonce is valid */ if( !wp_verify_nonce( $_POST['review_post_metabox_nonce'], 'review_post_metabox') || !wp_verify_nonce( $_POST['source_post_metabox_nonce'], 'source_post_metabox') || !wp_verify_nonce( $_POST['sticky_post_metabox_nonce'], 'sticky_post_metabox') ) : return; endif; /** Ensure that an AUTOSAVE is not taking place */ if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) : return; endif; /** Ensure that the user has permission to update this option */ if(!current_user_can('edit_post', $post_id)) : return; endif; /** * Everything is valid, now the custom data can be updated */ /** Check to see if the 'my_sticky_post' option was checked */ if(isset($_POST['sticky_post'])) : // It was... update_option('sticky_post', $_POST['sticky_post']); // Update the option else : // It was not... /** Check to see if the option was checked prior to the options being updated */ if($_POST['was_checked'] != 0) : // It was... update_option('sticky_post', 0); // Set the option to '0' endif; endif; /** Update and save the field so it can be used in our template */ if ( isset( $_POST['source_post'] ) ) { $data = sanitize_text_field( $_POST['source_post'] ); update_post_meta( $post_id, 'post_source', $data ); } /** Update and save the field so it can be used in our template */ if ( isset( $_POST['review_post'] ) ) { $data = sanitize_text_field( $_POST['review_post'] ); update_post_meta( $post_id, 'post_review', $data ); } } add_action('save_post', 'save_metabox_data');
[ "stackoverflow", "0015413607.txt" ]
Q: WCF SSL connection configurations? I wrote wcf service server and client aplications, both client and server works well with basic http binding. Now I want to change configuration to use SSL for connection. Is there any body that can explain how can I that and give an example about it Thanks a lot A: Here is a really nice article about just that and a nice post on Stack here. The key will be within your Config file. <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicSecure"> <security mode="Transport" /> </binding> </basicHttpBinding> </bindings> <services> <service name="WcfServiceLibrary.Echo.EchoService"> <endpoint address="https://localhost:8888/EchoService/" binding="basicHttpBinding" bindingConfiguration="BasicSecure" contract="WcfServiceLibrary.Echo.IEchoService"> <identity> <certificateReference storeName="My" storeLocation="LocalMachine" x509FindType="FindByThumbprint" findValue="f1b47a5781837112b4848e61de340e4270b8ca06" /> </identity> </endpoint> <host> <baseAddresses> <add baseAddress="http://localhost:8080/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> They thing to note here, is security mode = "Transport" and the CertificateReference. Those will be very, very important. You'll have to ensure your Ports are properly configured for this to work. Keep in mind also wshttpBinding has this encryption enabled by default. Good luck.
[ "math.stackexchange", "0000692228.txt" ]
Q: A problem in a Question paper on Linear Transformation anyone please solve it . Let the linear transformation $T: F^2\to F^3$ be defined by $T(x_1,x_2)=(x_1,x_1+x_2,x_2)$ . Then the nullity of T is 0 1 2 3 Also please mention how it is solved A: Hints: solve the linear system $$\begin{cases}x_1=0\\{}\\x_1+x_2=0\\{}\\x_2=0\end{cases}$$ which is a rather trivial system. It's solution set's dimension is your map's nullity.