text
stringlengths
64
81.1k
meta
dict
Q: How to use Vue components with separated files? (TS/HTML/SCSS) I installed the Vue sample with Vue CLI 3 (with Typescript and Scss) and I changed the HelloWorld.vue to these separated files: But it does not work. I got this error in build. These dependencies were not found: * HelloWorld.html?vue&type=template&id=5a1e3016&scoped=true&lang=html& in ./src/ components/HelloWorld.vue * HelloWorld.scss?vue&type=style&index=0&id=5a1e3016&lang=scss&scoped=true& in . /src/components/HelloWorld.vue To install them, you can run: npm install --save HelloWorld.html?vue&type=templa te&id=5a1e3016&scoped=true&lang=html& HelloWorld.scss?vue&type=style&index=0&id= 5a1e3016&lang=scss&scoped=true& Ivan You said in here this should be possible but does not work for me How to do this? A: Try to add to your source "./...", i.e. src="./HelloWorld.html" src="./HelloWorld.scss"
{ "pile_set_name": "StackExchange" }
Q: How to getting browser current locale preference using javascript? Does anyone know how to obtain the browser culture from Firefox and Google Chrome using javascript? Note: This is an asp.net 3.5 web application. The requirement is to try and set the application's display culture based on the browser culture. I have found very few bits and pieces of information for the other browsers but they do not seem to work. I am able to get it in IE with the following snippet of code: var browserCulture = this.clientInformation.browserLanguage; Any info would be great! A: The following properties exist on the navigator object (which can also be known as clientInformation on IE but there's no reason ever to use that name): language (non-IE, browser install language) browserLanguage (IE, browser install language) userLanguage (IE, user-level OS-wide language setting) systemLanguage (IE, OS installation language) But! You should never use any of these properties! They will be the wrong language in many cases. None of them reflect the language settings the user actually gets to configure in the browser's ‘preferred languages’ UI, and they are difficult-to-impossible for users to change. You will cause big frustration by using any of these values without an additional easy manual way to switch languages. The correct place you should sniff to decide what language to use by default, as configured by the normal browser UI, is the Accept-Language header passed to your server in the HTTP request. This is a ranked list of preferred languages from which you can pick, and it's what ASP.NET uses to guess an automatic client Culture, if you use that. Unfortunately, this property is not available from JavaScript! What you typically do is use your server side to parse the Accept-Language header and choose a single appropriate language to use from it. In ASP.NET you can get a pre-sorted list from HttpRequest.UserLanguages and pick the first that you like. You then spit that language name out into a <script> element to pass the language information to the client side. A: Try this: var l_lang; if (navigator.userLanguage) // Explorer l_lang = navigator.userLanguage; else if (navigator.language) // FF l_lang = navigator.language; else l_lang = "en"; Source: http://forums.digitalpoint.com/showthread.php?t=631706 A: navigator.languages is an array and contains all the selected languages in order. And only works for Chrome and Firefox. It is not the same as navigator.language and by that I mean that navigator.language does not necessarily match navigator.languages[0]. Just to be clear.
{ "pile_set_name": "StackExchange" }
Q: Enums with constructors and using it in switch JAVA I have enum, for example: public enum Type { Type1(10), Type2(25), Type3(110); private final int value; Type(int value) { this.value = value; } public int getValue() { return value; } } And I want to use it enum in switch: switch (indexSector) { case Type.Type2.getValue(): //... break; } but IDE says "Constant expression required". How can I use Enum this type in switch? A: You can use an enum in a switch, but your cases must be the items of the enum themselves, not a method return value. Type x = ... switch (x) { case Type1: ... break; case Type2: ... break; case Type3: ... break; }
{ "pile_set_name": "StackExchange" }
Q: fastboot flashall -w Halts I have a Samsung Nexus S. I have erased recovery and boot pertitions using fastboot erase <partition> and when I do fastboot flashall -w it stops on sending 'boot' (XXXX KB)... What might be wrong? UPDATE: I successfully managed to flashed my NS back to stock ROM. Please refer to my own answer below. Regards, A: NOTE: attempting fastboot flash on ur device may cost you your data. So be careful I figured out that I had an outdated Android SDK. I downloaded the latest one, and did: fastboot flash boot fastboot flash recovery fastboot flash userdata and in a couple of minutes I had the stock ROM up and running.
{ "pile_set_name": "StackExchange" }
Q: iPhone: UITableView not refreshing I have read many topics about UITableViews not refreshing on iPhone, but couldn't find anything matching my situation, so I'm asking for help. In my class, which extends UIViewController, I have a TableView and an 'ElementList' (which is a wrapper for NSMutableArray) used as data source. A separate thread adds a new Element to the array via the 'updateList:' method. When this happens, I want the tableView to be refreshed automatically, but this doesn't happen. By debugging my app, I can see that 'cellForRowAtIndexPath' is never called and I can't figure out why. I tried to add an Observer, which calls the 'reloadTableView' method (it is actually called) but the tableView is not updated. This is my code: #import <UIKit/UIKit.h> @interface ListViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { UITableView *tableView; ElementList *elementList; // Wrapper for NSMutableArray } // Called by someone else, triggers the whole thing -(void)updateList:(Element *)element; // Added out of desperation -(void)reloadTableView; @end @implementation ListViewController -(void)loadView { // Create the TableView tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain]; assert(tableView != nil); tableView.delegate = self; tableView.dataSource = self; [tableView reloadData]; self.view = tableView; // Added out of desperation [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableView) name:@"UpdatedListNotification" object:nil]; } -(void)reloadTableView { // Try anything [tableView reloadData]; [tableView setNeedsLayout]; [tableView setNeedsDisplay]; [tableView reloadData]; [self.view setNeedsLayout]; [self.view setNeedsDisplay]; } // Called by someone else, triggers the whole thing -(void)updateList:(Element *)element { assert(element != nil); [elementList addElement:element]; [element release]; // Notify the observer, which should update its table view [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdatedListNotification" object:self]; } // TableView Delegate protocol - (void)tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)indexPath { Element *selected_element = [elementList getElementAtIndex:indexPath.row]; if (selected_element == nil) { NSLog(@"ERROR: Selected an invalid element"); return; } [table deselectRowAtIndexPath:indexPath animated:YES]; NSLog(@"Selected %@", selected_element.name); } // TableView Data Source protocol - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [elementList count]; } - (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Set the cell label cell.textLabel.text = [[elementList getElementAtIndex:indexPath.row] name]; cell.textLabel.frame = cell.bounds; cell.textLabel.textAlignment = UITextAlignmentLeft; return cell; } @end Any help is greatly appreciated, thank you. A: Notifications are executed in the same thread as the caller. Updating the UI should really be done in the main thread, so you should call -reloadData on the main thread: -(void)updateList:(Element *)element { assert(element != nil); [elementList addElement:element]; [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil]; } Also note that you shouldn't release an object that you don't own. So don't call [element release] in your -updateList method. The release should be called by the caller of the function.
{ "pile_set_name": "StackExchange" }
Q: Difficulties implementing the Hysteresis step of Canny Algorithm in Halide without define_extern func The problem is that when a pixel marked as weak-edge (between the two thresholds) changes to strong-edge (accepted, as described here) it is required to apply the same logic to your connected neighbors recursively (tracking the edges). In an imperative language, when changing from weak to strong edge, a Stack could be used to store the position (x,y). Then, at the end, process the neighbors while the stack is not empty, updating the Stack as needed. But, how to implement anything similar in pure Halide, without define_extern func? I have used this code to hysteresis, but lacks the dynamic recursion and/or stack to do hysteresis on the neighbors when needed, which is what I can't find how to implement: magnitude = input(x, y); // mask receives only 0, 1, or 2. mask(x, y) = select(magnitude > high_threshold, 2/*strong-edge*/, magnitude < low_threshold, 0/*no-edge*/, 1/*weak-edge*/); // when mask(x,y) == 1 checks the neighbors to decide. hysteresis(x, y) = select(mask(x, y) == 0, 0, mask(x, y) == 2, 255, mask(x-1, y-1) == 2 || mask(x, y-1) == 2 || mask(x+1, y-1) == 2 || mask(x-1, y) == 2 || mask(x+1, y) == 2 || mask(x-1, y+1) == 2 || mask(x, y+1) == 2 || mask(x+1, y+1) == 2, 255/*weak-to-strong edge*/, 0); The doubt, is there a way to, with recursion, stack, or anything else, do something like this: if (hysteresis(x, y) above changes from weak to strong edge, do) { hysteresis(x-1, y-1); hysteresis(x, y-1); hysteresis(x+1, y-1); hysteresis(x-1, y); hysteresis(x+1, y); hysteresis(x-1, y+1); hysteresis(x, y+1); hysteresis(x+1, y+1); } A: Short answer: No. There's no way to use non-image data structures (like a stack), and no way to do dynamic recursion. It's not clear that Halide would really add much value here, because that algorithm doesn't seem to be tileable, parallelizable or vectorizable as it is written. You may however be able to re-write the algorithm as one that makes iterative sweeps over the image flipping edges from weak to strong. It can be thought of as a cellular automata on three states (weak, strong, not an edge) run to completion, and we could vectorize/parallelize each pass. See test/correctness/gameoflife.cpp in the Halide repo for an example. I think this way of doing it would have a lousy computational complexity though. You'd be doing work at every pixel, not just at the live edge of pixels that are flipping. You could also run it as a cellular automata that does in-place updates along some wavefront, e.g. do a sweep from top to bottom, bottom to top, left to right, and right to left. You can then vectorize along the wavefront. The schedule would be similar to an IIR (see https://github.com/halide/CVPR2015/blob/master/RecursiveFilter/IirBlur.cpp). That approach would handle a linear edge along any direction, but any fixed numbers of sweeps would miss a spiral moving from weak to strong. But rather than contort your code in these ways, I would just use a different algorithm, or use define_extern.
{ "pile_set_name": "StackExchange" }
Q: Numpy indexing set 1 to max value and zero's to all others I think I've misunderstood something with indexing in numpy. I have a 3D-numpy array of shape (dim_x, dim_y, dim_z) and I want to find the maximum along the third axis (dim_z), and set its value to 1 and all the others to zero. The problem is that I end up with several 1 in the same row, even if values are different. Here is the code : >>> test = np.random.rand(2,3,2) >>> test array([[[ 0.13110146, 0.07138861], [ 0.84444158, 0.35296986], [ 0.97414498, 0.63728852]], [[ 0.61301975, 0.02313646], [ 0.14251848, 0.91090492], [ 0.14217992, 0.41549218]]]) >>> result = np.zeros_like(test) >>> result[:test.shape[0], np.arange(test.shape[1]), np.argmax(test, axis=2)]=1 >>> result array([[[ 1., 0.], [ 1., 1.], [ 1., 1.]], [[ 1., 0.], [ 1., 1.], [ 1., 1.]]]) I was expecting to end with : array([[[ 1., 0.], [ 1., 0.], [ 1., 0.]], [[ 1., 0.], [ 0., 1.], [ 0., 1.]]]) Probably I'm missing something here. From what I've understood, 0:dim_x, np.arange(dim_y) returns dim_x of dim_y tuples and np.argmax(test, axis=dim_z) has the shape (dim_x, dim_y) so if the indexing is of the form [x, y, z] a couple [x, y] is not supposed to appear twice. Could someone explain me where I'm wrong ? Thanks in advance. A: What we are looking for We get the argmax indices along the last axis - idx = np.argmax(test, axis=2) For the given sample data, we have idx : array([[0, 0, 0], [0, 1, 1]]) Now, idx covers the first and second axes, while getting those argmax indices. To assign the corresponding ones in the output, we need to create range arrays for the first two axes covering the lengths along those and aligned according to the shape of idx. Now, idx is a 2D array of shape (m,n), where m = test.shape[0] and n = test.shape[1]. Thus, the range arrays for assignment into first two axes of output must be - X = np.arange(test.shape[0])[:,None] Y = np.arange(test.shape[1]) Notice, the extension of the first range array to 2D is needed to have it aligned against the rows of idx and Y would align against the cols of idx - In [239]: X Out[239]: array([[0], [1]]) In [240]: Y Out[240]: array([0, 1, 2]) Schematically put - idx : Y array ---------> x x x | X array x x x | v The fault in original code Your code was - result[:test.shape[0], np.arange(test.shape[1]), .. This is essentially : result[:, np.arange(test.shape[1]), ... So, you are selecting all elements along the first axis, instead of only selecting the corresponding ones that correspond to idx indices. In that process, you were selecting a lot more than required elements for assignment and hence you were seeing many more than required 1s in result array. The correction Thus, the only correction needed was indexing into the first axis with the range array and a working solution would be - result[np.arange(test.shape[0])[:,None], np.arange(test.shape[1]), ... The alternative(s) Alternatively, using the range arrays created earlier with X and Y - result[X,Y,idx] = 1 Another way to get X,Y would be with np.mgrid - m,n = test.shape[:2] X,Y = np.ogrid[:m,:n]
{ "pile_set_name": "StackExchange" }
Q: Decouple the class that retrieves data from the parser and from the view updater I want to create a class that handles Flash-PHP client-server communication. Basically, Flash sends (eg after clicking a button in my UI) a variable to PHP and PHP in turn sends a value to Flash. The class could be similar to the following: package { import flash.net.URLLoader; import flash.net.URLVariables; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.events.Event; import flash.events.IOErrorEvent; // public class CSManager extends MovieClip { // var scriptLoader:URLLoader; // public function CSManager() { scriptLoader = new URLLoader(); scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful); scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError); } //; public function handleLoadSuccessful($evt:Event):void { trace("Message sent."); } // public function handleLoadError($evt:IOErrorEvent):void { trace("Message failed."); } // public function sendLoad(variable):void { var scriptRequest:URLRequest = new URLRequest("http://mydomain/myapp/my.php"); var scriptVars:URLVariables = new URLVariables(); scriptVars.var1 = variable; scriptRequest.method = URLRequestMethod.POST; scriptRequest.data = scriptVars; scriptLoader.load(scriptRequest); } } } So, I imagine that in the body of the method called by the button I instantiate this class and call the CSManager sendLoad method. As you can see, sendLoad sends data to the server and two methods handle the result. When data is received the app should parse the result and update a view but I want to leave this class decoupled from the parser and from the class that updates the view, and use it only to retrieve data from the server. This specifically means I don't want to parse the data and update the view from inside the body of the handleLoadSuccessful method but I want to find a different solution. Which could be a good approach to solve this problem? Edit: I found a better piece of code, but it seems the problem here is the same. A: Dispatch an event. This is one effective technique to decouple your code. Your class extends MovieClip, and MovieClip extends Sprite which extends InteractiveObject which extends EventDispatcher. This means that your object is an EventDispatcher and thus can dispatch an event thusly: dispatchEvent(new Event(MYEVENT)); In the code that is using this class, you would listen to the event like this: var csManager:CSManager=new CSManager(); csManager.addEventListener(MYEVENT,myHandler); also you'd need the constant string const MYEVENT:String ="MYEVENT"; defined somewhere sensible (like as static class property of the CSManager) Just to clarify, I am not suggesting you call your event MYEVENT, you can change that to something more meaningful like STRAWBERRIES_AND_CREAM or whatever makes sense in your specific context.
{ "pile_set_name": "StackExchange" }
Q: Is there an analog of ArcGIS Desktop's “Results” tab in QGIS? I want to rerun previously started QGIS tools without manually specifying inputs again. ArcGIS "Results" tab save all input parameters so I can double click on it and start tool again without retyping all inputs. How can I do the same using QGIS? A: There is a "History" which allows you to run the last operation you did but without the possibility to change any values. However, if you change the geometry of the input values the results will reflect that change. (e.x. change/add a point to a shapefile and the count will be updated) you can find it under Processing -> History. Just double-click on an entry and you will run the algorithm
{ "pile_set_name": "StackExchange" }
Q: Min $+$ convolution is associative Although the following question was encountered in a Communication Networking textbook, the problem is still one of algebraic and analytic manipulation. Define the (min,+) convolution of two real valued functions (domain is $\mathbb{R}^+$) f,g as $$f*g= \inf_{0 \leq s \leq t}\{ f(s) + g(t-s)\}$$ Interested readers may compare it with the usual definition of convolution. Anyhow, I needed to prove that this convolution was commutative and associative. I was able to prove the commutative part but associative seems to elude me. Here is how far I got: $$f*(g*h) = \inf_{0 \leq s \leq t}\{ f(t-s) + (g*h)(s)\}$$ $$ = \inf_{0 \leq s \leq t}\{ f(t-s) + \inf_{0 \leq u \leq s}\{ g(u) + h(s-u)\}\}$$ $$= \inf_{0 \leq s \leq t}\{ \inf_{0 \leq u \leq s} \{f(t-s) + g(u) + h(s-u)\}\}$$ I couldn't proceed from here. I have also tried expanding $(f*g)*h$ and trying to see if the steps "meet in the middle" but to no avail. I'd appreciate it if someone could give me some insight on how to proceed with this. Additional Info In case of the convolution integral/summation, I used indicator functions to allow me to swap integrals. But here I need to swap two infima, the inner one dependent on the outer one. Is there an indicator function like trick that can be used here? A: The infinum swapping is more straightforward than you think. In general, let $S\subseteq \mathbb{R}$ be non-empty, and $S=\bigcup_{\alpha\in I} S_\alpha$ for some arbitrary index set $I$. We have $S_\alpha \subseteq S$ for all $\alpha$, so $$\inf S \leq \inf S_\alpha\quad \forall\alpha\in I.$$ Further, $$\forall \epsilon>0\quad\exists s\in S\text{ s.t. } \inf S + \epsilon > s,$$ and thence $$\forall \epsilon>0\quad\exists \alpha\in I \text { s.t. } \exists s\in S_\alpha\text{ s.t. } \inf S + \epsilon > s_\alpha \geq \inf S_\alpha.$$ So $$\inf S = \inf\ \{\inf S_\alpha | \alpha\in I\}.$$ Applying this to a function defined on a domain $D\subseteq \mathbb{R}^2$, let $D_u=\{(u,v)\,|\,v\in \mathbb{R},\ (u,v)\in D\}\subseteq D$, and substitute $S=f(D)$ and $S_u=f(D_u)$ above. Then \begin{align*} \inf f(D) &= \inf_{u}\ (\inf f(D_u) )\\ &= \inf_{u}\ \inf_{v\in D_u} f(u,v) \end{align*} In particular, it means that \begin{multline} \inf_{0\leq s\leq t} \inf_{0\leq u\leq s} (f(t-s)+g(u)+h(s-u)) =\\ \inf_{0\leq u \leq s\leq t} (f(t-s)+g(u)+h(s-u)). \end{multline}
{ "pile_set_name": "StackExchange" }
Q: Can very high power laser beams self-focus in vacuum? I first recall reading about such an effect in a SF story entitled "Rails Across the Galaxy" which involved self focusing laser beams. And in a science paper here A: From your link's abstract: We argue that long-range photon-photon attraction induced by the dipole interaction of two electron-positron loops can lead to “vacuum self-focusing” of very intense laser beams. The focusing angle θF is found to increase with the beam intensity I as θF∼I^4∕3; for the laser beams available at present or in the near future, θF≃10^−10 - 10^−7. This is a very small angle, practically non measurable as they say in their conclusion: Our calculation shows that the focussing effect is present even for the plane wave, for which the leading order contribution from the box diagram of Fig. 1(a) vanishes. The magnitude of the expected effect however makes its experimental observation challenging. In particular, in a realistic experimental setup it would have to be distinguished from the non–linear effects caused by the presence of the air. Even in vacuum observing such small focusing will be hard, let alone using it for some purpose, imo.
{ "pile_set_name": "StackExchange" }
Q: Why isn't Election Day a federal holiday in the US? Inspired by this question The United States has low levels of voter turnout as compared to other developed democracies. As seen in the above question, low-income individuals are less likely to vote than their higher-income counterparts. Given that low-income individuals are the most likely to not vote largely because they need to work - often being paid hourly and needing the money more desperately than others, and that low-income individuals are more likely to be Democrats than Republicans, why hasn't a democratic politician spearheaded this effort that could see increased turnout from their base? I understand that perhaps for purely political reasons a Republican wouldn't want to champion this and risk higher turnout in demographics they don't necessarily have support from, but for a Democrat this seems like something that would be easy to make a case for and would enjoy popular support from the nation. What arguments have been posed for and against Election Day being a holiday, and is there a partisan split in the debate (if any)? I realize that some federal holidays generally entail most people having the full day off or at least reduced hours, such as Christmas Day, while others such as Columbus Day go largely unnoticed. I would assume the Election Day holiday would be more like the former than the latter A: In some states, election day is a holiday. The counter argument you are looking for is that the federal government shouldn't dictate how states implement their elections. If the states wish to declare their own civic holidays on election day they are free to do so, without the federal government requiring it and the corresponding loss of productivity from anyone else who doesn't want the holiday. Other states solve the issue differently, for instance Colorado, Oregon, and Washington hold their elections via the postal system. Legislators can argue that the loss of economic activity due to the closing of businesses adversely affect the state, and other avenues of solving the problem of lack of participation are available. Another alternative solution proposed would be to move the current election day to always land on November 11th, which happens to be Veterans Day and is already a federal holiday that is widely observed. This can be done without taking the step of declaring election day itself a holiday around the same time in November when elections are generally held, and a lot of people already have the day off of work so there will be less work hours lost than having a separate holiday. Additionally, the left-leaning Slate published an article pointing out that, even though many people would get the day off, other certain types of establishments that don't generally close for federal holidays still won't benefit because they won't observe the holiday. (Inc.com also published a similar argument.) Restaurants, retail, healthcare, all are businesses that generally get inundated with customers on other federal holidays, causing those industries an undue strain on the same day where their workers would need time off to go to polls also. Still further, the problem of low-income voters not voting may be an XY-problem. Perhaps it's not because they can't get the time off to vote, but rather they don't believe voting would do them any good if they did, making the exercise not worthwhile in their eyes. If their employer closes in deference to a holiday, they may be adversely affected financially against their will. One final observation is that there is more to an election than just the day of voting. The only holiday we're talking about is the day of the actual election, but counting primaries and run-offs there could be more days throughout the year that require voter participation. These elections are arguably more important, since they determine who gets to appear on the ballot. Creating a federal holiday for the election won't encourage people to participate in choosing who is available in the pool of candidates to pick from. A: The reason is simple: There isn't enough support in the US Congress to make Election Day a federal holiday. Democracy Day Democracy Day is the tentative name of a possible federal holiday in the United States, proposed by Democratic Representative John Conyers of Michigan. The bill was referred to the House Committee on Oversight and Government Reform in January 2005 and ultimately had 110 co-sponsors. The bill has since lapsed and would need to be reintroduced before the proposal could be reconsidered. A companion resolution was introduced in the Senate on May 26, 2005 by Democratic Senator Debbie Stabenow of Michigan. It was co-sponsored by Democratic Senators Mary Landrieu of Louisiana and Carl Levin of Michigan. The companion resolution did not leave the Senate Committee on the Judiciary and has now also lapsed. The bill was recently reintroduced on Nov. 12, 2014 by independent Senator Bernie Sanders. It has not been enacted. https://en.wikipedia.org/wiki/Democracy_Day_(United_States) Why the lack of support? Here are several possible reasons: "It would be like trying to pass a constitutional amendment," said Michele Swers, a professor of American government at Georgetown University. The last event to become a federal holiday was Martin Luther King, Jr.’s birthday back in 1986. 1 Aside from congressional hurdles, companies are likely resistant to adding another holiday to their work schedule. "If you’re going to make it a federal holiday, that’s basically forcing companies to give workers additional vacation time, so that’s going to cost them money and productivity,” Swers said." 1 Then there’s the idea of holding Election Day on a weekend, something government officials determined is a costly alternative, according to a study from the United States Government Accountability Office (GAO) assessing the cost of a two-day voting weekend. For security alone, officials estimated the extra cost time overseeing ballots would range from about $100,000 [in one jurisdiction] to as much as $400,000 [in another jurisdiction].1 Another argument against the weekend might be that it conflicts with the Sabbath. If voting is on Friday or Saturday, many Jews may not be able to vote. If voting is on a Sunday, many church-goers may object. Then there are the many businesses that remain open on federal holidays: [Proponents of making Election Day a federal holiday haven't] paid a lot of attention to what actually happens on most federal holidays. Big businesses like banks and the white collar jobs at pharmaceutical companies shut down, and all the employees get a day off with pay. Schools and universities shut down, giving teachers and professors time to vote. But you know what doesn't shut down for federal holidays? Retail. Restaurants. Hospitals. Smaller businesses that can't afford to lose a day of revenue, and if they do, they certainly can't afford to pay people for the time off. What does that mean? If you make election day a federal holiday, you'll have all the people who work in these types of jobs still having to work, being inundated with customers who have the day off and they won't have child care because the schools will be closed. Some businesses may close, but their hourly paid employees will either have to use a PTO day or not get paid. Now, if you just want white collar people to vote, by all means, make it more difficult for blue collar people by removing their child care, and increasing their work hours because companies will take advantage of the holiday to run sales and promotions.2 Then there's data from the US Census, which suggests that an election day holiday would not increase participation for lower-income voters: The question of who would benefit from an Election Day holiday is further complicated by looking more closely at the Census Bureau’s data on nonvoters. In 2014, registered voters from households making more than $150,000 a year were the most likely to say they were too busy to head to the polls — more than 35 percent of them claimed so, while none of the income brackets less than $40,000 had more than 25 percent of respondents report they were too busy. Unsurprisingly, lower-income nonvoters are more likely than wealthier nonvoters to cite illness and disability or trouble getting to the polls as problems. Wealthier nonvoters, less impeded by these kinds of challenges, say they have mostly their schedules to blame. Given this, an Election Day holiday would remove a significant barrier to participation for relatively well-to-do potential voters while doing little to make voting easier for a significant number of less privileged ones.3 1 Why Election Day isn’t a federal holiday 2 No, Election Day Should Not Be a Federal Holiday 3 Maybe Making Election Day a National Holiday Wouldn’t Really Work A: You might also look at the kind of jobs that low income people have. Food prep, host(ess), wait staff, or dishwasher. Cashier. Amusement park attendant or movie usher/ticket taker. Farm worker. Personal and home care aides. On a holiday, the first three are more likely to work, as they provide services for people not working. On a normal workday, they might have an evening shift where they could vote during the day easily (or an early morning shift where they could vote afterwards). On a holiday they might have an extra long day shift, since it is extra busy. Farm workers in the United States are mostly non-citizens, so even if they would get the day off, they couldn't vote. Personal and home care aides are often needed every day. So most won't get the day off even if it is a holiday. Most people get off Christmas because it is a major holiday where people simply would refuse to work, not because it is a federal holiday. But even then, there are some restaurants and gas stations open.
{ "pile_set_name": "StackExchange" }
Q: Measurements in quantum mechanics Why does measurement change things? I read that measurement changes things because we have to bounce photons off an object to 'see' it and that changes its position, momentum etc... But on the other hand, Griffiths' QM book seems to suggest we don't know what it is about measurement that changes the state of something. We don't know what's special about measurement, or what exactly constitutes measurement. The photon idea sort of makes sense to me, so if it isn't actually the accepted answer, then why not? If this question is metaphysical/doesn't have a definite answer I apologise, but I thought I'd check in case it does. It's just that the photon thing and Griffiths seem to say different things. A: In quantum mechanics all predictions and descriptions of nature come with a probability distribution . A simple example are the orbitals of the hydrogen atom.. The probability for an electron to be found at (x,y,z,t) can be calculated and the result, is called an orbital, because it is not a classical orbit. To compare a probability distribution with the data one has to get many samples, both for classical and quantum probability distributions. One instance which contributes to the probability distribution is a measurement ( otherwise called in graphic language "collapse of the wavefunction"). For the particular event measured so as to accumulate the probability distribution and check the theoretical model, the wavefunction will have changed due to new boundary conditions. That is what is meant as "measurement changing things". Measuring the photon from an excited energy level of the hydrogen atom, implies a change in the orbital of the electron.
{ "pile_set_name": "StackExchange" }
Q: uniqueness of uniformizers Let R be a noetherian normal domain (if it makes any difference, I'm happy to assume R is also local). If $p$ is a height one prime, then the localization $R_p$ is a dvr, hence the maximal ideal $pR_p$ is principal, generated by a uniformizer $\pi$. It's easy to see we can pick $\pi \in p$. Similarly, if $\pi' \in p$ is another uniformizer then there exist $s,t \in R - p$ such that $t\pi' = s\pi$. Can one do better than this? More precisely, is there a uniformizer $\pi_0 \in p$ such that any other uniformizer $\pi'$ is of the form $\pi' = s\pi_0$ for $s \in R - p$? EDIT: David's answer shows that an affirmative answer to the question above actually implies p itself is principal (which is very strong). So here's a weaker question. Since p is noetherian, it can be generated by finitely many elements $f_1,\ldots,f_r$. Can one arrange so that $ord_p(f_i) < ord_p(f_{i+1})$? The motivation for this question comes from the following standard example. Take $R = k[x,y,z]/(z^2 - xy)$. Take $p = (x,z)$. This is a height one prime ideal. Here $z$ is a uniformizer. Although $p$ is not principal, one needs only one element of order one to generate it. EDIT 2: I would also happily assume that R is moreover complete and an algebra over a field (of say characteristic zero). A: This is the same as asking that $p$ is principal. In one direction, if $p = (\pi)$, then take $\pi$ to be the uniformizer. In the reverse direction, suppose $\pi$ has the stated property. I claim that $p = (\pi)$. Let $f$ be a nonzero element of $p$; we must show that $f$ is a multiple of $\pi$. Since $R$ is a noetherian domain, $\bigcap p^n = (0)$, so there is some $n$ for which $f \in p^n \setminus p^{n+1}$. Thus, $f = \pi_1 \pi_2 \cdots \pi_n$ where each $\pi_i \in p \setminus p^2$, and is thus a uniformizer. By the hypothesis, each $\pi_i$ is of the form $s_i \pi$, so $f = (\prod s_i) \pi^n$. We have shown that $\pi$ divides $f$. A Krull domain has all height one primes principal iff it is a UFD. A normal noetherian domain is Krull. Thus, your condition holds for all height one primes if and only if $R$ is a UFD. Response to the new question: Let $p_k = \{ x \in R : \mathrm{ord}_p(x) \geq k \}$. So $p = p_1$, but note that $p_2$ is probably larger than $p^2$. (In your example, $y \in p_2$ but $y \not \in p^2$.) I claim your new condition is equivalent to saying that $p/p_2$ is a free $R/p$ module. Proof: If $p = \langle f_1, f_2, \ldots, f_r \rangle$ as you propose, then $p/p_2 = \langle f_1 \rangle$. Conversely, if $p/p_2 = (R/p) f$, then lift $f$ to $f_1 \in p$ and $p/(R f_1 + p_2)=0$. Choosing generators for $p_2$, we have your claim. I don't know a general result about when $p/p_2$ is free, but I see three observations: (1) It is not always true. Take $R = k[w,x,y,z]/(wz-xy)$ and $p = \langle w,x \rangle$, so $R/p = k[y,z]$. Then $p_2 = \langle w^2, wx, x^2 \rangle$ and $p/p_2$ is the $k[y,z]$ module on generators $w$ and $x$ subject to the relation $z \cdot w = y \cdot x$, which is not true. (2) It is true in Dedekind domains, since $p_2 = p^2$ and $p/p^2$ is a field. (3) It is true if $R$ is normal and local of dimension $2$, since then $R/p$ is a dvr. This argument was false. I'll modify it to (3') The statement is true if $R$ is normal and $R/p$ is a dvr. Over a dvr, every torsion free finitely generated module is free. The $R/p$ module $p/p_2$ is torsion free, and is rank $1$ since $R$ is regular at $p$.
{ "pile_set_name": "StackExchange" }
Q: Uploading a tvOS application to iTunes Connect fails The news section in iTunes Connect says: You can now create and upload apps for the App Store on Apple TV I've tried and got this error: I've added a new tvOS target to an existing App, which is already available in the App Store. Both targets (iOS, tvOS) are using the same bundle identifier. Does anyone have an idea of what went wrong or has anyone been able to successfully submit a built to iTunes Connect? The error message is not helpful. A: use the "Application Loader.app" of the current Xcode Beta to upload your binary. Works for me.
{ "pile_set_name": "StackExchange" }
Q: Unable to deserialize polymorphic list from xml I deserialize from an xml file using XmlSerializer over classes generated by Xsd2Code from an xsd file with elements extending a base element. Here is a simplified example: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="Vehicle" abstract="true"> <xs:sequence> <xs:element name="Manufacturer" type="xs:string" nillable="false" /> </xs:sequence> </xs:complexType> <xs:complexType name="Car"> <xs:complexContent> <xs:extension base="Vehicle"> <xs:sequence> <xs:element name="Configuration" type="xs:string" nillable="false" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="Truck"> <xs:complexContent> <xs:extension base="Vehicle"> <xs:sequence> <xs:element name="Load" type="xs:int" nillable="false" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:element name="Garage"> <xs:complexType> <xs:sequence> <xs:element name="Vehicles" type="Vehicle" minOccurs="0" maxOccurs="unbounded" nillable="false" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Generated code: public partial class Garage { public Garage() { Vehicles = new List<Vehicle>(); } public List<Vehicle> Vehicles { get; set; } } [System.Xml.Serialization.XmlIncludeAttribute(typeof(Truck))] [System.Xml.Serialization.XmlIncludeAttribute(typeof(Car))] public partial class Vehicle { public string Manufacturer { get; set; } } public partial class Truck : Vehicle { public int Load { get; set; } } public partial class Car : Vehicle { public string Configuration { get; set; } } The XML: <?xml version="1.0" encoding="utf-8" ?> <Garage> <Vehicles> <Vehicle> <Manufacturer>Honda</Manufacturer> <Configuration>Sedan</Configuration> </Vehicle> <Vehicle> <Manufacturer>Volvo</Manufacturer> <Load>40</Load> </Vehicle> </Vehicles> </Garage> And the deserializing code: var serializer = new XmlSerializer(typeof(Garage)); using (var reader = File.OpenText("Settings.xml")) { var garage = (Garage)serializer.Deserialize(reader); var car = garage.Vehicles[0] as Car; Console.WriteLine(car.Configuration); } I get an exception The specified type is abstract: name='Vehicle', namespace='', at <Vehicle xmlns=''>. on the deserializing line. If I remove the abstract attribute from the Vehicle element in XSD I get a null reference exception because garage.Vehicles[0] cannot be cast to Car. I want to be able to deserialize and then cast into Car and Truck. How can I make this work? A: The basic problem is that your XML does not match your XSD. If you try to validate the XML using .Net (sample fiddle) you will see the following errors: The element 'Vehicles' is abstract or its type is abstract. The element 'Vehicles' has invalid child element 'Vehicle'. List of possible elements expected: 'Manufacturer'. These errors have the following meaning: The element 'Vehicles' has invalid child element 'Vehicle'. List of possible elements expected: 'Manufacturer'. The problem here is that your XSD specifies that the <Vehicles> list does not have a container element. Instead, it should just be a repeating set of elements like so: <Garage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Vehicles> <Manufacturer>Honda</Manufacturer> <Configuration>Sedan</Configuration> </Vehicles> <Vehicles> <Manufacturer>Volvo</Manufacturer> <Load>40</Load> </Vehicles> </Garage> For which the corresponding c# class is: public partial class Garage { public Garage() { Vehicles = new List<Vehicle>(); } [XmlElement] public List<Vehicle> Vehicles { get; set; } } To specify an outer wrapper element with inner elements named <Vehicle>, your XSD would have to have an extra intermediate element ArrayOfVehicle: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="Vehicle" abstract="true"> <xs:sequence> <xs:element name="Manufacturer" type="xs:string" nillable="false" /> </xs:sequence> </xs:complexType> <xs:complexType name="Car"> <xs:complexContent> <xs:extension base="Vehicle"> <xs:sequence> <xs:element name="Configuration" type="xs:string" nillable="false" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="Truck"> <xs:complexContent> <xs:extension base="Vehicle"> <xs:sequence> <xs:element name="Load" type="xs:int" nillable="false" /> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <!-- BEGIN CHANGES HERE --> <xs:complexType name="ArrayOfVehicle"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="unbounded" name="Vehicle" nillable="true" type="Vehicle" /> </xs:sequence> </xs:complexType> <xs:element name="Garage"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="Vehicles" type="ArrayOfVehicle" /> </xs:sequence> </xs:complexType> </xs:element> <!-- END CHANGES HERE --> </xs:schema> In your question, you wrote Here is a simplified example. Is there a chance the extra level of nesting in the XSD was manually omitted when writing the question? The element 'Vehicles' is abstract or its type is abstract. You are trying to serialize a polymorphic list by specifying possible subtypes using XmlIncludeAttribute. When doing this, it is necessary for each polymorphic element in the XML to assert its actual type using the w3c standard attribute xsi:type (short for {http://www.w3.org/2001/XMLSchema-instance}type), as is explained in Xsi:type Attribute Binding Support. Only then will XmlSerializer know the correct, concrete type to which to deserialize each element. Thus your final XML should look like: <Garage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Vehicles xsi:type="Car"> <Manufacturer>Honda</Manufacturer> <Configuration>Sedan</Configuration> </Vehicles> <Vehicles xsi:type="Truck"> <Manufacturer>Volvo</Manufacturer> <Load>40</Load> </Vehicles> </Garage> Or, if you prefer to have an outer wrapper element for your vehicle collection: <Garage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Vehicles> <Vehicle xsi:type="Car"> <Manufacturer>Honda</Manufacturer> <Configuration>Sedan</Configuration> </Vehicle> <Vehicle xsi:type="Truck"> <Manufacturer>Volvo</Manufacturer> <Load>40</Load> </Vehicle> </Vehicles> </Garage> The latter XML can be successfully deserialized into your current Garage class without errors, as is shown here. Incidentally, an easy way to debug this sort of problem is to create an instance of your Garage class in memory, populate its vehicle list, and serialize it. Having done so, you would have seen inconsistencies with the XML you were trying to deserialize.
{ "pile_set_name": "StackExchange" }
Q: Is (2R,3S)-2,3-dichloropentane optically inactive? Two confusing thing about (2⁠R,3⁠S)-2,3-dichloropentane: The 2 stereocenters have opposite absolute configuration. But there is no plane of symmetry. So, is (2⁠R,3⁠S)-2,3-dichloropentane optically inactive? (This is actually a follow-up question of: Monochlorination of 2-chloropentane and possible enantiomer products) A: To have an optically inactive meso compound with two chiral centers: 1) the chiral centers must have opposite configuration 2) the chiral centers must have the same set of fragments bonded to them Among other things the 2 carbon has a methyl group bonded to it versus the 3 carbon having an ethyl group instead. You do not satisfy (2), so you do not have the symmetry required for a meso compound, and the molecule is still chiral and optically active.
{ "pile_set_name": "StackExchange" }
Q: javascript security concern (jQuery DataTables) I am building a web application to present data in a DataTable to our team and our customers. When a customer is logged in, I want to hide all data except theirs. Certain rows, certain columns. When the team is logged in, I want all data visible. If I construct one page and hide the content using DataTables columns.visible options depending on who is logged in, would the customer simply be able to open the browser's developer tools and make modifications to the javascript, thereby showing all the hidden data? If this is true, do I need to filter out the data (supplied through json via AJAX) before it leaves my server? A: When a customer is logged in, I want to hide all data except theirs. Certain rows, certain columns. When the team is logged in, I want all data visible. Let's define what you mean by "hide", do you mean: Not visible on their monitor, or Not sent to their machine in page source or response messages. 1) is UI-centric, while 2) is security-centric. Remember that any data you send over HTTPS will be in memory on the user's machine; even if it's not visible in the GUI, there are ways to access it. If you hide the content using DataTables columns.visible, then this accomplishes 1), but not 2) since the data is still being sent, right? If the user opens their browser's dev tools and views the raw HTTP response, all the data will be there. If that data is sensitive - say addresses and phone numbers - then this would count as a vulnerability in the application. do I need to filter out the data before it leaves my server? If the data should not be viewable by the user for security reasons, then simply turning off its visibility is not enough: you can't be transmitting the data at all. So yes, filter it out at the server before sending the response.
{ "pile_set_name": "StackExchange" }
Q: WatchKit app submission I have created an app with WatchKit. I have tried with three different bundle identifier: com.xyz.myappname com.xyz.myappname.extension com.xyz.myappname.extensionapp If I set this and try to validate my app I am getting extension app and WatchKit app bundle identifier does not match. If I keep same bundle identifier for both app then I am getting CFBundle identifier collision. Error as follows CFBundleidentifier collision : There more than bundle with the CFBundleidentifier value com.xyz.myappname.extension under the IOS application myappname.app Please let me know whats going wrong and how to set this to publish on AppStore A: Had the same problem today! Select your main App target, and go to Build Phases. Under "Copy Bundle Resources", I had to remove the "APPNAME Watchkit App.app". After that, I was able to submit my App to the App Store.
{ "pile_set_name": "StackExchange" }
Q: What is the attraction of vertical antennas for HF? I understand that MW broadcast stations use vertical antennas because that polarization works much better for groundwave propagation. But in amateur radio, I would assume the focus for communications on the HF bands would be via ionospheric propagation, where the polarization doesn't matter a great deal. As I contemplate what antenna to install next (after a simple inverted-vee hung out a second story window), I am struck by just how many articles/recommendations and even locals are using vertical antennas for HF communications. The huge drawback to a vertical seems to be the ground plane required: instead of two light quarter-wavelength wires hung in various fashions across a yard/trees/attic, you instead need a sturdy tower for starters and as the icing on the cake, placement of dozens and dozens of fairly long wires all through your yard. If you have room for a proper radial system, wouldn't you also have room for a decent loop or inverted vee? What is the attraction of replacing one of the "poles" of a dipole with dozens of almost-as-long radials instead? A: Cribbing a few quotes from answers to related questions, here's a start. From https://ham.stackexchange.com/a/195/1362: The primary advantages of vertical antennas are that they are omnidirectional, and with an appropriate ground plane (radials) yield a low radiation angle; this reduces the number of "hops" that HF signals must make to reach their destination. This makes a lot of sense: a horizontal dipole will have nulls off its ends, whereas the null of a vertical will point up into space. From https://ham.stackexchange.com/a/494/1362: At the lower end of the HF spectrum, the λ/2 height requirement for horizontal antennas can become cumbersome (even though a horizontal phased array may weaken this requirement by allowing somewhat lower heights). A vertical HF antenna can get away with a height of only λ/4. This is something I keep neglecting to consider: that ideally (at least assuming low-angle radiation is the goal) a horizontal antenna needs to be really really high, i.e. twice as high as a vertical for the same band. And of course the good old-fashioned https://ham.stackexchange.com/a/555/1362: …the coax shield makes just as fine of an antenna as the dipole. It distorts the radiation pattern horribly, but since a dipole wasn't a directional antenna to begin, it hardly matters. It could mean that you get a lot of RF in the shack, but if you are transmitting with 100W this is unlikely to cause any serious problems. i.e. sometimes the results of an "antenna" are actually the results of a long leaky feedline plus a generous amount of transmit power. Unless they are operating as loaded end-feds or something, this is the only explanation I can figure out for how HF verticals like the Comet CHA250B might be working in practice with no radials.
{ "pile_set_name": "StackExchange" }
Q: Calculate Satellite Coordinates From TLE Data I know it is not that hard for those familiar with the equations for it, but I am having trouble with the math. In order to fully understand the orbit elements of TLEs I read this which I found very helpful, but I am struggling with turning that into latitude and longitude coordinates. I am coming into this with no knowledge of the necessary algorithms which is what I am hoping someone can point me to. This post provides some relevant information but if I understand correctly is only explaining how to get the longitude at a specific time while I would like the full coordinates. A: There are a number of software packages, many of them free, that deal with those two line elements. Use one of them. Those two line elements are not Keplerian elements. They are instead Brouwer-Lyddane mean orbital elements. Keplerian elements assume a spherical central body and no forces other than gravitation. The Brouwer-Lyddane mean orbital elements address the first six spherical harmonics and attempt to account for atmospheric drag. The mathematics of Keplerian elements is a bit messy. The mathematics of those two line elements is beyond messy. It's a "math-out". (Think of a blizzard where all you see is whiteness. Blizzards are white-out conditions. The paper describing the two line elements is a math-out. All you see is mathematics.) The mathematics is described in F.R. Hoots, "Reformulation of the Brouwer geopotential theory for improved computational efficiency", Celestial Mechanics 24 (1981). A: you can use PyEphem just like this sudo apt-get install python sudo apt-get install python-dev sudo apt-get install python-pip pip install pyephem create test.py: import ephem import datetime ## [...] name = "ISS (ZARYA)"; line1 = "1 25544U 98067A 12304.22916904 .00016548 00000-0 28330-3 0 5509"; line2 = "2 25544 51.6482 170.5822 0016684 224.8813 236.0409 15.51231918798998"; tle_rec = ephem.readtle(name, line1, line2); tle_rec.compute(); print tle_rec.sublong, tle_rec.sublat; A: Depending on which algorithm/set of equations you are using to convert, you may need to convert the TLE parameters into ECEF coordinates, then convert that into latitude, longitude, and altitude. Here is a page that explains the ECEF-to-LLA conversion: http://www.gmat.unsw.edu.au/snap/gps/clynch_pdfs/coordcvt.pdf A common math difficulty is that the true anomaly and the mean anomaly are related by Kepler's equation, which is a transcendental equation as your first link mentioned. An iterative method like Newton's Method is usually used for this part of the conversion. I can't seem to find a webpage that has the set of algorithms for converting TLE to ECEF, but this page gives the algorithm for converting GPS ephemerides (orbital parameters) into ECEF coordinates: http://web.ics.purdue.edu/~ecalais/teaching/geodesy/EAS_591T_2003_lab_4.htm If I remember correctly the TLE conversion is pretty similar, so that might get you on the right track. If you don't have a textbook with the algorithm, it might be online in a paper or something.
{ "pile_set_name": "StackExchange" }
Q: Loops - Will not start over, just spams out a string So I'm trying to get loops to work with a program (credits to Codeacademy for PygLatin). I've tried with various "break" and other syntax's with no success. What I want the loop to do is to start over, from the input (line 4). As of now I manage to stop the loop with PygLatin = False, but not start over again. As you see on the last line I write PygLatin = True, but that only spams out "Not a string". Any help would be greatly appreciated! pyg = 'ay' print("Welcome to PygLatin!") original = input('Enter a word: ') #Asks user to enter a word PygLatin = True while PygLatin: if len(original) > 0 and original.isalpha(): word = original.lower() first = word[0] if first in ["a","e","i","o","u"]: new_word = word + pyg print(new_word) PygLatin = False else: new_word = word[1:] + word[0] + pyg print(new_word) PygLatin = False else: print('Error: Not a string!') PygLatin = True A: You need to loop over the input, too: while True: original = input(...) PygLatin = True while PygLatin: if len(original) > 0 and original.isalpha(): ... else: print('Error: Not a string!') ui = input("Try again? (y/n): ").lower() if ui not in ("y", "yes"): break This will ask the user each time if they want to loop again.
{ "pile_set_name": "StackExchange" }
Q: Boolean function with specific ОBDD representation I am looking for a class of boolean functions on $n$ variables with the following property: When represented by read twice palindromic ordered bdd (i.e. the order is 1..n n..1) the size of the OBDD is polynomial in $n$ Read once polynomial size OBDD doesn't exist for the boolean function. I did some experiments with the CUDD package to no success. Any ideas how to find an instance of such function? (There is a chance such functions don't exist but I would not bet much money on this). A: Fix $k=\log n$ and define the following function on $n$ bits: take the first $k^2$ bits and view them as $k$ numbers in the range $1..2^k$: $p_1 ... p_k$. Now take the $p_1$'st bit, $p_2$'nd bit ... $p_k$'th bits of the input and view them as a $k$ bit number $p$. The output is the value of the $p$'th bit of the input. A palindromic OBDD of size $exp(k^2)$ can solve it by first reading and remembering $p_1 ... p_k$, then reading these $k$ bits, on the first pass, and remembering $p$ and then reading the $p$'th bit on the 2nd pass. Look at a single pass OBDD and let us restrict the function by dictating that $p_1 ... p_k$ will be equal to the last $k$ indices of the input, and thus $p$ is specified by the last $k$ bits of the input. It is easy to see that $\Omega(n)$ bits need to be remembered about the first $n-k^2-k$ non-restricted bits of the input in order for the value of the $p$'th bit to be recovered (this is the Index function in communication complexity -- see example 4.18 in Communication Complexity book, page 49). This gives a gap $n^{\log n}$ vs. $exp(n)$ -- to get poly vs non-poly just use $N=n^{\log n}$ bits and ignore all but the first $n$. A: I think all pointer functions are hard for OBDDs and easy for a 2-OBDD. Example for such pointer functions are The hidden weighted bit function $HWB_n(x) = x_{sum}$ with $sum = x_1 + \ldots +x_n$ and $x_0 := 0$ The indirect storage access (similar to the function in Noam's answer) $ISA_n$ with $n = 2^k$. Input is $(x,y)$ with $x \in \lbrace 0,1 \rbrace^n$ and $k \in \lbrace 0,1 \rbrace^k$. Let $\vert y \vert$ the integer represented by the binary number $y$. Then the input $y$ gives a part $x_{\vert y \vert},\ldots,x_{\vert y \vert +k-1}$ of the input $x$ (indices are taken mod $n$). Let $a$ be the integer represented by this part. The output of $ISA_n(x,y)$ is $x_a$. It is known that for these function the OBDD size is exponential (see e.g. Branching Programs and Binary Decision Diagrams). But there is a polynomial 2-OBDD for these functions by parsing the address in the first phase and reading the relevant data in the second.
{ "pile_set_name": "StackExchange" }
Q: Objectify GAE/J Google App Engine: Understanding asynchronous load I'm new to Objectify and I don't understand something (a stupid thing). I'm building a Restful Web Service (with restlet) and I'm creating a JSON response. So: Party party; for(Ref<Game> jref : party.games) { JSONObject object = new JSONObject(); try{ Game gAux = jref.get(); //If the value ref is not load, the excetion throws } catch(IllegalStateException e) { //Is asynchronous jref = ObjectifyService.ofy().load().ref(jref); } serializeGame(jref.get(), object); } Ok, the code is very simple, I get a Game object and then I serialize it to JSON object, then I send the response. But I don't understand how the asynchronous load() work. If load().ref(jref) is asynchronous: What does it return? So, if load().ref() returns a empty object o a "future" object: What's happend when I use the object? (I use a null values object?, a "still wating" object)? How do I know the object is ready? (some listener, handler?) to use it? Extra: If there isn't any manner to know when the object is ready, how do I load a ref synchronous? Thanks a lot A: This was answered here: https://groups.google.com/forum/?fromgroups=#!topic/objectify-appengine/8dLAbSWJVB4 The "short answer" is that Ref/Map/List are asynchronous facades that synchronously block when you try to materialize a POJO. Just like Future.
{ "pile_set_name": "StackExchange" }
Q: Docker ASPNET Core container with Python installed I have an application that is running some processes and exposes them through WebAPI. Part of these processes need to execute Python scripts through the IronPython library. For this to happen though, Python 2.7 must also be installed on the system. Has anyone solved this problem by figuring out how to install Python in the ASPNET Core Docker image (or by any other means). The only other hack I can think of it putting the Python executable into a dependency directory for the API. Our current Docker File contents: FROM microsoft/aspnetcore:2.0 ARG source WORKDIR /app EXPOSE 80 COPY ${source:-obj/Docker/publish} . ENTRYPOINT ["dotnet", "Api.dll"] A: You can use the RUN command to install it on the image. Simply add the following to your Dockerfile. The image I pulled from Dockerhub seemed to be running Debian Linux as the base OS so the following should work. If it's another linux distro as the base in your instance, try yum instead or for windows OS chocolatey. FROM microsoft/aspnetcore:2.0 RUN apt-get update -y && apt-get install python2.7 -y ARG source WORKDIR /app EXPOSE 80 COPY ${source:-obj/Docker/publish} . ENTRYPOINT ["dotnet", "AIA.Vietnam.dll"] Now the python executable should be available in /usr/bin/python2.7
{ "pile_set_name": "StackExchange" }
Q: Java new line after 80 char input i'am making a simple text editor in java. In this connection, I am looking for a function that wraps a given string input after a number of characters. For example, wrap after 10 chars on the given input: input: qwertyuiopasdfghjkløæ Output: qwertyuiop\n" asdfghjklø\n" æ\n" Is there a simple way to do this? A: If you want to wrap the lines at word boundaries (whitespace), Apache Commons Lang has the class org.apache.commons.lang3.text.WordUtils, which has the methods: public static String wrap(String str, int wrapLength) public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) * You can download the library from here.
{ "pile_set_name": "StackExchange" }
Q: How to make this .htaccess rule case insensitive? This is a rule in my .htaccess # those CSV files are under the DOCROOT ... so let's hide 'em <FilesMatch "\.CSV$"> Order Allow,Deny Deny from all </FilesMatch> I've noticed however that if there is a file with a lowercase or mixed case extension of CSV, it will be ignored by the rule and displayed. How do I make this case insensitive? I hope it doesn't come down to "\.(?:CSV|csv)$" (which I'm not sure would even work, and doesn't cover all bases) Note: The files are under the docroot, and are uploaded automatically there by a 3rd party service, so I'd prefer to implement a rule my end instead of bothering them. Had I set this site up though, I'd go for above the docroot. Thanks A: This page from the apache docs says that you can do it like this: <FilesMatch \.(?i:csv)$> A: Case insensitive: <FilesMatch "(?i)\.(js|css|eot|ttf)$">
{ "pile_set_name": "StackExchange" }
Q: Disable payment options-only cash on delivery for particular product-magento I am using Magento 1.4.1.1 and i want to disable payment option for some products.i want to show only Cash on Delivery method for some products and need to hide other. Any body there to help me?How can i manage this?Is there any option at admin or do i need to customize the code.If so,could you please provide me a code and the exact path to the files? thanks in advance. A: An unobtrusive way of filtering payment method is to implement observer for event called payment_method_is_active Steps 1> Register the event: ‘payment_method_is_active’ in config.xml. Add the following xml code in app/code/local/MagePsycho/Paymentfilter/etc/config.xml: ... <global> ... <events> <payment_method_is_active> <observers> <paymentfilter_payment_method_is_active> <type>singleton</type> <class>paymentfilter/observer</class> <method>paymentMethodIsActive</method> </paymentfilter_payment_method_is_active> </observers> </payment_method_is_active> </events> ... </global> ... 2> Implement the observer model Create observer file: app/code/local/MagePsycho/Paymentfilter/Model/Observer.php and paste the following code: <?php /** * @category MagePsycho * @package MagePsycho_Paymentfilter * @author [email protected] * @website http://www.magepsycho.com * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ class MagePsycho_Paymentfilter_Model_Observer { public function paymentMethodIsActive(Varien_Event_Observer $observer) { $event = $observer->getEvent(); $method = $event->getMethodInstance(); $result = $event->getResult(); $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode(); if($someTrueConditionGoesHere){ $result->isAvailable = true; }else{ $result->isAvailable = false; } } } A: First create a product attribute (name : 'magepal_payment_filter_by_product', type : yes/no) to identify these products. E.g base of Magento v1.7 you could Auto enable payment module programmatically see https://stackoverflow.com/a/14023210/1191288 Enable all applicable payment module and filter which module to show where In /app/code/local/MagePal/PaymentFilterByProduct/etc/config.xml <?xml version="1.0"?> <config> <modules> <MagePal_PaymentFilterByProduct> <version>1.0.1</version> </MagePal_PaymentFilterByProduct> </modules> <global> <helpers> <paymentfilterbyproduct> <class>MagePal_PaymentFilterByProduct_Helper</class> </paymentfilterbyproduct> <payment> <rewrite> <data>MagePal_PaymentFilterByProduct_Helper_Payment_Data</data> </rewrite> </payment> </helpers> </global> </config> In /app/code/local/MagePal/PaymentFilterByProduct/Helper/Payment/Data.php <?php class MagePal_PaymentFilterByProduct_Helper_Payment_Data extends Mage_Payment_Helper_Data { public function getStoreMethods($store = null, $quote = null) { $methods = parent::getStoreMethods($store, $quote); if(!Mage::getStoreConfig('paymentfilterbyproduct/general_option/paymentfilterbyproduct_enable', Mage::app()->getStore()) || !$quote){ return $methods; } //get a list of product in cart $cart = Mage::getSingleton('checkout/session'); $specialProductInCart = array(); foreach ($cart->getQuote()->getAllItems() as $item) { $specialProductInCart[] = $item->getMagepalPaymentFilterByProduct(); } // if special product in cart // need to if check $item->getMagepalPaymentFilterByProduct() return 'yes/no' or '0/1) if(in_array('yes', $specialProductInCart)){ $filter_csv = Mage::getStoreConfig('paymentfilterbyproduct/filter_option/paymentfilter_special_products', Mage::app()->getStore()); } else{ $filter_csv = Mage::getStoreConfig('paymentfilterbyproduct/filter_option/paymentfilter_all_product', Mage::app()->getStore()); } $filter_array = explode(",", $filter_csv); foreach ($methods as $k => $method){ if(!in_array($method->getCode(), $filter_array)) unset($methods[$k]); }//methods return $methods; } } In /app/code/local/MagePal/PaymentFilterByProduct/etc/system.xml <?xml version="1.0"?> <config> <tabs> <magepal translate="label" module="paymentfilterbyproduct"> <label>MagePal</label> <sort_order>900</sort_order> </magepal> </tabs> <sections> <paymentfilterbyproduct translate="label" module="paymentfilterbyproduct"> <label>Payment Method Filter by Product</label> <tab>magepal</tab> <sort_order>1000</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <groups> <general_option translate="label"> <label>General Options</label> <frontend_type>text</frontend_type> <sort_order>1</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <fields> <paymentfilter_enable translate="label"> <label>Enable Payment Filter</label> <frontend_type>select</frontend_type> <source_model>adminhtml/system_config_source_yesno</source_model> <sort_order>50</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </paymentfilter_enable> </fields> </general_option> <filter_option translate="label"> <label>Payment Method Filter Configuration</label> <frontend_type>text</frontend_type> <sort_order>2</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> <comment>Please enable all applicable payment methods in system payment config</comment> <fields> <paymentfilter_all_products translate="label"> <label>Select Default Payment option for All Products</label> <frontend_type>multiselect</frontend_type> <source_model>MagePal_PaymentFilterByProduct_ActivePaymentMethod</source_model> <sort_order>30</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </paymentfilter_admin> <paymentfilter_special_products translate="label"> <label>Select Payments for Cart with Special Products</label> <frontend_type>multiselect</frontend_type> <source_model>MagePal_PaymentFilterByProduct_ActivePaymentMethod</source_model> <sort_order>40</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </paymentfilter_store> </fields> </filter_option> </groups> </paymentfilterbyproduct> </sections> </config> In /app/code/local/MagePal/PaymentFilterByProduct/Helper/Data.php <?php class MagePal_PaymentFilterByProduct_Helper_Data extends Mage_Core_Block_Template { } In /app/code/local/MagePal/PaymentFilterByProduct/ActivePaymentMethod.php <?php class MagePal_PaymentFilterByProduct_ActivePaymentMethod { //get all active (enable) payment method public function toOptionArray() { $payments = Mage::getSingleton('payment/config')->getActiveMethods(); foreach ($payments as $paymentCode=>$paymentModel) { if($paymentModel->canUseCheckout() == 1){ $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title'); $methods[$paymentCode] = array( 'label' => $paymentTitle, 'value' => $paymentCode, ); } } return $methods; } } In /app/etc/modules/MagePal_PaymentFilterByProduct.xml <?xml version="1.0"?> <config> <modules> <MagePal_PaymentFilterByProduct> <active>true</active> <codePool>local</codePool> </MagePal_PaymentFilterByProduct> </modules> </config>
{ "pile_set_name": "StackExchange" }
Q: Existentially quantified types Could not deduce in the typeclass context {-# LANGUAGE ExistentialQuantification, DeriveDataTypeable #-} import Data.Typeable; data EnumBox = forall s. (Enum s, Show s) => EB s deriving Typeable instance Show EnumBox where show (EB s) = "EB " ++ show s This works. But if I want to add a instance of Class Enum for EnumBox likes: instance Enum EnumBox where succ (EB s) = succ s It fails with the message: Could not deduce (s ~ EnumBox) from the context (Enum s, Show s) bound by a pattern with constructor EB :: forall s. (Enum s, Show s) => s -> EnumBox, in an equation for `succ' at typeclass.hs:11:9-12 `s' is a rigid type variable bound by a pattern with constructor EB :: forall s. (Enum s, Show s) => s -> EnumBox, in an equation for `succ' at typeclass.hs:11:9 In the first argument of `succ', namely `s' In the expression: succ s In an equation for `succ': succ (EB s) = succ s Why the first show can be deduced but the second succ cannot? A: You're only problem is that succ has the type succ :: Enum a => a -> a So you need succ (EB s) = EB . succ $ s Just boxing it up again. Also you'll probably want instance Enum EnumBox where toEnum = EB fromEnum (EB i) = fromEnum i As this is the minimum definition of completeness, since succ = toEnum . succ . fromEnum
{ "pile_set_name": "StackExchange" }
Q: Complement for a minimal normal subgroup in a solvable group Let $G$ be a solvable group, $N$ a minimal normal subgroup of $G$ and suppose that exist $H$ a proper subgroup of $G$ such that $G=NH$. I want to prove that there is a complement of $N$ in $G$. Right now I don't know how to start with this. Any hints? A: Hints: What does '$G$ is solvable' tell you about the structure of a minimal normal subgroup $N$ of $G$? Use this to show $N\cap H$ is normal in $G$.
{ "pile_set_name": "StackExchange" }
Q: when android's isValidFragment() from PreferenceActivity gets called? For some application on which I was working, for devices with API level 19 I'm getting exception Caused by: java.lang.RuntimeException: Subclasses of PreferenceActivity must override isValidFragment(String) to verify that the Fragment class is valid! com... has not checked if fragment com...$. is valid. Then, I found out that for those applications android frameworks protected boolean isValidFragment(String fragmentName) is getting called, which has code if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.KITKAT) { throw new RuntimeException( "Subclasses of PreferenceActivity must override isValidFragment(String)" + " to verify that the Fragment class is valid! " + this.getClass().getName() + " has not checked if fragment " + fragmentName + " is valid."); } else { return true; } Then I tried to replicate the error I took my sample app's code from Preferences Activity Example and added line <uses-sdk android:targetSdkVersion="19" /> in manifest. But strangely, I'm not getting the error(isValidFragment() not getting called in that case). So please tell me how to replicate that error in my sample app. A: The answer to your question is in this post. This is a duplicate question: isValidFragment Android API 19 --Updated-- Here is what the solution is: Basically, whichever Activity is using your fragment "com...$" in the error above, you must update it with the fix below. You should update all the Activities in your project with this fix for any Acitvity that uses a Fragment. The documentation states: protected boolean isValidFragment (String fragmentName) Added in API level 19 Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception. You can fix this error by overriding this method to the Activity/FragmentActivity: @Override protected boolean isValidFragment (String fragmentName) { return [YOUR_FRAGMENT_NAME_HERE].class.getName().equals(fragmentName); } If you are being lazy and just want to test out if this fix works before coding all your fragments into this method, you can simply return true without any checking: @Override protected boolean isValidFragment (String fragmentName) { return true; } I had the same issues when testing on the emulator and this was the solution. A: Seems to be a bug or a 4.4 security restriction. Workaraound is to use anything below 19 that is still compatible with PreferenceActivity, and bite the bullet for compiling with an older target. I am using the headers "pattern" for the PreferenceActivity (overriding public void onBuildHeaders(List<Header> target)), and I assume the OP is too, most likely being the place where stuff happens and crashes. In my case, I have narrowed this exception to <uses-sdk android:targetSdkVersion="19" />, and anything in [14-18] build targets will compile and run without issues. Suggestion (for Eclipse): I never messed directly messed with such stuff, but I'm assuming if you compile your PreferenceActivity (and maybe fragments) on a different project, targeting 18 or under (pun not intended :O ), and then using that project as a library for your main project targeting KitKat (19), perhaps you can avoid the crash scenario at run-time while still using the features you need from the latest build (as long as those features aren't in the build-18-bound PreferenceActivity). If this does not succeed, try with that project in jar form (pre-compiled) instead of using project as library. UPDATE: also take note of Camille Sévigny's answer. If the issue has anything to do with that other question (50% chance IMHO), all apps targeting API 18 are vulnerable to fragment injection attacks (see his linked question). A: Here you go! Slap this in there, and you're good! Collect all the inner classes found in this PreferenceActivity. I chose to put the list in a static field variable: public class whatever extends PreferenceActivity { static final Class<?>[] INNER_CLASSES = whatever.class.getDeclaredClasses(); Then, override the method, ValidFragment, and ensure the fragment about to be displayed is one the 'parent' activity is aware of: /** * Google found a 'security vulnerability' and imposed this hack. * Have to check this fragment was actually conceived by this activity. */ @Override protected boolean isValidFragment(String fragmentName) { Boolean knownFrag = false; for (Class<?> cls : INNER_CLASSES) { if ( cls.getName().equals(fragmentName) ){ knownFrag = true; break; } } return knownFrag; }
{ "pile_set_name": "StackExchange" }
Q: c++ socket receive image and showing without saving I want to receive a image from client. We can show the image at server side when we save it to a JPG file. Like this... char *buff = (char*)malloc(sizeof(char) * (240*360)); FILE *output; output = fopen("test.jpg", "wb"); unsigned int readBytes = 0; while(true) { int ret = recv(sClient, buff+readBytes, (240*360)-readBytes, 0); if (ret <= 0) { break; } readBytes += ret; } fwrite(buff, sizeof(char), readBytes, output); fclose( output ); Mat img_2 = imread( "test.jpg"); But is there any way to get the Mat of received image directly by received char* ?? Thanks! A: "But is there any way to get the Mat of received image directly by received char* ??" yes, there is. instead of saving to disk and reloading, you could use imdecode()
{ "pile_set_name": "StackExchange" }
Q: Running command on server, but have the server read/write local files Is it possible to have a remote machine run a command, but redirect all reads and writes to a local machine. Example: I have a bunch of scripts in folder 'project'. When 'make simulate' is run in 'project' a heavy simulation is run according to some input files and when done, output files are saved in the same folder. All this happens on my laptop, which is limited by battery and isn't as high-end as my desktop. Is there a way to have the simulation run on the desktop (for example via ssh) without going through the hassle of first copying the folder to the desktop, run the simulation there and then copy it all back? All relevant programs must of course be installed on the desktop. A: I think that the easiest solution is to "see" the local file system (or a part of it) on the server. For instance, you can use SSHFS.
{ "pile_set_name": "StackExchange" }
Q: Need help making constructor I need help with my c++ code. I need to make constructor and object for class Posao in this code. But when I make constructor it shows me error. #include<iostream> #include<string> using namespace std; class Radnik { private: string ime; string prezime; int koeficijentSS; bool zaposlen; public: Radnik(string, string, int, bool); string getIme(); string getPrezime(); int getKoeficijent(); bool getStatus(); void promeniIme(string); void promeniPrezime(string); void promeniKoeficijent(int); void promeniStatus(bool); }; class Posao: public Radnik { private: Radnik radnik1; Radnik radnik2; public: void PromeniRadnik1(Radnik); void PromeniRadnik2(Radnik); }; Radnik::Radnik(string a, string b, int c, bool d) { ime = a; prezime = b; koeficijentSS = c; zaposlen = d; } string Radnik::getIme() { return ime; } string Radnik::getPrezime() { return prezime; } int Radnik::getKoeficijent() { return koeficijentSS; } bool Radnik::getStatus() { return zaposlen; } void Radnik::promeniIme(string e) { ime = e; } void Radnik::promeniPrezime(string f) { prezime = f; } void Radnik::promeniKoeficijent(int g) { koeficijentSS = g; } void Radnik::promeniStatus(bool h) { zaposlen = h; } void Posao::PromeniRadnik1(Radnik x) { radnik1.promeniIme(x.getIme()); radnik1.promeniPrezime(x.getPrezime()); radnik1.promeniKoeficijent(x.getKoeficijent()); radnik1.promeniStatus(x.getStatus()); } void Posao::PromeniRadnik2(Radnik y) { radnik2.promeniIme(y.getIme()); radnik2.promeniPrezime(y.getPrezime()); radnik2.promeniKoeficijent(y.getKoeficijent()); radnik2.promeniStatus(y.getStatus()); } int main() { Radnik radnikPrvi("djuro", "djuric", false, 3); Radnik radnikDrugi("momcilo", "sportista", true, 2); Radnik radnikTreci("gavrilo", "burek", false, 1); return 0; } Can you write me how to make constructor with parameters and object for class Posao. I need this for school project. Hope you can find way to fix it. Thanks Thanks in advance, BlackAdder A: As Posao inherits from Radnik, Posao's constructor will call Radnik's constructor. As user4581301 said, Radnik has no default constructor, which is the only constructor the compiler can call for you, so you must call it explicitely using Initializer list. But, do you really want Posao inherit from Radnik? Seems that you want Posao use Radnik, but don't be a Radnik subclass...
{ "pile_set_name": "StackExchange" }
Q: Suitable key for NSDictionary Is there a way to determine if a class is suitable as a key and will work as you expect, for example I want to use NSIndexPath as a key in NSDictionary but I don't know for certain if two different NSIndexPath instances with the same integer values will always return the same hash value. A: Apple's NSObject's isEqual document says: If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass. Look the following code: NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:0 inSection:0]; NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:0 inSection:0]; NSObject *obj1 = [[NSObject alloc] init]; NSObject *obj2 = [[NSObject alloc] init]; NSLog(@"NSIndexPath isEqual's Result: %d", [indexPath1 isEqual:indexPath2]); NSLog(@"NSObject isEqual's Result: %d", [obj1 isEqual:obj2]); Output Result: NSIndexPath isEqual's Result: 1 NSObject isEqual's Result: 0 The implementation of NSObject isEqual is that comare the address of two objects, and hash implementation is that return object's address. NSIndexPath is inherited from NSObject, according to NSIndexPath isEqual output result, NSIndexPath's isEqual implementation should override superclass's isEqual method, and NSIndexPath also override superclass's hash method. In attition, NSIndexPath also conform to the NSCopying protocol. So NSIndexPath can be used as the Key class of NSDictionary. A: How an object behaves as a key depends on how it implements isEqual:. This will determine whether two keys collide. For example, index paths are equal - and therefore will collide - when the paths have the same set of indexes. So two distinct objects describing the same path will be seen by the dictionary as the same key... probably how you'd like it to be.
{ "pile_set_name": "StackExchange" }
Q: High-level Java filesystem content manipulation : old style vs. jcr? what is the best way to choose for managing text/binary content on filesystem? Typically when building web applications with a lot of multimedia binaries and other various text based content stored on filesystem, JDK 6 java.io is still too much low level. It will change with java 7 as you can see here thanks to new java.nio.file.* package But until java 7 is out and implemented by IDEs etc., I really don't know what to use for this, except of org.apache.commons.io. I tried few samples with JackRabbit, but I'm not sure if it is a good idea for the purpose I mentioned at the beginning. Is it possible to manage all that filesystem binary/text content by JackRabbit ? Put it all into nodes and properties instead of directories. Does it bring advantages ? A: It's not really clear what you're looking for, but Google's Guava libraries have an io package, and in particular, a Files class full of static methods for file manipulation. It's not a content repository system, but may provide enough functionality for what you're trying to do.
{ "pile_set_name": "StackExchange" }
Q: Как отследить вызов функции jQuery? Если использовать val(), то on('change') не работает. Я хочу написать функцию, которая вызывается после выполнения val(), в ней проверяется - у какого элемента была вызвана val(). И если это нужный мне элемент, то происходит trigger('change'). Как такое сделать? A: Необязательно придумывать какую-то новую функцию. Достаточно после вызова функции val() дописать .trigger('change') (или просто .change()) - это "даст сигнал" вашему обработчику события change и выполнит код, описанный в нем: $('button').on('click', function() { $('input').val(str_rand()).trigger('change'); }); /* ДЛЯ ДЕМОНСТРАЦИИ */ var changed = 0; $('.input').on('change', function() { // обработчик change changed++; $('.changed').text('Изменено ' + changed + ' раз'); }); function str_rand() { // случайный набор символов var result = ''; var words = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'; var max_position = words.length - 1; for (i = 0; i < 5; ++i) { position = Math.floor(Math.random() * max_position); result = result + words.substring(position, position + 1); } return result; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input" /><br /> <button class="val1">val()</button> <div class="changed"></div> Если же возможности прописать триггер нет (например, если функция .val() вызывается из стороннего скрипта), можно немного переписать функцию .val(): Решение, как оказалось, лежало в этом ответе, но, к сожалению, без пояснений. var oldVal = $.fn.val; // переопределяем функцию .val() $.fn.oldVal = oldVal; // на .oldVal() $.fn.val = function(value) { // и определяем новый функционал .val() if (!value) { // если value пустое return this.oldVal(); // возвращаем текущее value } else { this.oldVal(value).trigger('change'); // задаем value по аналогии со "старой" .val() и вызываем событие change } }; /* ДЛЯ ДЕМОНСТРАЦИИ */ $('button').on('click', function() { $('input').val(str_rand()); }); var changed = 0; $('.input').on('change', function() { // обработчик change changed++; $('.changed').text('Изменено ' + changed + ' раз'); }); function str_rand() { // случайный набор символов var result = ''; var words = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'; var max_position = words.length - 1; for (i = 0; i < 5; ++i) { position = Math.floor(Math.random() * max_position); result = result + words.substring(position, position + 1); } return result; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input" value="val" /> <button class="change">val()</button> <div class="changed"></div> Как вариант, но, наверное, самый неправильный - можно запустить постоянную проверку через setTimeout(). ВАЖНО учитывать, что такой вариант довольно сильно нагрузит браузер, вследствие чего снизится производительность. $('.input').each(function() { var inp = $(this), old = inp.val(); // старое value setInterval(function() { if (inp.val() !== old) { // если новое value не равно старому inp.trigger('change'); // вызываем событие change old = inp.val(); // и переписываем старое value } }, 100); }); /* ДЛЯ ДЕМОНСТРАЦИИ */ $('button').on('click', function() { $('input').val(str_rand()); }); var changed = 0; $('.input').on('change', function() { // обработчик change changed++; $('.changed').text('Изменено ' + changed + ' раз'); }); function str_rand() { // случайный набор символов var result = ''; var words = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'; var max_position = words.length - 1; for (i = 0; i < 5; ++i) { position = Math.floor(Math.random() * max_position); result = result + words.substring(position, position + 1); } return result; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="input" value="val" /> <button class="change">val()</button> <div class="changed"></div>
{ "pile_set_name": "StackExchange" }
Q: Style editText for android I'm running Android 2.3 on my phone and notice a lot of apps using ICS edit Text fields such as square up and tumblr. Do anyone know how they are using to achieve this ? A: You can apply custom style to your edit text. Here's how: - Create a xml file in your drawables folder (edit_text_holo_dark.xml) - Put this xml code inside the file created: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/textfield_default_holo_dark" /> <item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/textfield_disabled_holo_dark" /> <item android:state_enabled="true" android:state_focused="true" android:drawable="@drawable/textfield_activated_holo_dark" /> <item android:state_enabled="true" android:state_activated="true" android:drawable="@drawable/textfield_focused_holo_dark" /> <item android:state_enabled="true" android:drawable="@drawable/textfield_default_holo_dark" /> <item android:state_focused="true" android:drawable="@drawable/textfield_disabled_focused_holo_dark" /> <item android:drawable="@drawable/textfield_disabled_holo_dark" /> </selector> Copy the drawables mentioned in the above xml from platforms folder (platform android-15) to your project's drawable folder. Create a styles.xml file inside your values folder and put this code: <style name="EditTextHoloDark" parent="android:style/Widget.EditText"> <item name="android:background">@drawable/edit_text_holo_dark</item> <item name="android:textColor">#ffffff</item> </style> Finally in your layout file, add style attribute to edittext: style="@style/EditTextHoloDark" A: Please Read this it may help you //Dead Link above is invalid now, you might take a look at this instead
{ "pile_set_name": "StackExchange" }
Q: Using Carbon to return a human readable datetime difference I'm using Laravel 4 to create my project. I am currently building the comments section and I want to display how long ago the post was created, kind of like Facebook's '10 mins ago' & '2 weeks ago' etc. I have done a little bit of research and found that a package called Carbon can do this. After reading the Laravel doc's, it says: By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class. But when I return a date column that I have created, it doesn't display it like on Facebook. The code that I'm using is: return array('time'); Has any body used this Carbon package that could give me a hand in doing what I need, I'm quite confused. A: By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon. So, your code should be just like this: $comment->created_at->diffForHumans(); It's very cool. It'll produce string like 2 minutes ago or 1 day ago. Plurar or singular, seconds, minutes, hours, days, weeks, or years, it runs automatically. I've tested it on Laravel version 4.1.24. A: If you read the Carbon docs to get what you want you call the diffForHumans() method. <?php echo \Carbon\Carbon::createFromTimeStamp(strtotime($comment->created_at))->diffForHumans() ?> A: For any version of Laravel $message->updated_at->diffForHumans();
{ "pile_set_name": "StackExchange" }
Q: Initializing many object member variables in initializer list I've a question regarding best practices in initializing many object members in one class. Background of this question is an embedded project where I'm frequently using references and constructor injection: class ComponentA { public: ComponentA(SomeComponent1& dependency1, SomeComponent2& dependeny2) private: /* ... */ }; Now imagine I've many other Classes like ComponentA and they have to be instantiated in one class: class Layer { private: ComponentA componentA; // Composition /* ...and many other components */ public: Layer(SomeComponent1& firstDepOfA, SomeComponent2& secondDepOfA, ...) : componentA(firstDepOfA, secondDepOfA), /* other components */ }; I was thinking of the builder pattern to reduce the complexity: class Layer { private: ComponentA componentA; // Composition /* ...and many other components */ /* now private */ Layer(SomeComponent1& firstDepOfA, SomeComponent2& secondDepOfA, ...) : componentA(firstDepOfA, secondDepOfA), /* other components */ public: ComponentAIntf& getComponentA ( ... ); class Builder { private: SomeComponent1* firstDepOfA; SomeComponent2* secondDepOfA; /* other dependencies/constructor parameters */ public: /* returns Builder, because we want a fluent api */ Builder& setFirstDepOfA(SomeComponent1* dep) {firstDepOfA = dep; return *this;} Builder& setSecondDepOfA(SomeComponent2* dep) {secondDepOfA = dep; return *this;} Layer& build() { /* check parameters */ ... /* create instance, constructor will be called once when scope is entered */ static Layer layer(/* parameters */); return layer; } } }; A major drawback of the builder class is that the constructor parameters of the member instances are duplicated. I think this can be also achieved with templates, but I haven't found any resources. An example would be nice, but I wanted to avoid using templates. Any help is appreciated. I think I'm missing something... Thanks in advance A: Using the Builder pattern here would be dangerous, because it would be possible for you to call build before all of the dependencies have been set. (One of the reasons to use constructor injection is to prevent the class from being instantiated without explicitly specifying all of its dependencies.) You should inject ComponentA into Layer, rather than let it create its dependency directly. For example: class Layer { private: ComponentA& componentA; // Composition /* ...and many other components */ public: Layer(ComponentA& componentA, ...) : componentA(componentA), /* other components */ }; When using dependency injection, you should ultimately have a composition root where you actually build your object graph. (This is where all of the dependency injection actually occurs.) If you need to instantiate ComponentA on demand, then you can consider delegating the responsibility to a factory: class ComponentFactory { private: SomeComponent1* firstDepOfA; SomeComponent2* secondDepOfA; /* other dependencies/constructor parameters */ public: ComponentFactory(SomeComponent1* firstDepOfA, SomeComponent2* secondDepOfA, ...) : firstDepOfA(firstDepOfA), secondDepOfA(secondDepOfA), ... { } ComponentA CreateComponentA() { return ComponentA(firstDepOfA, secondDepOfA); } ... }; class Layer { private: ComponentFactory& componentFactory; // Composition /* ...and many other components */ public: Layer(ComponentFactory& componentFactory, ...) : componentFactory(componentFactory), /* other components */ void DoSomethingThatUsesComponentA() { ComponentA = componentFactory.CreateComponentA(); ... } };
{ "pile_set_name": "StackExchange" }
Q: Create gray IplImage from gray UIImage I'm a trying to create a gray IplImage from a gray scaled UIImage and Im using the method below. - (IplImage *)createGrayIplImageFromUIImage:(UIImage *)image { CGImageRef imageRef = [image CGImage]; CFDataRef dat = CGDataProviderCopyData(CGImageGetDataProvider(imageRef)); const unsigned char *buffer = CFDataGetBytePtr(dat); IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 1); for (int i=0; i<image.size.width*image.size.height; i++) { iplimage->imageData[i] = buffer[i]; NSLog(@"in creategrayiplimage - %d --- %d",buffer[i], iplimage->imageData[i]); } return iplimage; } When i log the data in for loop, buffer has correct values (0-255) but iplimage->imageData has signed values even its IPL_DEPTH_8U. e.g in creategrayiplimage - 149 --- -107 in creategrayiplimage - 247 --- -9 in creategrayiplimage - 127 --- 127 in creategrayiplimage - 128 --- -128 This seems like a small problem but I am stuck and I wonder why i get minus values from iplimage. Thanks in advance A: A byte is a byte is a byte. The data itself doesn't know whether it's signed or unsigned -- it's all in how you interpret the data. Change your NSLog() statement to use %u (unsigned int) instead of %d (signed int) for the format specifier and your data will be displayed unsigned.
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2012 Windowing function to calculate a running total I need some help with windowing functions. I have been playing around with sql 2012 windowing functions recently. I know that you can calculate the sum within a window and the running total within a window. But i was wondering; is it possible to calculate the previous running total i.e. the running total not including the current row ? I assume you would need to use the ROW or RANGE argument and I know there is a CURRENT ROW option but I would need a CURRENT ROW - I which is invalid syntax. My knowledge of the ROW and RANGE arguments is limited so any help would be gratefully received. I know that there are many solutions to this problem, but I am looking to understand the ROW, RANGE arguments and I assume the problem can be cracked with these. I have included one possible way to calculate the previous running total but I wonder if there is a better way. USE AdventureWorks2012 SELECT s.SalesOrderID , s.SalesOrderDetailID , s.OrderQty , SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID) AS RunningTotal , SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID) - s.OrderQty AS PreviousRunningTotal -- Sudo code - I know this does not work --, SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID -- ORDER BY SalesOrderDetailID -- ROWS BETWEEN UNBOUNDED PRECEDING -- AND CURRENT ROW - 1) -- AS SudoCodePreviousRunningTotal FROM Sales.SalesOrderDetail s WHERE SalesOrderID IN (43670, 43669, 43667, 43663) ORDER BY s.SalesOrderID , s.SalesOrderDetailID , s.OrderQty Thanks in advance A: You could subtract the current row's value: SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID) - s.OrderQty Or according to the syntax at MSDN and ypercube's answer: <window frame preceding> ::= { UNBOUNDED PRECEDING | <unsigned_value_specification> PRECEDING | CURRENT ROW } --> SUM(s.OrderQty) OVER (PARTITION BY SalesOrderID ORDER BY SalesOrderDetailID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
{ "pile_set_name": "StackExchange" }
Q: Android app crashes when switching Fragment after showing a keyboard that is set with nextFocusDown I have an app that was working nicely with multiple fragments that are switching based on a navigation bar interaction. One of the screens has multiple text fields, and I decided to order these fields so the keyboard "next" would automatically take the user to the next fillable text field by using nextFocusDown. The last one leads to RadioGroup which results in the "done" button being shown. The fields look like this (they are within LinearLayout that is within a NestedScrollView within another LinearLayout that is under the root FrameLayout): <EditText android:id="@+id/firstName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName|textCapWords" android:nextFocusDown="@id/lastName" android:text="" /> <EditText android:id="@+id/lastName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPersonName|textCapWords" android:nextFocusDown="@id/email" android:text="" /> <EditText android:id="@+id/email" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:nextFocusDown="@id/localId" android:text="" /> There are many more fields, some include hints for text etc. If I run the app, pick one field, and hit the "next" button until the keyboard disappears on its own - everything works well. The problem appears when I pick a field, the keyboard appears, and I hit the android down button that causes the keyboard to disappear. After doing so, everything within this screen looks good, and everything functions normally, until I switch a fragment, then the app crashes and I see in the logs these errors: 04-10 00:12:24.763 redacted E/AndroidRuntime: FATAL EXCEPTION: main Process: redacted, PID: 24660 java.lang.NullPointerException: Attempt to invoke interface method 'void android.view.inputmethod.InputConnection.closeConnection()' on a null object reference at android.view.inputmethod.InputConnectionWrapper.closeConnection(InputConnectionWrapper.java:270) at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:541) at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 04-10 00:12:24.769 redacted E/UncaughtException: java.lang.NullPointerException: Attempt to invoke interface method 'void android.view.inputmethod.InputConnection.closeConnection()' on a null object reference at android.view.inputmethod.InputConnectionWrapper.closeConnection(InputConnectionWrapper.java:270) at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:541) at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Any idea what's going on and how to avoid it? P.S. Since I am pretty sure it is related to the nextFocusOn and the keyboard, I didn't post more (it's a pretty big file), if you think anything is needed in addition, let me know, and I'll upload the relevant part. A: The thing that solved the issue for me was: Clean the build (Build->Clean Project) Exit Android Studio Restart the android device Start Android Studio (AFTER DEVICE STARTED) Run I have no idea why it solved the issue for me (I mostly write apps for iOS, and I never experienced bugs that require a device restart...). The weird thing is that I restarted the device, Android Studio, and clean the projects many times - so it appears the whole process has to be in that order... A: I faced with that bug today as well. I´m not sure if it will help in your case but it helped me. Based on answers in this topic: Android Studio 3.1 EditText StackOverflowError. In my case it was enough just to disable advanced profiling Run --> Edit Configuration --> Profiling Tab In my case bug happen after changing conductor Controller from one with inputs to another. Error was exactly the same. And same as in related link i updated AS to 3.1.1 today.
{ "pile_set_name": "StackExchange" }
Q: Adding data to database When I try to add a user to the database with POST a new user is added but all fields are Null. Any help guys ? Thank you in advance.This is my source code: if($_SERVER['REQUEST_METHOD'] == "POST") { // Get data $name = isset($_POST['name']) ; $email = isset($_POST['email']); $password = isset($_POST['password']); $status = isset($_POST['status']); // Insert data into data base $sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')"; $qur = mysql_query($sql); if($qur){ $json = array("status" => 1, "msg" => "Done User added!"); }else{ $json = array("status" => 0, "msg" => "Error adding user!"); } }else{ $json = array("status" => 0, "msg" => "Request method not accepted"); } @mysql_close($conn); /* Output header */ header('Content-type: application/json'); echo json_encode($json); ** A: isset return only true or false so if you want to insert value you can check it with if condition replace your code with above it will be work fine if($_SERVER['REQUEST_METHOD'] == "POST"){ $name = (isset($_POST['name']))?$_POST['name']:'' ; $email = (isset($_POST['email']))?$_POST['email']:''; $password = (isset($_POST['password']))?$_POST['password']:''; $status = (isset($_POST['status']))?$_POST['status']:''; $sql = "INSERT INTO users (`name`, `email`, `password`, `status`) VALUES ('$name', '$email', '$password', '$status')"; $qur = mysql_query($sql); if($qur){ $json = array("status" => 1, "msg" => "Done User added!"); }else{ $json = array("status" => 0, "msg" => "Error adding user!"); } }else{ $json = array("status" => 0, "msg" => "Request method not accepted"); } @mysql_close($conn); header('Content-type: application/json'); echo json_encode($json); save this form in html file and check it with this edited example <form method="post"> <input type="text" name="name" value="Red Symbol" /> <input type="text" name="email" value="[email protected]" /> <input type="text" name="password" value="chock" /> <input type="text" name="status" value="1" /> <input type="submit" name="submit" value="Submit" /> </form>
{ "pile_set_name": "StackExchange" }
Q: No toma los cambios al generar archivos de publicación. Angular 8 Tengo un proyecto en angular 8 y C# WebApi el cual publico en un servidor IIS, hasta este punto todo bien, cuando realice la primera publicación no hubo problema pero Al momento de realizar cambios en mi aplicación y volver a generar los archivos, digamos al publicar la Versión 2, no toma los cambios realizados en mí FrontEnd Angular al ingresar a la aplicación, solo lo hace cuando recargo la página con ctrl + Shift + R. Esto es un gran problema para los usuarios que utilizan la aplicación ya que si no recargan seguirán trabajando en la primera versión. Esta es la forma en la que genero los archivos: ng build --prod --output-hashing=all Esta línea me genera los siguientes archivos: Tengo estas líneas de código en el index.html <meta http-equiv="Expires" content="0"> <meta http-equiv="Last-Modified" content="0"> <meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> No sé que pasa pero solo toma la nueva versión solo si se recarga la página de esa forma. Edicion: Este es mi archivo WebConfig: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="Angular Routes" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <!-- <action type="Rewrite" url="./index.html" /> --> <action type="Rewrite" url="/" /> </rule> </rules> </rewrite> <caching> <profiles> <add varybyquerystring="*" location="Any" duration="00:00:01" policy="CacheForTimePeriod"> </profiles> </caching> </system.webServer> </configuration> Me gustaría que limpiara y forzara y la cache al momento de generar los archivos. ¿Existe alguna forma de hacer esto desde código o al generar los archivos ? A: Configura el caching de tu IIS desde el web config de tu aplicación. Esto sobrescribirá cualquier configuración del Output Cache que tengas a nivel de servidor: <configuration> <system.webServer> <staticContent> <clientCache cacheControlMode="DisableCache" /> </staticContent> </system.webServer> </configuration> Puedes filtrar también por extensión para que se cacheen ciertos archivos estáticos.
{ "pile_set_name": "StackExchange" }
Q: jQuery and HTML visual glitches on table cell .toggle I have table that gets dynamically created. When using jQuery and toggle, everything works. I however get a small visual glitch - it seems the HTML sometimes get selected. How would I disable this on a faulty drag or mouse operation? Is there a difference in the DOM between text in a cell and 'not text' or buffered space in a td? A: If you're saying that you want to disable text selection in your table, there are ways to do it using CSS. Although it doesn't work for IE or Opera as far as I know. #myTable { user-select: none; -webkit-user-select: none; -moz-user-select: -moz-none; -khtml-user-select: none; } Other than that, maybe some sort of invisible overlay element in your table cells?
{ "pile_set_name": "StackExchange" }
Q: How to write a function to search for a string within an array This is what I have so far: for(i = 0; i <= 9; i++){ printf("%d", i); found = strpbrk(nameholder[i], searchterm); if(strpbrk(nameholder[i], searchterm) == searchterm){ printf("found\n"); foundwhere = i + 1; break; } }// end for When I run the program, the strpbrk function finds the string, but for some reason it never triggers the if statement. What am I missing? A: If I correctly understood (your description is vague) what you are trying to do, then you seem to be using a wrong function. Quoting cpp docs on strpbrk: Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches. That's not what you want it to do, right? You should be looking at strcpm function. http://www.cplusplus.com/reference/clibrary/cstring/strcmp/ Your code should look like: for(i = 0; i <= 9; i++){ if(strcmp(nameholder[i], searchterm) == 0){ printf("found\n"); foundwhere = i + 1; break; } }// end for
{ "pile_set_name": "StackExchange" }
Q: How to implement SwipeView? I want to swipe each image to switch to another image like gallery app. I am now using this https://github.com/nicklockwood/SwipeView, but I don't know how to implement it. Should I drag a collection view inside my PhotoDetailViewController, or I only use it in coding. May anyone help me with this. Here is my code: import Foundation import UIKit import AAShareBubbles import SwipeView class PhotoDetailViewController: UIViewController, AAShareBubblesDelegate, SwipeViewDataSource, SwipeViewDelegate { @IBOutlet var topView: UIView! @IBOutlet var bottomView: UIView! @IBOutlet var photoImageView: UIImageView! var photoImage = UIImage() var checkTapGestureRecognize = true var swipeView: SwipeView = SwipeView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height)) override func viewDidLoad() { title = "Photo Detail" super.viewDidLoad() photoImageView.image = photoImage swipeView.dataSource = self swipeView.delegate = self let swipe = UISwipeGestureRecognizer(target: self, action: "swipeMethod") swipeView.addGestureRecognizer(swipe) swipeView.addSubview(photoImageView) swipeView.pagingEnabled = false swipeView.wrapEnabled = true } func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! { return photoImageView } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("SwipeCell", forIndexPath: indexPath) as! SwipeViewPhotoCell return cell } @IBAction func onBackClicked(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } @IBAction func onTabGestureRecognize(sender: UITapGestureRecognizer) { print("on tap") if checkTapGestureRecognize == true { bottomView.hidden = true topView.hidden = true self.navigationController?.navigationBarHidden = true let screenSize: CGRect = UIScreen.mainScreen().bounds let screenWidth = screenSize.width let screenHeight = screenSize.height photoImageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) checkTapGestureRecognize = false showAminationOnAdvert() } else if checkTapGestureRecognize == false { bottomView.hidden = false topView.hidden = false self.navigationController?.navigationBarHidden = false checkTapGestureRecognize = true } } func showAminationOnAdvert() { let transitionAnimation = CATransition(); transitionAnimation.type = kCAEmitterBehaviorValueOverLife transitionAnimation.subtype = kCAEmitterBehaviorValueOverLife transitionAnimation.duration = 2.5 transitionAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transitionAnimation.fillMode = kCAFillModeBoth photoImageView.layer.addAnimation(transitionAnimation, forKey: "fadeAnimation") } @IBAction func onShareTouched(sender: AnyObject) { print("share") let myShare = "I am feeling *** today" let shareVC: UIActivityViewController = UIActivityViewController(activityItems: [myShare], applicationActivities: nil) self.presentViewController(shareVC, animated: true, completion: nil) // print("share bubles") // let shareBubles: AAShareBubbles = AAShareBubbles.init(centeredInWindowWithRadius: 100) // shareBubles.delegate = self // shareBubles.bubbleRadius = 40 // shareBubles.sizeToFit() // //shareBubles.showFacebookBubble = true // shareBubles.showTwitterBubble = true // shareBubles.addCustomButtonWithIcon(UIImage(named: "twitter"), backgroundColor: UIColor.whiteColor(), andButtonId: 100) // shareBubles.show() } @IBAction func playAutomaticPhotoImages(sender: AnyObject) { animateImages(0) } func animateImages(no: Int) { var number: Int = no if number == images.count - 1 { number = 0 } let name: String = images[number] self.photoImageView!.alpha = 0.5 self.photoImageView!.image = UIImage(named: name) //code to animate bg with delay 2 and after completion it recursively calling animateImage method UIView.animateWithDuration(2.0, delay: 0.8, options:UIViewAnimationOptions.CurveEaseInOut, animations: {() in self.photoImageView!.alpha = 1.0; }, completion: {(Bool) in number++; self.animateImages(number); print(String(images[number])) }) } } A: Just drag and drop a UIView to your storyboard/XIB, and set its customclass to SwipeView. Also set the delegate and datasource to the view controller which includes the UIView you just dragged. Then in the viewcontroller, implement the required delegate methods similar to how you'd implement the methods for a tableview.
{ "pile_set_name": "StackExchange" }
Q: How to link a website using barcode scanner I have made an app that scans Barcodes/QR. I want to be able to scan the recipt and have it take me to that direct site. EX. I Scan a barcode and i want it to go directly to a survey and pass up all the other website options. Such as a survey for a store, instead of typing in the whole site I would just to go there directly with a scan. A: QRCode has this feature built-in. You just need to make sure the URL you encoded is a complete website URL, i.e., with the prefix http:// or https://. If you encode the content as www.example.org, then the URL will not be opened.
{ "pile_set_name": "StackExchange" }
Q: Node.js cloud hosts with Windows support I've researched many node.js cloud hosts, yet I'm having trouble finding one that suits my needs. The host needs to have free service for as long as an application is in development (sandbox mode). It also needs to have a Windows client, and ease of use is a huge plus. If possible, I'd like the host to be out of beta. Can anyone recommend a simple node.js host that meets my needs? A: Have you checked out Azure hosting? The host needs to have free service for as long as an application is in development (sandbox mode) They're currently offering a 90-day free trial and they've spent some real effort making Node.js work with their platform. It also needs to have a Windows client, and ease of use is a huge plus. They have a socket.io example and an example of using their free Windows-based dev tools to get up and running. If possible, I'd like the host to be out of beta. Node.JS has yet to hit version 1.0. At some level the whole tool chain is beta. However, Windows Azure is paid for and supported. They have people actively working on both Node.JS and some drivers (such as SQL Server support). To me, that's as "non-beta" as you'll get right now.
{ "pile_set_name": "StackExchange" }
Q: Save and Load an ArrayList Under Strings? I'm using PrintWriter to save an ArrayList to a file. I'm using more than one ArrayList. Is it possible to save and load an ArrayList under a string? Let's say I want to use the strings below: Admins - ArrayList here. - ArrayList here. Bans - - IPs - - Above this what I want the file saved to look like. I'm using a scanner to load the ArrayList. Is it possible to load the ArrayList under the strings above? Below is some of the code I'm using to save the ArrayList. public static void save() { String adminsConfigs1 = killAdmins.toString(); try { PrintWriter pw1 = new PrintWriter(new FileOutputStream(FILE)); pw1.write(adminsConfigs1); pw1.close(); } } A: Not an exact solution, but you should get the idea: Your save could look something like: ArrayList<String>killAdmins; //or whatever File saved_items = new File("saved.txt") try { PrintWriter pw1 = new PrintWriter(new FileOutputStream(saved_items)); for(String item_to_save : killAdmins){ pw1.append(item_to_save + "\n"); } pw1.append("-----------") pw1.close(); } Then to load your could do something like: File saved_items = new File("saved.txt") BufferedReader stream_in = new BufferedReader(new FileReader(saved_items)); String line; ArrayList<String> list; while((line = stream_in.readline)!=null){ if(line.contains("-----------")){ break; } list.add(line.trim()); }
{ "pile_set_name": "StackExchange" }
Q: How to use service method inside a component? I am not able to use the service method inside a component. I have a service and a component. Component import { Component, OnInit } from '@angular/core'; import { Customer, Userdetails} from "./usermaster.model"; import { UsermasterService } from './usermaster.service'; @Component({ selector: 'ngx-usermaster', templateUrl: './usermaster.component.html', styleUrls: ['./usermaster.component.scss'], providers: [ UsermasterService ] }) export class UsermasterComponent implements OnInit { values: any; UsermasterService: any; constructor(private service: UsermasterService) { } cust:Customer; user_details:Userdetails; ngOnInit() { this.cust={id:1,name:'dinesh'}; console.log(this.cust); this.values = this.UsermasterService.get_data(); console.log(this.values); } } Service: import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class UsermasterService { httpClient: any; constructor() { } get_data(){ var array=[]; array['id']='1'; array['name']='dineshss'; return array; // this.httpClient.get('http://localhost/tasker/api/index.php/Welcome/get_data') // .subscribe( // (data:any[])=>{ // console.log(data); // } // ) } } I need to call the method get_data in component.ts When i run a code i get the error cannot read property get_data of undefined. Please help me fix this. A: Because in UsermasterComponent, this.UsermasterService is undefined. You declare it as a property, but never assign it any value. There's no connection whatsoever between the property UsermasterService and the class UsermasterService. With constructor constructor(private service: UsermasterService) { } you should access the service as this.service.
{ "pile_set_name": "StackExchange" }
Q: Extending/Subclassing admin Groups & Users classes in Django I'd like to extend/subclass admin Groups & Users classes in Django. CourseAdmin group should be doing what admin can do, and they have extra information like email, phone, address. CourseAdmin should be able to create CourseAdmins, Teachers, Courses and Students. Teacher should be able to edit courses and students belong to them. They can't create anything new. I want to make use of current Django admin classes Group & User instead of doing my own. Please kindly advise. Thank you! A: Do you mean that the whole group CourseAdmin has one email, phone and address? I doubt that. Otherwise you don't have to subclass anything. Just create a user profile model (that includes e.g. email, phone, address), create the groups: CourseAdmin, Teacher, Students and set up the permissions accordingly. You can distinguish the users by checking in which group they are in. More about user authentication.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap table overflow event Based on my previous question: How to detect table that have overflow when reach bottom [jQuery] I've become crazy to redesign UI for table with overflow style (bad at front-end). This bootstrap example give me the good UI but I hadn't found element to detect the scroll event when reach bottom row. Example: http://jsfiddle.net/andrefadila/vbcwbz5m/2/ $('.fixed-table-body').on('scroll', function () { if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { alert('end reached'); } }) Thanks in advance A: The issue I believe is the binding for the scroll event, as the element with the class .fixed-table-body, doesn't exist until the bootstrap table has finished rendering. To get round this, bind the scroll event when the post header event for the bootstrap table fires. $("table").on("post-header.bs.table",function() { $("#console").append("<div>hello</div>"); $('.fixed-table-body').unbind().on("scroll", function () { $("#console").append("<div>hello</div>"); }); }); http://jsfiddle.net/v0c4rtnf/9/
{ "pile_set_name": "StackExchange" }
Q: Attaching ID data to listview items I have an application that fetches announcements stored as xml files on a server and loads the title and author of each announcement into a ListView item. What I also need to store with each item is the ID of each announcement but I don't actually need to display it. I thought about maybe storing the ID in the hash map I use to fill the list and then find the associated ID with the title clicked but I think it would be unsafe to use since two announcements could have the same title (and author and date). I also thought about adding an invisible TextView to each item to store the ID but that was causing layout problems. Lastly, I searched around and found setTag() and getTag() which I think would be perfect for what I want to do but I'm not really sure how to use them with SimpleAdapter (I'm relatively new to this...). If the TextView idea is what I need to do (though I doubt it), here is the layout I'm using for each item: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@android:id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="6dip" android:textAppearance="?android:attr/textAppearanceMedium"/> <LinearLayout android:orientation="horizontal" android:id="@+id/items" android:weightSum="100" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@android:id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="6dip" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_weight="85"/> <LinearLayout android:orientation="vertical" android:id="@+id/itemCB" android:layout_weight="15" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center"> <CheckBox android:id="@+id/cbSelected" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> </LinearLayout> And I'm using the following adapter to fill the list: for(int i = 0; i < ann.length; i++) { map = new HashMap<String, String>(); map.put("line1", ann[i].getTitle()); map.put("line2", "Posted by: " + ann[i].getAuthor() + "\n" + ann[i].date.toLongString()); list.add(map); } String[] from = { "line1", "line2"}; int[] to = { android.R.id.text1, android.R.id.text2}; SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.twoline_checkbox_id_listitem, from, to); setListAdapter(adapter); Thank you for any help! A: Theoretically you could do either approaches and it will probably work without problems. In the long run however, I would say you'll be better of with a simple entity object and a custom adapter. More specifically, from the looks of it, I would opt for an ArrayAdapter, and you already seem to be using some sort of simple entity object for the array ann. There are tons of examples that can show you how to extend ArrayAdapter. The most important part however is the getView() method, which in it's most basic form could look somewhat like this: public View getView(int position, View convertView, ViewGroup parent) { View row; if (null == convertView) { row = mInflater.inflate(R.layout.list_item, null); } else { row = convertView; } MyObject item = (MyObject) getItem(position); TextView tv = (TextView) row.findViewById(android.R.id.xxx); tv.setText(item.getTitle); // same for other fields/views; e.g. author, date etc return row; } In stead of creating a SimpleAdapter, now create an instance of your CustomAdapter, pass it your array (or list) of entity objects, and set the whole as adapter to your list: MyObject[] objects = ... setListAdapter(new ArrayAdapter<string>(this, R.layout.list_item, objects)); Since you're now dealing with the objects directly, in stead of first creating a bunch of strings representation out of the different fields, you can also easily access the 'id' of every item. Even better, you can add a whole lot of different fields without worrying how it will look like in the list, since the visual representation is determined by what you set (and don't set) in the getView() method of your adapter. A: I just want to explain in little more detail answer of MH. In your myArrayAdapter class in getView function you can assign your ID to the View (which actually means "row") like this: public View getView(int position, View convertView, ViewGroup parent){ View v = convertView; if (v == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = inflater.inflate(mItemLayout, null); } String[] dataForOneRow = this.allRowsData.get(position); // Tag is expected to be an Object (Integer is an object) // our data are in String array - that's why we need to convert it into Integer // I assume here, your ID number is first item (No.0) in the array of data v.setTag(new Integer( Integer.valueOf(dataForOneRow[0]) )); /* ...here you will set your data to display in your TextViews... */ return v; } And then you need to know the ID of the row when (for example) user clicked on the row and some detailed Activity is going to start. I have my ListView in the Fragment and this is the piece of code from my main Activity , from the declaration of Fragment , placed in the function onCreateView: // here we assign "onClick listener" when user clicks a row myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent myRowClickIntent = new Intent(getActivity(), myDetailActivity.class); // we can send some data to the new Activity through "extras" // remember - our Tag is an object (Integer object) but putExtra() awaits some integer or string or some other type // so here we are saying that it should be understood/treated as an Integer myRowClickIntent.putExtra("item_id", (Integer)view.getTag() ); startActivity(myRowClickIntent); } }); And finally here is piece of code from onCreate method of my DetailActivity: Bundle myExtras; int myItemId; myExtras = getIntent().getExtras(); if (myExtras != null) { myItemId = myExtras.getInteger("item_id"); } Hope it helps somebody... :) I'm also new to Android. Big thank you to StackOverflow for such help in learning Android development :)
{ "pile_set_name": "StackExchange" }
Q: Ansible - List available hosts I got some hosts in my ansible inventory which the ansible server cannot connect to (there is no pubkey deployed). How do I list all of them? (List unreachable hosts) Maybe there is a way to generate an inventory file with all of the hosts? (the less elegant way is to write a playbook and to copy the command line output, but is there a better way?) A: To list them, you can use the ping module, and pipe the output : ANSIBLE_NOCOWS=1 ansible -m ping all 2>&1 | grep 'FAILED => SSH' | cut -f 1 -d' ' If you want to generate an inventory, you can just redirect the output in a file : ANSIBLE_NOCOWS=1 ansible -m ping all 2>&1 | grep 'FAILED => SSH' | cut -f 1 -d' ' > hosts_without_key Then, you can use it later providing the -i switch to ansible commands : ansible-playbook -i hosts_without_key deploy_keys.yml If you can ssh using passwords, and assuming you have a key deploying playbook (e.g. deploy_keys.yml), you can issue : ansible-playbook -i hosts_without_key deploy_keys.yml -kKu someuser But if the point is to deploy keys on hosts that don't have them, remember Ansible is idempotent. It does no harm to execute the deploy_keys.yml playbook everywhere (it's just a bit longer). Good luck.
{ "pile_set_name": "StackExchange" }
Q: How to change onClick tracking for Universal Analytics? On some of the websites I work on there is a facility to generate an online quote. If a visitor wants to generate a quote, they have to complete 4 steps, each with a "next" button at the bottom of the page. The URL does not change when moving on to the next step of the form so a virtual page view is sent each time a "next" button is clicked. This allowed me to set up a goal with funnel to see how visitors interact with the quote form. This is what the piece of code I'm using currently looks like: onClick="javascript:_gaq.push(['_trackPageview', '/Quote1']);" I have now created a new Universal property in analytics where I'm going to set up and check my goals before upgrading the original property from the asynchronous version. So, my question is, do I need to change this bit of code to work with Universal Analytics? Or will this work with both versions? I'm a marketing guy and I know very little about coding so I'd really appreciate a response! Cheers, Andrew A: Yes, you will need to the old code to the new Universal Analytics syntax, which should make a little more sense to you, marketing guy. The updated code will look like this: onclick="ga('send', 'pageview', '/Quote1');" *I removed the javascript prefix from the onclick because it's redundant.
{ "pile_set_name": "StackExchange" }
Q: PHP setcookie warning I have a problem with 'setcookie' in PHP and I can't solve it. so I receive this error "Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\VertrigoServ\www\vote.php:14) in C:\Program Files\VertrigoServ\www\vote.php on line 86" and here is the file.. line 86 is setcookie ($cookie_name, 1, time()+86400, '/', '', 0); is there any other way to do this ?? <html> <head> <title>Ranking</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body bgcolor="#EEF0FF"> <div align="center"> <br/> <div align="center"><div id="header"></div></div> <br/> <table width="800" border="0" align="center" cellpadding="5" cellspacing="0" class="mid-table"> <tr><td height="5"> <center> </tr> </table> </center> </td></tr> <tr><td height="5"></td></tr> </table> <br/> <?php include "conf.php"; $id = $_GET['id']; if (!isset($_POST['submitted'])) { if (isset($_GET['id']) && is_numeric($_GET['id'])) { </div></td></tr> <tr><td align="center" valign="top"><img src="images/ads/top_banner.png"></td></tr> </table> </form> <?php } else { echo '<font color="red">You must select a valid server to vote for it!</font>'; } } else { $kod=$_POST['kod']; if($kod!=$_COOKIE[imgcodepage]) { echo "The code does not match"; } else { $id = mysql_real_escape_string($_POST['id']); $query = "SELECT SQL_CACHE id, votes FROM s_servers WHERE id = $id"; $result = mysql_query($query) OR die(mysql_error()); $row = mysql_fetch_array($result, MYSQL_ASSOC); $votes = $row['votes']; $id = $row['id']; $cookie_name = 'vote_'.$id; $ip = $_SERVER['REMOTE_ADDR']; $ltime = mysql_fetch_assoc(mysql_query("SELECT SQL_CACHE `time` FROM `s_votes` WHERE `sid`='$id' AND `ip`='$ip'")); $ltime = $ltime['time'] + 86400; $time = time(); if (isset($_COOKIE['vote_'.$id]) OR $ltime > $time) { echo 'You have already voted in last 24 hours! Your vote is not recorded.'; } else { $votes++; $query = "UPDATE s_servers SET votes = $votes WHERE id = $id"; $time = time(); $query2 = mysql_query("INSERT INTO `s_votes` (`ip`, `time`, `sid`) VALUES ('$ip', '$time', '$id')"); $result = mysql_query($query) OR die(mysql_error()); setcookie ($cookie_name, 1, time()+86400, '/', '', 0); } } } ?> <p><a href="index.php">[Click here if you don't want to vote]</a></p><br/> <p><a href="index.php">Ranking.net</a> &copy; 2010-2011<br> </p> </div> </body> </html> Thanks a lot! A: You cannot have any output before header() and setcookie() calls. https://stackoverflow.com/search?q=+headers+already+sent+by https://stackoverflow.com/tags/php/info Any output includes any <html> before the openeing <?php marker, or any print or echoing of content. Another culprit is the UTF-8 BOM http://en.wikipedia.org/wiki/Byte_Order_Mark - which most text editors do not show visibly, but confuses PHP when at the beginning of files.
{ "pile_set_name": "StackExchange" }
Q: how to store an image to redis using java / spring I'm using redis and spring framework on my image upload server. I need to store the images to redis. I have found the following question but it was for python. how to store an image into redis using python / PIL I'm not sure if it's the best way but I would like to know how to do it in java (preferably using spring framework). I'm using spring-data-redis which uses jedis. I would like to know if it is a good strategy to store images in redis. A: Redis is binary safe so, in the case of Jedis, you can use BinaryJedis to store binary data just as any other kind of value that you store in Redis. And no, I don't think storing images in Redis, and thus in-memory, is a good strategy. That would have to be a very special use-case.
{ "pile_set_name": "StackExchange" }
Q: Advanced indexing for sympy? With numpy, I am able to select an arbitrary set of items from an array with a list of integers: >>> import numpy as np >>> a = np.array([1,2,3]) >>> a[[0,2]] array([1, 3]) The same does not seem to work with sympy matrices, as the code: >>> import sympy as sp >>> b = sp.Matrix([1,2,3]) >>> b[[0,2]] results to an error message: **Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/sympy/matrices/dense.py", line 94, in __getitem__ return self._mat[a2idx(key)] File "/usr/lib/python2.7/dist-packages/sympy/matrices/matrices.py", line 4120, in a2idx raise IndexError("Invalid index a[%r]" % (j, )) IndexError: Invalid index a[[0, 2]] My question is whether there would be a way to do this in sympy? A: Your a and b does not represent similar objects, actually a is a 1x3 "matrix" (one row, 3 columns), namely a vector, while b is a 3x1 matrix (3 rows, one column). >>> a array([1, 2, 3]) >>> b Matrix([ [1], [2], [3]]) The numpy equivalent would be numpy.array([[1], [2], [3]]), not your a. Knowing that, b[[0,2]] has no meaning because you are missing index for one of your dimension. If you want to select only the first and third rows, you need to specify the second dimension: >>> b[[0, 2], :] Matrix([ [1], [3]]) Note: Using numpy, you could access a 3x1 matrix the way you want, it looks like simply is more strict than numpy.
{ "pile_set_name": "StackExchange" }
Q: pyPdf PdfFileReader vs PdfFileWriter I have the following code: import os from pyPdf import PdfFileReader, PdfFileWriter path = "C:/Real Python/Course materials/Chapter 12/Practice files" input_file_name = os.path.join(path, "Pride and Prejudice.pdf") input_file = PdfFileReader(file(input_file_name, "rb")) output_PDF = PdfFileWriter() for page_num in range(1, 4): output_PDF.addPage(input_file.getPage(page_num)) output_file_name = os.path.join(path, "Output/portion.pdf") output_file = file(output_file_name, "wb") output_PDF.write(output_file) output_file.close() Till now I was just reading from Pdfs and later learned to write from Pdf to txt... But now this... Why the PdfFileReader differs so much from PdfFileWriter Can someone explain this? I would expect something like: import os from pyPdf import PdfFileReader, PdfFileWriter path = "C:/Real Python/Course materials/Chapter 12/Practice files" input_file_name = os.path.join(path, "Pride and Prejudice.pdf") input_file = PdfFileReader(file(input_file_name, "rb")) output_file_name = os.path.join(path, "out Pride and Prejudice.pdf") output_file = PdfFileWriter(file(output_file_name, "wb")) for page_num in range(1,4): page = input_file.petPage(page_num) output_file.addPage(page_num) output_file.write(page) Any help??? Thanks EDIT 0: What does .addPage() do? for page_num in range(1, 4): output_PDF.addPage(input_file.getPage(page_num)) Does it just creates 3 BLANK pages? EDIT 1: Someone can explain what happends when: 1) output_PDF = PdfFileWriter() 2) output_PDF.addPage(input_file.getPage(page_num)) 3) output_PDF.write(output_file) The 3rd one passes a JUST CREATED(!) object to output_PDF , why? A: The issue is basically the PDF Cross-Reference table. It's a somewhat tangled spaghetti monster of references to pages, fonts, objects, elements, and these all need to link together to allow for random access. Each time a file is updated, it needs to rebuild this table. The file is created in memory first so this only has to happen once, and further decreasing the chances of torching your file. output_PDF = PdfFileWriter() This creates the space in memory for the PDF to go into. (to be pulled from your old pdf) output_PDF.addPage(input_file.getPage(page_num)) add the page from your input pdf, to the PDF file created in memory (the page you want.) output_PDF.write(output_file) Finally, this writes the object stored in memory to a file, building the header, cross-reference table, and linking everything together all hunky dunky. Edit: Presumably, the JUST CREATED flag signals PyPDF to start building the appropriate tables and link things together. -- in response to the why vs .txt and csv: When you're copying from a text or CSV file, there's no existing data structures to comprehend and move to make sure things like formatting, image placement, and form data (input sections, etc) are preserved and created properly.
{ "pile_set_name": "StackExchange" }
Q: Key error en django al usar kwargs.pop os agradecería la ayuda, parece que estoy bloqueado con esto, y no debería ser complicado. Tengo una función en views.py que instancia un formulario del siguiente modo: form = BusquedaPresenciaForm(initial={'fecha_inicio': datetime.date.today(), 'fecha_fin': datetime.date.today()}, form_kwargs={'usuario_actual': request.user.id}) En forms.py tengo el siguiente formulario class BusquedaPresenciaForm(forms.ModelForm): def __init__(self, *args, **kwargs): usuario_actual = kwargs.pop('usuario_actual') super(BusquedaPresenciaForm, self).__init__(*args, **kwargs) self.fields['usuario'].queryset = Coordinacion.objects.filter(coordinador=usuario_actual.id) Se trata de que en un campo del formulario nos filtre un <select> del campo usuario del formulario, según el usuario actual. El error que me está devolviendo es: Exception Type: KeyError Exception Value: 'usuario_actual' En la línea: usuario_actual = kwargs.pop('usuario_actual') A: Lo he replanteado un poquito y lo he puesto a funcionar los cambios son cuando se instancia el formulario en views.py form = BusquedaPresenciaForm(initial={'fecha_inicio': datetime.date.today(), 'fecha_fin': datetime.date.today()}, usuario_actual=request.user) Parece que no es necesario usar "form_kwargs=" para pasar valores al formulario, leí algo relativo a esto en la documentación y parece ser que lo entendí de forma erronea.
{ "pile_set_name": "StackExchange" }
Q: C stuck inside for loop So here's my code int find_h(int i, int j, int current[N+1][N], int goal[N+1][N]) { int sum=0; int a, b; int cp[N*3], gp[N*3]; for(a=0;a<N;a++) { for(b=0;b<N;b++) { cp[4*a+b]=current[a][b]; gp[4*a+b]=goal[a][b]; printf("b = %d\n", b); } printf("\n"); } return sum; } N=4 and current and goal are filled with the numbers from 0 to 15 inclusive, only appearing once each. It loops fine the first 3 iterations (until a=3) but then it keeps outputting b = 0 forever. Thanks A: I don't know what you want to do, but I'll tell you something: cp and gp are too much small. As written, they should be big N * N instead of N * 3 (== 12). Now, here cp[4*a+b] you should have written N*a+b. If N == 4 then it's the same. Otherwise... And it isn't clear: int current[N+1][N] this will be (with N == 4) a 20 array element. You are then copying in a linearized array of N * N elements (or perhaps N * 3, see above)...
{ "pile_set_name": "StackExchange" }
Q: How to make Sanskrit Title in Devanagari Package I generally type sanskrit using the "devnag" preprocessor. But when making a sanskrit title it is showing an error. Can you please help me in rectifying this. My input vivekachoodamani.dn file is given below: \documentclass[10pt]{article} \usepackage[ansinew]{inputenc} \usepackage[T1]{fontenc} \usepackage{devanagari} \usepackage{fontspec,bera} \usepackage[width=4.5in, height=7.0in, top=1.0in, papersize={5.5in,8.5in}]{geometry} \begin{document} \title{{\dn vivekachoodama.ni}} \author{Sri Sankaracharya} \maketitle \begin{flushleft} {\dn sarvavedaantasiddhaantagocara.m tamagocara.m | \\ govinda.m paramaananda.m {sad}guru.m pra.nato.asmyaham || 1} {\small I prostrate myself before Govinda, the perfect teacher, who is absorbed always in the highest state of bliss. His true nature cannot be known by the senses or the mind. It is revealed only through knowledge of the scriptures.} \end{document} A: The end of the flushleft environment is missing. I changed the input encoding from ansinew to utf8, since my editor uses it and it better matches XeLaTeX. Further I got a geometry error, so I removed the package. After I fixed those things, this example could be compiled with XeLaTeX: \documentclass[10pt]{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{devanagari} \usepackage{fontspec,bera} \begin{document} \title{{\dn vivekachoodama.ni}} \author{Sri Sankaracharya} \maketitle \begin{flushleft} {\dn sarvavedaantasiddhaantagocara.m tamagocara.m | \\ govinda.m paramaananda.m {sad}guru.m pra.nato.asmyaham || 1} {\small I prostrate myself before Govinda, the perfect teacher, who is absorbed always in the highest state of bliss. His true nature cannot be known by the senses or the mind. It is revealed only through knowledge of the scriptures.} \end{flushleft} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Show that $A=\{x\in X\mid a\leq f(x)\leq b\:;\;a,b\in\mathbb{R}\}$ is closed if $f:X\to \mathbb R$ is continuous. Let $X$ be a set. Suppose that $f:X\to\mathbb{R}$ is a continuous function and let $A=\{x\in X\mid a\leq f(x)\leq b\:;\;a,b\in\mathbb{R}\}$. Is $A$ closed, open, clopen or none? So I started by saying that $f(A)=\{p=f(x)\mid a\leq p\leq b\;\text{for some}\;x\in X\}$ but I can't figure out if the set is closed. A: It is closed. The simplest way to see it is the following: Let $\{x_n\}_{n\in\mathbb N}\subset\{x:a\le f(x)\le b\}$, with $x_n\to x_0$. Then, $$ a\le f(x_n)\le b, \quad\text{for all $n$}, $$ and as $f$ is continuous, $f(x_n)\to f(x_0)$, which implies that $$ a\le f(x_0)\le b. $$ Thus $x_0\in\{x:a\le f(x)\le b\}$, and hence $\{x:a\le f(x)\le b\}$ is closed.
{ "pile_set_name": "StackExchange" }
Q: How to make versioning with Swagger and Spring Boot? I've read a lot of StackOverflow questions, but there is no good solution for me. I'm searching for a way to document our API with a version number. We have v1 and v2. So the best way is to generate 2 different swaggers. The controllers are in different packages and for one version is one controller. Is this possible with swagger? And how we can do it? A: The best way to do this is to use swagger groups. Check out this documentation: Springfox Documentation
{ "pile_set_name": "StackExchange" }
Q: Getting specific JSON data after clicking a button I'm building a React Native app that works with JSON data and shows the upcoming movies. It looks like this: https://image.ibb.co/kuOt9m/app.png . My problem is whenever I click the Summary button I get all the summaries, for all the movies. What i want is to get a specific summary for the movie I clicked. In the JSON there's a movie id that is totally unique and I guess I should set it on the Button or the CardSection itself. My code looks like this: import React, { Component } from 'react'; import { ScrollView } from 'react-native'; import axios from 'axios'; import MovieSummary from './MovieSummary'; class SummaryList extends Component { state = { movies: [] }; componentDidMount() { axios.get('https://api.themoviedb.org/3/movie/upcoming?api_key=22d8da68cffba151bfa886d5003aac02&language=en-US&page=1') .then(response => this.setState({ movies: response.data.results })); } renderSummary() { return this.state.movies.map(movie => <MovieSummary key={movie.id} movie={movie} /> ); } render() { console.log(this.state); return ( <ScrollView> {this.renderSummary()} </ScrollView> ); } } export default SummaryList; then in another class i show the data like this: import React from 'react'; import { View, Text } from 'react-native'; const MovieSummary = (props) => ( <View> <Text> {props.movie.overview} </Text> </View> ); export default MovieSummary; and then with a Router class (react-native-router-flux library) I use Router/Scene to connect the two screens. I'm gonna post the CardSection.js or Button.js code if it's gonna make it anymore clear and there's where I need to add an ID. edit: adding more information my CardSection.js looks like this: import React from 'react'; import { View } from 'react-native'; const CardSection = (props) => ( <View style={styles.containerStyle}> {props.children} </View> ); const styles = { containerStyle: { *some view styles* } }; export default CardSection; my Button.js looks like this: import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; const Button = ({ onPress, children }) => ( <TouchableOpacity onPress={onPress} style={styles.buttonStyle} > <Text style={styles.textStyle}> {children} </Text> </TouchableOpacity> ); const styles = { buttonStyle: { *button styles* }, textStyle: { *text styles* } }; export default Button; A: First thing, I think there's a bit of confusion about your second screen, you're calling it SummaryList and it's working on an array of movies - whereas if I understand correctly you want your second screen to just deal with one movie. I'd rename a few things: MoviesList is fine MovieDetail -> MoviesListItem (these are rows in your MovieList, renaming to avoid confusion with your second screen) SummaryDetail is fine (this will be your single-movie scene. I'd probably actually call this MovieDetail but that would get confusing!) Forget about SummaryList - we don't need it. You only have one list we're concerned about, that's MoviesList. First, modify your Router so that you have a MoviesList and a SummaryDetail scene: // Router.js // ... const RouterComponent = () => ( <Router navigationBarStyle={styles.viewStyle} titleStyle={styles.textStyle} sceneStyle={{ paddingTop: 53 }} > <Scene key="upcoming" component={MoviesList} title="Upcoming Movies" /> <Scene key="summaryDetail" component={SummaryDetail} title="Summary Detail" leftButtonIconStyle={{ tintColor: '#a52a2a' }} /> </Router> ); // ... So now your MoviesListItem is the component with a summary Button in it. This needs to lead to your SummaryDetail scene. You can navigate to your SummaryDetail scene by calling Actions.summaryDetail() from react-native-router-flux, but you actually want to tell this scene which movie it's dealing with. Pass the movie (which you already have as a prop of MovieListItem) as a param, via an argument to Actions.summaryDetail(...) like this: // MovieListItem.js // ... <View style={{ justifyContent: 'flex-end' }}> <Button onPress={() => { Actions.summaryDetail({ movie: props.movie }); // <- Important bit! }}> Summary </Button> </View> // ... Now, you should have the movie available in your SummaryDetail screen as the movie prop. // SummaryDetail.js // ... const SummaryDetail = (props) => ( <View> <Text> {props.movie.overview} </Text> </View> ); // ... You might want to split off parts of SummaryDetail into separate presentational components later, and you might want to turn it into a class and use componentDidMount to fetch some extra movie detail you don't already have. But this should be enough to get you started with one movie on a second screen.
{ "pile_set_name": "StackExchange" }
Q: Get last day of a given quarter and Year in SQL I have 2 variables year and quarter that I get from the view. I have to pass these values to get the last date of that particular Quarter and Year. Is there a way to do that in SQL? For example: select (QuarterEndDate) where Year = @year and Quarter = @quarter A: I would use datefromparts() and eomonth(): select eomonth(datefromparts(@year, 3 * @quarter, 1)) Demo on DB Fiddlde: declare @year int; declare @quarter int; set @year = 2020; set @quarter = 3; select eomonth(datefromparts(@year, 3 * @quarter, 1)) last_quarter_day GO | last_quarter_day | | :--------------- | | 2020-09-30 |
{ "pile_set_name": "StackExchange" }
Q: Is it possible to integrate AdMob in an Android app using Uno Platform I have a few UWP apps I would like to migrate to Android. I already migrated some using Xamarin.Forms I have discovered Uno Platform that seems to be great. But I didn't find any information about integration AdMob advertisement in an Android project using Uno Platform. Has anyone done it already? A: Yes, it is possible and I have been able to get it working in my Uno Platform app on Android and iOS. I am planning to write a blogpost about getting AdMob and AdSense running on Android, iOS and WASM, and publish a Uno Platform library on NuGet that will do all the heavy lifting for you, so stay tuned :-) . For now, here is a unedited, raw version of the control I am using currently. It requires that you install the Google Play Services Ads NuGet packages in the Android project and in the iOS project. Android #if __ANDROID__ using Android.Gms.Ads; using Android.Widget; using System; using System.Collections.Generic; using System.Text; using Uno.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace SmsTicket.Core.Controls { public partial class AdControl : ContentControl { public AdControl() { var adView = new AdView(ContextHelper.Current); adView.AdSize = AdSize.SmartBanner; adView.AdUnitId = "YOUR AD UNIT ID"; HorizontalContentAlignment = HorizontalAlignment.Stretch; VerticalContentAlignment = VerticalAlignment.Stretch; var adParams = new LinearLayout.LayoutParams( LayoutParams.WrapContent, LayoutParams.WrapContent); adView.LayoutParameters = adParams; adView.LoadAd(new AdRequest.Builder().AddTestDevice("YOUR TEST DEVICE ID").Build()); Content = adView; } } } #endif iOS #if __IOS__ using Google.MobileAds; using System; using System.Collections.Generic; using System.Text; using UIKit; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml; using CoreGraphics; namespace SmsTicket.Core.Controls { public partial class AdControl : ContentControl { public AdControl() { HorizontalContentAlignment = HorizontalAlignment.Stretch; VerticalContentAlignment = VerticalAlignment.Stretch; Background = SolidColorBrushHelper.Red; Width = AdSizeCons.LargeBanner.Size.Width; Height = AdSizeCons.LargeBanner.Size.Height; Windows.UI.Xaml.Window.Current.Activated += Current_Activated; } private void LoadAd() { if (!(Content is BannerView)) { var adView = new BannerView(AdSizeCons.LargeBanner) { AdUnitID = "YOUR AD UNIT ID", RootViewController = GetVisibleViewController() }; adView.LoadRequest(GetRequest()); Content = adView; } } Request GetRequest() { var request = Request.GetDefaultRequest(); // Requests test ads on devices you specify. Your test device ID is printed to the console when // an ad request is made. GADBannerView automatically returns test ads when running on a // simulator. After you get your device ID, add it here request.TestDevices = new[] { Request.SimulatorId.ToString(), "YOUR TEST DEVICE ID" }; return request; } UIViewController GetVisibleViewController() { UIViewController rootController; if (UIApplication.SharedApplication.KeyWindow == null) { return null; } else { rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; } if (rootController.PresentedViewController == null) return rootController; if (rootController.PresentedViewController is UINavigationController) { return ((UINavigationController)rootController.PresentedViewController).VisibleViewController; } if (rootController.PresentedViewController is UITabBarController) { return ((UITabBarController)rootController.PresentedViewController).SelectedViewController; } return rootController.PresentedViewController; } private void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e) { LoadAd(); } } } #endif Also make sure to include the Ad control only conditionally (as I have provided only Android and iOS version here).
{ "pile_set_name": "StackExchange" }
Q: In .NET Windows Forms, how can I send data between two EXEs or applications? The scenario that I bring forward is basically that of, interaction between two .NET executables. I have made a .NET Windows Forms application in C# (Application-A) that runs on a user's machine and does some specific activity, due to which it collects some data. Now I have another .NET Windows Forms executable (Application-B), also made in C#, which also does some specific activity based certain inputs or data provided. Now what I want to do here is, call Application-B from the Application-A and pass the some data to it. How do I accomplish this? A: You can use several options. You have some resources for each option below. .NET Remoting WCF Use a communication file MSMQ Two last options are valid only if the processes are in the same machine. Since they are two separated processes I think that the easiest way to do this is using .NET Remoting. Here you can find documentation and examples about how to do it. An alternative to Remoting is WCF (>= .NET 3.0). It performs better than remoting. If the processes will be always in the same machine, if you don't want to use remoting on localhost you can communicate them through a file (simple solutions usually work fine!) And other more complex solution is communicate them using a Message Queue (MSMQ). Here you cand find out an example about how to use it.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to utilize the LINQ portion of the foreach inside the loop? I have this view in an ASP.NET MVC application: <% var path = Path.Combine(HttpRuntime.AppDomainAppPath, "uploads"); foreach (var file in Directory.GetFiles(path).OrderBy(f => new FileInfo(f).Length)) { var item = new FileInfo(file); %> <tr> <td></td> <td> <%=Html.Encode(Path.GetFileName(item.Name))%> </td> <td> <%=Html.Encode(Functions.FormatBytes(item.Length))%> </td> <td> <%=Html.FileLink(item.Name)%> </td> </tr> <% } %> Is it possible to access my variable f inside the loop, or is there some other way to do this so I do not have to dimension two instances of FileInfo(file)? Thanks! A: var fileInfos = new DirectoryInfo(path).GetFiles().OrderBy(f => f.Length); foreach (var fileInfo in fileInfos) { ... }
{ "pile_set_name": "StackExchange" }
Q: Aligning checkboxes via inherited css? I have a php page, which launches a popup window containing a form with checkboxes. The originating window includes an external stylesheet. The form html for the popup window is: <form name="statusForm" action="post.php=" method="post" enctype="multipart/form-data"> <label for="Test">Test:</label> <input name="checkboxes[]" value="Test" type="checkbox"> <br> <label for="Test">TestTest:</label> <input name="checkboxes[]" value="Test" type="checkbox"> <br> <label for="Test">TestTestTest:</label> <input name="checkboxes[]" value="Test" type="checkbox"> <br> <input name="Submit" value="submit" type="submit"> </form> The form has been trimmed, and fields renamed to test for posting.. In the external stylesheet, I have: label { min-width: 5em; } The checkboxes are still not aligned. Do I have to included the stylesheet explicitly in the html of the popup window, or is it something else? A: Yes, the popup window needs to be its own full HTML page. Edit Unless it is an AJAX popup, in which case it does NOT need to be a full HTML page.
{ "pile_set_name": "StackExchange" }
Q: How can I remove the upper padding of the second and third blocks? After the h tags were added, the upper indents of the blocks appeared in the html code. How can I remove the upper padding of the second and third blocks? And why it happened? Without h blocks are displayed normally html code <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link href="main.css" rel="stylesheet"> <title>1</title> </head> <body> <div id="container"> <div class="block block1"> <h3>Mark Manson</h3> <h1>The<br> dark side of the digital nomad</h1> </div> <div class="block block2"> text </div> <div class="block block3"> comments </div> </div> </body> </html> CSS * { margin: 0; padding: 0; } body { font-family: Verdanta; font-size: 14px; color: #333; background: #DCDCDC; } #container { font-size: 0; } .block { display: inline-block; width: 250px; height: 440px; background-color: white; background-size: cover; margin-right: 50px; box-sizing: border-box; font-size: 14px; } .block1 { background-image: url("https://images.unsplash.com/photo-1453396450673-3fe83d2db2c4?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=5eb7a0fcc589f787ef254317fcbf88c0"); background-repeat: no-repeat; background-size: 250px 405px; color: white; padding-top: 150px; } A: It's not padding issue, it's related to vertical-align, you can set it to top for solve this. check below snippet * { margin: 0; padding: 0; } body { font-family: Verdanta; font-size: 14px; color: #333; background: #DCDCDC; } #container { font-size: 0; } .block { display: inline-block; width: 250px; height: 440px; background-color: white; background-size: cover; margin-right: 50px; box-sizing: border-box; font-size: 14px; vertical-align: top; } .block1 { background-image: url("https://images.unsplash.com/photo-1453396450673-3fe83d2db2c4?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=5eb7a0fcc589f787ef254317fcbf88c0"); background-repeat: no-repeat; background-size: 250px 405px; color: white; padding-top: 150px; } <div id="container"> <div class="block block1"> <h3>Mark Manson</h3> <h1>The<br> dark side of the digital nomad</h1> </div> <div class="block block2"> text </div> <div class="block block3"> comments </div> </div>
{ "pile_set_name": "StackExchange" }
Q: add markers googlemap with javascript since JSON external external JSON: { "playas": [ { "nombre": "Laredo", "ubicacion": { "municipio": { "nombre": "Laredo", "codigoPostal": 39035 }, "latitud": 43.419746, "longitud": -3.453788 }, "descripcion": { "detalle": "De entorno urbano y de 5000 metros de extensión es la playa de Laredo con un alto grado de ocupación en la época estival.", "fondo": "Arena", "mar": "Fuerte", "vientos": [ { "viento": "S" }, { "viento": "SO" }, { "viento": "NO" } ], "marea": "Subiendo", "tamaño": "1-1.5", "olas": [ { "nombre": "El Espigón", "descripcion": "derecha potente con fondo de lastra" }, { "nombre": "La Playa", "descripcion": "buenas derechas" } ], "nivel": "medio" }, "foto": "img/playas/laredo.jpg" }, { "nombre": "Berria", "ubicacion": { "municipio": { "nombre": "Santoña", "codigoPostal": 39079 }, "latitud": 43.465348, "longitud": -3.450717 }, "descripcion": { "detalle": "Playa de aproximadamente 2 kilómetros de arena que se encuentra en un entorno semi-urbano mezclado con áreas verdes y pequeñas dunas. En verano mucha afluencia.", "fondo": "Arena", "mar": "Fuerte", "vientos": [ { "viento": "S" }, { "viento": "SO" }, { "viento": "NO" } ], "marea": "Subiendo", "tamaño": "1-1.5", "olas": [ { "nombre": "Variables", "descripcion": "" } ], "nivel": "medio" }, "foto": "img/playas/berria.jpg" }, { "nombre": "El Brusco", "ubicacion": { "municipio": { "nombre": "Noja", "codigoPostal": 39047 }, "latitud": 43.476887, "longitud": -3.512989 }, "descripcion": { "detalle": "También llamado Helgueras y ubicado al final de la Playa de Trengandín. Se llega a través de un camino mal asfaltado desde Noja. Hay que caminar por la playa para ver su verdadero “poderío”. En verano mucha afluencia.", "fondo": "Arena", "mar": "Fuerte", "vientos": [ { "viento": "S" } ], "marea": "Subiendo", "tamaño": "2", "olas": [ { "nombre": "Variables", "descripcion": "Tanto derecha como izquierda potente. Rápidas y tuberas" } ], "nivel": "experto" }, "foto": "img/playas/elbrusco.jpg" }, { "nombre": "Langre", "ubicacion": { "municipio": { "nombre": "Ribamontán al Mar", "codigoPostal": 39061 }, "latitud": 43.477961, "longitud": -3.695723 }, "descripcion": { "detalle": "Playa de unos 1.000 metros de longitud con un entorno de altos acantilados con accesos muy mejorados y en donde se practica al final de la playa el nudismo desde hace muchos años. Buen ambiente playero en verano.", "fondo": "Arena", "mar": "Medio", "vientos": [ { "viento": "S" }, { "viento": "SO" }, { "viento": "E" } ], "marea": "Subiendo", "tamaño": "1", "olas": [ { "nombre": "Variables", "descripcion": "divertido para pasar un buen rato, control para no llevarse a nadie por delante" } ], "nivel": "bajo" }, "foto": "img/playas/langre.jpg" } ] } and the javascript where i read the JSON and add the markers with latitude and longitud for each object var READY_STATE_UNINITIALIZED = 0; //No inicializado objeto creado, pero no se ha invocado el metodo open var READY_STATE_LOADING = 1; //Cargando objeto creado pero no se ha invocado el metodo send var READY_STATE_LOADED = 2; //Cargado se ha invocado el metodo send, pero el servidor aún no ha respondido var READY_STATE_INTERACTIVE = 3; //Interactivo se ha recibido algunos datos, aunque no se puede emplear la propiedad var READY_STATE_COMPLETE = 4;//Se ha recibido todos los datos var peticion_http; var documento_json; var playasJson = []; function initialize() { var options = { zoom: 10, center: new google.maps.LatLng("43.597436","-3.653516"), mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('contenedorMapa'), options); setMarkers(map,playasJson); }; function rellenarJson(playas) { //Preguntar a fernando poruqe tienen ubicacion0 si ordenados tienen posicion 0 y el otro 1 for (var i = 0; i < playas.length; i++) { playasJson.push({ nombre:playas[i].nombre, lat:playas[i].ubicacion.latitud, long:playas[i].ubicacion.longitud }); } } // Obtener la instancia del objeto XMLHttpRequest function inicializa_xhr() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml3.XMLHTTP"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP"); } else if (window.ActiveXObject) { return ActiveXObject("Microsoft.XMLHTTP"); } } //Mostrar la info del json function muestraContenido() { if (peticion_http.readyState === READY_STATE_COMPLETE) { if (peticion_http.status === 200) { documento_json = peticion_http.responseText; var objeto = eval("(" + documento_json + ")"); var playasObtenidas = objeto.playas; rellenarJson(playasObtenidas); } } } //Llamar al json en una variable y añadir funcion function cargarContenido(url, metodo, funcion) { peticion_http = inicializa_xhr(); if (peticion_http) { peticion_http.onreadystatechange = funcion; peticion_http.open(metodo, url, true); peticion_http.send(null); } } function descargaArchivo() { cargarContenido("json/listadoPlayas.json", "GET", muestraContenido); } function setMarkers(map,playasArray) { descargaArchivo(); for (var k = 0; k < playasArray.length; k++) { var beach = playasArray[k]; var myLatLng = new google.maps.LatLng(beach.lat,beach.long); var marker = new google.maps.Marker({ position: myLatLng, map: map, //icon: image, //shape: shape, title: beach[0], zIndex: beach[3] }); } } google.maps.event.addDomListener(window, 'load', initialize); and the html <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=es"></script> <script type="text/javascript" src="map_1.js"></script> </head> <body> <div id="contenedorMapa" style="width: 100%;height: 900px;">TODO write content</div> </body> </html> PLease someone know why doesn't work?? i don't know why?? thanks so much! A: If that's the json the server is sending back, it's bad formed. That could explain why the markers aren't showing up. You can check it's validity here. In order to solve the problem, just add ] } at the end of your current json. I've tested your code substituting the ajax calls by the json string with the fixes I mentioned and it works fiddle. Hope it helps. UPDATE The problem is that the function that adds the markers gets called much before that the AJAX call is completed (remember that AJAX is asynchronous). That means that when you add markers, there are none in the array. You have to call the function that adds the markers once the AJAX call has finished and the array has been populated properly. You could do something like this: var READY_STATE_UNINITIALIZED = 0; //No inicializado objeto creado, pero no se ha invocado el metodo open var READY_STATE_LOADING = 1; //Cargando objeto creado pero no se ha invocado el metodo send var READY_STATE_LOADED = 2; //Cargado se ha invocado el metodo send, pero el servidor aún no ha respondido var READY_STATE_INTERACTIVE = 3; //Interactivo se ha recibido algunos datos, aunque no se puede emplear la propiedad var READY_STATE_COMPLETE = 4;//Se ha recibido todos los datos var peticion_http; var documento_json; var playasJson = []; var map; function initialize() { var options = { zoom: 10, center: new google.maps.LatLng("43.597436", "-3.653516"), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('contenedorMapa'), options); descargaArchivo(); } function rellenarJson(playas) { //Preguntar a fernando poruqe tienen ubicacion0 si ordenados tienen posicion 0 y el otro 1 for (var i = 0; i < playas.length; i++) { playasJson.push({ nombre: playas[i].nombre, lat: playas[i].ubicacion.latitud, long: playas[i].ubicacion.longitud }); } setMarkers(map, playasJson); } // Obtener la instancia del objeto XMLHttpRequest function inicializa_xhr() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml3.XMLHTTP"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } else if (window.ActiveXObject) { return new ActiveXObject("Msxml2.XMLHTTP"); } else if (window.ActiveXObject) { return ActiveXObject("Microsoft.XMLHTTP"); } } //Mostrar la info del json function muestraContenido() { if (peticion_http.readyState === READY_STATE_COMPLETE) { if (peticion_http.status === 200) { documento_json = peticion_http.responseText; var objeto = JSON.parse(documento_json); var playasObtenidas = objeto.playas; rellenarJson(playasObtenidas); } } } //Llamar al json en una variable y añadir funcion function cargarContenido(url, metodo, funcion) { peticion_http = inicializa_xhr(); if (peticion_http) { peticion_http.onreadystatechange = funcion; peticion_http.open(metodo, url, true); peticion_http.send(null); } } function descargaArchivo() { cargarContenido("json/listadoPlayas.json", "GET", muestraContenido); } function setMarkers(map, playasArray) { for (var k = 0; k < playasArray.length; k++) { var beach = playasArray[k]; var myLatLng = new google.maps.LatLng(beach.lat, beach.long); var marker = new google.maps.Marker({ position: myLatLng, map: map, //icon: image, //shape: shape, title: beach[0], zIndex: beach[3] }); } } google.maps.event.addDomListener(window, 'load', initialize); Rest of the code remains the same though I'd change that eval(...) to JSON.parse(documento_json). You also have to remove the call to descargaArchivo from setMarkers
{ "pile_set_name": "StackExchange" }
Q: Efficient method to return first and last item from pandas df I am trying to implement a more efficient method to return the first and last item of a pandas df where equal to a specific value. I'll post my current method below but there could be a more efficient way. import pandas as pd d = ({ 'X' : ['X','Y','X','Z','X'], 'Y' : [2,5,3,5,1], }) df = pd.DataFrame(data=d) So I want to return the first and last item in Y where X == X. This is my attempt but I think there could be a more efficient way. df = df[df['X'] == 'X'] df_first = df.drop_duplicates(subset=['X'], keep = 'first') df_last = df.drop_duplicates(subset=['X'], keep = 'last') df1 = pd.concat([df_first, df_last]) # my expected output df1 X Y 0 X 2 4 X 1 A: Using query (or any selection method, really) and iloc, this should be straightforward. df.query('X == "X"').iloc[[0, -1]] X Y 0 X 2 4 X 1 Assumes there are no NaNs in Y. Otherwise, chain dropna: df.query('X == "X"').dropna(subset=['Y']).iloc[[0, -1]] X Y 0 X 2 4 X 1 Another option using agg, thought this was interesting. This is useful if your "Y" has NaNs. df.loc[df['Y'].where(df['X'] == 'X').agg( ['first_valid_index', 'last_valid_index'])] X Y 0 X 2 4 X 1
{ "pile_set_name": "StackExchange" }
Q: Good way to keep iPad clean? I don't have a case or screen protector just yet for my iPad. What is a cost effective way to keep the screen clean and remove fingerprints? A: Use the Fingerspoo iPad wallpaper and you won't notice fingerprints anymore. A: Yesterday I was using mine in a meeting, and a guy next to me said, "What do you use to wipe the screen down?" I said, "My shirt." And I demonstrated my super-fancy wipe-the-screen-on-my-shirt maneuver I've worked out. It's cheap, and it works. It's not exactly high class, but whatever. A: Use a micro fiber cloth, like the ones used for cleaning glasses. Works for my touch screen devices all the time and needs no extra liquids or any other fancy gear.
{ "pile_set_name": "StackExchange" }
Q: Restore database in amazon web services RDS in SQL Server I have created a new database instance of SQL Server in Amazon Web Services RDS. I have connected to it using SQL Server Management Studio from my computer. Now I want to restore adventureworks.bak database which is present on my computer. But the problem is that I cannot select the file (adventure.bak) from my computer as it only allows me to select file paths where the database is stored on the AWS instance. I have also tried the option restore from S3, but is only showing option to restore amazon aurora and mysql database but not SQL Server database. Is there any way to restore the database from that file? Please help me. Thanks in advance. A: If you want to restore a database backup to an MS SQL Server hosted on RDS, you need to follow the steps detailed in the RDS Native Backup and Restore docs: Upload your adventure.bak file to an S3 bucket Create an IAM Role that grants your RDS database access to that S3 bucket Call the rds_restore_database stored procedure from within SQL Server Management Studio and provide the parameters @restore_db_name (the database name to restore to) and @s3_arn_to_restore_from, the S3 ARN of the adventure.bak file. See the documentation for step-by-step instructions.
{ "pile_set_name": "StackExchange" }
Q: How to reference text boxes that have been added in run time My program creates a random number of TextBox controls when the form loads. I need to then reference what has been typed into these textboxes elsewhere in the code. My problem is is that an error comes up when I try to do so. Below is my code. Dim userAct As New TextBox userAct.Location = New Point(386, 379) userAct.Size = New Size(95, 34) userAct.Font = New Font("Luicida Fax", 12.0!) userAct.BackColor = SystemColors.InactiveCaption userAct.BorderStyle = BorderStyle.None userAct.Multiline = True Me.Controls.Add(userAct) userAct is created but I cannot reference this textbox anywhere within the code. Is there anyway to overcome this? Thanks A: I'm guessing that you're declaring userAct in a sub/function procedure. Although the control is added to the form at runtime, the variable userAct goes out of scope after the sub/function is completed. There are several possible solutions to this, but would suggest the following You can use the code you have, but also assign a "userAct" string to the .Name property and access the control using something like directcast(Me.Controls.Find("userAct", False)(0),TextBox) This can then be used in exactly the same way as a normal TextBox .. directcast(Me.Controls.Find("userAct", False)(0),TextBox).Text="Hi there" or Dim S as string = directcast(Me.Controls.Find("userAct", False)(0),TextBox)(0).Text
{ "pile_set_name": "StackExchange" }
Q: Why JavaScript Not Execute? my javascript won't work I tried everything here is the example function prep2() { if (f1.c1.value, f1.a1.value, f1.t1.value != "") { var character = f1.c1.value; var age = f1.a1.value; var thing = f1.t1.value; document.getElementByid("lolo").innerHTML = "hi my name is " + character + ", i am " + age + " years old. and i love " + thing; } } <head> <title>test</title> </head> <body> <h1>Story Maker</h1> <form name="f1"> Character <input type="text" name="c1"><br><br> Age&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="number" name="a1"><br><br> Favourite <input type="text" name="t1"><br><br> <input type="button" onclick="prep2()" value="sumbit"> <h1>Story:</h1><br> <p id="lolo"></p> </form> </body> _________________________________________________________________________________________________________________________________________________________________________________________________________________________-- A: Looks like your code had document.getElementByid instead of document.getElementById. The below code seems to be working: function prep2() { if (f1.c1.value, f1.a1.value, f1.t1.value != "") { var character = f1.c1.value; var age = f1.a1.value; var thing = f1.t1.value; document.getElementById("lolo").innerHTML = "hi my name is " + character + ", i am " + age + " years old. and i love " + thing; } } <head> <title>test</title> </head> <body> <h1>Story Maker</h1> <form name="f1"> Character <input type="text" name="c1"><br><br> Age&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="number" name="a1"><br><br> Favourite <input type="text" name="t1"><br><br> <input type="button" onclick="prep2()" value="Submit"> <h1>Story:</h1><br> <p id="lolo"></p> </form> </body>
{ "pile_set_name": "StackExchange" }
Q: Number of integers coprime to l A long time ago I've seen a paper considering, given $\ell$ fixed, estimates for $$ \sum_{n \leq x, (n, \ell) = 1} 1 $$ Of course, this is easy to estimate with a trivial error term of $O(\varphi(l))$. However in the paper I am looking for the authors attempted obtaining better bounds, using some Fourier analysis (in particular the Fourier series for the fractional part of x). I think, bounds in the sum $$ \sum_{n \leq x} (n, \ell) $$ are essentially an equivalent variation of the problem, so references on this problem are welcome aswell. The reason why I am interested in this problem is ... pure curiosity. I am curious to see how the Fourier methods meshed in, and what kind of bounds they gave, even though of course we cannot really expect anything too fantastic in this problem. A: It is easy to explain "how the Fourier analysis meshed in". Namely, using the standard notation for the Möbius function, the Euler's totient function, and the integer / fractional part functions, your sum can be written as $$ \sum_{n\le x} \sum_{d\mid(n,l)} \mu(d) = \sum_{d\mid l} \mu(d) \lfloor x/d \rfloor = x \sum_{d\mid l} \frac{\mu(d)}d + R = \frac{\phi(l)}lx + R, $$ where $$ R = \sum_{d\mid l} \mu(d) \{x/d\}. $$ As Fedor Petrov observed, this already suffices to improve the remainder term from $\phi(l)$ to $\tau(l)$ and indeed, to the number of square-free divisors of $l$, which is $2^{\omega(l)}$. To get better estimates, one can try to plug in the Fourier expansion for $\{x/d\}$ and estimate the resulting sums. As to the paper you mention, I think I was able to spot it out: is it "Extremal values of $\Delta(x,N)=\sum_{n<xN,(n,N)=1} 1-x\phi(N)$" by P. Codeca and M. Nair, published in Canad. Math. Bull. 41 (3) (1998), pp. 335–347? Another paper by the same authors on the same subject: "Links between $\Delta(x,N)=\sum_{n<xN,(n,N)=1} 1-x\phi(N)$ and character sums", Boll. Unione Mat. Ital. Sez. B Artic. Ric. Mat. 6 (2) (2003), pp. 509–516. I could find one more paper on this problem published in a Canadian journal: "The distribution of totatives" by D.H. Lehmer, Canad. J. Math. 7 (1955), pp. 347–357.
{ "pile_set_name": "StackExchange" }
Q: Failed commit in SmartGit I did a commit (& push) in SmartGit but I was not connected to the internet. It is represented by a red cross in SmartGits "Output"-window. The text reads: Unable to access '_____': could not resolve host: '_____'. After this I did a successful commit of some other files and a successful push. Do I need to fix something? Will the failed commit that happened earlier mess things up or is everything ok? A: Everything is fine. You should see now two commits in the Outgoing view. Once you are connected to the Internet, just invoke Push and your commits will be transmitted to the server.
{ "pile_set_name": "StackExchange" }
Q: Close Resource violation in Sonar In my Dao classes, for closing db resources I have written a small function which takes in ResultSet, Connection and Statement objects and closes it. I call this from finally block of each DB access method that I have. But Sonar is showing these as violations like: Ensure that resources like this Statement object are closed after use Is there any way to let Sonar know that these are handled? Profile used is 'Sonar Way' A: This rule is brought by PMD into Sonar, and it is quite basic: it just checks if there's a "myResource.close()" call in the finally block. Full stop. If you're extensively using your "small function", then you should probably consider deactivating this rule as it will generate too many false positives. You could also try to activate Findbugs rules that may be more intelligent. See those rules on our Sonar demo instance - Nemo.
{ "pile_set_name": "StackExchange" }
Q: Making JS/CSS menu - hover not working properly Live example is here What my problems are: when moving mouse from sub menu over minus sign, the sub menu fades in again (this should not occur) when leaving menu outside the sub menu by moving mouse upwards or leftwards the plus sign, the sub menu does not fade out These problems could be managed by exchanging z-index of plus sign and sub menu. But then the minus sign is not displayed in the style I want it to be displayed (because it lays behind the semi transparent sub menu). Relevant JS code is: $(document).ready(function() { if ($(".nav").length) { $(".nav ul ul").css({ opacity: 0.9 }).mouseleave(function(e) { e.stopPropagation(); $(this).fadeOut().parent().prev().children("div").html("+").css({ lineHeight: "30px", paddingBottom: 0 }); }); $(".nav > ul").find("li:first").each(function() { $(this).append($("<div>").html("+").mouseenter(function(e) { e.stopPropagation(); $(this).html("&ndash;").css({ lineHeight: "26px", paddingBottom: "4px" }).parent().next().children("ul").fadeIn(); })); }); } }); A: The ul for the dropdown menu should be semantically a part of your drop down button, this way it is a child of the drop down 'button', and I believe this will solve your problem. Edit: i.e. your drop-down <ul> should be a child of your +/- button, not a sibling.
{ "pile_set_name": "StackExchange" }
Q: What is the distance of Earth from the 7 planets, moons and the Sun at a point of time? I wanted to know the distance of the 7 planets (Mercury, Mars, Venus, Jupiter, Saturn, Uranus, Neptune ) each (or at least 5 planets) from the earth and the angle that it will make with a line connecting the centers of earth and the respective planet at a point of time. Also I need the same for the earth and moon system and sun and earth as they are big influences. At point of time because in the course of revolution of planets the distances with respect to earth will vary. Being an engineering student I have the wish :) to calculate the mechanical forces acting on the earth at a point of time due to nearby heavenly bodies. Basically I need the data or in case someone already attempted to calculate the force components I would be delighted to look at it. A: There are plenty of sky simulators where you can calculate that information yourself. e.g. Celestia, KStars Just install one of them and it will tell you position in sky and distance to most known bodies in Solar System, for any given time.
{ "pile_set_name": "StackExchange" }
Q: Expression for setting lowest n bits that works even when n equals word size NB: the purpose of this question is to understand Perl's bitwise operators better. I know of ways to compute the number U described below. Let $i be a nonnegative integer. I'm looking for a simple expression E<$i>1 that will evaluate to the unsigned int U, whose $i lowest bits are all 1's, and whose remaining bits are all 0's. E.g. E<8> should be 255. In particular, if $i equals the machine's word size (W), E<$i> should equal ~02. The expressions (1 << $i) - 1 and ~(~0 << $i) both do the right thing, except when $i equals W, in which case they both take on the value 0, rather than ~0. I'm looking for a way to do this that does not require computing W first. EDIT: OK, I thought of an ugly, plodding solution $i < 1 ? 0 : do { my $j = 1 << $i - 1; $j < $j << 1 ? ( $j << 1 ) - 1 : ~0 } or $i < 1 ? 0 : ( 1 << ( $i - 1 ) ) < ( 1 << $i ) ? ( 1 << $i ) - 1 : ~0 (Also impractical, of course.) 1 I'm using the strange notation E<$i> as shorthand for "expression based on $i". 2 I don't have a strong preference at the moment for what E<$i> should evaluate to when $i is strictly greater than W. A: On systems where eval($Config{nv_overflows_integers_at}) >= 2**($Config{ptrsize*8}) (which excludes one that uses double-precision floats and 64-bit ints), 2**$i - 1 On all systems, ( int(2**$i) - 1 )|0 When i<W, int will convert the NV into an IV/UV, allowing the subtraction to work on systems with the precision of NVs is less than the size of UVs. |0 has no effect in this case. When i≥W, int has no effect, so the subtraction has no effect. |0 therefore overflows, in which case Perl returns the largest integer. I don't know how reliable that |0 behaviour is. It could be compiler-specific. Don't use this!
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2008, Sum two columns from different tables I'm trying to return a table with only 3 columns: CMP, CODE and Totalization. On the first table I need to Sum all the amount data and then group by CODE. Then I query a second table and get the code and Forecast. Finally, I need to sum the sum_cash with Forecast and group them by code. The snippet below works for MySQL, but in SQL server, it keeps giving me this error: "Column 'cash.sum_cash' is invalid in the select list because it is not contained in either an aggregate function or group by. I'm really open to modify the code as long as I can get those 3 columns. I'm Pretty sure the problem relies on the "Totalization" thing. But I'm no expert on SQL server, or any other SQL language, so I really need help for this one. SELECT cash.CMP as 'Name', cash.CODE as 'Code', (cash.sum_cash + bal.FORECAST) as 'Totalization' From( Select CMP, CODE, sum(CASE when BUDGET in ('4','25') then AMOUNT else AMOUNT * -1 end) sum_cash From TEST1 where Nature=12 GROUP BY CODE ) cash, ( SELECT CODE, FORECAST FROM TEST2 where BALANCE_TYPE=-2 ) bal GROUP BY cash.CMP, cash.CODE; A: You are probably getting a syntax error from: Select CMP, CODE, sum(CASE when BUDGET in ('4','25') then AMOUNT else AMOUNT * -1 end) sum_cash From TEST1 where Nature=12 GROUP BY CODE You probably need a full group by: Select CMP, CODE, sum(CASE when BUDGET in ('4','25') then AMOUNT else AMOUNT * -1 end) sum_cash From TEST1 where Nature=12 GROUP BY CMP, CODE or if CMP is functionally dependent on code you can apply an aggregate for CMP to make it valid: Select MAX(CMP) as CMP, CODE, sum(CASE when BUDGET in ('4','25') then AMOUNT else AMOUNT * -1 end) sum_cash From TEST1 where Nature=12 GROUP BY CODE Next thing I find peculiar is that you are doing a cross join between your two sub-selects, are they guaranteed to return exactly 1 row each? I would guess that what you are trying to do should be something like: SELECT cash.CMP as Name, cash.CODE, cash.sum_cash + bal.FORECAST as Totalization From( Select MAX(CMP) as CMP, CODE , sum(CASE when BUDGET in ('4','25') then AMOUNT else AMOUNT * -1 end) sum_cash From TEST1 where Nature=12 GROUP BY CODE ) cash JOIN ( SELECT CODE, FORECAST FROM TEST2 where BALANCE_TYPE=-2 ) bal ON cash.code = bal.code
{ "pile_set_name": "StackExchange" }
Q: java.lang.IllegalArgumentException: URL query string must not have replace block I am using Retrofit and GET Request: @GET("Master/GetConsignerPartyList?prefix={claimId}") Observable<ConsignerPartyResponse> consignerPartyReq(@HeaderMap Map<String, String> headers, @Path("claimId") String search); and getting this error: java.lang.IllegalArgumentException: URL query string "prefix={claimId}" must not have replace block. For dynamic query parameters use @Query. What's going wrong? A: Remove ?prefix={claimId} from your url because query name should not be static in url. @GET("Master/GetConsignerPartyList") Observable<ConsignerPartyResponse> consignerPartyReq( @HeaderMap Map<String, String> headers, @Query("prefix") String search); It's will work :-)
{ "pile_set_name": "StackExchange" }
Q: Is Schnorr's digital signature a non-interactive zero-knowledge proof? If yes, is there any paper that proves it? Unifying Zero-Knowledge Proofs of Knowledge, by Ueli Maurer, argues that Schnorr's interactive protocol is zero-knowledge. If this is true, using the Fiat-Shamir transform, can we convert Schnorr's protocol into a NIZK proof? A: Yes, and in fact, Schnorr's signature scheme was originally described as a non-interactive protocol. I think the confusion around interactivity comes from the fact that the same paper first described a interactive identification scheme, which can be viewed as a specialization of the signature scheme for empty messages. In both schemes, challenges can be generated either interactively or using hashes. The non-interactive variant can be viewed as an application of the Fiat-Shamir transform, although Schnorr did not describe it as such. Note that while more general formulations of the Fiat-Shamir transform involve a random oracle assumption, the Schnorr signature scheme in particular has weaker requirements -- see Navel et al. and Chen et al.
{ "pile_set_name": "StackExchange" }
Q: Python and Pandas: How to make pandas to behavior similarly to numpy.loadtxt? I have a table like this with 12 columns and several lines: 1095 20 27595 14.1 106.4 191 1 0 0 0 6.998509 10.22539 1001 32 9958 10.9 -30.6 13 1 0 0 0 6.908755 9.206132 1122 9 6125.9 23.5 -16.3 14 1 0 0 0 7.022868 8.720281 578 -9 16246 5.9 -25.7 -21 1 0 0 0 6.359574 9.695602 If I use numpy.loadtxt it works very well. However, I would like to use pandas. I have tried something like this df = pd.read_csv('myFile.txt', sep=" ",header=None) However, it is not working. The error is pandas.parser.CParserError: Error tokenizing data. C error: Expected 90 fields in line 2, saw 92 A: You passed a single space as the separator, you could have done sep='\s+' or better is delim_whitespace=True, it failed because your txt file is has a varying number of spaces. In [61]: import io import pandas as pd pd.read_csv(io.StringIO(t), delim_whitespace=True, header=None) t="""1095 20 27595 14.1 106.4 191 1 0 0 0 6.998509 10.22539 1001 32 9958 10.9 -30.6 13 1 0 0 0 6.908755 9.206132 1122 9 6125.9 23.5 -16.3 14 1 0 0 0 7.022868 8.720281 578 -9 16246 5.9 -25.7 -21 1 0 0 0 6.359574 9.695602""" pd.read_csv(io.StringIO(t), delim_whitespace=True, header=None) Out[61]: 0 1 2 3 4 5 6 7 8 9 10 11 0 1095 20 27595.0 14.1 106.4 191 1 0 0 0 6.998509 10.225390 1 1001 32 9958.0 10.9 -30.6 13 1 0 0 0 6.908755 9.206132 2 1122 9 6125.9 23.5 -16.3 14 1 0 0 0 7.022868 8.720281 3 578 -9 16246.0 5.9 -25.7 -21 1 0 0 0 6.359574 9.695602 Or you could have used read_fwf: In [62]: pd.read_fwf(io.StringIO(t), header=None) Out[62]: 0 1 2 3 4 5 6 7 8 9 10 11 0 1095 20 27595.0 14.1 106.4 191 1 0 0 0 6.998509 10.225390 1 1001 32 9958.0 10.9 -30.6 13 1 0 0 0 6.908755 9.206132 2 1122 9 6125.9 23.5 -16.3 14 1 0 0 0 7.022868 8.720281 3 578 -9 16246.0 5.9 -25.7 -21 1 0 0 0 6.359574 9.695602
{ "pile_set_name": "StackExchange" }
Q: How can I solve crash in Xamarin Forms UWP app "The parameter is incorrect." I have a Xamarin Forms app which works fine on iOS and Android. I am adding UWP support to it, and going through each page fixing issues as I go. I've recently run into a crash on one of my pages which gives me the following stack: System.ArgumentException: The parameter is incorrect. element at Windows.UI.Xaml.VisualStateManager.GetVisualStateGroups(FrameworkElement obj) at Xamarin.Forms.Platform.UWP.SwitchRenderer.UpdateOnColor() at Xamarin.Forms.Platform.UWP.SwitchRenderer.OnControlLoaded(Object sender, RoutedEventArgs e) The crash happens after I push the page that contains switches but I don't know exactly what might be causing it and the error message doesn't give any good information. How can I diagnose this or fix the problem? A: As @Jason linked, this is a bug in Xamarin Forms 3.6.0.2XXXX I upgraded to Xamarin Forms 3.6.0.344457 and that solved the problem.
{ "pile_set_name": "StackExchange" }
Q: How to know I have done enough work in one semester? I am a PhD student in computer science (theory). I am worried about my productivity. I try to do as much as possible. I used to take four courses per semester during my first two years of studying. Now I have started doing research. In the last 4 months, I have only read 2-3 proofs and one research paper. It took 2-3 weeks to go over each mathematical proof. Question: How do I know I have done enough work in one semester? I mean is there any parameter to measure the work that I have done in the last semester? I have heard some students read only one research paper per one semester. I can get feedback from my research supervisor, but the problem is he might say I did enough work just to keep my motivation high. A: Everyone works at their own pace; moreover, the pace can fluctuate a lot depending on the time of year, your personal life, and "position of stars in the sky". Even though the semester seems like a decent amount of time to average out those fluctuations, I don't think it is. I would try to use the following criteria to estimate the term success: feedback from your advisor how did the term go compared to the original plan (yep, here I assume that you make the plans for your term/month/week and correct them accordingly. Hopefully, some milestones are discussed with the advisor as well) feedback from your committee (in some universities, Ph.D. students meet with their committee regularly or send them the progress report to hear their feedback) I would certainly not recommend comparing your progress with other students because they are different, they have different goals, and you don't have complete information about their progress either. It is very easy to get discouraged for no reason. To sum it up, I would stress the importance of initial planning and correcting the plans throughout the term. Then, you will have a very good measure of your success. You will end up with a different question of "how to plan", but that is a totally different problem. A: Quality is more important than quantity in research. One solid proof that proves an important result likely matters far more than a bunch of smaller, less significant proofs. Similarly, one big research advance that shows long-term promise will matter more than a bunch of small experiments that don't open any new doors research-wise. Also remember that most research does not succeed at first! I tell my students when they're getting started that research will likely be a bunch of failures punctuated by the occasional success. This is not to discourage them, but rather to get them to realize that the process is slow and winding. At this early stage, I want to get them familiar with the tools they need and the skills they must develop, rather than focusing on early breakthroughs. So don't try to plan your research too closely—you should have some goalposts and markers in mind so that you're not a perpetual grad student, but you don't need to micromanage your work down to the day or week (other than keeping track of external deadlines). Focus on doing the best work you can, and talk to your advisor about your progress. A: Worrying about whether you've been productive enough is not going to make you more productive. I suggest that you diversify your goals for yourself. You mentioned two prongs to your work: reading papers, and writing proofs. See if you can find some additional prongs to add to your definition of "being productive." Here are a few ideas to get you started: Get to know the publications in your area, and figure out what parts of each are of most interest to you. Regularly browse the most recent issues of those publications. Gradually get better at skimming articles to get a general idea what they're about. Develop a system for cataloguing your notes about your journal reading. Attend department seminars. Try to gradually increase your level of understanding of these talks. When you feel ready, start to ask questions, either during the Q&A part at the end, or afterwards, more informally. Form a study group with some fellow students. Attend some thesis defenses. Attend a conference. Start figuring out what you think makes a good talk. Start working on your writing and powerpoint skills. I don't mean that you should necessarily try to do all of the above, and of course, the papers and the proofs do need to continue being in center stage. But a bit of diversification may help you worry less and produce more.
{ "pile_set_name": "StackExchange" }
Q: Geräusch für "Pferd stoppen" Gibt es im Deutschen einen Laut, den man macht, wenn man ein Pferd stoppen möchte und an den Zügeln zieht? A: Willst Du wissen, wie es klingt, oder suchst Du einen Fachausdruck dafür? Falls ersteres, wäre das wohl "Brrrrrrr" - da ich selbst nicht reite, kenne ich das allerdings nur aus Büchern und Filmen (vor allem Western). A: Laut Duden macht man das Geräusch brr. Diese Interjektion ähnelt dem Geräusch, das man macht, um zu zeigen, dass einem kalt ist. Dabei handelt es sich eher um ein Geräusch als ein Wort (auch wenn es im Duden steht). Der entsprechend übliche Gegenlaut (um das Pferd zum Beschleunigen zu bringen) ist ein Schnalzen (Bsp. 4 im DWDS), das ich nicht ausschreiben kann. Bei YouTube kann man sicher Beispiele finden. Tatsächliche Wörter, die der Kommunikation mit dem Pferd dienen und den gleichen Zweck erfüllen: hott (Vorwärts! / Rechts!) und hü (Vorwärts! / Halt!). A: Das gebräuchlichste Wort ist sicherlich das bereits in den anderen Antworten erwähnte Brr! Im südbadischen, bzw bayrischem Raum gibt es allerdings noch folgende Begriffe O! oh! oha!, bzw öha!
{ "pile_set_name": "StackExchange" }
Q: C# File Name Formatted Like a Web Address I've got a file name that I am unable to change. This is an example of what the file name looks like "www.Test.somee.com" If I try and path to this file name in Visual Studio it will error because of all the full stops. What's a way of making C# recognize this is a file name and not code? This is the line I'm using it for. public partial class www.Test.somee.com_Website_Default : System.Web.UI.Page I recieve all these errors for that one line. Error 2 Invalid token '.' in class, struct, or interface member declaration Error 3 Invalid token ':' in class, struct, or interface member declaration Error 5 The namespace '<global namespace>' already contains a definition for 'www' A: You can't have a page that has such name, because it's invalid. (that's what those errors mean) If you want such ugly names, you'd have to substitute . for a different character, for instance _ or -. Please see general guidelines for naming your classes. http://msdn.microsoft.com/en-us/library/ms229040%28v=vs.110%29.aspx
{ "pile_set_name": "StackExchange" }
Q: Python create shell for several processes I have several command execution in python on Windows using subprocess.call(), but for each one I need to execute batch file with environmet setup before calling proper command, it looks like this subprocess.call(precommand + command) Is there way to "create" shell in python that will have batch file executed only once and in that shell command will be executed several times? A: Write commands to a bat-file (tempfile.NamedTemporaryFile()) Run the bat-file (subprocess.check_call(bat_file.name)) (not tested): #!/usr/bin/env python from __future__ import print_function import os import subprocess import tempfile with tempfile.NamedTemporaryFile('w', suffix='.bat', delete=False) as bat_file: print(precommand, file=bat_file) print(command, file=bat_file) rc = subprocess.call(bat_file.name) os.remove(bat_file.name) if rc != 0: raise subprocess.CalledProcessError(rc, bat_file.name)
{ "pile_set_name": "StackExchange" }
Q: C programming Multithreading Segmentation Fault When I run this code I just get a straight up Seg fault. I do not know how to fix it. I am trying to create a simple multithreading programming. It compiles completely fine but it when i run it by typing "./testing", the print statement "what?" at the beginning of the main function won't even print and just seg faults. I've been stuck on this for couple of hours now. Any ideas? Thanks #include <pthread.h> #include <stdio.h> #include <stdlib.h> static pthread_mutex_t mutex1; static pthread_mutex_t mutex2; static int arrayX[4]; static int arrayY[4]; static pthread_t threads[20]; static void *function(void *index) { pthread_mutex_lock(&mutex1); int *in = (int *)index; arrayX[*in]++; pthread_mutex_unlock(&mutex1); pthread_mutex_lock(&mutex2); arrayY[*in]--; printf("X Finished"); pthread_mutex_unlock(&mutex2); } void main() { printf("what?"); //initialize the mutex pthread_mutex_init(&mutex1, NULL); pthread_mutex_init(&mutex2, NULL); //Initialize the arrayX int x = 0; for (x; x < 4; x++) { arrayX[x] = 0; printf("START arrayX[%d]: %d", x, arrayX[x]); } //Initialize the arrayY for (x = 0; x < 4; x++) { arrayY[x] = 0; printf("START arrayY[%d]: %d", x, arrayY[x]); } pthread_mutex_init(&mutex1, NULL); pthread_mutex_init(&mutex2, NULL); int *input = 0; for (x = 0; x < 20; x++) { *input = x % 4; pthread_create(&(threads[x]), NULL, function, input); } } A: int *input = 0 is setting the memory address of input to nullptr, therefor you can't store data in this address because it's invalid, you can simply leave it uninitialized int *input and then when you assign it to an int, the compiler would choose a suitable free memory location and assign the data to it. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static pthread_mutex_t mutex1; static pthread_mutex_t mutex2; static pthread_t threads[20]; static int arrayX[4]; static int arrayY[4]; static void *function (void *index) { int in = *((int *) index); pthread_mutex_lock (&mutex1); arrayX[in]++; pthread_mutex_unlock (&mutex1); pthread_mutex_lock (&mutex2); arrayY[in]--; pthread_mutex_unlock (&mutex2); // printf ("X Finished\n"); } int main (int argc __attribute__((unused)), char **argv __attribute__((unused))) { int x = 0; int *input; printf ("what?\n"); // Initialize the mutex pthread_mutex_init (&mutex1, NULL); pthread_mutex_init (&mutex2, NULL); // Initialize arrayX and arrayY memset (arrayX, 0, sizeof (arrayX)); memset (arrayY, 0, sizeof (arrayY)); // Increment values inside arrays for (x = 0; x < 20; x++) { *input = x % 4; pthread_create (&(threads[x]), NULL, function, input); } // Print array values for (x = 0; x < 4; x++) printf ("arrayX[%d]: %d\n", x, arrayX[x]); for (x = 0; x < 4; x++) printf ("arrayY[%d]: %d\n", x, arrayY[x]); return 0; } Edit: Dereferencing (which means using * operater to asign value to an already declared pointer i.e. *ptr = something) an uninitialized pointer (which means declaring a pointer without assigning value to it i.e. int *pointer;) is not a good pratice, although it may work but it can cause a crash sometimes, this is because the uninitialized pointer may point to a memory address that is being used by the system will cause an Undefined Behaviour and possibly a crash. A corret approach would be to initialize the pointer to NULL or use malloc to get a valid pointer, however when you initialize a pointer to NULL you can not dereference it becuase it's an invalid pointer. So instead of doing: int *input; *input = x % 4; We can do: int *input; input = malloc (sizeof (int)); *input = x % 4; When sending input pointer to one thread then changing its value and sending it to another thread, the input value would be changed in the first thread to the new value as well, this happens because you are sharing the same pointer input (therefore the same memory address) with all the threads. To make sure that every thread gets the intended input value you can do: for (x = 0; x < 20; x++) { // Create a new valid pointer input = malloc (sizeof (int)); *input = x % 4; pthread_create (&(threads[x]), NULL, function, input); } This will pass a different pointer to each thread, However when you dynamically allocate memory using malloc for example, you have to free this allocated memory, we can do that from within each thread: static void *function (void *index) { int *in = (int *) index; pthread_mutex_lock (&mutex1); arrayX[*in]++; pthread_mutex_unlock (&mutex1); pthread_mutex_lock (&mutex2); arrayY[*in]--; printf ("X Finished"); pthread_mutex_unlock (&mutex2); // Freeing the allocated memory free (in); } When creating threads using pthread_creat, the main threads terminates when it hits the end of the main function without waiting for the other threads to finish work, unless you tell the main thread to wait for them, to do that we can use pthread_join: // Create new threads for (x = 0; x < 20; x++) { *input = x % 4; pthread_create (&(threads[x]), NULL, function, (void *) input); } // Wait for the threads to finish for (x = 0; x < 20; x++) { pthread_join (threads[x], NULL); } This will force the main thread to keep running until all the other threads has done their work before it exits.
{ "pile_set_name": "StackExchange" }
Q: how to decrypt Dreamweaver site passwords? When I set a site on the Dreamweaver and configure a server ftp for the site, many times I forgot the passwords so that I want to find a way to recover it. A: The Dreamweaver just gives you the option to export the site manager data. Site=>Manage Sites=>select the site=>export this will save on your computer a readable xml file with extension .ste Just open it in word-pad or any other application to read the xml and search for the needed server password and get the value of the attribute pw in the tag server Then use this javascript function to decrypte the password from this value function decodeDreamWaverPass(hash){ var pass = ''; for (var i=0 ; i<hash.length ; i+=2){ pass+=String.fromCharCode(parseInt(hash[i]+''+hash[i+1],16)-(i/2)); } return pass; } Hope that it will be helpful for you...
{ "pile_set_name": "StackExchange" }
Q: Java Generics : Unchecked cast from List to List I have a warning : Type safety: Unchecked cast from List < capture#10-of ?> to List < Object> There is the call, stock.getListDVD().getListDVD() is an ArrayList<DVD> jTablePanier=new JTableUt(stock.getListDVD().getListDVD(), DVD.class); So i know the class it's a DVD.class private ModelJTableUt model; public JTableUt(List<?> list, Class<?> classGen) { model=new ModelJTableUt((List<Object>) list, classGen); // <-- This line cause the warning, i convert List<?> to List<Object> } public ModelJTableUt(List<Object> list, Class<?> classGen) { How can i resolve this warning without using @SuppressWarning("unchecked") Thanks a lot for your help. It save me many hours. The solution is public JTableUt(List<? extends Object> list, Class<?> classGen){ model=new ModelJTableUt(list, classGen); } List<Object> list; public ModelJTableUt(List<? extends Object> list2, Class<?> classGen) { list = new ArrayList<Object>(); //I construct a new List of Object. for (Object elem: list2) { list.add(elem); } } A: Change List<?> list to List<? extends Object> in : public JTableUt(List<?> list, Class<?> classGen) From Java Generics tutorial : It's important to note that List <Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.
{ "pile_set_name": "StackExchange" }
Q: Search and Replace in PHPMyAdmin database for Wordpress (absolute beginner) I apologise in advance for I know that this question has been asked several times already, but being a complete beginner at wordpress coding and database handling, I am still not sure about what those answers really meant. So having just coded a website and converted it into WordPress, I now find myself having to change all of the localhost strings to the accurate ones, but with hundreds to go through, I just wanted to know if any of you were able to recommend a program or technique within PHPMyAdmin (that I may not be aware of) to avoid having to change them one at a time. Thank you all in advance for your time and attention. A: First, let me start by saying this is very dangerous, especially for an absolute beginner such as yourself. Please use this with extreme caution as you can potentially bring the entire site down by replacing values in your database with the wrong data. With that said, there is a script specifically designed for doing search and replace on the WordPress MySQL database. http://interconnectit.com/products/search-and-replace-for-wordpress-databases/ Here's the direct download link: https://github.com/interconnectit/Search-Replace-DB/archive/master.zip You will extract the folder from the donwloaded zip, then upload the folder to the root of your WordPress install. Once its uploaded just reference the folder in the browser. I always rename the folder to sr (shorthand for search and replace) so its easier to write out the full URL. So as an example, once its in the root of the WordPress install you'd access it like www.example.com/sr/. After you access the script in the browser, you'll have a GUI with two boxes at the top. The first you'll enter the string you're searching for, and the replace string goes in the second box. Your MySQL details/login should already be populated. After entering your S&R terms scroll down and click "Update Details", then do the "Dry Run" option first. It'll run through the database and show you the values that will be changed. If you are satisfied with the changes, click "Live Run". Depending on the database size it'll take just a short time to complete. This is the easiest way to S&R the WordPress database. Important: for security reasons you'll want to delete this folder from your server after you have finished using it. You don't want a database S&R utility just lingering around for no reason. Another possible option if you're familiar with WP-CLI is to use the wp search-replace command: https://developer.wordpress.org/cli/commands/search-replace/ This would be done through Terminal or another command line utility.
{ "pile_set_name": "StackExchange" }
Q: How do I include a lot of log file data in my question? What's the process for including log file data in a question? I'd like to link to it separately, so it doesn't distract from the main question. Does SO provide some sort of external file reference, or do I have to post the file somewhere else and link to it? A: Does SO provide some sort of external file reference, or do I have to post the file somewhere else and link to it? The answer is "No" to both parts. Stack Overflow does not have a file hosting service (apart from an agreement with imgur for image files). Next, you should not link the entire log file from your question. (This would still be true even if there was a Stack Overflow file service.) If it's too much information to be copy-pasted into the question itself, then you should trim it until the relevant parts do fit. Figuring out which parts are relevant is part of the work you need to do before asking a question, just as you're expected to create a Minimal, Complete, Verifiable Example for specific code that's acting incorrectly. A: The problem with external links is that if you don't maintain it, your question will become obsolete in time. You might just need to take your logs and cut some data to just show what's relevant, and then copy that in your question.
{ "pile_set_name": "StackExchange" }
Q: Adding disqus to a meteor.js project i am trying to add the disqus commentsystem to my application. I followed the instruction written in this article KLICK I created a template called disqus.html <template name="disqus"> {{#isolate}} <div id="disqus_thread"></div> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> {{/isolate}} </template> If this template is rendered, embed.js should load once and disqus makes a reset. Template.disqus.rendered = function() { Session.set("loadDisqus", true); return typeof DISQUS !== "undefined" && DISQUS !== null ? DISQUS.reset({ reload: true, config: function() {} }) : void 0; }; React on sessionchange in deps.autorun Meteor.startup (function () { Deps.autorun(function() { if(Session.get("loadDisqus") && !window.DISQUS) { var disqus_shortname = '<example>'; // required: replace example with your forum shortname (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); } }); }); This works fine in Firefox 25.0.1. I can login, logout and create comments. But it isnt working in Chrome 31.0.1650.57 m. It is not possible for me to login. No error is thrown. What can i do? Any suggestions? Even a login to disqus in discovermeteor.com/... is not possible for me. A: Using session here is interesting but unnecessary. Here is what i migth do in your disqus.js file: var isDisqusLoaded = false, myScriptLoader = function funcMyScriptLoader(jsEl, callback) { if (window.attachEvent) { // for IE (sometimes it doesn't send loaded event but only complete) jsEl.onreadystatechange = function funcOnReadyStateChange() { if (jsEl.readyState === 'complete') { jsEl.onreadystatechange = ""; } else if (jsEl.readyState === 'loaded') { jsEl.onreadystatechange = ""; } if (typeof callback === 'function') { callback(); } }; } else { // most browsers jsEl.onload = function funcOnLoad () { if (typeof callback === 'function') { callback(); } }; } }; Template.disqus.rendered = function funcTplDisqusRendered() { if (!isDisqusLoaded) { var myElJs = document.createElement('script'), s = document.getElementsByTagName('script')[0]; myElJs.type = 'text/javascript'; myElJs.async = true; myElJs.src = '//' + disqus_shortname + '.disqus.com/embed.js'; myScriptLoader(myElJs, function funcEventLoaded() { isDisqusLoaded = true; }); s.parentNode.insertBefore(myElJs, s); } }; Using that script you won't need to use Deps.autorun and Session. You should use that kind of feature only where you want to get realtime, but if don't need it, avoid it coz it will degrade your app performance. You can add Disqus.reset if it's really needed but i'm not sure, look at the disqus documentation. I didn't test the script but it should be ok.
{ "pile_set_name": "StackExchange" }