text
stringlengths
64
81.1k
meta
dict
Q: What level of math is required for machine learning research There are several levels of math understanding: Know the math Know the intuitions behind math concepts Know the intuitions and proofs of math concepts Know the intuitions, proofs of math concepts and be able to apply them to deduce new results My question is what level of understanding is required for machine learning research? Especially for publishing papers in conferences like CVPR or NeurIPS. A: There can be no objective answer to this question. Obviously the more one understands the better, but the field of ML is vast, quite specialized and ranges from very theoretical to very applied research, so it's perfectly reasonable to publish in ML without a strong background in maths. A better way to estimate your own ability to publish papers in a particular area or journal is to study recent papers published in this area/journal. You should be able not only to understand them but to redo the reasoning: Understand the problem and the solution proposed by the authors starting from the initial problem, how would you solve it? Can you think of alternatives to the authors' solution? Can you find limitations to their approach and improve on it? If you reach step 3 then congratulations: you are ready to publish your own research!
{ "pile_set_name": "StackExchange" }
Q: What's 'fs:[0]' doing and how can I execute it step by step? In a 32 bits Windows binary, I see this code: push next push fs:[0] mov fs:[0], esp int3 ... next: I see that something happens on the int3 (an error), but I don't understand why, and how to follow execution while keeping control. A: TL;DR the first 3 lines set an exception handler (an 'error catcher') the int3 generates an exception execution resumes at next Explanation this trick is (ab)using Structured Exception Handling, a mechanism to define exception handlers, typically by compilers when try/catch blocks are used. In 32bits versions of Windows, they can be set on the fly, without any pre-requirement (unless the binary is compiled with /SafeSEH). The first element of the exception handlers' chain is pointed by the first member of the Thread Information Block (TIB), in turn a member of the Thread Environment Block (TEB), which is pointed to by fs:0 (which is also reachable 'directly' - via something like ds:7efdd00, depending on the OS version etc) So here is what happens: the first two push reserve stack space for the structure _EXCEPTION_REGISTRATION_RECORD. the new top handler the previous top handler, which was until now at fs:[0] the mov sets the current stack position as the new structure. When an exception happens, next will be now the first called handler. int3 triggers an exception instantaneously (there are many other kinds of exception triggers). as an exception is triggered, Windows dispatches the exception to the first handler, and the next one if it's not handled, until one of them has handled it. Following execution This is done here under OllyDbg 1.10. YMMV. As we want to go through exceptions ourselves, we have to ask OllyDbg not to handle them: go to debugging options: Alt-O, tab Exceptions unselect INT3 breaks And when an exception is triggered, we have to enforce that execution is done via exceptions (see below). Here are 3 methods of increasing level to follow the exception handling execution safely: step by step: set a breakpoint manually As the handler has just been set on the stack, you can manually set a breakpoint then run. select the new handler address on the stack Right-click or F10 select Follow in Dump in the dump window, open the menu (same shortcut) select BreakPoint, then Hardware, on execution Execute: menu Debug/Run / shortcut F9 / command-line g Exceptions will be triggered Execute with exception handling: shortcut Shift-F9 / command-line ge. shortcut: execute until exception handler via command-line as the address is on the stack, the easiest way is to type via the command line ge [esp+4], which means, Go with Exceptions, until the 2nd address on the stack is encountered. Thus, no need to set and unset a breakpoint. in the case of a more complex example, where the address might not be obvious on the stack anymore, then the absolute formula would be ge ds:[fs:[0]+4], which just gets the actual address from the TIB. keeping full control: break on KiUserExceptionDispatcher KiUserExceptionDispatcher is the Windows API handling all user-mode exceptions. Setting a breakpoint there guarantees that you keep full control - but then, you're in the middle of a Windows API ;) In this case, you can ask OllyDbg to skip exceptions, as you will still break execution manually in any cases. You might also want to combine that with a script. Of course, some advanced code might check that you set a breakpoint on it before triggering an exception.
{ "pile_set_name": "StackExchange" }
Q: How to construct a good PRF from a block cipher? We want to explicitly construct a good (as tentatively defined below) Pseudo-Random Function $F$ with $b$-bit input and output, from (preferably just) one Pseudo-Random Permutation $E$ of $b$-bit, as instantiated in practice by TDEA for $b=64$ or AES-256 for $b=128$, and one fixed random secret key. I tentatively define a good PRF to be one indistinguishable (with small constant advantage) from a random function, assuming $2^{b(1-\epsilon)}$ queries to an oracle implementing our construction of $F$ from $E$, and delegating invocations of $E$ (edit: and in addition of $E^{-1}$ if that helps) to a random oracle for that. Fix this definition as necessary (Update: I'm told by the answers that for $\epsilon<1/2$, this is roughly what's called a PRF with beyond the birthday bound security). Are there simple constructions of $F$ from $E$ with a security argument? $F(x)=E(x)$ is squarely unfit: it can be distinguished from a random function by detecting collisions after $2^{b/2}$ distinct queries, which happens with sizable probability for a random function but not for a random permutation. That can even be done with constant memory, using Floyd's cycle finding. A distinguisher can also be built against $F(x)=E(x)\oplus x$. Right now I fail to find a distinguisher for $F(x)=E(E(x)\oplus x)$, but that's not even a weak security argument. Update: If the security of that is unprovable, I'm still interested by a distinguishing attack, in order to get a feeling of how insecure in practice that could be. A: What you're looking for is often called a construction of a PRF with "beyond the birthday bound security," and you can probably find some constructions by searching on variants of that term. For concreteness, this paper by Iwata (alternate link) almost gives a solution to your problem: The only deficiencies are that the resulting $F$ has inputs one bit narrower than $E$, and it does not achieve your definition of security for every $\varepsilon > 0$. Specializing that construction down to your setting, and using your notation, it defines $F(x)$ for $x\in\{0,1\}^{b-1}$ as $$F(x) = E(x\|0)\oplus E(x\|1),$$ where $\|$ denotes concatenation. Its proof applies for a number queries well beyond $2^{b/2}$, which is obviously non-trivially better than the direct $F(x) = E(x)$ construction. A: I agree with David Cash that what you are looking for is a construction of a PRF with "beyond the birthday bound" security. There has been a variety of work on this topic. Stefan Lucks analyzes several simple constructions: SUM$^2$: Here $F_{K,K'}(x) = E_K(x) \oplus E_{K'}(x)$. This has security for up to about $2^{2b/3}$ queries, which is better than the trivial construction. SUM$^d$: This is the obvious generalization: $F_{K_1,\dots,K_d}(x) = E_{K_1}(x) \oplus \dots \oplus E_{K_d}(x)$. This has security up to about $2^{db/(d+1)}$ queries. TWIN$^2$: Here $F_K(x) = E_K(x||0) \oplus E_K(x||1)$ (the same construction as David Cash mentions). This has security for up to about $2^{2b/3}$ queries. TWIN$^d$: Here $F_K(x) = E_K(dx+0) \oplus E_K(dx+1) \oplus \dots \oplus E_K(dx+d-1)$, where we consider $0 \le x <2^b/d$. This has security up to about $2^{db/(d+1)}$ queries. Here is the paper: The Sum of PRPs is a Secure PRF, Stefan Lucks. Eurocrypt 2000. I think there is still more work out there on this topic. A: I think this paper may help: M. Bellare, T. Krovetz and P. Rogaway (1998), "Luby-Rackoff backwards: Increasing security by making block ciphers non-invertible", Advances in Cryptology - EUROCRYPT '98, Lecture Notes in Computer Science, Vol. 1403. "Abstract: We argue that the invertibility of a block cipher can reduce the security of schemes that use it, and a better starting point for scheme design is the non-invertible analog of a block cipher, that is, a pseudorandom function (PRF). Since a block cipher may be viewed as a pseudorandom permutation, we are led to investigate the reverse of the problem studied by Luby and Rackoff, and ask, how can one transform a PRP into a PRF in as security-preserving a way as possible? The solution we propose is "data-dependent re-keying." As an illustrative special case, let $E: \{0,1\}^n \times \{0,1\}^n \to \{0,1\}^n$ be the block cipher. Then we can construct the PRF $F$ from the PRP $E$ by setting $F(k,x) = E(E(k,x),x)$. We generalize this to allow for arbitrary block and key lengths, and to improve efficiency. We prove strong quantitative bounds on the value of data-dependent re-keying in the Shannon model of an ideal cipher, and take some initial steps towards an analysis in the standard model." A PDF of the paper is available here. (The PDF link on the abstract page is wrong, it leads to the PS version.)
{ "pile_set_name": "StackExchange" }
Q: Limits question. $\lim_{x\to0}\space \frac {\sin(\pi (\cos ^2 (x)))}{x^2}$ Please solve this limit question without using L'Hopital's Law... $$\lim_{x\to0}\space \frac {\sin(\pi (\cos ^2 (x)))}{x^2}$$ A: Use equivalents, more precisely, $\sin u\sim_0 u$. Note first that $\;\sin(\pi\cos^2x)=\sin(\pi-\pi\sin^2x)=\sin(\pi\sin^2x)$, hence $$\frac{\sin(\pi\cos^2x)}{x^2}=\frac{\sin(\pi\sin^2x)}{x^2}\sim_0\frac{\pi\sin^2x}{x^2}\sim_0\frac{\pi \,x^2}{x^2}=\pi.$$
{ "pile_set_name": "StackExchange" }
Q: Why two seperataly doped semiconductors cannot be joined to form a junction? My textbook says that when a slab of P-type semiconductor and another slab of N-type semiconductor are joined, they cannot form a junction because no matter however smooth the surface is, there will always be some irregularities present in it and hence continuous contact will not be possible. Why is this continuous contact necessary? Maybe it is necessary for electrons to jump from one slab to another. But in case of two metallic slabs, we can make electricity flow in it. How is this happening? In other words, how are electrons trapped at the interface of a semiconductor but are not at the interface of a metal? A: At the interface of semiconductors, the silicon structure ends abruptly causing unwanted effect. Silicon atoms will not be able to make the usual 4 covalent bonds, causing electrons to be "trapped" more easily. These trapped states are annoying and will have several undesired effects. For all practical purposes, that destroys the diode characteristic. The whole idea of a PN junction depends on the flow of holes and electrons and how they balance out. However, in metals, there's only one game in town: electrons... Free electrons, and lots of it! Having a few irregularities at a metal contact is not that big of a deal if you have so many free charge carriers floating around. If you sandwich the metal between the junctions, however, you remove any "semiconductor interaction" as you force holes and electrons indiscriminately through that sea of electrons. Holes are immediately recombined, electrons get lost in the sea. That being said, some rectifying behavior can still happen for a metal-semiconductor junction (as is the case for a schottky diode). But it will not be the same curve as a PN junction.
{ "pile_set_name": "StackExchange" }
Q: Shouldn't we have a "differences" tag? Is there a point in that? There seems to be a lot of questions that deal with the differences, pros and cons of using one expression compared to another one. Should all this questions be filed under the "differences" tag, or is that the wrong approach? A: I'd think that questions discussing when to use one fragment over the other easily falls under grammar. Or even usage.
{ "pile_set_name": "StackExchange" }
Q: adding search bar to the nav menu in wordpress http://www.lundarienpress.com/ ( this is a wordpress site) This is my site, I am trying to add a search bar to the nav menu and have it to the right. Any ideas ? I have not found a way to do it. I am hoping some one from the forum can help me. A: @rockmandew is right - this code shouldn't work without setting get_search_form() to false. But even after making that change, the function wouldn't work. I initially added a search form to my nav menu by adding this to my functions file: /** * Add search box to nav menu */ function wpgood_nav_search( $items, $args ) { $items .= '<li>' . get_search_form( false ) . '</li>'; return $items; } add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 ); This is a good solution if you have one menu or want a search box added to all menus. In my case, I only wanted to add a search box to my main menu. To make this happen, I went with this: /** * Add search box to primary menu */ function wpgood_nav_search($items, $args) { // If this isn't the primary menu, do nothing if( !($args->theme_location == 'primary') ) return $items; // Otherwise, add search form return $items . '<li>' . get_search_form(false) . '</li>'; } add_filter('wp_nav_menu_items', 'wpgood_nav_search', 10, 2); It's worth noting my main nav is named 'primary' in my functions file. This can vary by theme, so this would need to be changed accordingly, i.e. 'main' or as in the initial solution, 'header_menu'. A: Function.php code: function add_last_nav_item($items, $args) { if ('header_menu' === $args->menu_id) { $homelink = get_search_form(false); $items .= '<li>'.$homelink.'</li>'; return $items; } return $items; } add_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2 ); Here get_search_form() is function to get search box.
{ "pile_set_name": "StackExchange" }
Q: Noob seeking help with Database [Access] I'm fairly new at access and I have no clue how to handle this situation. I dont even know where to start so any help would be greatly appreciated. So I have to design this data base that has items such as "audio board X.xx" When a customer orders lets say "audio board 2.4", the database will know that the board requires 2x4K Resisters and 4x2uf Capacitors and 2X4401 BJTs. And it would automatically pull them from the inventory when processing this order so later on I can just look at the inventory list lets say at the end of the week and will know what parts i would need to order to restock. now, i looked for help online, the only thing i could find similar was something called "Bill of Materials" AKA "BOM" sheets or something... but none of them told me how to make one or anything like that. I'm really new at this, and am a total noob. I'm using Access 2010. Any Help would be appreciated. A: First, read http://r937.com/relational.html You will need a design on the lines of: Parts ID -->Primary key Description Etc Components ID -->Primary key Description Etc PartsComponents --> Junction table PartID ---) ?? ComponentID ---) If a part can have only one of each component, life is simple enough and PartID + ComponentID is your primary key, if a part can only have a set number of a particular component, it may be possible to treat the set as a single item, if the part can have a variable number of a component, things get a little more complicated. A quantity field in the junction table would probably work, though. You then have a fairly standard set of tables for customers and orders, including an order detail table, which gets updated by an append query from the junction table information when a customer selects a part.
{ "pile_set_name": "StackExchange" }
Q: Use QgsAbstractProviderConnection in PyQGIS (3.14) I created a PostGIS connection named 'test_conn' and try to access it via from qgis.core import QgsAbstractProviderConnection con = QgsAbstractProviderConnection('test_conn') as described in https://qgis.org/pyqgis/master/core/QgsAbstractProviderConnection.html?highlight=qgsabstractproviderconnection#module-QgsAbstractProviderConnection but I get Traceback (most recent call last): File "C:\OSGEO4~1\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> TypeError: qgis._core.QgsAbstractProviderConnection represents a C++ abstract class and cannot be instantiated Is this intended behavior or a bug or am I missing something? A: Works with this code: p = QgsProviderRegistry.instance().providerMetadata('postgres') con = p.connections()['test_con'] con.executeSql('SELECT * FROM mytable')
{ "pile_set_name": "StackExchange" }
Q: How to display Custom local page if url fails to load in Cordova inappbrowser I am Using InApp browser and calling a page. What I want is that if the Internet is connected to a device then it has to display the url and if is not connected then it displays the local page. function onDeviceReady() { document.addEventListener('pause', onPause.bind(this), false); document.addEventListener('resume', onResume.bind(this), false); var inAppBrowserbRef; inAppBrowserbRef = window.open('http://www.xxxxx.com', '_self', 'location=no,toolbar=no'); inAppBrowserbRef.addEventListener('loadstart', inAppBrowserbLoadStart) inAppBrowserbRef.addEventListener('loadstop', inAppBrowserbLoadStop); inAppBrowserbRef.addEventListener('loaderror', inAppBrowserbLoadError); inAppBrowserbRef.addEventListener('exit', inAppBrowserbClose); function inAppBrowserbLoadStart(event) { var options = { dimBackground: true }; SpinnerPlugin.activityStart("Loading...", options); if (navigator.connection.type == Connection.NONE) { navigator.notification.alert('An internet connection is required to continue', alertSuccess, "Network Error", "Ok"); } function alertSuccess() { navigator.app.exitApp(); } } function inAppBrowserbLoadStop(event) { SpinnerPlugin.activityStop(); if (navigator.connection.type == Connection.NONE) { navigator.notification.alert('An internet connection is required to continue', alertSuccess, "Network Error", "Ok"); } function alertSuccess() { navigator.app.exitApp(); } } function inAppBrowserbLoadError(event) { SpinnerPlugin.activityStop(); if (navigator.connection.type == Connection.NONE) { navigator.notification.alert('An internet connection is required to continue', alertSuccess, "Network Error", "Ok"); } function alertSuccess() { navigator.app.exitApp(); } } function inAppBrowserbClose(event) { SpinnerPlugin.activityStop(); inAppBrowserbRef.removeEventListener('loadstart', iabLoadStart); inAppBrowserbRef.removeEventListener('loadstop', iabLoadStop); inAppBrowserbRef.removeEventListener('loaderror', iabLoadError); inAppBrowserbRef.removeEventListener('exit', iabClose); } Does anyone know where I have to put redirect page? A: You'll want to use the cordova-plugin-network-information plugin (which it looks like you're using) to detect online/offline state. In your onDeviceReady() event handler you can add listeners to respond to the offline/online events: document.addEventListener("offline", goOffline, false); document.addEventListener("online", goOnline, false); function goOffline() { // Redirect to your local/offline page here } function goOnline() { // Load the actual online content in InAppBrowser }
{ "pile_set_name": "StackExchange" }
Q: Android parse.com setObjectId How set objectId with Parse.com with primary key.Can you help me ? When i create new row, i want setObjectId of row. final ParseObject parseObject = new ParseObject(ChapsModel.PARSE_OBJECT); parseObject.put(ChapsModel.PARSE_FIELD_NAME_CHAPS, chapsModel.get(i) .getNamChap()); parseObject.put(ChapsModel.PARSE_FIELD_LINK_CHAP, chapsModel.get(i) .getLinkChap()); parseObject.put(ChapsModel.PARSE_FILED_TEAM_TRANSLATE, chapsModel.get(i) .getTeamTranslate()); parseObject.put(ChapsModel.PARSE_FIELD_OBJECT_MANGA, ParseObject.createWithoutData(MangaModel.PARSE_OBJECT, chapsModel.get(i) .getObjectManga())); parseObject.saveInBackground(new SaveCallback() { @Override public void done(final ParseException e) { if (e == null) { Log.e(">>>>>", "done" + ojectId); // parseObject.setObjectId(ojectId); } else { Log.e(">>>>>", "else" + e.getMessage()); } } }); Log java.lang.RuntimeException: objectIds cannot be changed in offline mode. Log: Sorry my english. thank A: It's not possible to set objectId with Parse.com with primary key. Although parse.com doesn't allow us to set the objectId of a row, you can create a new column named anything you want and you can set that new column to any objectId you want. For example, you can create a new column named myObjectId and set it to a string. From the parse.com website at https://www.parse.com/docs/js/guide#cloud_code The Data Browser The Data Browser is the web UI where you can update and create objects in each of your apps. Here, you can see the raw JSON values that are saved that represents each object in your class. When using the interface, keep in mind the following: The objectId, createdAt, updatedAt fields cannot be edited (these are set automatically).
{ "pile_set_name": "StackExchange" }
Q: Resistance between VCC and GND drops to 3k Ohms I am kind of lost because of this problem. When my board is connected to my power supply and up and running the resistance between VCC and GND is at about 18M-Ohms. As soon as I power the board off, and it's no longer running, the resistance between VCC and GND drops slowly to about 3k-Ohms, then stays there. What could be causing this? A: What could be causing this? When the board is off this is a little unusual because most often the leakage current through transistors or loads when the power is off is in the 1-100kΩ range for most of the boards I have with voltage regulators on them. If you had something with a high side switch or a relay this could explain why the numbers are so high. When the board is on, it really matters how your meter is measuring current, and often doesn't make sense. If you really want to find the equivalent load, measure both voltage and current going into the board with a nice digital power supply or a power supply and a multimeter to measure current. Then use this equation. \$ R_{eq}=V/I\$
{ "pile_set_name": "StackExchange" }
Q: VB.NET convert 24hours mySQL TIME() to 12hours format Okay, I know there are similar post to this. But all I can see is they are using DATETIME() data type, mine is TIME() only. I manage to store time using mysql time(now()). The format it stored is in 24hours format. When I retrieve its value to some label in VB.NET I need to display it in 12 hours format. What I have done so far is the code below. but no luck. dataSet = New DataSet adapter.SelectCommand.CommandText = "SELECT timein_pm from dtr WHERE cats_id='" & Trim(lblId.Text) & "'" adapter.Fill(dataSet) Label6.Text = dataSet.Tables(0).Rows(0)("timein_pm").ToString("hh:mm tt") How do I do it? Also is it possible to do it via mySQL time format or something? EDITED: Database Values: id date timein_pm id 57 2013-12-04 15:24:13 0828 A: If you need a MySQL solution you can use TIME_FORMAT() function SELECT TIME_FORMAT(timeout_pm, '%h:%i:%s %p') time_12h FROM dtr WHERE ... Here is SQLFiddle demo
{ "pile_set_name": "StackExchange" }
Q: When does a Perl script need to call `tzset` before calling `localtime`? I recently learned how to change the timezone returned by localtime in Perl. use POSIX qw(tzset); print localtime . "\n"; $ENV{TZ} = 'America/Los_Angeles'; print localtime . "\n"; tzset; print localtime . "\n"; Outputs Wed Apr 15 15:58:10 2009 Wed Apr 15 15:58:10 2009 Wed Apr 15 12:58:10 2009 Notice how the hour only changes after calling tzset. This is perl, v5.8.8 built for x86_64-linux-thread-multi However, on my systems I'm getting, Fri Jul 8 19:00:51 2016 Fri Jul 8 16:00:51 2016 Fri Jul 8 16:00:51 2016 Notice how on my system, the hour changes without calling tzset. This holds true on recent versions of Perl in Ubuntu and Illumos, as well as Perl v5.8.8 on Solaris 10. So if all my tests indicate that tzset has no effect, why / what other systems require tzset to be called explicitly? Do I still need to call tzset to remain compatible with certain environments, or is it now a thing of the past? A: TL;DR: Starting with Perl v5.8.9 (released in 2011) calling tzset when changing $ENV{TZ} isn't needed anymore. Perl's localtime calls localtime_r(3) internally, which isn't required to call tzset(3). The Linux manpage advises: According to POSIX.1-2004, localtime() is required to behave as though tzset(3) was called, while localtime_r() does not have this requirement. For portable code tzset(3) should be called before localtime_r(). In older non-multithreaded Perls, or if localtime_r(3) wasn't available during build, localtime(3) is used instead. In that case, a call to tzset would have been unnecessary, per POSIX: Local timezone information is used as though localtime() calls tzset() although there seem to have been times where glibc didn't adhere to that: As for any code which doesn't call tzset all the time: this definitly won't change. It's far too expensive. And for what? The 0.000001% of the people who take the laptops on a world tour and expect, e.g., syslog messages with dates according to the native timezone. This is not justification enough. Just restart your machine. This did change though and glibc now does act as if tztime(3) was called, but only for non-reentrant localtime which might not be what your Perl was compiled to use. There have been two Perl bug reports regarding this: #26136 and #41591. As a fix, Perl now decides at configuration time whether an implicit tzset(3) needs to be done, which makes specifying it in user code superfluous.
{ "pile_set_name": "StackExchange" }
Q: Can someone explain to me how to download a file asynchronously from parse using PFFile? Ive been stuck on this problem for a good while now, I read a bunch of threads but none describe my problem I tried a whole bunch of different methods to do it but none worked. I have a PFFile that I pulled from array and sent through a segue to a download detail view. This file is called "download file".I am trying to program a button when clicked to initiate the download. here is the code: this is my download detail.h #import <UIKit/UIKit.h> #import <Parse/Parse.h> @interface PDFDetailViewController : UIViewController { } @property (strong, nonatomic) IBOutlet UILabel *PDFName; @property (strong, nonatomic) IBOutlet UILabel *PDFDescription; @property (strong, nonatomic) NSString* PDFna; @property (strong, nonatomic) NSString* PDFdes; @property (retain,nonatomic) PFFile * downloadfile; - (IBAction)Download:(id)sender; @end my download detail button - (IBAction)Download:(id)sender { [self Savefile]; } -(void) Savefile { NSData *data = [self.downloadfile getData]; [data writeToFile:@"Users/Danny/Desktop" atomically:NO]; NSLog(@"Downloading..."); } @end and here is the segue that sends the download file: detailVC.downloadfile=[[PDFArray objectAtIndex:indexPath.row]objectForKey:@"PDFFile"]; I get the array data using the PFQuery and store it into "PDFArray". This is a synchronous download because a warning message comes up when i click the button saying that main thread is being used. Although the file doesn't show up on my desktop. A: Have you tried using this Parse method? getDataInBackgroundWithBlock: -(void) Savefile { [self.downloadfile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) { if (error) { // handle error } else if (data) { [data writeToFile:@"Users/Danny/Desktop" atomically:NO]; } }]; }
{ "pile_set_name": "StackExchange" }
Q: Displaying array as tree structure in php I have an array: Array ( [0] => dir0|file0.txt [1] => dir0|file1.txt [2] => dir1|file2.txt [3] => dir1|filea.txt [4] => dir2|fileb.txt ) I would like it to be displayed as a tree, such as: dir0 file0.txt file1.txt dir1 file2.txt filea.txt dir2 fileb.txt Can any one explain how I can do that? Edit: Updated for multidimentional array: $paths[0][0] = 'dir0|file0.txt'; $paths[0][1] = 400; $paths[1][0] = 'dir0|filea.txt'; $paths[1][1] = 500; $paths[2][0] = 'dir1|file1.txt'; $paths[2][1] = 600; $paths[3][0] = 'dir1|fileb.txt'; $paths[3][1] = 700; $paths[4][0] = 'dir2|filec.txt'; $paths[4][1] = 700; I would like the output to be: dir0 (900) file0.txt (400) filea.txt (500) dir1 (1300) file1.txt(600) fileb.txt (700) dir2 (700) filec.txt (700) The values need to be added and displayed in root. A: The best way would be to reformat the array so the keys were the directories, and the array values were arrays containing file names, like so: $array = array( ..); $reformatted = array(); foreach( $array as $k => $v) { list( $key, $value) = explode( '|', $v); if( !isset( $reformatted[$key])) $reformatted[$key] = array(); $reformatted[$key][] = $value; } Then you just have to iterate over the new array, like so: foreach( $reformatted as $dir => $files) { echo $dir . "\n"; foreach( $files as $file) echo "\t" . $file . "\n"; } This outputs: dir0 file0.txt file1.txt dir1 file2.txt filea.txt dir2 fileb.txt Note that this will only work for plain text environment (such as <pre></pre>, like in the demo). Otherwise, you'll need to use <br /> instead of \n for line breaks, or use an ordered or unordered list. For HTML output, use this, whose output can be seen here echo '<ul>'; foreach( $reformatted as $dir => $files) { echo "<li>$dir</li>"; echo '<ul>'; foreach( $files as $file) echo "<li>$file</li>"; echo '</ul>'; } echo '</ul>'; Generates: dir0file0.txtfile1.txtdir1file2.txtfilea.txtdir2fileb.txt For your updated array, here is the solution: $reformatted = array(); $weights = array(); foreach( $paths as $k => $v) { list( $key, $value) = explode( '|', $v[0]); if( !isset( $reformatted[$key])) $reformatted[$key] = array(); if( !isset( $weights[$key])) $weights[$key] = 0; $reformatted[$key][] = array( $value, $v[1]); $weights[$key] += $v[1]; } foreach( $reformatted as $dir => $files) { echo $dir . ' (' . $weights[$dir] . ")\n"; foreach( $files as $file) echo "\t" . $file[0] . ' (' . $file[1] . ")\n"; } This outputs: dir0 (900) file0.txt (400) filea.txt (500) dir1 (1300) file1.txt (600) fileb.txt (700) dir2 (700) filec.txt (700) I'll leave it up to you to translate that into HTML if necessary.
{ "pile_set_name": "StackExchange" }
Q: Multiple Divs follow cursor all with variable speeds I've done some research on how to get a div/graphic to follow the cursor - Resource Here - I am trying to create this effect for multiple divs where each div has it's own random speed where some elements are lagging behind more than others. I have created a JS Fiddle to show the current progress, you can see it kind of works to some extend. But I am hoping to achieve a more dramatic effect than what I currently have. JS Fiddle Code HTML <div class="container"> <div class="following blue"></div> <div class="following red"></div> <div class="following yellow"></div> <div class="following orange"></div> <div class="following green"></div> <div class="following purple"></div> <div class="following pink"></div> </div> Code JS var mouseX = 0, mouseY = 0, limitX = 400 - 15, limitY = 550 - 15; $(window).mousemove(function(e) { // with the math subtractnig the boundary mouseX = Math.min(e.pageX, limitX); mouseY = Math.min(e.pageY, limitY); }); // cache the selector var followers = $(".following"); var x_pixels = 0, y_pixels = 0; var loop = setInterval(function() { // Loop through each follower to move and have random speeds followers.each(function() { // Set a max Number to allow for the randomIntFromInterval // function to work var max = followers.length * 15; var min = followers.length; x_pixels += (mouseX - x_pixels) / randomIntFromInterval(min, max); y_pixels += (mouseY - y_pixels) / randomIntFromInterval(min, max); $(this).css({ left: x_pixels, top: y_pixels }); }); }, 40); function randomIntFromInterval(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } Any advice on how to do this is greatly appreciated. Thanks! A: Let's start with why it isn't too random. First off these calculations are run for each dot every 40ms. This has interesting consequences. x_pixels += (mouseX - x_pixels) / randomIntFromInterval(min, max); y_pixels += (mouseY - y_pixels) / randomIntFromInterval(min, max); Say the blue dot gets a set of random numbers {1, 4, 7, 8, 4, 3, 10, 6, 6} and the red dot gets a set of random numbers {8, 7, 5, 4, 5, 7, 9, 4, 3}. The problem is the average of these is going to be the same (5.44 and 5.77 respectively). Because the movements are happening so fast they have a little jitter but their bigger movements tend to be the same. The second problem is that you are using the same x_pixels and y_pixels for each dot. You declare this on top: var x_pixels = 0, y_pixels = 0; But then you don't ever go get the current value back from the dot. You recycle them by += but each dot shares the same position. I have two solutions for you as this problem is fairly broad and could be interpreted multiple ways. Both of these solutions address the problems listed above by assigning a friction coefficient that stays with the dot. The first example keeps the random friction for the lifetime of the dot, the second changes the friction coefficient every so often. jsfiddle.net/e3495jmj/1 - First solution jsfiddle.net/e3495jmj/2 - Second solution Cheers!
{ "pile_set_name": "StackExchange" }
Q: How to conditional render vue.js on template tag? I'm studying vue.js through reference document on Vue.js Reference Doc. and then, i'm following up example. but, conditional part example dosen't work. this is my code. <template id="app-3"> <div v-if="ok"> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> </div> </template> <script src="vue.js"></script> <script> var app = new Vue({ el : '#app-3', data : { ok : true } }); </script> and this code is work. <transition id="app-3"> <template v-if="ok"> <div> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> </div> </template> </transition> <script src="vue.js"></script> <script> var app = new Vue({ el : '#app-3', data : { ok : true } }); </script> i want to know first code why doesn't work! A: @xyiii pointed the error that is displayed in the console. As you commented on @xyiii answer: hmm so, Vue.js Doc example is wrong code? Nope. They are just explaining the case where you want to toggle multiple elements depending on same property. So instead of doing it like this: Title Paragraph 1 Paragraph 2 You can group them in a template tag and do it like this: <template v-if="ok"> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p> </template> <template> tag is just like a placeholder. It will not be rendered on to the DOM. So you can have two root elements by mistake as: <template v-if="ok"> <div>Root element 1</div> <div>Root element 2</div> </template> So to prevent this vue throws an error. To know why only one root element checkout @LinusBorg's comment here.
{ "pile_set_name": "StackExchange" }
Q: How to divide Flutter widgets into separate nodes in the Semantics tree I have created a custom widget to represent a tile in a ListView, an example of which is included below. The tile contains an Inkwell, such that it can be tapped. The tile also contains a MaterialButton. I've wrapped everything in Semantics accordingly, but whenever Talkback is enabled and I tap the tile, the entire tile is highlighted. This makes the button within impossible to tap. How do I get each Widget to be treated as an individual node in the Semantics tree? The MergeSemantics documentation (https://api.flutter.dev/flutter/widgets/MergeSemantics-class.html) seems to imply that Widgets should be treated individually unless they are wrapped in a MergeSemantics. import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: ListView( children: [Tile()], ), ), ); } } class Tile extends StatelessWidget { @override Widget build(BuildContext context) => Padding( padding: EdgeInsets.only(top: 12), child: InkWell( onTap: () => print('Tile tapped'), child: _tile(), ), ); Widget _tile() => Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(5)), border: Border.all(color: Colors.grey, width: 1), shape: BoxShape.rectangle, ), child: Row( children: [ _textAndCount(), SizedBox(width: 12), _button(), ], ), ); Widget _textAndCount() => Expanded( child: Column( children: [ SizedBox( width: double.infinity, child: _text(), ), _count(), ], ), ); Widget _text() => Text( 'text', overflow: TextOverflow.ellipsis, maxLines: 2, textAlign: TextAlign.start, ); Widget _count() => Padding( padding: EdgeInsets.only(top: 12), child: Row( children: [ Semantics( label: '0 things', child: ExcludeSemantics( child: Container( padding: EdgeInsets.symmetric(horizontal: 12), decoration: BoxDecoration( shape: BoxShape.rectangle, color: Colors.grey, borderRadius: BorderRadius.circular(10), ), child: Text('0'), ), ), ), ], ), ); Widget _button() => Semantics( label: 'button', button: true, child: Tooltip( message: 'button', excludeFromSemantics: true, child: ExcludeSemantics( child: MaterialButton( onPressed: () => print('Button tapped'), child: Container( child: SizedBox( height: 44, width: 44, child: Icon(Icons.add), ), decoration: BoxDecoration( border: Border.all(color: Colors.grey, width: 2), shape: BoxShape.circle, ), ), ), ), ), ); } A: Posted an issue on the Flutter GitHub repo and got the following reply: https://github.com/flutter/flutter/issues/54725. Turns out Semantics widgets have a container property, which, when set to true, has the wrapped object behave as its own node in the Semantics tree.
{ "pile_set_name": "StackExchange" }
Q: What is the vim feature: --enable-pythoninterp I am going to build vim and see that it supports the pythoninterp feature by --enable-pythoninterp. What is it? Since I am a big Python fan, I'd like to know more about it. And also, what's the --with-python-config-dir=PATH for? A: vim supports scripting in various languages, Python being one of them. See :h python for more details.
{ "pile_set_name": "StackExchange" }
Q: Refactor an ugly loop into LINQ I have the following peace of code, that factors an int to prime numbers: private static IEnumerable<int> Factor(int input) { IList<int> result = new List<int>(); while (true) { var theSmallestDivisor = GetTheSmallestDivisor(input); if (theSmallestDivisor == 0) { result.Add(input); return result; } result.Add(theSmallestDivisor); input = input/theSmallestDivisor; } } I'm looking for hints on how to improve it, possibly using LINQ. A: Here's an iterator version: private static IEnumerable<int> Factor(int input) { while (true) { var theSmallestDivisor = GetTheSmallestDivisor(input); if (theSmallestDivisor == 0) { yield return input; yield break; } yield return theSmallestDivisor; input = input / theSmallestDivisor; } } LINQ would only make this code less readable in that particular case. A: LINQ's operators are mostly designed to generating a new list from an existing list. e.g. IEnumerable<B> LinqOperator(this IEnumerable<A> list, ...) Not so much for generating a list from scratch as you a trying to do. But, since you are returning IEnumerable, you may as well make it lazy: private static IEnumerable<int> Factor(int input) { while (true) { var theSmallestDivisor = GetTheSmallestDivisor(input); if (theSmallestDivisor == 0) { yield return input; yield break; } yield return theSmallestDivisor; input = input/theSmallestDivisor; } }
{ "pile_set_name": "StackExchange" }
Q: MAMP Python-MySQLdb issue: Path to libssl.1.0.0.dylib changing once Python file called I'm trying to use python MySQLdb to access my MySQL database on my MAMP server. When I initially tried to call a Python file with python-sql to access my database on MAMP I got the image not found error regarding the libssl.1.0.0.dylib library Traceback (most recent call last): File "desktopsql.py", line 3, in <module> import _mysql as ms File "build/bdist.macosx-10.5-x86_64/egg/_mysql.py", line 7, in <module> File "build/bdist.macosx-10.5-x86_64/egg/_mysql.py", line 6, in __bootstrap__ ImportError: dlopen(/Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx- 10.5-x86_64.egg-tmp/_mysql.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so Reason: image not found So I fixed it to a certain extent by changing the libssl.1.0.0.dylib path using export DYLD_LIBRARY_PATH=/Users/username/anaconda/lib/:$DYLD_LIBRARY_PATH, but it has to be done for every folder I wish to execute the Python file in. So when I try to execute the Python file through PHP on my MAMP webpage I get the error again, and I can't use my makeshift fix this time to cover it up. I have tried to fix it further using install_name_tool to change the false library location /Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so to where it is actually stored in /Users/username/anaconda/lib/ sudo install_name_tool -change libssl.1.0.0.dylib /Users/username/anaconda/lib/libssl.1.0.0.dylib /Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so After doing so I use otool -L to see the status of what I've changed and the result states that the file path has certainly changed to the correct location. otool -L /Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so /Users/username/anaconda/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0) However when I run the python file again, I get the image not found error. Upon running otool -L again the result shows that the file path has reverted back again. /Users/username/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so: libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0) So it changes to the correct location until I run the python file and it's back again to what it was before. Why is this happening? Is there something I can do to make it maintain what I've changed it to? A: So I discovered I should be working with the libssl.1.0.0.dylib file in /usr/lib, not the file that was mentioned by the error, which was Users/$USERNAME/.python-eggs/MySQL_python-1.2.5-py2.7-macosx-10.5-x86_64.egg-tmp/_mysql.so in my case. I created a symlink to where libssl.1.0.0.dylib should be referenced from, (/Users/$USERNAME/anaconda/lib/ for me), using sudo ln -s /Users/$USERNAME/anaconda/lib/libssl.1.0.0.dylib /usr/lib/libssl.1.0.0.dylib and, once that's done, the same for libcrypto.1.0.0.dylib, as it threw the same error. sudo ln -s /Users/$USERNAME/anaconda/lib/libcrypto.1.0.0.dylib /usr/lib/libcrypto.1.0.0.dylib As a side note when listing the files in /usr/bin these two are listed as libss.dylib and libcrypto.dylib.
{ "pile_set_name": "StackExchange" }
Q: How to extract 'for' loop Method? I am attempting to extract my 'for' loop in order to call it in printPartyBreakdownInHouse() method. Basically removing any chance of duplicate code or "code smell" as well as my printdetails() method, but when doing this I'm getting '2' as a result. Any ideas? public void printPartyBreakdownInSenate() { int numDemocrats = 0; int numRepblican = 0; int numIndepent = 0; String senateData; ArrayList<MemberOfCongress> members; senateData = CongressDataFetcher.fetchSenateData(congressNum); members = parseMembersOfCongress(senateData); for (MemberOfCongress party : members){ if (party.getParty().equals("D")){ numDemocrats++; } else if (party.getParty().equals("R")){ numRepblican++; } else if (party.getParty().equals("I")){ numIndepent++; } } pintDetails(numIndepent, numIndepent, numIndepent, numIndepent, members); } /** * printDetails method */ void pintDetails(int congressNum, int numDemocrats, int numRepblican, int numIndepent, ArrayList<MemberOfCongress> members){ System.out.println("Number of Members of the Senate of the " + congressNum + " Congress : " + members.size() ); System.out.println("# of Democrats: " + numDemocrats); System.out.println("# of Republican: " + numRepblican); System.out.println("# of Indep: " + numIndepent); } /** * Calculate and print the number of Democrats, Republicans, and Independents in this House */ public void printPartyBreakdownInHouse(){ String houseData; ArrayList<MemberOfCongress> members; houseData = CongressDataFetcher.fetchHouseData(congressNum); members = parseMembersOfCongress(houseData); } A: You could use a method which accepts the members list as parameter and returns the member counts via an additional helper class as follows: class MemberCounter { int numDemocrats; int numRepblican; int numIndepent; }; MemberCounter countMembers(List<MemberOfCongress> members) { MemberCounter counter = new MemberCounter(); for (MemberOfCongress party : members) { if (party.getParty().equals("D")) { counter.numDemocrats++; } else if (party.getParty().equals("R")){ counter.numRepblican++; } else if (party.getParty().equals("I")){ counter.numIndepent++; } } return counter; }
{ "pile_set_name": "StackExchange" }
Q: Sum of image values for three consecutive images in collection GEE I have a collection of 457 images, where each image is the total precip in a month, 1981-present. I want to find the total precip in each quarter i.e. reduce three consecutive images by sum thereby producing another image collection of sie ~ 152 I have the below code, but I am unable to iterate it through all the images var listofmonthlyprecip = collection.toList(collection.size());// convert collection of 457 images into a list print (listofmonthlyprecip); var trial1 = ee.Image(listofmonthlyprecip.get(0));// Jan 1981 var trial2 = ee.Image(listofmonthlyprecip.get(1));// Feb 1981 var trial3 = ee.Image(listofmonthlyprecip.get(2));// Mar 1981 var imgcollection = ee.ImageCollection([trial1, trial2, trial3]); //make collection of first three months var quarter_trial = imgcollection.reduce(ee.Reducer.sum());// add values print (quarter_trial); Map.addLayer (quarter,{min:0, max: 1143}, 'first quarter'); map How do I iterate through all images to get sum of values for groups of 3 consecutive images? A: You should first make a list of all quarters and a list of all years. You can then map over both to calculate a summed image for each quarter: // set the collection (unsure what you use...) var collection = ee.ImageCollection("IDAHO_EPSCOR/GRIDMET").select('pr'); // set list to map over var quarters = ee.List.sequence(1,10,3); var years = ee.List.sequence(1980, 2020); // Group by year and quarter, reduce within groups by sum(); var byQuarter = ee.ImageCollection.fromImages( years.map(function (year) { // map over years year = ee.Number(year); var images = quarters.map(function(quarter){ // map over quarters quarter = ee.Number(quarter); var start = ee.Date.fromYMD(year, quarter, 1); var yearEnd = ee.Number(ee.Algorithms.If(quarter.eq(10), year.add(1), year)); var quarterEnd = ee.Number(ee.Algorithms.If(quarter.eq(10), 1, quarter.add(3))); var end = ee.Date.fromYMD(yearEnd, quarterEnd, 1); return collection.filterDate(start, end).sum().set({ 'system:time_start': start.millis(), 'system:time_end': end.millis(), quarterStart: quarter, quarterEnd: quarter.add(3), year: year}); }); return images }).flatten()) // optionally filter out empty images .filter(ee.Filter.listContains('system:band_names', 'pr')); Unsure what image colleciton you used, so I just picked one with precipitation. See here the full link.
{ "pile_set_name": "StackExchange" }
Q: JS object sorting date sorting I have JS object defined as follows - var item = {}; item[guid()] = { symbol: $('#qteSymb').text(), note: $('#newnote').val(), date: $.datepicker.formatDate('mm/dd/yy', dt) + " " + dt.getHours() + ":" + minutes, pagename: getPageName() }; At some point in my app I am getting a list of those (Items) back from chrome.storage and I would like to be able to sort it based on the date Here is what I am doing var sortable = []; $.each(Items, function (key, value) { if (value.symbol == $('#qteSymb').text() || all) { sortable.push([key, value]); } }); console.log(sortable); sortable.sort(function (a, b) { a = new Date(a[1].date); b = new Date(b[1].date); return a > b ? -1 : a < b ? 1 : 0; }); console.log(sortable); It doesn't seem to work. The first and second console.log(sortable); is the same. I have tried changing return a > b ? -1 : a < b ? 1 : 0; to return a < b ? -1 : a > b ? 1 : 0; just to see if I am getting any change to sortable but nothing happens... Thank you~ A: Both console.log show the same array because when you use console.log(sortable), sortable is passed by reference, and console output happens AFTER finishing your script - when sortable has been already sorted. Making your code simple: var arr = [3,2,1]; console.log(arr); // Produces `[1,2,3]` because its printed // to the console after `arr.sort();` arr.sort(); console.log(arr); // Produces `[1,2,3]`, as expected Demo: http://jsfiddle.net/Rfwph/ Workaround If you want to be able to do console.log with an array to see it before being modifyed, you can use .slice(0) to copy the array, i.e. to obtain another array which contains the same elements as your array. var arr = [3,2,1]; console.log(arr.slice(0)); // [3,2,1] arr.sort(); console.log(arr); // [1,2,3] Demo: http://jsfiddle.net/Rfwph/2/ Edit: better use .slice(0) instead of .slice(), which is supported on FF but ecma262 spec says only end argument is optional.
{ "pile_set_name": "StackExchange" }
Q: Need a Mental Challenge I am running a custom campaign and I have run into an issue. The group got to a quest where the ruler of the country is dying of old age and a has no heir. So someone needs to prove themselves to both the Orcs and the Elves. They took on the Orc physical challenge with no problem, but I have no idea what mental challenge to throw at them when they reach the Elves. The Orc challenge was more or less straight forward. They got to the main camp of the orcs and had to challenge the Orc Warlord to a physical fight. The only thing that wasn't quite what it seemed was the there was a huge warrior orc in the middle of the tent training, the Warlord was sitting on the ground in the back watching. After a while they figured out who the Warlord was. I am hoping for a mental challenge similar to this, seeming straight forward, with a slight twist. A: Well, if this is a test of their ability as a ruler, I would suggest something like Chess or something else that has mental strategy to it. To make it interesting, make it so the pieces are people and not played on a regular board. They would act out the moves to show that they understood strategy. The other option is for the elves to give them a mental task to choose between two hard choices, like the classic, "You can only save one person, who will it be"? Make sure there will be a legitimate tough choice for the PC's as they will be easily detached from the decision if they do not care about the NPCs involved. This test could be more of a test to see if they will make tough decisions, not necessarily what is the right answer. As you can see there is more than one way to approach this.
{ "pile_set_name": "StackExchange" }
Q: Footnotemark after period in bibliography I need footnotes in either the pages or addendum fields of some of my references. Since I don't have control over the period appended at the end of those fields, the footnote mark will end up before the period, which is ugly. See this MWE: \RequirePackage{filecontents} \begin{filecontents*}{\jobname.bib} @BOOK{KandR, AUTHOR = {Kernighan, Brian W. and Ritchie, Dennis M.}, TITLE = {{The C Programming Language Second Edition}}, PUBLISHER = {Prentice-Hall, Inc.}, YEAR = {1988}, ADDENDUM = {An Addendum$^{\dagger}$} } \end{filecontents*} \documentclass{article} \usepackage[% backend=bibtex % use BibTeX % backend=biber % Use biber ]{biblatex} \addbibresource{\jobname.bib} \begin{document} Hello \cite{KandR}. How are you? \printbibliography \end{document} I'm using BibLaTeX to process by bibliography. A: Add the following lines in your preamble: \renewbibmacro*{addendum+pubstate}{% \iffieldundef{addendum} {\renewcommand{\finentrypunct}{\addperiod}}% {\renewcommand{\finentrypunct}{}% \printfield{addendum}% \newunit\newblock \printfield{pubstate}}} This checks if the field addendum is defined. If yes, deletes the final period at the end of the entry. Obviously you have to manually insert the period in your addendum fields. MWE: \RequirePackage{filecontents} \begin{filecontents*}{\jobname.bib} @BOOK{KandR, AUTHOR = {Kernighan, Brian W. and Ritchie, Dennis M.}, TITLE = {{The C Programming Language Second Edition}}, PUBLISHER = {Prentice-Hall, Inc.}, YEAR = {1988}, ADDENDUM = {An Addendum.$^{\dagger}$} } @BOOK{Book, AUTHOR = {Author A.}, TITLE = {A title}, PUBLISHER = {A publisher}, YEAR = {1988} } \end{filecontents*} \documentclass{article} \usepackage[% backend=bibtex % use BibTeX % backend=biber % Use biber ]{biblatex} \renewbibmacro*{addendum+pubstate}{% \iffieldundef{addendum} {\renewcommand{\finentrypunct}{\addperiod}}% {\renewcommand{\finentrypunct}{}% \printfield{addendum}% \newunit\newblock \printfield{pubstate}}} \addbibresource{\jobname.bib} \begin{document} Hello \cite{KandR}. How are you?\cite{Book} \printbibliography \end{document} Output:
{ "pile_set_name": "StackExchange" }
Q: NaN-Error at d3js error bars Here is the important part of my code. For some reasons, there is a problem with the "errorBars2". It always returns this error: Invalid value for <path> attribute d="M40.5,NaNL40.5,NaNZ" I spent now hours on searching for the mistake but I can't find it! Could somebody explain me what's the problem with the "errorBars2"? A: In errorBarArea2 you have written for .y0(function (d) { return y0(+d.top_after + +d.moe3); }) but in the JSON structure it is not available change it to +d.moe3_after and you have written .y1(function (d) { return y0(+d.low_after - +d.moe4); }) but in the JSON structure it is not available change it to +d.moe4_after So the final code is var errorBarArea2 = d3.svg.area() .x(function (d) { return x3(d.name) +x3.rangeBand()/2; }) .y0(function (d) { return y0(+d.top_after + +d.moe3_after); }) .y1(function (d) { return y0(+d.low_after - +d.moe4_after); })
{ "pile_set_name": "StackExchange" }
Q: Checked remote service exception translated to StatusCodeException in tomcat I've got a GWT app that does regular RPC calls to a RemoteService whose methods may throw a ServiceException: public class ServiceException extends Exception implements java.io.Serializable { private static final long serialVersionUID = 1L; public ServiceException() {} public ServiceException(final Throwable cause) { super(cause); } public ServiceException(final String errorMsg) { super(errorMsg); } } This works perfectly fine in development mode where I get the expected exception messages in my onFailure async callback but when I compile the app and deploy it to tomcat my exception gets translated to com.google.gwt.user.client.rpc.StatusCodeException: 500 The call failed on the server; see server log for details Just as in dev mode, my server logs show the expected exception reason which I logged myself just before throwing the ServiceException. I've looked this up in google but could not find anything relevant. (I'm working on Mac OS X Lion with GWT 2.4, java 1.6 and Tomcat 7.0.16) A: Stupid mistake. I finally figured out that the problem came from an accidental typo in the configuration of the java obfuscator I am using. Because of that my class name was renamed when building the war that I was deploying in tomcat.
{ "pile_set_name": "StackExchange" }
Q: Searchkick: Elasticsearch not indexing "FORBIDDEN/12/index read-only"? I've setup a new development environment on my iMac and moved my rails app from a macbook air. It was working fine and indexing the data as well. Using the same version of gems. When indexing it gives following error. Searchkick::ImportError: {"type"=>"cluster_block_exception", "reason"=>"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"} on item with id '74' Is there any way I can solve this issue by modifying my elasticsearch.yml? A: I had the same issue today, and the following worked for me: Model.search_index.clean_indices A: This solution from salihsagdilekon on https://github.com/ankane/searchkick/issues/1040 resolved this same issue for me: curl -XPUT -H "Content-Type: application/json" > http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
{ "pile_set_name": "StackExchange" }
Q: SQL query comparison (join condition in ON clause or in WHERE clause) SQL fiddle link for sample data Basically my doubt is , is it same if we specify a condition in ON clause of LEFT OUTER JOIN or we specify condition in WHERE clause with null check ? Table schema : Create table App(ID number , STATUS varchar2(10)); Create table App_Child(child_id number , STATUS varchar2(10), ID number ); Query 1 SELECT a.ID AS appID, a.STATUS AS appSTATUS, b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID FROM App a LEFT OUTER JOIN App_Child b ON (a.id=b.id AND b.STATUS <> 'disabled') WHERE a.ID = ?; Query 2 SELECT a.ID AS appID, a.STATUS AS appSTATUS, b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID FROM App a LEFT OUTER JOIN App_Child b ON (a.id=b.id) WHERE a.ID = ? AND (b.STATUS IS NULL OR b.STATUS<>'disabled'); A: Not not is the same neither in results and readability. When you write condition in on clause you include all rows from App. When you write condition in where clause you filter rows from result: In your case an App with row related with a App_Child with b.STATUS='disabled' will be filtered Here a sample: INSERT INTO App VALUES(1,'active'); INSERT INTO App_Child VALUES(3,'disabled',1); SELECT a.ID AS appID, a.STATUS AS appSTATUS, b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID FROM App a LEFT OUTER JOIN App_Child b ON (a.id=b.id AND b.STATUS <> 'disabled') WHERE a.ID = 1; --- has results --- SELECT a.ID AS appID, a.STATUS AS appSTATUS, b.child_id AS acOWNID,b.STATUS AS acSTATUS, b.id AS acID FROM App a LEFT OUTER JOIN App_Child b ON (a.id=b.id) WHERE a.ID = 1 AND (b.STATUS IS NULL OR b.STATUS<>'disabled'); -- don't has results --
{ "pile_set_name": "StackExchange" }
Q: Bundle Adjustment in the Large and Rodrigues' Rotation Formula We use a pinhole camera model; the parameters we estimate for each camera area rotation R, a translation t, a focal length f and two radial distortion parameters k1 and k2. The formula for projecting a 3D point X into a camera R,t,f,k1,k2 is: P = R * X + t (conversion from world to camera coordinates) p = -P / P.z (perspective division) p' = f * r(p) * p (conversion to pixel coordinates) where P.z is the third (z) coordinate of P. In the last equation, r(p) is a function that computes a scaling factor to undo the radial distortion: r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4. This gives a projection in pixels, where the origin of the image is the center of the image, the positive x-axis points right, and the positive y-axis points up (in addition, in the camera coordinate system, the positive z-axis points backwards, so the camera is looking down the negative z-axis, as in OpenGL). Where, there camera and point indices start from 0. Each camera is a set of 9 parameters - R,t,f,k1 and k2. The rotation R is specified as a Rodrigues' vector. Is the R in the pinhole model the same R as they talk about in the 9 parameters in the buttom? I cant seem to make sense of R*X+t should give a new 3x1 vector P if R is just a vector? What part am I mising? I would like to understand their way of using the pinhole model. A: No its not same. From your equations; P = R * X + t (conversion from world to camera coordinates) p = -P / P.z (perspective division) p' = f * r(p) * p (conversion to pixel coordinates) R * X is not possible as R and X are both 3x1 vectors. So R has to be 3x3 matrix. Lets assume that R is a 3x3 rotation matrix in pinhole model whereas R_ is 3x1 rotation vector obtained by taking Rodrigues of R. K is camera Intrinsic matrix containing f,k1,k2. Following will be the proper way to solve this problem. H = R_ x K; P = H * X + t (conversion from world to camera coordinates) p = -P / P.z (perspective division) p' = f * r(p) * p (conversion to pixel coordinates) The code below is taken from OpenCV's bundle adjuster. It shows how to get a new vector P'. double R1[9]; Mat R1_(3, 3, CV_64F, R1); Mat rvec(3, 1, CV_64F); rvec.at<double>(0, 0) = cam_params_.at<double>(i * 4 + 1, 0); rvec.at<double>(1, 0) = cam_params_.at<double>(i * 4 + 2, 0); rvec.at<double>(2, 0) = cam_params_.at<double>(i * 4 + 3, 0); Rodrigues(rvec, R1_); double R2[9]; Mat R2_(3, 3, CV_64F, R2); rvec.at<double>(0, 0) = cam_params_.at<double>(j * 4 + 1, 0); rvec.at<double>(1, 0) = cam_params_.at<double>(j * 4 + 2, 0); rvec.at<double>(2, 0) = cam_params_.at<double>(j * 4 + 3, 0); Rodrigues(rvec, R2_); const ImageFeatures& features1 = features_[i]; const ImageFeatures& features2 = features_[j]; const MatchesInfo& matches_info = pairwise_matches_[i * num_images_ + j]; Mat_<double> K1 = Mat::eye(3, 3, CV_64F); K1(0, 0) = f1; K1(0, 2) = features1.img_size.width * 0.5; K1(1, 1) = f1; K1(1, 2) = features1.img_size.height * 0.5; //LOGLN("\nf1: " << f1 << "\tf2: "<<f2); Mat_<double> K2 = Mat::eye(3, 3, CV_64F); K2(0, 0) = f2; K2(0, 2) = features2.img_size.width * 0.5; K2(1, 1) = f2; K2(1, 2) = features2.img_size.height * 0.5; Mat_<double> H1 = R1_ * K1.inv(); Mat_<double> H2 = R2_ * K2.inv(); for (size_t k = 0; k < matches_info.matches.size(); ++k) { if (!matches_info.inliers_mask[k]) continue; const DMatch& m = matches_info.matches[k]; Point2f p1 = features1.keypoints[m.queryIdx].pt; double x1 = H1(0, 0)*p1.x + H1(0, 1)*p1.y + H1(0, 2); double y1 = H1(1, 0)*p1.x + H1(1, 1)*p1.y + H1(1, 2); double z1 = H1(2, 0)*p1.x + H1(2, 1)*p1.y + H1(2, 2); double len = std::sqrt(x1*x1 + y1*y1 + z1*z1); //x1 /= z1; y1 /= z1; x1 /= len; y1 /= len; z1 /= len; Point2f p2 = features2.keypoints[m.trainIdx].pt; double x2 = H2(0, 0)*p2.x + H2(0, 1)*p2.y + H2(0, 2); double y2 = H2(1, 0)*p2.x + H2(1, 1)*p2.y + H2(1, 2); double z2 = H2(2, 0)*p2.x + H2(2, 1)*p2.y + H2(2, 2); len = std::sqrt(x2*x2 + y2*y2 + z2*z2); //x2 /= z2; y2 /= z2; x2 /= len; y2 /= len; z2 /= len; double mult = (f1 + f2)/2; //std::sqrt(f1 * f2); err.at<double>(3 * match_idx, 0) = mult * (x1 - x2); err.at<double>(3 * match_idx + 1, 0) = mult * (y1 - y2); err.at<double>(3 * match_idx + 2, 0) = mult * (z1 - z2); match_idx++; }
{ "pile_set_name": "StackExchange" }
Q: Maximum value of $\int_0 ^1 f(x)(x^2) dx - \int_0^1 x(f(x)^2) dx $ Let $f: [0,1] \to \mathbb R$ be a continuous function. What is the maximum value of the following functional? $$\displaystyle \int_0 ^1 f(x)(x^2) \,\mathrm d x - \int_0^1 x(f(x)^2) \,\mathrm d x $$ Unable to understand how to solve this problem. I have thought about it analytically and think that the following points are important: $x^2 \le x$ for $x\in [0,1]$ $(f(x) )^2 x ^2 \le x(f(x))^2$ How do I proceed from here? A: We have $$ \begin{aligned} \int_0^1 f(x) \cdot x^2 \,dx - \int_0^1 f^2(x) x \,dx &\leq \sqrt{\left(\int_0^1 f^2(x) x \,dx \right)\left(\int_0^1 x^3 \,dx\right)} - \int_0^1 f^2(x) x \,dx \\ &= \frac{1}{2}\sqrt{\int_0^1 f^2(x) x \,dx } - \int_0^1 f^2(x) x \,dx\\ &\leq \frac{1}{16} + \int_0^1 f^2(x) x \,dx - \int_0^1 f^2(x) x \,dx\\ &= \frac{1}{16}, \end{aligned} $$ where the first inequality follows from the Cauchy-Schwarz inequality, and the second inequality follows from the AM-GM inequality. It can be verified that all inequalities become equalities when $f(x) = x/2$. A: This sort of hand wavy, but I think it works. Let $g(s,t) = st(s-t)$ and find its max and min on $[0,1]\times [0,1].$ The max turns out to be at $(1,1/2),$ which is on the boundary of the domain. When we need this result, we can scale it to any square $[0,a]\times [0,a].$ Now take your expression, and push the integrals together to get $$\int_0^1 x^2f(x) - x(f(x)^2) \; dx = \int_0^1 xf(x)(x-f(x)) \; dx.$$ Rescale $f(x)$ so that its range is $[0,1]$. (I suppose we just divide $f(x)$ by its maximum value on $[0,1].$) The integrand is of the form $st(s-t)$ so to make it as large as possible we want $t=s/2$ by from the result above. So I think that shows that $f(x) = x/2$ and the integrand is $x(x/2)(x/2)$ making the max $1/16$.
{ "pile_set_name": "StackExchange" }
Q: Losing hover when moving mouse CSS So, I'm a beginner with HTML and CSS and all that, and I've attempted to learn jQuery and JavaScript but no success just yet. Anyway, I wanted to hover over one place, and trigger a div elsewhere, so I used the adjacent siblings code, but the problem is that once the event has been triggered, and the box that I want is there, if I move my mouse, it triggers it again, instead of staying on the 'hover' element until I move my mouse off. Is there any way to fix this? This is the adjacent sibling elements part of the CSS: .b:hover ~ .a { position:absolute; height:1000%; width:100px; margin-top:-1000px; margin-left:100px; background-color:#b6c9e7; z-index:1000; opacity:1; transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; -o-transition: all 0.4s ease-in-out 0s; -webkit-animation-duration: 2s; }​ Here is my code: in JSFiddle Help would be much appreciated! A: Your zindex is off. When you move the mouse you are actually rolling over a not b, and as it is b that has the hover state you are pining the roll out, which is resetting the position. set a to be behind b and it will work as desired. z-index:999; http://jsfiddle.net/2g2uY/ The zindex is basically the stack number so if something has a higher zindex it means it is in front of another element. This only really comes into play when elements overlay, when using absolutely and relatively positioned elements. Also, when you use a :hover selector you don't need to redefine the elements that you are not changing. They are all inherited; only change the attributes that are different on the hover state.
{ "pile_set_name": "StackExchange" }
Q: Error while trying to launch Pig script with JAVA I'm trying to launch a pig script from JAVA. Here is my code: import java.io.IOException; import java.util.Properties; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; public class pigCV { public static void main(String args[]){ PigServer pigServer; try { Properties props = new Properties(); props.setProperty("fs.default.name", "hdfs://hdfs://localhost:8022"); props.setProperty("mapred.job.tracker", "localhost:8021"); pigServer = new PigServer(ExecType.MAPREDUCE, props); pigServer.registerScript("Desktop/text_v3.pig"); } catch (ExecException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } But some exceptions are thrown: 2013-05-23 01:34:54,666 ERROR [main] conf.Configuration(1151): Failed to set setXIncludeAware(true) for parser org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@1787038:java.lang.UnsupportedOperationException: This parser does not support specification "null" version "null" java.lang.UnsupportedOperationException: This parser does not support specification "null" version "null" at javax.xml.parsers.DocumentBuilderFactory.setXIncludeAware(DocumentBuilderFactory.java:590) at org.apache.hadoop.conf.Configuration.loadResource(Configuration.java:1149) at org.apache.hadoop.conf.Configuration.loadResources(Configuration.java:1125) at org.apache.hadoop.conf.Configuration.getProps(Configuration.java:1064) at org.apache.hadoop.conf.Configuration.get(Configuration.java:424) at org.apache.hadoop.mapred.JobConf.checkAndWarnDeprecation(JobConf.java:1709) at org.apache.hadoop.mapred.JobConf.(JobConf.java:164) at org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.init(HExecutionEngine.java:169) at org.apache.pig.backend.hadoop.executionengine.HExecutionEngine.init(HExecutionEngine.java:137) at org.apache.pig.impl.PigContext.connect(PigContext.java:200) at org.apache.pig.PigServer.(PigServer.java:169) at org.apache.pig.PigServer.(PigServer.java:158) at org.apache.pig.PigServer.(PigServer.java:154) at pigCV.main(pigCV.java:21) Do you have any idea to help me ? Thank you. A: You might have a(n old) Xerces implementation in your classpath. Try to set -Djavax.xml.parsers.DocumentBuilderFactory= com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl (in Eclipse: VM argument) or in code: System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); Remark: There's probably a typo in fs.default.name : Shouldn't it be hdfs://localhost:8022 instead of hdfs://hdfs://localhost:8022 ?
{ "pile_set_name": "StackExchange" }
Q: Compare app code on Android test phone to code on the IDE I tested an app on my phone then I changed the code and the app stopped working properly. (I tested it on the emulator this time so the test phone has an older version)Can I download the app code from the phone to see what I may have erased erroneously. The specific issue is that I had a recycler view open when the activity was called but it stopped doing that. I have to navigate away from it and back for it to work. If I can get the answer to the first part, that's what I need in the long run if this happens again and if you can guide me on the second part, it would be a plus. A: you can do that using reverse engineering for you Apk , there are many tools to do that and you will got your java code , have a look on this link But my advice to find the Error with your new code not to go back to old one
{ "pile_set_name": "StackExchange" }
Q: Should I include both fflush(stdin) and a space in scanf() or will only one of them suffice? My calculator app hasn't been working properly after a user inputs a number. So I added fflush(stdin) and a space after the %d in scanf(). My question is should I only include both fflush(stdin) and a space after %c or will only one of the options suffice? I'm working on a Macbook, so I'm concerned that if I leave one out it won't work on other operating systems. #include <stdio.h> #include <stdlib.h> //PROTOTYPE int operationSwitch(); //Function to calculate total of operand1 and operand2. int menu(); //Function for main menu. int iResume(); //Function to continue the program or not. char iOperation = '\0'; //choices (1-7) float operand1 = 0; //number 1 float operand2 = 0; //number 2 float operandTotal = 0; //total int testPrime, counter, prime = 0; char cContinue = '\0'; char symbol = '\0'; int main(){ menu(); return 0; } int menu (){ do { printf("\nPlease choose an operation: "); printf("\n(1) Addition\n "); printf("\n(2) Subtraction\n "); printf("\n(3) Multiplication\n "); printf("\n(4) Division\n "); printf("\n(5) Modulus (integers only)\n "); printf("\n(6) Test if Prime (integers only)\n "); printf("\n(7) Exit\n "); printf("\nChoose (1-7):\t"); fflush(stdin); scanf(" %c", &iOperation); } while (iOperation < 49 || iOperation > 55 ); if (iOperation != 54 && iOperation != 55){ //ASCII 55 == 7) printf("\nEnter number 1:\t"); fflush(stdin); scanf(" %f", &operand1); printf("\nEnter number 2:\t"); fflush(stdin); scanf(" %f", &operand2); } operationSwitch(); /*** RESULTS ***/ if ( symbol == '/' && operand2 == 0) { printf("\n\t-----| Answer: %.2f / %.2f = Undefined |-----\n", operand1,operand2); } else if (iOperation != 54) { printf("\n\t-----| Answer: %.2f %c %.2f = %.2f |-----\n", operand1, symbol, operand2, operandTotal); } iResume(); return 0; } //End Menu /********************************* SWITCH FUNCTION *********************************/ int operationSwitch() { switch (iOperation) { case 49://1 Addition Ascii 49 == 1 43 == + operandTotal = operand1 + operand2; symbol = '+'; break; case 50: //2 Substraction operandTotal = operand1 - operand2; symbol = '-'; break; case 51: //3 Multiplication operandTotal = operand1 * operand2; symbol = '*'; break; case 52: //4 Division operandTotal = operand1 / operand2; symbol = '/'; break; case 53: //5 Modulus operandTotal = (int)operand1 % (int)operand2; symbol = '%'; break; case 54: //6 prime = 1; printf("\nEnter number to be tested for prime: "); fflush(stdin); scanf(" %d", &testPrime); for(counter = 2; counter <= (testPrime/2); counter++ ) { if(testPrime % counter == 0) { prime = 0; break; } } if (prime == 1) { printf("\n\t| %d is a prime number. |\n", testPrime); } else { printf("\n\t| %d is not a prime number. |\n", testPrime); printf("\n\t| %d * %d = %d \n", testPrime/counter, counter , testPrime); } break; case 55: printf("\nGood Bye\n"); exit(0); break; default: printf("\nYou entered: %c - Please try again ", iOperation ); break; } //End Switch iOperation return 0; } //End Switch Function /********************************* RESUME FUNCTION *********************************/ int iResume() { printf("\nWould you like to try again?\nPress \'Y\' to go to menu,\nor any key to quit?\t"); fflush(stdin); scanf(" %c", &cContinue); if (cContinue == 'y' || cContinue == 'Y'){ menu(); } else { printf("Good Bye!\n" ); } return 0; } A: fflush(stdin) is undefiined behavior. int fflush(FILE *ostream); ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
{ "pile_set_name": "StackExchange" }
Q: how to know the phone or system connected to my modem in android? I want to know how many phone or system connected to my modem? I tried to scan the IP from 1 to 254 for discovering connected devices. but when im trying InetAddress.isreachable(2000) it works on my phone but does not work on some devices (always return True or always return false). I also tried to ping the devices but it also worked on my device but did not work on some devices. I also tried to make a socket to devices but when target's device is Linux like Android it did not work. Is there anyway to know the devices connected to my modem in android? thank you A: Here is a Network Scanner that you can think of : android-network-discovery Features : Discover Machines on a LAN (connect/ping discovery, dns discovery) , TCP Port Scanner (connect() scan)
{ "pile_set_name": "StackExchange" }
Q: How setup template file for chart tooltip? I use angularJS and kendo. How setup template (separated) for chart tooltip ? <div id="buildLogChart" kendo-chart k-tooltip="{ visible: true, template: '#TooltipTemplate' }"> </div> A: You can use k-tooltip="tooltipOptions" where on your controller define $scope.tooltipOptions then you can simply set the template from your controller like for example $scope.tooltipOptions = { visible :true, template : "<div id='testId' class='testClass' style='font-size:15px;'>\ <div>${series.name}</div>\ <div>${series.color}</div>\ <div>${value}</div>\ </div>" }; Explanation : You can pretty much use id class or inline css to suit your styling(the content of the tooltip) needs The list of information you can acess from within is listed here Dont forget to add '\' if you intend to create a multiline otherwise you need to finish it in 1 line(bad for readabilty though) And Finally here's DEMO Also if you want to put it on separate file (i'm not sure if i got your question 100%), you can use kendo template by creating a page and add a kendo template script <script id="customTooltipTemplate" type="text/x-kendo-template"> <div id='testId' class='testClass' style='font-size:15px; color:black; background-color:white;'> <div>${series.name}</div> <div>${series.color}</div> <div>${value}</div> </div> </script> Then import/link the file to your controller then you can use it like : $scope.tooltipOptions = { visible :true, template : kendo.template($("#customTooltipTemplate").html()) }; And Finally here's DEMO NOTE: i'm not creating it on a separate file because i obviously can't do it here on kendo dojo, but this kendo template can be placed on other page but you need to import/link the file to your current file first. Read more about kendo template here
{ "pile_set_name": "StackExchange" }
Q: Saytzev and Hofmann elimination in E1 From what I have read, E1 largely produces the more substituted alkene because of the fact that more substituted alkenes are more stable as a result of hyperconjugation. However, in E2 the situation is different for a number or reasons. One of these reasons is steric effects of potentially large substituents on the $\beta$- carbon which would promote formation of the less substituted alkene. This effect does not seem to be mentioned for E1 but surely it must still be valid, right? Do large subtituents or bulky bases promote the formation of less substituted alkenes in E1? If not why not? A: In the E2 reaction, the size of the base can affect the selectivity of the deprotonation, because the steric interaction of a large base with a hindered proton will go over a higher transition state than the interaction of a large base with a less-hindered proton. This is kinetic control. I'm not aware of any practical case where the selectivity of an E1 reaction can be controlled by the size of the base. The reason is that the deprotonation of the carbocation intermediate will have a transition state that is very close in energy to the carbocation itself. I agree with you that the size of the base should have some influence on the transition state energy, but in practice, it seems that it has less influence than the stability of the resulting alkene. Also note that often E1 is run under equilibrating conditions, where even if a less-substituted (less-stable) alkene is formed, it can be protonated to reform the carbocation, and the material will funnel to the most stable product. This is thermodynamic control.
{ "pile_set_name": "StackExchange" }
Q: Do multiple callback reduce nodejs performance? I am developing an express app with mysql. My node version is 6.11.2. My router file is const router = require("express").Router(); const project = require("../../modules/project/"); // individual project routes router.get("/", project.getAllProject); Now my getAllProject function code as follows. /* Get all project */ getAllProject(req, res, next) { buildQuery(req) /* Build query based on logged in user */ .then(query => runDbQuery(req, query)) /* execute query */ .then(results => formatResult(results)) /* Build response for front end */ .then(output => res.send(output)) /* return results */ .catch(err => next(err, req, res, next) ); /* catch error and pass it error middle ware */ } buildQuery, runDbQuery, fromatResult return promise. On my code review client commented as below In your method here called “getAllProjects” there are 3 callback checks needed to be made and completed before the data is delivered and a total of 4 callbacks in all. This is too many. This is slow because these callbacks need to complete before the data can be sent to the client which is taking up server processing power He also asked me to do everything in one callback and return data to client. Do promise and callback approach reduce performance. He also suggest to use RXJS Observable in express. A: Theoretically, each function invocation costs some resources (like context/closure construction). So, yeah, having three .then() is by definition slower than a single .then() even if same work is done in both case inside those then-s. It is really hard to tell how much the multi-then case is slower compared to the single-then case without running a benchmark ...so, I created a simple one which you can try yourself. On my old and really sloooooooooow laptop, the results of the benchmark look likes this: Hope, this answers your question. Now, performance is not the only criteria for code assessment. The other one is readability. In some cases your code will look more readable if you have multiple .then() calls, where each declares a specific data transformation step. Just a side note. I personally prefer readability over performance, because to me it's picking higher chance of correctness over performance. Your client may think differently. As far as the Observable goes, you may or may not want to use them. It depends on the nature of your app. Observable rocks when it comes to event streams and manipulation. Promises, however, rock with ES6's await/async feature. So, no clear answer here, unless we know more about the context.
{ "pile_set_name": "StackExchange" }
Q: W3C validation for complete site I am working on a project where I have to validate the complete site, which has around 150 pages, through W3C Markup Validation. Is there a way to check W3C Markup Validation of an entire website? A: The W3C doesn't offer this on w3.org. http://validator.w3.org/docs/help.html#faq-batchvalidation But you can use this tool and check "Validate entire site": (Also w3.org refers to this site!) http://www.htmlhelp.com/tools/validator/ But you have a limit of 100 URLs to validate and will get this message when you reach 100 URLs: Batch validation is limited to 100 URLs at one time. The remaining URLs were not checked. Also there's a limit of errors displayed for each url. A: The WDG offers two free solutions: Validate entire site (select 'validate entire site') Validate multiple URLs (batch) A: You can run the validator yourself. As of 2018, W3C are using v.Nu for their validator, the code is at https://github.com/validator/validator/releases/latest and usage instructions are at https://validator.github.io/validator/#usage For example, the following command will run it on all html files under the public_html directory: java -jar vnu.jar --skip-non-html public_html
{ "pile_set_name": "StackExchange" }
Q: What is the simplest method of inter-process communication between 2 C# processes? I want communicate between a parent and child process both written in C#. It should be asynchronous, event driven. I does not want run a thread in every process that handle the very rare communication. What is the best solution for it? A: Anonymous pipes. Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback. A: If your processes in same computer, you can simply use stdio. This is my usage, a web page screenshooter: var jobProcess = new Process(); jobProcess.StartInfo.FileName = Assembly.GetExecutingAssembly().Location; jobProcess.StartInfo.Arguments = "job"; jobProcess.StartInfo.CreateNoWindow = false; jobProcess.StartInfo.UseShellExecute = false; jobProcess.StartInfo.RedirectStandardInput = true; jobProcess.StartInfo.RedirectStandardOutput = true; jobProcess.StartInfo.RedirectStandardError = true; // Just Console.WriteLine it. jobProcess.ErrorDataReceived += jp_ErrorDataReceived; jobProcess.Start(); jobProcess.BeginErrorReadLine(); try { jobProcess.StandardInput.WriteLine(url); var buf = new byte[int.Parse(jobProcess.StandardOutput.ReadLine())]; jobProcess.StandardOutput.BaseStream.Read(buf, 0, buf.Length); return Deserz<Bitmap>(buf); } finally { if (jobProcess.HasExited == false) jobProcess.Kill(); } Detect args on Main static void Main(string[] args) { if (args.Length == 1 && args[0]=="job") { //because stdout has been used by send back, our logs should put to stderr Log.SetLogOutput(Console.Error); try { var url = Console.ReadLine(); var bmp = new WebPageShooterCr().Shoot(url); var buf = Serz(bmp); Console.WriteLine(buf.Length); System.Threading.Thread.Sleep(100); using (var o = Console.OpenStandardOutput()) o.Write(buf, 0, buf.Length); } catch (Exception ex) { Log.E("Err:" + ex.Message); } } //... } A: I would suggest using the Windows Communication Foundation: http://en.wikipedia.org/wiki/Windows_Communication_Foundation You can pass objects back and forth, use a variety of different protocols. I would suggest using the binary tcp protocol.
{ "pile_set_name": "StackExchange" }
Q: Why isn't this simple NHibernate one-to-many relation bidirectional? I'm trying to set up a simple association in NHibernate (this is the first project in which I want to make use of it from the ground up) - it seems like a simple, contrived, book example, but for some reason I can't get the relation to work bidirectionally. I have a class called Contact which can contain many Addresses. Here is the simplified Contact class: public class Contact { // firstName, lastName, etc, etc omitted // ixContact is the identity value public virtual int ixContact { get; set; } public virtual ICollection<Address> addresses { get; set; } } and here is Address: public class Address { public virtual int ixAddress { get; set; } public virtual Contact contact { get; set; } } here is the relevant part of the mapping file, Contact.hbm.xml: <id name="ixContact"> <generator class="hilo" /> </id> <bag name="Addresses" inverse="true" cascade="save-update"> <key column="ixContact" /> <one-to-many class="Address /> </bag> here is the relevant part of the Address.hbm.xml mapping file: <id name="ixAddress"> <generator class="hilo" /> </id> <many-to-one name="contact" class="Contact" column="ixContact" /> Given that setup, I run the following code: _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly(typeof(Contact).Assembly); _sessionFactory = _configuration.BuildSessionFactory(); _session = _sessionFactory.OpenSession(); new SchemaExport(_configuration).Execute(false, true, false); Contact firstContact = new Contact { firstName = "Joey", middleName = "JoeJoe", lastName = "Shabadoo" }; using( ITransaction tx = _session.BeginTransaction()) { firstContact.Addresses = new List<Address>(); Address firstAddress = new Address { /* address data */ }; firstContact.Addresses.Add(firstAddress); _session.SaveOrUpdate(firstContact); tx.Commit(); } _session.Close(); _session.Dispose(); Once I run this code, the Contact is inserted into the Contact table just fine, and the Address is also inserted into the Address table, except that the Address's ixContact field is NULL, not associated with the value of the Contact's ixContact field, as I would expect. If I explicitly specify the other side of the relation and say firstAddress.Contact = firstContact, it works fine, but I was under the impression that NHibernate took care of this automagically? If so, what am I doing wrong? Or do I have to specify RandomContact.Addresses.Add(foo), foo.Contact = RandomContact every time? A: You do need to set both sides of the relationship explicitly.
{ "pile_set_name": "StackExchange" }
Q: LINQ query on List to get List based on minimum value I have a List<UserLoginRecord> object which consists of three properties. UserID ID2 LoginTimeStamp 1234567 300009 04/08/2015 18:55:45 1234567 300009 04/08/2015 09:12:32 7654321 300010 14/08/2015 11:55:45 7654321 300010 20/08/2015 13:38:00 I want to run Linq query to return only the first record for UserID and UserID2 combination. i.e. the following output UserID ID2 LoginTimeStamp 1234567 300009 04/08/2015 09:12:32 7654321 300009 14/08/2015 11:55:45 I have tried the following which unfortunately doesn't work. Can someone please help me? var newList = o_userLoginList.GroupBy(gby => new {gby.UserID, gby.ID2}) .Select(x => new UserLoginRecord { UserID = x.UserID, ID2 = x.ID2, LoginTimeStamp = x.Min(LoginTimeStamp), }); A: var newList = o_userLoginList.GroupBy(gby => new {gby.UserID, gby.ID2}) .Select(x => new UserLoginRecord { UserID = x.Key.UserID, ID2 = x.Key.ID2, LoginTimeStamp = x.Min(y=>y.LoginTimeStamp), });
{ "pile_set_name": "StackExchange" }
Q: is require.js the right tool (for the job) for "normal" web sites" I have started building a web site and have used Require.js for selectively loading scripts which I require to implement functionality. What I am experiencing is: the "main" script has not finished executing (or even downloading) before some of my code uses "require" to load dependencies. What this means is that the require.js config has not run and does not know the locations of my scripts. because the require.js config has not run by the time my code needs to use it, the "shim" mechanism has not been initialised and cannot be used. The Common Errors page along with a lot of the issues I seem to be reading about online while trying to solve my own problems seem to suggest that this is not the right tool for the job. This seems to be useful for single page applications or node.js applications, but not traditional sites where other scripts could be running before require.js has been initialised. If require.js is not the right tool for the job, is there a right tool for this job? If so then what is? A: Are you loading the require.js script asynchronously (with an async='async')? You want requirejs to load synchronously. Once it's loaded, it will load further scripts, like your main.js file, asynchronously. They may all load out of order, but the code will actually get executed in the right order (respecting the declared dependencies). So in your page template, you would have this: <script src="/Scripts/require.js" type="text/javascript" data-main="main.js"></script> That will load RequireJS, and once it's loaded it starts loading your main.js asynchronously. Typically main.js does not define any modules, it just makes use of modules defined in other files. These dependencies are listed in the require() call: require(["moduleA", "moduleB"], function(A, B){ // Do something with A and B A.someFunction(); B.someOtherFunction(); }); The files moduleA.js and moduleB.js must wrap their contents inside a define(). In moduleA.js (which depends on module C): define(["moduleC"], function () { // Build up an A var A = ....; return A; }); I wonder now if you're wrapping your modules in a define call. Not doing that could explain the out-of-order execution you're experiencing. RequireJS is a perfectly valid tool on a traditional site, not just on a single-page site.
{ "pile_set_name": "StackExchange" }
Q: Load directly gz file into pandas dataframe I have this gz file from dati.istat.it: within it's a csv file (with different name) that i want load directly in pandas dataframe. If i unzip with 7zip i easily load with this code pd.read_csv("DCCV_OCCUPATIT_Data+FootnotesLegend_175b2401-3654-4673-9e60-b300989088bb.csv", sep="|", engine = "python") how i can do it without unzip with 7zip frist? thx a lot! A: You can use library zipfile: import pandas as pd import zipfile z = zipfile.ZipFile('test/file.gz') print pd.read_csv(z.open("DCCV_OCCUPATIT_Data+FootnotesLegend_175b2401-3654-4673-9e60-b300989088bb.csv"), sep="|", engine = "python") Pandas supports only gzip and bz2 in read_csv: compression : {‘gzip’, ‘bz2’, ‘infer’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’, then use gzip or bz2 if filepath_or_buffer is a string ending in ‘.gz’ or ‘.bz2’, respectively, and no decompression otherwise. Set to None for no decompression.
{ "pile_set_name": "StackExchange" }
Q: LibGdx Project Runs on desktop but not on Android simulator I recently started learning LibGdx I made a splash screen. It runs on desktop quite fine but when i try to run on android emulator/simulator or android mobile it doesn't runs. It shows a black screen only. Please help me over this. I've attached the link to project in this query. https://docs.google.com/file/d/0B38mBPsRVO3ScU83M1dXblItS00/edit?usp=sharing i am adding code here Android Applications AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); cfg.useGL20 = true; Main LibGdx Project Code public void show() { batch = new SpriteBatch(); Texture splashTexture = new Texture("image/splash.PNG"); splash = new Sprite(splashTexture); splash.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } public void render(float delta) { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); splash.draw(batch); batch.end(); } Its the simple splash screen code. I did research on net but didn't find anything useful with this. Please Help me over this. A: @Override public void show() { manaer=new AssetManager(); batch = new SpriteBatch(); manager.load("Image/splash.PNG",Texture.class); manager.finishLoading(); Texture splashTexture = manager.get("Image/splash.PNG",Texture.class); splash = new Sprite(splashTexture); splash.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } Thing is ur assets is not completely loaded before it is drawn. so using manager.finishloading() u compel the code to stop execution till image gets loaded
{ "pile_set_name": "StackExchange" }
Q: Image not appearing, shows 0 x 0 pixels The image is not showing, and when I inspect element, it shows "0 x 0 pixels (Natural 620px x 480px)". Putting a display:block on the img didn't help. How can I fix this? The test site is below, image should appear on the left under the "FREE SHIPPING ON ORDERS OVER $99" promo. (link removed) A: The image appears for me if I turn off the Chrome extension Ghostery, which you are probably running as well (or a similar ad blocking extension). The image is classified as an advertisement and therefore hidden.
{ "pile_set_name": "StackExchange" }
Q: Is there a point to collecting as many cyber-hearts as possible? In Far Cry 3: Blood Dragon, cyber-hearts are looted from fallen enemies. Similar to Far Cry 3, looting / pilfering takes some time, which can be quite annoying when you have or want to do it frequently. I learned that cyber-hearts can be used to lure blood dragons to a location. Aside from that, are there other uses for the cyber-hearts? Should I attempt to collect as many cyber-hearts as possible or just stockpile enough to be able to lure blood dragons? A: you can only hold 99 hearts, and when you get the skill for auto-loot on takedown, this number will be reached very quickly (if you do a lot of takedowns of course). You'll probably only use maybe 25 hearts throughout the whole game, though. I would still continue to loot cyber soldiers (just not obsessively), because they do give money. A: Cyberhearts are only useful for luring blood-dragons. You rarely need to do that, and when you do, you only need a few of them. But notice that looting enemies does not just give you cyber hearts, it also gives you some credits.
{ "pile_set_name": "StackExchange" }
Q: tar to pipe but keep -v verbose output separate from STDERR A normal tar command tar cvf foo.tar ./foo >foo.out 2>foo.err has three output IO streams archive data to foo.tar list of filenames to STDOUT (redirected into foo.out) error messages to STDERR (redirected into foo.err) I can then inspect foo.err for error messages without having to read through the list of filenames. if I want to do something with the archive data (pipe it through netcat or a special compression program) I can use tar's -f - option thus tar cvf - ./foo 2>foo.err | squish > foo.tar.S But now my list of filenames is mixed in with my error messages because tar's -v output obviously can't go to STDOUT (that's where the archive data flows) so tar cleverly writes that to STDERR instead. Using Korn shell, is there a way to construct a command that pipes the archive stream to another command but still capture the -v output separately from any error messages. A: If your system supports /dev/fd/n: tar cvf /dev/fd/3 ./foo 3>&1 > foo.out 2>foo.err | squish > foo.tar.S Which with AT&T implementations of ksh (or bash or zsh) you could write using process substitution: tar cvf >(squish > foo.tar.S) ./foo > foo.out 2>foo.err That's doing exactly the same thing except that this time, the shell decides of which file descriptor to use instead of 3 (typically above 9). Another difference is that this time, you get the exit status of tar instead of squish. On systems that do not support /dev/fd/n, some shells may resort to named pipes for that feature. If your system doesn't support /dev/fd/n or your shell can't make use of named pipes for its process substitution, that's where you'd have to deal with named pipes by hand. A: You have to use a named pipe for that. First create one in the folder: mkfifo foo.pipe Then use that command: tar cvf foo.pipe ./foo >foo.out 2>foo.err & cat foo.pipe >foo.tar Notice: the cat-part, can now also be gzip or whatever, that can read from a pipe: tar cvf foo.pipe ./foo >foo.out 2>foo.err & gzip -c foo.pipe >foo.tar Explanation: The output is written to the name pipe (foo.pipe), where another proccess (cat, gzip, netcat) reads from. So you don't loose the stdout/stderr channels for information. A: GNU tar's --index-file option works well: tar cvf - ./foo 2>foo.err --index-file=foo.out | squish > foo.tar.S
{ "pile_set_name": "StackExchange" }
Q: Fourier series of translated square I can't seem to find the correct Fourier series coefficients ($s_n$) of the following periodic function. I know how to get the Fourier series of the same one that is not vertically translated and has no negative values for any $t$ (Result is $A sinc(n\pi)$), but this one I'm having trouble with. The function is periodic, and during it's period T, is defined with: $$ x(t) = \begin{cases} A, & t\in(0,\frac{T}{4}) \\ -A, & t\in(\frac{T}{4},\frac{3T}{4}) \\ A, & t\in(\frac{3T}{4},T) \end{cases} $$ How I tried solving this: $$ s_n = \frac{1}{T}\int_{-T/2}^{T/2}{x(t)e^{-inw_0t}dt} = \frac{1}{T}\Bigg[\int_{-T/2}^{-T/4}{-Ae^{-inw_0t}dt} + \int_{-T/4}^{T/4}{Ae^{-inw_0t}dt} + \int_{T/4}^{T/2}{-Ae^{-inw_0t}dt}\Bigg]$$ Integrating I get: $$ s_n = \frac{A}{inw_0T}\Bigg[ (e^{inw_0\frac{T}{2}}-e^{-inw_0\frac{T}{2}})-2(e^{inw_0\frac{T}{4}}-e^{-inw_0\frac{T}{4}})\Bigg]$$ Applying Euler's identity and $w_0 = \frac{2\pi}{T}$ and the definition of the $sinc$ function finally I get: $$ s_n = Asinc(n\pi) - Asinc(\frac{n\pi}{2})$$ That differs from the answer I have in my textbook which says the answer is only $A sinc(\frac{n\pi}{2})$. It would help if someone could shed some light on where I've done wrong. A: Since it is said that $x$ is $T$-periodic, you have that $x(t) = -A$ for $t\in(-T/2,-T/4)$, so you will have to re-evaluate the integrals. Then, note that $$\text{sinc}(n\pi) = 0$$
{ "pile_set_name": "StackExchange" }
Q: Stuck on a particular 2nd order non-homogeneous ODE ($y'' + 4y' + 5y = t^2$) $y'' + 4y' + 5y = t^2$ So I solve for $r^2 + 4r + 5 = 0$ returning $r = 2 \pm 2i$. So $y_c = e^{-2t}(C_1\cos(2t) + C_2\sin(2t)$. For $y_p(t)$ I pick $At^2$. So $2A + 8At + 5At^2 = t^2$. I have been stuck on finding a particular solution for 30 minutes now. My first question: Is there any particular method for finding $y_p(t)$? Secondly, how to find $y_p(t)$ here? A: You should use method of undetermined coefficients. Take $$y_{p}(t)=at^2+bt+c$$ then $$ y'_{p}(t)=2at+b $$ $$ y''_{p}(t)=2a $$ and substitue it in differential equation $$2a+8at+4b+5at^2+5bt+5c=t^2$$ from equality of polynomials we have $5a=1,8a+5b=0,2a+4b+5c=0$ from here we can find $a=\frac{1}{5},b=\frac{-8}{25},c=\frac{22}{125}$. So $$ y_{p}(t)=\frac{1}{5}t^2+\frac{-8}{25}t+\frac{22}{125} $$
{ "pile_set_name": "StackExchange" }
Q: How to inject angular services correctly I created a service called notifier that use toastr to alert the user during the log in process if the user successfully logged in or not. here is my log in module: var login = angular.module('login',[]); login.controller('mvLoginCtrl', function($scope, $http){ $scope.signin = function(username, passowrd){ $http.post('/login', {username:username, passowrd:passowrd}).then(function(response){ if(response.data.success){ mvNotifier.notify('You have successfully signed in!'); }else{ mvNotifier.notify('Username/Password combination incorrect'); } }) } }) i got no errors till here but when i try to sign in i get this obvious error : ReferenceError: mvNotifier is not defined i changed my log in module at the line 2 including the required dependencies: login.controller('mvLoginCtrl', function($scope, $http, mvNotifier) but then i got different error Error: [$injector:unpr] http://errors.angularjs.org/1.2.20/$injector/unpr?p0=mvIdentityProvider%20%3C-%20mvIdentity and i want to ask what is the reason i got this error and how to solve it. here is my mvNotifier module code: var notifier = angular.module('notifier', []); notifier.value('mvToastr', toastr); notifier.factory('mvNotifier', function(myToastr){ return{ notify: function(msg){ mvToastr.success(msg); console.log(msg); } } }) thank you. A: You need to inject myNotifier something like this: var login = angular.module('login',['notifier']); login.controller('mvLoginCtrl', ['$scope','$http','mvNotifier',function($scope, $http,mvNotifier){ $scope.signin = function(username, passowrd){ $http.post('/login', {username:username, passowrd:passowrd}).then(function(response){ if(response.data.success){ mvNotifier.notify('You have successfully signed in!'); }else{ mvNotifier.notify('Username/Password combination incorrect'); } }) } }]) More on Dependency Injection
{ "pile_set_name": "StackExchange" }
Q: Blindly converting structs to classes to hide the default constructor? I read all the questions related to this topic, and they all give reasons why a default constructor on a struct is not available in C#, but I have not yet found anyone who suggests a general course of action when confronted with this situation. The obvious solution is to simply convert the struct to a class and deal with the consequences. Are there other options to keep it as a struct? I ran into this situation with one of our internal commerce API objects. The designer converted it from a class to a struct, and now the default constructor (which was private before) leaves the object in an invalid state. I thought that if we're going to keep the object as a struct, a mechanism for checking the validity of the state should be introduced (something like an IsValid property). I was met with much resistance, and an explanation of "whoever uses the API should not use the default constructor," a comment which certainly raised my eyebrows. (Note: the object in question is constructed "properly" through static factory methods, and all other constructors are internal.) Is everyone simply converting their structs to classes in this situation without a second thought? Edit: I would like to see some suggestions about how to keep this type of object as a struct -- the object in question above is much better suited as a struct than as a class. A: For a struct, you design the type so the default constructed instance (fields all zero) is a valid state. You don't [shall not] arbitrarily use struct instead of class without a good reason - there's nothing wrong with using an immutable reference type. My suggestions: Make sure the reason for using a struct is valid (a [real] profiler revealed significant performance problems resulting from heavy allocation of a very lightweight object). Design the type so the default constructed instance is valid. If the type's design is dictated by native/COM interop constraints, wrap the functionality and don't expose the struct outside the wrapper (private nested type). That way you can easily document and verify proper use of the constrained type requirements.
{ "pile_set_name": "StackExchange" }
Q: Java Parsing A Json File Line To Return Part Of The Line I am having some trouble trying to figure out how to parse a line in a json file so that it only returns part of the line as a string. I will illustrate below: public String GetDistance(String origin, String destination) throws MalformedURLException, IOException { //URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins" + origin + ",UK+destination=" + destination + ",UK&key=mykey"); URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Cornwall,UK&destinations=London,UK&key=mykey"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String line, outputString = ""; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { if (line.contains("distance")) { outputString = reader.readLine().trim(); return outputString; } } return outputString; } What this function does is create a json file in my browser using Google Maps API: { "destination_addresses" : [ "London, UK" ], "origin_addresses" : [ "Cornwall, UK" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "284 mi", "value" : 456443 }, "duration" : { "text" : "4 hours 52 mins", "value" : 17530 }, "status" : "OK" } ] } ], "status" : "OK" } Currently the "outputString" returns the line: "text" : "284 mi". However, the desired output is to just return the miles, "284". I know this is most likely a re post, however I have been searching around for a solution to this and have been unsuccessful in implementing something that works. Any help on this would be greatly appreciated, Cheers. A: You can have 2 solutions: Parse the JSON and treat it as an object and then just return the String you're looking for. Split the line as follows: outputString = reader.readLine().trim(); That line above returns "text" : "284 mi" Then you need to split the line by :: outputString.split(":") That should create an array with 2 Strings: "text" and "284 mi" Then take the second String and split it by a space and take the first String: outputString.split("\\s") Now you have: "284 Then just return it from subindex 1 till the end, see docs: outputString.substring(1) And then just put it all together: return outputString.split(":")[1].split("\\s")[0].substring(1) I haven't tried above code but it should work. BTW follow Java Naming Conventions firstWordLowerCaseVariable firstWordLowerCaseMethod() FirstWordUpperCaseClass ALL_WORDS_UPPER_CASE_CONSTANT And use them consistently
{ "pile_set_name": "StackExchange" }
Q: ¿Por qué al agregar información a una variable, esta se superpone? Quiero traer el resultado de una sesión ssh a una variable local FILEBACK=$(sshpass -p 'pass' ssh [email protected] -p 22 -o StrictHostKeyChecking=no ':put $rvar;') al ver la variable el resultado es el correcto: $ echo "$FILEBACK" HOLA_COMO Pero si quiero agregarle una extensión a ese valor, se sobrepone al principio: $ echo "$FILEBACK.estas" .estasOMO el ".estas" se coloca sobre la parte de la variable "HOLA_C" y se muestra el resto. A: El problema está en que la cadena que coges tiene un retorno de carro "\r", por lo que cuando añades texto, lo hace a partir del principio de la misma línea: $ printf "hola\rXX\n" XXla # en lugar de "hola", sobrescribe XX encima del principio de "hola" Por tanto, lo que debes hacer es eliminar este carácter de tu cadena: FILEBACK=$(sshpass -p ... | tr -d '\r') En mi ejemplo de antes: $ printf "hola\rXX" | tr -d '\r' holaXX
{ "pile_set_name": "StackExchange" }
Q: NSDateComponents possible timezone bug? Wonder if I've found a bug with NSDateComponents. When using NSDateComponents to calculate dates and switching between time zones, it's possible to get the wrong date on the simulator (not tested on device). It seems that it's the right offset, but going in the wrong direction. Either that, or I'm fundamentally misunderstanding something (which is always a distinct possibility). Sample: Set the system time to a time zone other than UTC (mine was Mexico, UTC-05:00) // Get the components for the current absolute time. NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]]; // Get the calendar, which seems to set the time zone to the current time zone components.calendar = [NSCalendar currentCalendar]; // Set the time zone to UTC components.calendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; // Log the date NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]); // Outputs (e.g): "Date at time zone: GMT (GMT) offset 0 : 2013-06-21 14:55:56 +0000" // This should be absolute time, so any changes in the time zone should offset // relative to this. // Set the time zone to the local time zone (e.g. Mexico, 5 hours behind) components.calendar.timeZone = [NSTimeZone localTimeZone]; // Log the date NSLog(@"Date at time zone: %@ : %@", components.calendar.timeZone, [components date]); // Outputs (e.g.): "Date at time zone: Local Time Zone (America/Mexico_City (CDT) offset -18000 (Daylight)) :2013-06-21 19:55:56 +0000" Assuming Mexico, shouldn't the second date be five hours behind the first? A: After you have set components.calendar.timeZone to the Mexican time zone, components represents (in your example) 2013-06-21 14:55:56 in the Mexican time zone therefore [components date] returns an NSDate for that point in time. The NSLog output uses the description method of NSDate, and that prints the point in time always in the GMT time zone, which is 2013-06-21 19:55:56 +0000 So everything looks OK to me.
{ "pile_set_name": "StackExchange" }
Q: Is less than not working in a SQL query PHP I have a MYSQL table like this: point | z_id | ok| 300697.12 | 391 | 1 | 300701.88 | 391 | 1 | 300576.78 | 391 | 1 | 300576.78 | 391 | 1 | and I run this query SELECT MAX( `point` ) as `max` FROM `my_table` WHERE `point` < 300701.88 AND `z_id`='391' AND `ok`=1 It should return 300697.12, but I get 300701.88, I tried to put the number into '', but I get the same results. Even if I run the query like this SELECT * FROM `my_table` WHERE `point` < 300701.88 AND `z_id`='391' AND `ok`=1 the 300701.88 result is still there. My field type for point is float(10,2). Is there a problem with sql considering the number as a text? Thanks a lot :) A: From Mysql Docs Floating-point numbers sometimes cause confusion because they are approximate and not stored as exact values. A floating-point value as written in an SQL statement may not be the same as the value represented internally. Attempts to treat floating-point values as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies. The FLOAT and DOUBLE data types are subject to these issues. For DECIMAL columns, MySQL performs operations with a precision of 65 decimal digits, which should solve most common inaccuracy problems Clearly float datatype is the problem here which is also known as approximate datatype which will not store the exact value. This is the reason float should be avoided. Changing the datatype from float(10,2) to Decimal(10,2) will fix your problem Here is the demo
{ "pile_set_name": "StackExchange" }
Q: Is the cuspidal cubic $\{y^2 = x^3\} \subset \Bbb R^2$ not smooth? Cuspidal cubic $y^2=x^3$ in $\Bbb R^2$ "seems to be not smooth" intuitively because its pictured graph has a cusp at the origin. But I read from book that it is a smooth manifold. I feel so confused. How do we understand "smooth"? Furthermore, it is not a regular submanifold of $\Bbb R^2$. I don't know how to prove this. Any help will be appreciated. A: The cuspidal cubic $C := \{(x, y) : y^2 = x^3\} \subset \Bbb R^2$ certainly admits a smooth structure: The projection $C \to \Bbb R$ onto the $y$-axis is continuous and has continuous inverse $y \mapsto (y^{2 / 3}, y)$, so it is a homeomorphism, and hence using it to pull back the (usual) smooth structure on $\Bbb R$ defines a smooth structure on $C$. Like you say, however, $C$ is not an embedded (regular) submanifold of $\Bbb R^2$: the pullback by inclusion $C \hookrightarrow \Bbb R^2$ does not define a smooth structure on $C$. (One way to see this is to regard tangent vectors as equivalence of curves into $C$ and observe that any curve $\gamma: (-\epsilon, \epsilon) \to C$ such that $\gamma(0) = (0, 0)$ must satisfy $\gamma'(0) = (0, 0)$.)
{ "pile_set_name": "StackExchange" }
Q: How to inject SVG icon sprites in Angular component HTML DOM? I am building an Angular application (Angular 4/5/6) and would like to use SVG sprites in my component template. Question: Assuming I already have my SVG icon sprite generated (icons.svg), how can I get Angular to inject/import my SVG icon sprite into my component's template? Is there a way to inject/import my SVG icon sprite into my component without having to use any 3rd party modules/directives and do it natively with Angular itself? Background/Issue: As discussed in this article, icons.svg file would contain all the SVG icons defined as <symbol>. Then I can render selected icons in my HTML using <use> assuming the icons.svg is injected in the DOM. I generated SVG sprites using IcoMoon app, and saved the icons.svg into my Angular application. Below is my sample Angular component (app.component.ts) in which I am trying to inject/import the icons.svg file and trying to render the SVG icons in my HTML. However, Angular is not rending my SVG icons. I seems I am incorrectly injecting the SVG icon sprite file. Updates: I am already aware of a similar question, SVG icon system with angular-cli, where the suggested answer was to use the Node module svg-sprite to generate a SVG sprites using the CSS mode. However, this is NOT what I am asking. I am NOT trying to generate the SVG sprites. I am trying get Angular components to be aware of my SVG sprite, icons.svg, and get it to render them in the HTML whenever I make use of them. A solution was suggested,https://stackoverflow.com/a/50460361/4988010, to generate a CSS font from the SVG sprite. I feel this is NOT a feasible solution and instead is a "workaround" to not being able to use the SVG sprite. app.component.ts: Live example on StackBlitz: https://stackblitz.com/edit/angular-bbr2kh?file=src/app/app.component.ts import { Component } from '@angular/core'; // import `./icons.svg`; // This import method doesn't work @Component({ selector: 'my-app', template: ` <!-- This import method doesn't work --> <!-- <script src="./icons.svg"></script> --> <p> Hello this is a sample Angular 6 component. </p> <p>Testing to see if SVG icon sprite import works. See below if icons appear. </p> <p>Icon (home): <svg class="icon icon-home"><use xlink:href="#icon-home"></use></svg> </p> <p>Icon (rocket): <svg class="icon icon-rocket"><use xlink:href="#icon-rocket"></use></svg> </p> <p>Icon (wifi): <svg class="icon icon-connection"><use xlink:href="#icon-connection"></use></svg> <!-- This import method doesn't work --> <!-- <p>Icon (home): <svg class="icon icon-home"><use xlink:href="./icons.svg#icon-home"></use></svg> </p>--> </p> `, styles: [` .icon { display: inline-block; width: 1em; height: 1em; stroke-width: 0; stroke: currentColor; fill: currentColor; } `] }) export class AppComponent { } A: I think your root path is where you are having problems. In your code you are telling angular to look in app but the browser sees this as https://your-site.com./icons If you move your icon file under your /assets folder, then it should be available already because the src\assets folder is already included in angular.json, the "assets" collection tells Angular where to look. <svg class="icon"> <use xlink:href="/assets/icons.svg#icon-rocket"></use> // Notice root path not "./" </svg> If you would like your files to be served from another directory all you need to do is add a path in your angular.json: … "assets": [ "src/favicon.ico", "src/assets", "src/your-dir" ], … Then in your code <svg class="icon"> <use xlink:href="/your-dir/icons.svg#icon-rocket"></use> </svg> I wouldn't suggest adding /src/app as an asset path, this would basically open up your entire app for serving files, making your entire directory accessible. I forked your example and updated here
{ "pile_set_name": "StackExchange" }
Q: ElastiCache not utilizing read only replica I have a simple Redis ElastiCache cluster (cluster mode disabled) with a master node and a read only replica. When throwing traffic at the server, i.e. from redis-benchmark, it seems all GET traffic goes only to the master node, while the RO replica gets zero GET traffic (cache hit/miss and GetTypeCommands are all 0). Anyone has insights on why this is happening? I expected the traffic would be distributed between the two nodes. A: older question but I am answering since I am just learning this myself... I thought that the purpose was to balance the load between master and slave, but that is not the case. The slave exists so that it can be promoted to master if master fails for any reason. further reading: https://redis.io/topics/replication
{ "pile_set_name": "StackExchange" }
Q: Splash screen for universal windows 10 apps I am creating a windows 10 universal app targeted for both Windows Phones and Windows Desktop, the problem I am facing on is when adding splash screen through the package.manifest file to the app, there is no option to add splash screen which fits the phone's portrait orientation (see the image below), And when I deploy the app on the phone the splash screen appears like shown below. A: In this case, you will also want to specify the Background color, on your first screenshot. Read this - For a Windows Phone Store app, provide the 2.4x asset at a minimum; preferably all. The image file assets themselves should have a transparent background. In your app manifest, set the value of the SplashScreen@Image property to "Assets\.png", and set a value for VisualElements@BackgroundColor. You can read more from this link. The first half of the link seems to be talking about splash screens in the Windows 8.1 & Windows Phone 8.1, including the paragraph I quoted above, but the same rules apply to Windows 10. I don't think you can have a full page splash screen given all the different sized devices. Previously it would still be possible 'cause you could simply remove the splash screen and create a xaml startup usercontrol within your app, but since the splash screen becomes mandatory in UWP, I just don't see any other way to achieve this. A: If you want to make an advanced splash screen with a bigger image and ProgessBar or a ProgressRing . You should check Msdn on "how to extend the splash screen". You can read more about the Extended splash screen here. Best of luck !
{ "pile_set_name": "StackExchange" }
Q: Hadoop Pig ISO Date to Unix Timestamp I have a list of items in Pig consisting of ISO 8601 (YYYY-MM-DD) formatted date strings: (2011-12-01) (2011-12-01) (2011-12-02) Is there any way to transform these items into UNIX timestamps apart from implementing my own functions in Java? A: You need a UDF to do that = The good news it has already been done. Pig also comes with "piggybank" UDFs contributed by the community including date convert
{ "pile_set_name": "StackExchange" }
Q: Are there LEGO plates without the word “LEGO” on the studs? Yes, this question has already been asked here. This time, however, I was wondering if anyone can point to official LEGO web page on which this fact is confirmed. I've already read "Fair Play" document and "Fair Play Brochure" but all what they say is that "the LEGO logo is a trade mark and cannot be used w/o permission" meaning that if I have a brick with LEGO logo on it then I can be 99,99% sure that this is a genuine LEGO brick. What I need, however, is the "opposite" i.e. a sentence claiming that "a stud on a genuine LEGO brick has always had the LEGO logo since the year 19xx" or even more: "a stud on a genuine LEGO brick has never had this round cavity on the top" (cavities I mention are present e.g. on studs here). I've already asked the same question via the contact form on the official LEGO support page but received no answer yet. Context: I'm currently having a dispute whether a set of bricks that some guy sold me were genuine LEGO bricks. He claims that they were, I know that they were not. I will, however, have to provide evidence to the police. Information on lego.com page or answer from lego.com would do in my opinion. High resolution images of the 42009 set (battery part) on official LEGO page would also be good but this set is no longer present on lego.com this set does not have the close up of the part I need. High resolution images of 8293 (Power Functions Motor Set) are there but are they a proof I don't know yet (one can always say that these parts have LOGO lego now but they didn't in 2013). There is a movie with 42009 on lego.com but it is rendered and does not present real bricks and not sure if can be used. EDIT: yes, all the pieces of the brick set I received (the supposed 42009 set) are forged. I can tell this because the bricks I received differ in many aspects from bricks from original LEGO sets I've assembled so far (more than a dozen sets, mostly > 1000 bricks): some of them connect poorly, some of them connect so hard I struggled a lot to disconnect; the surface of liftarms is not as straight as LEGO liftarms; the liftarms have this extra filling around holes (google "lepin liftarm" and choose "large images" in "adv search" to see what I mean); some pieces are not cut properly e.g. the bushes have thin pieces of plastic connected to the hole on the side; and the main one: there is no LEGO logo on any of the parts: not only the studs but also the battery box and motor. However from legal point of view I can't just say that I am sure that these are not LEGO bricks. Moreover I cannot even prove that the bricks I present are indeed the bricks that the other guy sent me. So I took a closer look at the pictures from the auction (the pictures the seller made himself = the pictures of actual brick set he sent me) and found pieces with studs with no LEGO logo (Black Plate 2x3 (3021) , Motor 9V Power Functions L (99499c01) ). I was extremely lucky that this seller made pictures with such high resolution. And yes, I contacted the LEGO support and sent them exacly the same pictures as below and they confirm that these are NOT original LEGO bricks. I will post their full answer and some more content soon. A: If you would like to get an official statement on this, your best bet is to contact LEGO's customer service. Here are some pointers you might consider when communicating with them: It seems like your question is about some of the electronic components. So, let's narrow down your question to those. The battery in the #42009 LEGO Mobile Crane has two studs on top with the LEGO logo on them. In addition, right above the studs their is a "2006 The LEGO Group" moulded into the lighter colored plastic. And there are also larger LEGO logos moulded into the sides of the unit. So, five LEGO logos in total. This battery box has no alternates. It only came in this one version as evidenced by the BrickLink database, which is the most comprehensive database of all LEGO parts every made: ELECTTRIC 9-VOLT BATTERY BOX I would also add to this that smooth LEGO studs always have the LEGO logo moulded into them, and this has always been the case since the earliest days of the company. There are hollow studs (like in some electronic pieces, LEGO Technic pieces, LEGO windows, hollow 1x1 round studs, etc.), however in such cases the LEGO logo will appear on some other place on the piece. The very few exceptions to this rule are when pieces are so tiny that it was simply not possible/practical to print a LEGO logo on them (i.e. hollow 1x1 round stud, some very small minifigure accessories, etc.) Rather than being too generic like you did in your question above, when contacting LEGO's customer service, I would suggest to focus on two points. This can result in a quicker response and faster action. Ask them whether the specific electronic parts you are concerned about (list exact set and part numbers) were ever produced without a LEGO logo (the answer will be no, but for your legal case it's best to have this in writing directly from LEGO). Alert LEGO that someone is selling fake parts and claiming that they are genuine. LEGO's legal department will be very interested in this, which can help your personal case. It's even possible that this seller has been on their radar already, and the information you provide will be helpful to their case. There are lots of imitation LEGO out there, but the companies making them do not claim that their products are genuine LEGO. They sell under their own brand names for cheaper prices than LEGO can provide. LEGO's legal department is fighting these companies already. Someone selling fake LEGO and claiming that it's genuine is a whole other level of criminal. Please keep in mind that if this is someone like a small eBay seller, they may have been duped themselves and they really believed that the parts they acquired are genuine LEGO. So keep your communication professional and you may be satisfied with just a refund. If, however, the seller is a larger online store specializing in fake LEGO parts and selling them as genuine, definitely let LEGO's legal department know and you may pursue your own legal case as well.
{ "pile_set_name": "StackExchange" }
Q: How to re-ordering this dataframe? I read some txt file in R. For some reasons, the order of the text has been changed. Now, I want to re-order the dataframe. It will surely be silly but I got stuck on this and I can't find what I need on previous answers. Let's take this example, I have the following situation: df <- data.frame(doc_id = c(3, 10, 7, 1, 5, 2, 8, 4, 6, 9), Text = c("Text Text", "Text Stackoverflow", "Text Nice", "Text", "Text Not Nice", "Text Help", "Text Great", "Text programming", "Text Bad", "Text Example")) doc_id Text 1 3 Text Text 2 10 Text Stackoverflow 3 7 Text Nice 4 1 Text 5 5 Text Not Nice 6 2 Text Help 7 8 Text Great 8 4 Text programming 9 6 Text Bad 10 9 Text Example The first column needs to be re-ordered and the second column (just text) needs to follow the reordering in the first column. This is what I would like to get. doc_id Text 1 1 Text 2 2 Text Help 3 3 Text Text 4 4 Text programming 5 5 Text Not Nice 6 6 Text Bad 7 7 Text Nice 8 8 Text Great 9 9 Text Example 10 10 Text Stackoverflow Thanks a lot for your help. A: We can use arrange library(dplyr) df %>% arrange(doc_id) A: In Base: df[order(df$doc_id),] A: The other answers are excellent but since I often work on huge data, I would like to suggest the setorder() function from the data.table package. You'll find it useful if you ever work on some huge data frame/data table. setorder() should be faster than the base version and dplyr. Exemple : library(data.table) df <- setorder(df, doc_id)
{ "pile_set_name": "StackExchange" }
Q: Change class of a menuitem to active if page alias matches menu alias (in a foreach) I got a simple sidemenu that is displayed using a foreach: <? if($contentcr[0]['catid'] == '9'){ foreach($pagecr as $page){ $landingnospace = str_replace(' ', '_', $page['alias']); $title = $page['title']; if($title != '') { $contentje .= '<li><a href="http://www.website.nl/_extern/website1/'.$landingnospace.'.html">'.$title.'</a></li>'; } } echo $contentje; } else{ echo 'Alternatief sidemenu'; } ?> The alias of the page is displayed in the url using .htaccess: DirectoryIndex RewriteEngine on RewriteBase /_extern/website1/ #Indexes uitzetten Options -Indexes #Website1 RewriteRule ^(.*).html content.php?alias=$1 [L] I am currently using two queries on the page, one for db_content and one for db_categories db_content: // content $content = "SELECT * FROM `db_content` WHERE alias = '".$_GET['alias']."' "; $contentcon = $conn->query($content); $contentcr = array(); while ($contentcr[] = $contentcon->fetch_array()); db_categories // Pages $page = "SELECT con.title, con.alias, con.images, con.introtext FROM db_content con LEFT JOIN db_categories cat ON con.catid = cat.id AND cat.alias = '".$_GET['alias']."' WHERE con.state = 1 ORDER BY `ordering` DESC"; $pagecon = $conn->query($page); $pagecr = array(); while ($pagecr[] = $pagecon->fetch_array()); So how can I compare the results in the foreach to the alias in the url, and if they match add the class: current-menu-item to the list tag? A: You could introduce a $class variable and see if the current $page["alias"] equals the $_GET["alias"]. If so, apply the class current-menu-item, if not, leave it blank. <? if($contentcr[0]['catid'] == '9'){ $alias = $_GET["alias"]; foreach($pagecr as $page){ $landingnospace = str_replace(' ', '_', $page['alias']); $title = $page['title']; if($title != '') { // magic happens here $class = ($page["alias"] == $alias)?"current-menu-item":""; $contentje .= '<li><a class="'.$class.'" href="http://www.website.nl/_extern/website1/'.$landingnospace.'.html">'.$title.'</a></li>'; } } echo $contentje; } else{ echo 'Alternatief sidemenu'; } ?>
{ "pile_set_name": "StackExchange" }
Q: Does an existing gruntfile need to be edited? What is the common workflow? For an existing app, is there a proper protocol for specifying bower packages such that they're handled correctly when running "grunt build"? Does an existing gruntfile need to be edited? What is the common workflow? A: Your question is very abroad... If you are using a 3rd party package that is not yours, you don't need to edit the gruntfile.js. However the gruntfile.js for your app will be created/edited to fit your app needs.
{ "pile_set_name": "StackExchange" }
Q: How to manage AWS Secret Keys for local development I'm writing a lambda function in Python 3.8. The function connects with a dynamodb using boto3: db = boto3.resource('dynamodb', region_name='foo', aws_access_key_id='foo', aws_secret_access_key='foo') That is what I have while I am developing on my local machine and need to test the function. But, when I deploy this to lambda, I can just remove the credentials and my function will connect to the dynamodb if I have the proper IAM roles and policies setup in place. For example, this code would work fine when deployed to lambda: db = boto3.resource('dynamodb', region_name='foo') The question is, how can I manage this in terms of pushing code to lambda? I am using AWS SAM to deploy to AWS. Right now what I do is once I'm done developing my function, I remove the aws_access_key_id='foo' and aws_secret_access_key='foo' parts manually and then deploy the functions using SAM. There must be a better way to do this? Could I embed these into my IDE instead? I'm using PyCharm. Would that be a better way? If not, what else? A: You should never put credentials in the code like that. When running the code locally, use the AWS CLI aws configure command to store local credentials in a ~/.aws/config file. The AWS SDKs will automatically look in that file to obtain credentials.
{ "pile_set_name": "StackExchange" }
Q: TextPad Regex: How to Find and Replace character within angle brackets? I've got the below sample text Hello | World <Hi | Hello|How | are | you><test|string |for |regex> sample | text <however|replace|pipe> to be converted as below Hello | World <Hi ~ Hello~How ~ are ~ you><test~string ~for ~regex> sample | text <however~replace~pipe> i.e. Replace | within <> with ~ I tried this <(?:.*?)(\|)(?:.*?)> (http://regex101.com/r/mX1sO0) But it matches only the first | withing the angle <>. And I am not sure how to replace it. Any directions? A: If your angle brackets are never nested and always correctly balanced, then you can do it: \|(?=[^<>]*>) matches only those pipe characters where the next angle bracket is a closing angle bracket. Then just replace the matches with ~. See it live on regex101.com.
{ "pile_set_name": "StackExchange" }
Q: filter array of objects by array of values es6 i need a help to do a function to filter an array of object by an a array with values, example: my array with objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smith', age: 27, allergy: [ { idAllergy: 1, name: 'Fish' },{ idAllergy: 2, name: 'Nuts' } ] }, { personId: 2, name: 'Lara', lastName: 'Blake', age: 21, allergy: [ { idAllergy: 2, name: 'Nuts' } ] }, { personId: 3, name: 'Erick', lastName: 'Robinson', age: 30, allergy: [ { idAllergy: 3, name: 'Flowers' } ] }, { personId: 4, name: 'Hilda', lastName: 'Vianne', age: 35, allergy: [ { idAllergy: 4, name: 'Chocolat' } ] } ] my array with values to filter: // these are idAllergy let allergy = [2,3] so the plan is use allergy array values to seach into persons for people who has allergy to nuts and flowers and dont show them so my expected result will be: [{ personId: 4, name: 'Hilda', lastName: 'Vianne', age: 35, allergy: [ { idAllergy: 4, name: 'Chocolat' } ] }] thanks in advance A: const filtered = persons.filter(p => !p.allergy.some(a => allergy.includes(a.idAllergy))); const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smith', age: 27, allergy: [ { idAllergy: 1, name: 'Fish' },{ idAllergy: 2, name: 'Nuts' } ] }, { personId: 2, name: 'Lara', lastName: 'Blake', age: 21, allergy: [ { idAllergy: 2, name: 'Nuts' } ] }, { personId: 3, name: 'Erick', lastName: 'Robinson', age: 30, allergy: [ { idAllergy: 3, name: 'Flowers' } ] }, { personId: 4, name: 'Hilda', lastName: 'Vianne', age: 35, allergy: [ { idAllergy: 4, name: 'Chocolat' } ] } ] let allergy = [2,3] const filtered = persons.filter(p => !p.allergy.some(a => allergy.includes(a.idAllergy))); console.log(filtered);
{ "pile_set_name": "StackExchange" }
Q: How to limit access to certain users for those who have "administer users" permission EDIT: I have found out how to solve the 'administer users permission needed' problem so I don't really need to know the answer for this. I will not delete the question however, since I would like to know the answer out of curiosity anyway. Because of this I need to give the permission 'administer users' to everyone while still being able to manage access to individual users (to their view and edit pages as well as to their cancellation). Therefore I need to restrict users with 'administer users' permission to be able to edit just certain users (based on their id and the id of the user that is to be viewed or edited). (the access function itself is not the problem I already have that one) I thought about doing something like 'Administer Users by Role' plugin but as it seems there are just too many potential security issues there (the 'administer users permission' is not used only in access to user edit/view but e.g in access to user fields settings page as well. Any ideas? A: The administer users permission is a VERY powerful permission and you shouldn't give this permission anyone that you don't trust. Otherwise, the users with that permission can do all nasty things. For example: They can manage fields on user accounts at admin/config/people/accounts/fields They can manage permissions and grant/revoke users including themselves other permissions at admin/people/permissions They can add/cancel/edit users including admins! Conclusion: Never, ever give this permission to ANYONE! There are a few modules that let users granularly administer other users. One of them is the Administer Users by Role. Although, its latest version for Drupal 7 requires to give this mighty permission to the users, but there's a patch, which I also contributed, at this issue page. With this patch, you don't need to give 'administer users' permission to the users and still allow them to administer other users. There are also other related modules, but I cannot tell anything about them since I don't use them: Subuser This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created. Role Delegation This module allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
{ "pile_set_name": "StackExchange" }
Q: How to search a specific item in a string collection in java1.8 using Lambda? I have a collection of items as under List<String> lstRollNumber = new ArrayList<String>(); lstRollNumber.add("1"); lstRollNumber.add("2"); lstRollNumber.add("3"); lstRollNumber.add("4"); Now I want to search a particular RollNumber in that collection. Say String rollNumberToSearch = "3"; I can easily do it by looping through the collection and checking for every items and if there is any match, i can break through the loop and return a true from the function. But I want to use the Lambda expression for doing this. In C# we use(among other options), var flag = lstRollNumber.Exists(x => x == rollNumberToSearch); How to do the same in Java 1.8 ? I tried with String rollNumberToSearch = "3"; Stream<String> filterRecs = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch)); But I know it is wrong? Please guide. A: Your mistake is that you are using stream intermediate operation filter without calling the stream terminal operation. Read about the types of stream operations in official documentation. If you still want to use filter (for learning purposes) you can solve your task with findAny() or anyMatch(): boolean flag = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch)) .findAny().isPresent(); Or boolean flag = lstRollNumbers.stream().filter(rn -> rn.equals(rollNumberToSearch)) .anyMatch(rn -> true); Or don't use filter at all (as @marstran suggests): boolean flag = lstRollNumbers.stream().anyMatch(rn -> rn.equals(rollNumberToSearch)); Also note that method reference can be used here: boolean flag = lstRollNumbers.stream().anyMatch(rollNumberToSearch::equals); However if you want to use this not for learning, but in production code, it's much easier and faster to use good old Collection.contains: boolean flag = lstRollNumber.contains("3"); The contains method can be optimized according to the collection type. For example, in HashSet it would be just hash lookup which is way faster than .stream().anyMatch(...) solution. Even for ArrayList calling contains would be faster. A: Use anyMatch. It returns true if any element in the stream matches the predicate: String rollNumberToSearch = "3"; boolean flag = lstRollNumbers.stream().anyMatch(rn -> rn.equals(rollNumberToSearch));
{ "pile_set_name": "StackExchange" }
Q: PHP Code showing blank screen on browser instead of content The php code with html below is showing a blank white screen when I open it with a web browser. I have set up a php server to run it. What am I doing wrong? <!DOCTYPE html> <html> <head> <title>maro</title> <link rel="stylesheet" href="bootstrap.min.css"> <link rel="stylesheet" href="custom.css"> </head> <body> <div class="container-fluid"> <form action="imagesear.php" method="get"> <div class="row" id="bg"> <div class="col-sm-1" id="resdoodle"> <a href="index.html"><font color="#FF0000">m</font><font color="#FFA500">a</font><font color="#008000">r</font><font color="#0000FF">o</font></a> </div> <div class="col-sm-6" id="searchbx2"> <div class="input-group"> <input type="text" class="form-control" name="search" id="boxstyle2" required> <span class="input-group-btn"> <input type="submit" class="btn btn-secondary" name="search_btn" value="GO" id="btnstyle2"> </span> </div> </div> </div> </form> </div> <div class="result"> <?php $search=$_GET["id"]; $_con=mysqli_connect("localhost","augustus","password"); mysqli_select_db($_con,"websited"); $_sql2="select * from webd where stitle like '%$search%'"; $rs=mysqli_query($_con,$_sql2); if(mysqli_num_rows($rs)<1) { echo "<center><h4><b>Oops! No result found for your query</b></h4></center>"; exit(); } while($resul2=mysqli_fetch_assoc($rs)) { echo "<a href='".$resul2['slink']."'><img src='".$resul2['simg']."' height='200px' id="imgp"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; } ?> </div> <script src="jquery.min.js"></script> <script src="tether.min.js"></script> <script src="bootstrap.min.js"></script> </body> </html> I tried troubleshooting my php server but it's fine since other php codes are running perfectly. Please help fix this code A: I will give you some recommendations that will help you out and will improve your code. First: To have errors displayed, as the first thing you should do, above all the rest of your could, in the very first file you load, is to have the errors enabled for purpose of test. You can do some logic in there to not show up if it's production. You have to use these code line: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); Second: Try not to mix HTML with PHP. I recommend you to check out Smarty PHP Template. As well as, try to look for How to Implement PHP application with Layer Partner, or PHP Applications with MVC. Third As I mentioned before, you should not mix HTML with PHP, also, it's better if you use design pattern, that will put your database connection and logic away from the code of the screen. You should have HTML <= Page.php <=> Database.php Like this, the Page.php will control what will be shown at the HTML, and will use the functions on Database.php to process database data. The HTML page just outputs the values, it's meant to be just a template. Blank Pages: Blank page means you have some PHP error and it stopped. Usually showing the errors on the screen will help. This could be a simple type on your code for example.
{ "pile_set_name": "StackExchange" }
Q: Capistrano deployment error Can't activate jruby-openssl-0.9.5-java I have developed a new Rails (4.1.4) app in JRuby (1.7.10) and I am trying to deploy it with Capistrano v3 on a remote vps. The error I am getting looks like: INFO[551a80fb] Running ~/.rvm/bin/rvm default do bundle install --binstubs /home/deployer/apps/APPNAME/shared/bin --path /home/deployer/apps/APPNAME/shared/bundle --without development test on example.net DEBUG[551a80fb] Command: cd /home/deployer/apps/APPNAME/releases/20140919052426 && ~/.rvm/bin/rvm default do bundle install --binstubs /home/deployer/apps/APPNAME/shared/bin --path /home/deployer/apps/APPNAME/shared/bundle --without development test DEBUG[551a80fb] Gem::LoadError: can't activate jruby-openssl-0.9.5-java, already activated jruby-openssl-0.9.3 DEBUG[551a80fb] DEBUG[551a80fb] raise_if_conflicts at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/specification.rb:1988 DEBUG[551a80fb] DEBUG[551a80fb] activate at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/specification.rb:1238 DEBUG[551a80fb] DEBUG[551a80fb] gem at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_gem.rb:48 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:46 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/security.rb:11 DEBUG[551a80fb] DEBUG[551a80fb] require at org/jruby/RubyKernel.java:1083 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:55 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:53 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/package.rb:1 DEBUG[551a80fb] DEBUG[551a80fb] require at org/jruby/RubyKernel.java:1083 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:55 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:53 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/package.rb:43 DEBUG[551a80fb] DEBUG[551a80fb] require at org/jruby/RubyKernel.java:1083 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:55 DEBUG[551a80fb] DEBUG[551a80fb] require at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/core_ext/kernel_require.rb:53 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/dependency_installer.rb:1 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/rubies/jruby-1.7.10/lib/ruby/shared/rubygems/dependency_installer.rb:4 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundl DEBUG[551a80fb] er-1.7.3/lib/bundler/installer.rb:1 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/installer.rb:2 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/cli/install.rb:1 DEBUG[551a80fb] run at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/cli/install.rb:78 DEBUG[551a80fb] DEBUG[551a80fb] install at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/cli.rb:145 DEBUG[551a80fb] DEBUG[551a80fb] run at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/vendor/thor/command.rb:27 DEBUG[551a80fb] DEBUG[551a80fb] invoke_command at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/vendor/thor/invocation.rb:121 DEBUG[551a80fb] DEBUG[551a80fb] dispatch at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/vendor/thor.rb:363 DEBUG[551a80fb] DEBUG[551a80fb] start at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/vendor/thor/base.rb:440 DEBUG[551a80fb] DEBUG[551a80fb] load at org/jruby/RubyKernel.java:1099 DEBUG[551a80fb] DEBUG[551a80fb] start at /home/deployer/.rvm/gems/jruby-1.7.10@global/gems/bundler-1.7.3/lib/bundler/cli.rb:9 DEBUG[551a80fb] DEBUG[551a80fb] eval at org/jruby/RubyKernel.java:1119 DEBUG[551a80fb] DEBUG[551a80fb] (root) at /home/deployer/.rvm/gems/jruby-1.7.10@global/bin/jruby_executable_hooks:15 This is how the Gemfile looks like: source 'https://rubygems.org' ruby '1.9.3', :engine => 'jruby', :engine_version => '1.7.10' gem 'bouncy-castle-java', '<= 1.50' # my attempt to fix the version of jruby-openssl gem 'jruby-openssl', '0.9.5' # to 0.9.5. Tried with 0.9.3 but with no effect. gem 'rails', '4.1.4' gem 'sass-rails', '~> 4.0.3' gem 'uglifier', '>= 1.3.0' gem 'therubyrhino' gem 'jquery-rails' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc gem 'activerecord-jdbcmysql-adapter' gem 'devise' gem 'devise_invitable', :github => 'scambra/devise_invitable' gem "paperclip" gem 'acts_as_list' gem 'pry-rails', group: :development gem 'rubyzip' gem 'to_bool', '~> 1.0.1' gem "jquery-fileupload-rails" # Use Capistrano for deployment gem 'capistrano', group: :development gem 'capistrano-rvm', group: :development gem 'capistrano-bundler', group: :development gem 'capistrano-rails', group: :development gem 'trinidad', require: false gem 'trinidad_init_services', require: false gem 'rvm1-capistrano3', require: false Capfile: require 'capistrano/setup' require 'capistrano/deploy' require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/assets' require 'capistrano/rails/migrations' require 'rvm1/capistrano3' Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } deploy.rb: # config valid only for Capistrano 3.1 lock '3.2.1' set :bundle_flags, '--deployment' # tried removing switch deployment if installing as system gem helps set :deploy_user, "deployer" set :application, 'APPNAME' set :repo_url, '[email protected]:user/repo.git' server "example.net", user: 'deployer', roles: [:web, :app, :db] set :rvm_type, :user set :rvm1_ruby_version, 'jruby-1.7.10' set :scm, :git set :pty, true set :deploy_to, "/home/#{fetch(:deploy_user)}/apps/#{fetch(:application)}" set :linked_files, %w{config/database.yml} set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system} set :keep_releases, 5 after "deploy", "deploy:cleanup" namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do execute :touch, release_path.join('tmp/restart.txt') end end after :publishing, :restart after :restart, :clear_cache do on roles(:web), in: :groups, limit: 3, wait: 10 do # Here we can do anything such as: # within release_path do execute :rake, 'cache:clear' # end end end desc 'Delete shared bundle folder' task :remove_shared_bundle do on roles(:app), in: :sequence, wait: 5 do execute :rm, "-fr", "#{shared_path}/bundle" end end before :starting, :remove_shared_bundle end def template(from, to) erb = File.read(File.expand_path("../config/recipes/templates/#{from}", File.dirname(__FILE__))) # File.join(File.expand_path(File.dirname(__FILE__)), 'poi') # put ERB.new(erb).result(binding), to upload! StringIO.new(ERB.new(erb).result(binding)), to end namespace :deploy do desc "Install everything onto the server" task :install do on roles(:all), in: :sequence, wait: 1 do execute 'mkdir', '-p', fetch(:deploy_to) execute :sudo, 'apt-get', '-y', "update" execute :sudo, 'apt-get', '-y', "install", "build-essential zlib1g-dev libssl-dev libreadline-gplv2-dev python-software-properties curl git-core openjdk-7-jdk jsvc" end end end It seems the root of the error is Thor gem. If I remove bundle folder inside shared directory then it installs all the gems. But it fails next time onwards. With 'remove_shared_bundle' task I tried to delete the bundle folder before before each deploy which worked. But then it would do a fresh installation every time which is time taking. Is there a remedy for this issue? A: I think this issue might be related to JRuby's default gems being unchangeable in 1.7.10 ... it has been fixed since, so the immediate thing is to try JRuby 1.7.15 (or at least 1.7.13) I would than not declare gem 'jruby-openssl', '0.9.5' in the Gemfile (remove it completely) let JRuby use whatever it has available - wonder if there are any gem pulling it in, that could also help (if there's no gem pulling it into the bundle as a dependency) resolve it under 1.7.10.
{ "pile_set_name": "StackExchange" }
Q: c++ does not name a type So I'm having some type problems in my c++ program. Here is the code: #include "NHSFileparser.h" #include "NHSFileController.h" #include <string> #include <vector> std::string databasepath = "/media/sf_Documents/Skola/MVK/testdb/"; std::string dblang = "english"; std::vector<std::string> directories; std::string directory1 = "/media/sf_Documents/Skola/MVK/testdata/"; std::string directory2 = "/media/sf_Documents/Skola/MVK/testdata2/"; directories.push_back(directory1); directories.push_back(directory2); std::vector<std::string> queryterms; std::vector<std::string> return_files; int main() { NHSFileController fc(directory1, databasepath); bool b = fc.addDirectory(directory1); NHSDatabase database(databasepath, dblang); split( queryterms, "test", boost::is_any_of("_")); //Split on lots of chars std::cout << "Queryterms set." << std::endl; database.query(queryterms, return_files); std::cout << return_files.size() << std::endl; if (return_files.size() > 0){ std::cout << "File found: " << return_files[0] << std::endl; } return 0; } And when I compile using g++ 4.6 and -std=c++0x on Ubuntu 12.04 I get the following error: error: ‘directories’ does not name a type on both lines trying to push_back to directories vector. Everything I've found so far is problems with not declaring std::vector properly, which I (to the extent of my knowledge) have done. A: You cannot put statements outside functions, only declarations and definitions. Put your code inside main. A: directories.push_back(directory1); Code statements like that can only go inside functions. In C++11, you can initialise the vector in its declaration: std::vector<std::string> directories {"...", "..."}; If you're stuck in the past, then you could move the push_back statements inside main, or use something like the Boost.Assignment library, or write a function to return a populated vector: std::vector<std::string> make_directories() { std::vector<std::string> directories; directories.push_back("..."); directories.push_back("..."); return directories; } std::vector<std::string> directories = make_directories();
{ "pile_set_name": "StackExchange" }
Q: From where comes $scheme argument in image_style_deliver callback? In core image.module there is a menu item: $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(); $items[$directory_path . '/styles/%image_style'] = array( 'title' => 'Generate image style', 'page callback' => 'image_style_deliver', 'page arguments' => array(count(explode('/', $directory_path)) + 1), 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); As you can see, there is only one argument passed to it. But when we see "image_style_deliver" function, we see: function image_style_deliver($style, $scheme) { I don't know if I'm tired or what but... from where $scheme argument comes from? ;) A: Drupal passes on extra portions of the URL as parameters by default. So for example, a URL might look like this: http://example.com/sites/default/files/styles/style_name/public/foo/bar.jpg Which resolves in image_style_deliver to $style = 'style_name'; $schema = 'public'; The function then goes on to extract the rest of the unnamed arguments, and reconstitutes them to form the eventual path to the file.
{ "pile_set_name": "StackExchange" }
Q: What is this autoexec.cfg, and what does it do? I see a lot of configurations for Source games(Valve games) using an autoexec.cfg file, and I wonder why it is used instead of the config.cfg that is already in the game folder of each Source game. What is an autoexec.cfg file and what does it do? Furthermore do I have any advantages using that instead of in-game consoles or config.cfg? A: In short: It is used because it preserves your configuration. If you edit the config.cfg or use the ingame console directly the settings will only stay until you closed the game. First we need to clarify what happens when you start a source-engine game from steam. At startup steam - if activated - loads a config from the cloud and checks back with the local config. After that the config is loaded into the game but not into the settings. However if you change the settings via ingame menu - let's say controls for example - the config file will be rewritten from scratch. That's why changing the config directly might work for one startup but will be reset after the game closes because the game rewrites the config too at this point. Autoexec Autoexec does execute commands and settings on startup after the cloud sync and rewrites the config. There is no autoexec.cfg file per default so it needs to be created in the same folder as config.cfg (For example DotA2: …\Steam\SteamApps\common\dota 2 beta\dota\cfg\, some games have it's cfg folder one directory up). If you open the settings via ingame menu you will still see the old values because those consumerfriendly settings have higher priority resulting in another rewrite of the config. To circumvent this you need to unbind all keys from the ingame menu and set it once manually in the autoexec. This is not necessary for settings that have no binding at all like con_enable 1 However the autoexec itself is not touched by the source-engine, only read. So the config will be rewritten on every startup without the burden of changing the config itself every time. Another note: Using autoexec enables you to specify settings for your local machine that will not be overwritten if changed by another machine. For example imaging changing the net_graph position for your laptop resolution. Without usage of autoexec it will be saved in the cloud and overwrite your desktop configuration forcing you to adjust the net_graph position to your 1920x1080 desktop resolution again. If you use autoexec and start the game on the desktop resolution it will overwrite the net_graph position and adjust it for you since you defined it previously in the autoexec. Example // Net_graph positioning net_graph "1" net_graphinsetbottom "438" net_graphinsetright "-80" net_graphproportionalfont "0" echo "autoexec loaded" Lines with // will be ignored (comment). The remaining lines contain a command and a corresponding value. echo is a command to write any text (value here is "autoexec loaded") into the ingame console so you can see that your autoexec was loaded. Furthermore if you changed your autoexec.cfg and you do not want to restart the game you can use the exec command like exec autoexec.cfg. In fact you can exec any .cfg file but autoexec.cfg gets automatically loaded at startup. Summary Using autoexec.cfg is the safest way to control configurations in a source-engine game(valve) game and should be used especially for general settings like networking, graphics, etc
{ "pile_set_name": "StackExchange" }
Q: jQuery getJSON basics My first attempt at it, and the testing function does not seem to work: $.getJSON('questions.json', function(data) {alert(data);}) I am trying to alert all the contents of the JSON file which is really short. What am I doing wrong? and why am I getting [object Object] A: JSON is a way of encoding an object as a string so that it can be passed around a network easily. When jQuery receives a string containing JSON data, it deserializes it -- it turns it back into a Javascript object. This object is passed to your success handler -- you're calling it data. When you try to alert a Javascript object, it will give you [object Object], rather than a readable form. You should use a Javascript console as provided by your browser to debug data like this, with the console.log method.
{ "pile_set_name": "StackExchange" }
Q: NodeJS Mongoose connect-mongo Session Storage with Mongo I try to configure my connect-mongo in the way I can use session in nodejs that is persisted with mongo. I use following code var mongoose = require('mongoose'); function connect(url, callback) { mongoose.connect(url); var connection = mongoose.connection; connection.on('error', console.error.bind(console, 'connection error:')); connection.once('open', function() { console.log("Mongoose connected at: ", url); callback(connection); }); } var express = require("express"); var body_parser = require('body-parser'); var cookie_parser = require('cookie-parser'); var hogan_express = require('hogan-express'); var session = require('express-session'); var mongo_store = require('connect-mongo')(session); var express = require("express"); var app = express(); app.engine('html', hogan_express); app.set('view engine', 'html'); app.set("views", "views"); app.use("/libs", express.static("bower_components")); if (!config.development) { app.use(express.static("min")); } app.use(express.static("public")); connect("MONGODBURL",function(mongoose_connection){ app.use(body_parser.json()); app.use(cookie_parser()); app.use(session({ secret: "asd", store: new mongo_store({ mongoose_connection: mongoose_connection // db: mongoose_connection.db }) })); }) I have tried everything but executing some code I have never the object session in my res refrence. Getting: TypeError: Cannot set property 'asd' of undefined Code: app.get("/rest/test",function(req, res) { req.session.asd="test"; res.send(req.session.asd) }); Somone could give a hint for a solution? A: You need to define your routes after your configure your session. ... app.use(session.... ... app.get("/... Inside your connect's callback in your case. Probably start listening inside it only as well. connect("MONGODBURL",function(mongoose_connection){ app.use(body_parser.json()); app.use(cookie_parser()); app.use(session({ secret: "asd", store: new mongo_store({ mongoose_connection: mongoose_connection // db: mongoose_connection.db }) })); app.get("/rest/test",function(req, res) { req.session.asd="test"; res.send(req.session.asd) }); app.listen(... });
{ "pile_set_name": "StackExchange" }
Q: Is there a proper way to create a file format? I'm building a proprietary file format for an application I wrote in C# .NET to store save information and perhaps down the line project assets. Is there a standard on how to do this in any way? I was simply going to Serialize my objects into binary and create a header that would tell me how to parse the file. Is this a bad approach? A: The most straight-forward method is probably to serialize your structure to XML using the XMLSerializer class. You probably wouldn't need to create a separate header and body structure - but serialize all assets into XML. This allows you to easily inspect / edit your file structure outside of your own program, and is easily manageable. However, if your file structure is really complex, containing many different assets of different types, such that serializing the entire structure to XML is too burdensome, you might look at serializing each asset separately and compiling them into a single package using the Packaging library in C#. This is essentially how .docx, .xslx, .pptx, and other office file formats are constructed. A: From someone who has had to parse a lot of file formats, I have opinions on this from a different point of view to most. Make the magic number very unique so that people's file format detectors for other formats don't misidentify it as yours. If you use binary, allocate 8 or 16 randomly-generated bytes at the start of a binary format for the magic number. If you use XML, allocate a proper namespace in your domain so that it can't clash with other people. If you use JSON, god help you. Maybe someone has sorted out a solution for that abomination of a format by now. Plan for backwards compatibility. Store the version number of the format somehow so that later versions of your software can deal with differences. If the file can be large, or there are sections of it which people might want to skip over for some reason, make sure there is a nice way to do this. XML, JSON and most other text formats are particularly terrible for this, because they force the reader to parse all the data between the start and end element even if they don't care about it. EBML is somewhat better because it stores the length of elements, allowing you to skip all the way to the end. If you make a custom binary format, there is a fairly common design where you store a chunk identifier and a length as the first thing in the header, and then the reader can skip the entire chunk. Store all strings in UTF-8. If you care about long-term extensibility, store all integers in a variable-length form. Checksums are nice because it allows the reader to immediately abort on invalid data, instead of potentially stepping into sections of the file which could produce confusing results. A: Well, there are times what you describe can be a very bad approach. This is assuming when you say 'serialize' you're talking about using a language/framework's ability to simply take an object and output directly to some sort of binary stream. The problem is class structures change over the years. Will you be able to reload a file made in a previous version of your app if all your classes change in a newer one? For long term stability of a file format, I've found it better to roll up your sleeves a little bit now and specifically write your own 'serializing'/'streaming' methods within your classes. ie, manually handle the writing of values to a stream. Write a header as you state that describes the format version, and then the data you want saved in the order you want it in. On the reading side, handling different versions of the file format becomes a lot easier. The other option of course is XML or JSON. Not necessarily the greatest for binary heavy content, but simple and human readable... a big plus for long term viability.
{ "pile_set_name": "StackExchange" }
Q: OpenLayers Map with toolbar not displaying correctly I am trying to create a simple OpenLayers based map with a toolbar at the top of the screen. I want the toolbar and map to be centered with a margin/border around each element and no scroll bars. I will be eventually adding buttons to the toolbar but first I would like to get the layout nailed down. <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> <!-- <link rel="stylesheet" href="style.css" /> --> <script type="text/javascript" src="http://openlayers.org/api/2.12/OpenLayers.js"></script> <style> html, body { height: 100%; width: 100% margin: 0; background-color: black; } #toolbar { border: solid 1px #999; background-color: #ccc; margin: 10px; width: 100%; height: 3%; border-radius: 6px; } #map { border: solid 1px #999; background-color: #ccc; margin: 10px; width: 100%; height: 95%; } </style> <script type="text/javascript"> function init() { var map = new OpenLayers.Map("map"); var osm = new OpenLayers.Layer.OSM(); map.addLayer(osm); map.zoomToMaxExtent(); } </script> </head> <body onload="init()"> <div id="toolbar"></div> <div id="map"></div> </body> </html> A: Here is the corrected jsfiddle from comments. I just chenged the css to this: html, body { height: 96%; background-color: black; } #toolbar { border: solid 1px #999; background-color: #ccc; margin-bottom: 10px; width: 100%; height: 3%; border-radius: 6px; } #map { border: solid 1px #999; background-color: #ccc; margin-bottom: 10px; width: 100%; height: 100%; }
{ "pile_set_name": "StackExchange" }
Q: Segundo botão substituindo conteúdo do primeiro Com esse código abaixo quando clico no botão mat ele me trás os dados em uma table. Gostaria que ao clicar no botão sp substitua o conteúdo da tabela por outro. Código: <button id="mat" class="button"></button> <button id="sp"></button> <table id="matriz"> </table> <table id="saopaulo"> </table>   <script> $(document).ready(function(){ $("#matriz").hide(); $("#mat").click(function(){ if($("#matriz").is(":visible")){ $("#matriz").hide(); } else{ $("#matriz").show(); } $.ajax({ url: "../Conteudo/Matriz.html", cache: false, dataType: 'html' }) .done(function(retorno) { $("#matriz").html(retorno); }) .fail(function() { alert("Algo está errado"); }); }); $("#saopaulo").hide(); $("#sp").click(function(){ if($("#saopaulo").is(":visible")){ $("#saopaulo").hide(); } else{ $("#saopaulo").show(); } $.ajax({ url: "../Conteudo/saopaulo.html", cache: false, dataType: 'html' }) .done(function(retorno) { $("#saopaulo").html(retorno); }) .fail(function() { alert("Algo está errado"); }); }); }); </script> A: Basta adicionar dentro da function do done no ajax antes de atribuir o retorno no método .html(...); adicionar a seguinte linha: No ajax de do click sp: $("#matriz").empty(); //remove todos os nós filhos da table Mesma coisa no ajax do click mat: $("#saopaulo").empty(); //remove todos os nós filhos da table
{ "pile_set_name": "StackExchange" }
Q: Are peltier elements polarized? I'm looking to add a peltier element to one of my projects. However, I want to sometimes heat and sometimes cool, depending on the ambient temperatures on both sides of the element. Image from Wikimedia commons. Anyway, my first thought was to use a H-Bridge and then reverse the power for reversing the flow of heat. However, looking at the diagram above, it looks like it may be polarized. (I have no idea, though.) Conclusion one: since you'd be flipping the power, the P-type would act like a N-type and vice versa. This doesn't seem logical, but I've never taken an electronics class, so it may very well be true. P and N probably are treated differently (chemically). Conclusion two: it is polarized because the P-type always has to be attached to the positive side (and vice versa) so you can't flip it. Is either one right? Can I use an H-Bridge for this? A: A TEC is polarized in the sense that how it is connected matters. If you want to be able to heat and cool an element then a full Hbridge will work. This will allow you to pump current both directions across a TEC's terminals. If you apply a positive voltage to a TEC in one polarization then side A will get warm and side B will cool. If you then reverse polarity then side A will cool and side B will get warm. So if you just need heat pumped in one direction then a half bridge or even direct connection will be fine. Edit: Notice if you apply a positive voltage from one electrical connection to the other you are starting at "P". If you reverse connections you are still starting from "P" but now hot and cold will be flipped. A: They are polarized, but the only "bad" thing about reversing the polarity is, the hot side gets cold and vice-versa. So you can use one side of a peltier as a heater or cooler by simply reversing the polarity. So if you were using it to cool a CPU, and have the polarity wrong, you will be heating the CPU side instead of cooling it.
{ "pile_set_name": "StackExchange" }
Q: Is there a common strategy to measure if a difference-significance of two areas under two ROC curves I conduct sound detection experiments with mice. I have a stimulus sound and a "noise" sound that shoukd be ignored. I want to measure how well the mouse ignors the noise (with respect to, say, ignoring 100% of the noise stimuli). I have sessions with, say 200 trials of stimulus sound that sould be detected and 40 trials of noise sounds that should be ignored. I created the confusion matrix and ROC curve (I use Matlab). Now I want to know how well my mouse is performing compared with "ignoring all noise stims". Is there a way, or a common used formula, to get a evaluation or a confidence interval of "how good is my ROC AUC comparing to AUC(ROC) = 1"? Thanks! A: The AUC is a summary statistic of your dataset. As such, if you did the same experiment again you would get a slightly different value - and if repeated several times, you'd get a distribution of values. You probably want to show that your distribution rarely or never includes 0.5 (indicating random classification). When you have an empirical distribution like this, or a histogram of repeated experiments, you can just count how many of your estimates are $\approx 0.5$. If none, you're golden. Since you don't want to do your experiment multiple times, you could 'simulate' that scenario by using samples of your data, but otherwise performing the same process. This is called 'bootstrapping'. You can use this method to construct confidence intervals around your AUC metric, or equivalently, do a statistical test to see if the metric you get is different from 0.5. Some packages have bootstrapped confidence intervals built in to the AUC calculation, so you could just use that.
{ "pile_set_name": "StackExchange" }
Q: Query through HABTM with an exact set In Rails 4, I have a vanilla has_and_belongs_to_many relationship, say between Cars and Colors. Given a set of colors I'd like to find the cars that have exactly those colors. The closest I can get is: Car.joins(:colors).where('colors.id' => colors), but that returns all Cars with any of the colors. I'd like to do this entirely in ActiveRecord since both tables are liable to be huge, so something like Car.joins(:colors).where('colors.id' => colors).to_a.select{|car| car.colors == colors} is less than ideal. Any idea how to accomplish this? A: I was able to get it with having and some gnarly string interpolated SQL. I've made this into a scope you can use like so: # Car.with_exact(colors: colors) class ActiveRecord::Base class << self def with_exact(associations={}) scope = self associations.each do |association_name, set| association = reflect_on_association(association_name) scope = scope.joins(association_name) .group("#{table_name}.id") .having("COUNT(\"#{association.join_table}\".*) = ?", set.count) .having(%{ COUNT(\"#{association.join_table}\".*) = SUM( CASE WHEN \"#{association.join_table}\".\"#{association.association_foreign_key}\" IN (#{set.to_a.map(&:quoted_id).join(', ')}) THEN 1 ELSE 0 END ) }.squish) end scope end end end
{ "pile_set_name": "StackExchange" }
Q: CSS: Why h3 drops down its parent div? There is a simple example where a div element contains h3. But the h3 element drops down its parent div when h3 has position relative. Changing h3 position to absolute solves this problem. What is the reason? .personal-details{ background-color: green; } .personal-image{ display: inline-block; width: 150px; height: 150px; background-color: white; } .personal-description { display: inline-block; width: 150px; height: 150px; background: black; } .personal-description h3 { position: relative; /*absolute solves the problem*/ } <div class="personal-details"> <div class="personal-image"></div> <div class="personal-description"><h3 class="name">My Name</h3></div> </div> A: This is caused by the default vertical-align: baseline; property of inline-block elements. Overriding the default with vertical-align: top for your element will get you somewhere like correct: .personal-details { background-color: green; vertical-align: middle } .personal-image { display: inline-block; width: 150px; height: 150px; background-color: green; } .personal-description { display: inline-block; width: 150px; height: 150px; background: black; vertical-align: top; } .personal-description h3 { position: relative; background: yellow; } <div class="personal-details"> <div class="personal-image"></div> <div class="personal-description"><h3 class="name">My Name</h3></div> </div> Notice I say "somewhere like correct" as you will still have issues with space around the elements (notice the gap below the black square and space between the two child divs). But that is out of the scope of your question and has been dealt with many times before.
{ "pile_set_name": "StackExchange" }
Q: What is the proper way to terminate multi-threading code when one thread fails? I have the following code: def getdata3(self, page, data, apifolder, additional): tries = 10 for n in range(tries): try: except (ChunkedEncodingError, requests.exceptions.HTTPError) as e: ... if n == tries - 1: raise e # If arrived here - Terminate ! print ("{2} page {0} finished. Length is {1}".format(page,len(datarALL),str(datetime.now()))) return job Main code: with ThreadPoolExecutor(max_workers=num_of_workers) as executor: futh = [(executor.submit(self.getdata3, page, data, apifolder,additional)) for page in pages] for data in as_completed(futh): datarALL.extend(data.result()) print ("Finished generateing data.") return datarALL This code create threads for workers. When all work is done it returns the datarALL . My problem: What I want is that if one of the threads arrives here: if n == tries - 1: raise e # If arrived here - Terminate ! All existed threads will be terminated. No future threads will be created (terminate the for page in pages loop) and the entire program will be terminated. I read a few articles about the issue. I also read this Should I use Events, Semaphores, Locks, Conditions, or a combination thereof to manage safely exiting my multithreaded Python program? but the offered solutions are very complex and seem to add a lot code which I doubt I need. I tried to do: if n == tries - 1: exit(1) But when I check htop this doesn't shut down the entire process and threads.. I have some left over that are staying there as zombies. My Question: Is there a simple, clean solution to terminate the program with error notice? A: sys.exit() can stay stuck sometimes because it tries to exit gracefully. Some quick & dirty solution implies the use of os._exit(1) (1 is a possible return code indicating an error, 0 means success, you don't want to use that here. Stay in 0-255 range to avoid portability problems) On modern systems, resource tracking happens and the program quits, killing all attached resources (file handles, threads, memory...), so it is an acceptable solution. The downside is that it bypasses python exit/cleanup procedures, just like when you kill the python process using kill. On OSes lacking resource tracking management (we're talking ancient history), this would result in global memory leak/file descriptors. In your case, it doesn't matter because without this you cannot quit your application. But don't generalize it, reserve that for emergency exit procedures.
{ "pile_set_name": "StackExchange" }
Q: Why do I get a System.ArgumentOutOfRangeException: ''minValue' cannot be greater than maxValue. Parameter name: minValue' error? I've got an essential skills program which is very simple. The question is within the code. I want the question to be loaded from a text file. I have already added some questions to the text file. I have a list index where a random question will be picked from the text file and it will load as a label. The issue is when I try to load the question I get a: System.ArgumentOutOfRangeException: ''minValue' cannot be greater than maxValue. Parameter name: minValue' error Here is my code: private void LoadQuestions() { if(Globals.intQuestionNumber == 11) { MessageBox.Show("Quiz complete - Redirecting", "Quiz Complete"); var fileStream = new FileStream(@"H:\(4)Programming\Assignments\EssentialSkills - Optimised\EssentialSkills\Numeracy\QuestionsLvl0.txt", FileMode.Open, FileAccess.Read); using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { string line; while ((line = streamReader.ReadLine()) != null) { stringAllInfo.Add(line); MessageBox.Show(line); } } char[] delimiterChars = { ',' }; foreach (string l in stringAllInfo) { string[] words = l.Split(delimiterChars); strQuestion.Add(words[0]); strAnswer.Add(words[1]); Console.WriteLine(words[0]); Console.WriteLine(words[1]); } Menus.Summary sum = new Menus.Summary(); sum.Show(); this.Hide(); } else { lblCountdownval.Visible = false; lblCountdown.Visible = false; Globals.intQuestionNumber += 0; lblQuestionsNumber.Text = "Question Number: " + Globals.intQuestionNumber.ToString(); Random random = new Random(); Globals.listIndex = random.Next(0, strAnswer.Count - 1); lblQuestion.Text = strQuestion.ElementAt(Globals.listIndex); Globals.listQuestonsAsked.Add(strQuestion.ElementAt(Globals.listIndex)); btnCorrect.Text = strAnswer.ElementAt(Globals.listIndex).ToString(); btnAnswer1.Text = random.Next(200).ToString(); btnAnswer3.Text = random.Next(200).ToString(); int locationIndex = random.Next(0, 3); btnCorrect.Location = points.ElementAt(locationIndex); locationIndex = random.Next(0, 3); btnAnswer1.Location = points.ElementAt(locationIndex); while ((btnAnswer1.Location == btnCorrect.Location)) { locationIndex = random.Next(0, 3); btnAnswer1.Location = points.ElementAt(locationIndex); } locationIndex = random.Next(0, 3); btnAnswer3.Location = points.ElementAt(locationIndex); while ((btnAnswer3.Location == btnCorrect.Location) || (btnAnswer3.Location == btnAnswer1.Location)) { locationIndex = random.Next(0, 3); btnAnswer3.Location = points.ElementAt(locationIndex); } btnAnswer1.Show(); btnCorrect.BackColor = Color.White; btnAnswer3.Show(); } } and here are my Lists: public List<string> strQuestion = new List<string>(); public List<string> strAnswer = new List<string>(); public List<string> stringAllInfo = new List<string>(); I want the question from the text file to a label but I get that error. Any advice? Thanks. A: I assume you're falling down here Globals.listIndex = random.Next(0, strAnswer.Count - 1); Is strAnswer.Count 0? Check this by debugging. If not can you please identify which point causes the exception?
{ "pile_set_name": "StackExchange" }
Q: How to decrypt string with ansible-vault 2.3.0 I have been waiting for ansible 2.3 as it was going to introduce encrypt_string feature. Unfortuately I'm not sure how can I read the encrypted string. I did try decrypt_string, decrypt (the file), view (the file) and nothing works. cat test.yml --- test: !vault | $ANSIBLE_VAULT;1.1;AES256 37366638363362303836383335623066343562666662386233306537333232396637346463376430 3664323265333036663736383837326263376637616466610a383430623562633235616531303861 66313432303063343230613665323930386138613334303839626131373033656463303736366166 6635346135636437360a313031376566303238303835353364313434363163343066363932346165 6136 The error I'm geeting is ERROR! input is not vault encrypted data for test.yml How can I decrypt the string so I know what it's value without the need to run the play? A: You can also do with plain ansible command for respective host/group/inventory combination, e.g.: $ ansible my_server -m debug -a 'var=my_secret' my_server | SUCCESS => { "my_secret": "373861663362363036363361663037373661353137303762" } A: You can pipe the input then tell ansible-vault to output to stderr and then redirect the stdout to /dev/null since the tool prints Decryption successful. The /dev/stdin/ part may not be needed in new Ansible versions. Something like: echo 'YOUR_SECRET_VALUE' | ansible-vault decrypt /dev/stdin --output=/dev/stderr > /dev/null Here is a example: echo '$ANSIBLE_VAULT;1.1;AES256 30636561663762383436386639353737363431353033326634623639666132623738643764366530 6332363635613832396361333634303135663735356134350a383265333537383739353864663136 30393363653361373738656361613435626237643633383261663138653466393332333036353737 3335396631613239380a616531626235346361333737353831376633633264326566623339663463 6235' | ansible-vault decrypt /dev/stdin --output=/dev/stderr > /dev/null I hope they implement a simpler way of doing this. Edit: Environment Variables as Input: To have a similar behaviour with multi-line environment variables on bash use printf instead of echo Example (password: 123): export chiphertext='$ANSIBLE_VAULT;1.1;AES256 65333363656231663530393762613031336662613262326666386233643763636339366235626334 3236636366366131383962323463633861653061346538360a386566363337383133613761313566 31623761656437393862643936373564313565663633636366396231653131386364336534626338 3430343561626237660a333562616537623035396539343634656439356439616439376630396438 3730' printf "%s\n" $chiphertext | ansible-vault decrypt /dev/stdin --output=/dev/stderr > /dev/null A: since whole vault files do not play well with git histories, using vault strings within the variable files is the way to go, it also makes grepping out variables by name much clearer. Here is a simple worked example: I want to put fredsSecretString: value into vars.yml , (its value is fastfredfedfourfrankfurters but hush, don't let people know !!) $ ansible-vault encrypt_string 'fastfredfedfourfrankfurters' -n fredsSecretString >> vars.yml New Vault password: fred Confirm New Vault password: fred $ cat vars.yml fredsSecretString: !vault | $ANSIBLE_VAULT;1.1;AES256 36643662303931336362356361373334663632343139383832626130636237333134373034326565 3736626632306265393565653338356138626433333339310a323832663233316666353764373733 30613239313731653932323536303537623362653464376365383963373366336335656635666637 3238313530643164320a336337303734303930303163326235623834383337343363326461653162 33353861663464313866353330376566346636303334353732383564633263373862 To decrypt the value feed the encrypted string back into ansible-vault as follows: $ echo '$ANSIBLE_VAULT;1.1;AES256 36643662303931336362356361373334663632343139383832626130636237333134373034326565 3736626632306265393565653338356138626433333339310a323832663233316666353764373733 30613239313731653932323536303537623362653464376365383963373366336335656635666637 3238313530643164320a336337303734303930303163326235623834383337343363326461653162 33353861663464313866353330376566346636303334353732383564633263373862' | ansible-vault decrypt && echo Vault password: fred Decryption successful fastfredfedfourfrankfurters $
{ "pile_set_name": "StackExchange" }
Q: How to resizing issue of UISearchController.searchBar when focused? We have developed an application for iOS 5 long back where we used 'Search Bar and Search Display Controller' object on storyboard. Since iOS8 UISearchDisplayController is deprecated, I am trying to remove existing 'Search Bar and Search Display Controller' with UISearchController. As UISearchController is not available from 'Object Library' on interface, I have added it programatically to an UIView on interface using following code: //Set up Search Controller self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; self.searchController.searchResultsUpdater = (id)self; self.searchController.dimsBackgroundDuringPresentation = YES; self.searchController.searchBar.delegate = self; //Adding as subview to UIView 'searchBarContainer' [self.searchBarContainer addSubview:self.searchController.searchBar]; [self.searchBarContainer bringSubviewToFront:self.searchController.searchBar]; self.definesPresentationContext = YES; self.extendedLayoutIncludesOpaqueBars = YES; And set the frame of 'searchController' equal to the UIView as follows: UISearchBar *ctrlSearchBar = self.searchController.searchBar; ctrlSearchBar.frame = CGRectMake(0, 0, self.searchBarContainer.frame.size.width, self.searchBarContainer.frame.size.height); The size of searchBar is fine but when it is focused on clicking on it, the width of 'searchBar' increased automatically. I even tried using NSLayoutConstraints but didn't fix the issue. Can anyone please help how to fix the size of 'UISearchController.searchBar' even when it is focused? A: As surToTheW suggested in his comment, I have created a custom UIViewController with UISearchController in it. I added it as child view controller in to my main UIViewController and the search bar didn't exceed the custom UIViewController's view width.
{ "pile_set_name": "StackExchange" }
Q: Insert the attribute value of input element in form I have a form with no id or class. I need to insert attribute values for input elements. <form> <tr><td><input type="text" name="x"/></td></tr> <tr><td><input type="text" name="y"/></td></tr> <tr><td><input type="text" name="z"/></td></tr> </form> Here's jquery I tried: var x = $('form').find('input').first().val("some_value"); var y = $('form').find('input').second().val("some_value"); var z = $('form').find('input').third().val("some_value"); // Is there another possible way? var x = $("form").find('input[name="x"]').val("some_value"); A: You can use Attribute Equals Selector [name=”value”] to uniquely identify the inputs $('input[name=x]').val("some_value1"); $('input[name=y]').val("some_value2"); $('input[name=z]').val("some_value3"); Although I wont recommend the method you used to assign values to input, I would suggest you to use find() once and use the returned object collection to assign values. This will reduce the processing time and increase performance. var all = $('form').find('input'); all.eq(0).val("some_value1"); all.eq(1).val("some_value2"); all.eq(2).val("some_value3");
{ "pile_set_name": "StackExchange" }
Q: Can't make regular expression with negative lookaheads work to fix unescaped quotes in JSON I have some JSON code in the following format: [ { "abc ": "d ef", "g": "h i", "jk lm no": "pq", "r st": "uvw xyz" }, { "!1 2": " 3", "4 ": "5 6 7", " 8 ": "9 abc", "def": "hi "NAME" jk" }, ... ] I need to add backslashes in front of quotes in "NAME" to be able to parse this JSON correctly. So I need the above string to look like this: [ { "abc ": "d ef", "g": "h i", "jk lm no": "pq", "r st": "uvw xyz" }, { "!1 2": " 3", "4 ": "5 6 7", " 8 ": "9 abc", "def": "hi \"NAME\" jk" }, ... ] I tried using regex to replace (?!({ |": |", ))"(?!( }|: "|, ")) with '\\\\"', but I get: [ { \"abc ": \"d ef", \"g": \"h i", \"jk lm no": \"pq", \"r st": \"uvw xyz" }, { \"!1 2": \" 3", \"4 ": \"5 6 7", \" 8 ": \"9 abc", \"def": \"hi \"NAME\" jk" }, ... ] Please help to write a correct regular expression. A: Try this regex: (?<![{,:] )"(?![:,]| }) Description Demo http://regex101.com/r/tJ2dG0 Discussion Firstly, I assume that your regex flavor supports lookbehind. Secondly, how did I find this regex you'd say ? Often, when you build a regular expression, you either build it for matching what you want or you build it for matching what you don't want. I use the latter here. This is the regex for matching valid double quotes: (?<=[{,:] )"|"(?=[:,]| }) Demo: http://regex101.com/r/oX4uM5 As you can see in the demo, the regex (let's call it R) doesn't capture invalid quotes. So the regex we are looking for is its (particular) opposite (ie !R). particular because we'll take the opposite of the look(behind|ahead) but not the quote inside R. So (?<=...) becomes (?<!...) (?=...) becomes (?!...) "|" (read it " OR ") becomes (" AND ") simply " hence the final regex at the top of this answer.
{ "pile_set_name": "StackExchange" }
Q: Using repository class methods inside twig In a Symfony2.1 project, how to call custom entity functions inside template? To elaborate, think the following scenario; there are two entities with Many-To-Many relation: User and Category. Doctrine2 have generated such methods: $user->getCategories(); $category->getUsers(); Therefore, I can use these in twig such as: {% for category in categories %} <h2>{{ category.name }}</h2> {% for user in category.users %} {{ user.name }} {% endfor %} {% endfor %} But how can I get users with custom functions? For example, I want to list users with some options and sorted by date like this: {% for user in category.verifiedUsersSortedByDate %} I wrote custom function for this inside UserRepository.php class and tried to add it into Category.php class to make it work. However I got the following error: An exception has been thrown during the rendering of a template ("Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::__construct(), A: It's much cleaner to retrieve your verifiedUsersSortedByDate within the controller directly and then pass it to your template. //... $verifiedUsersSortedByDate = $this->getYourManager()->getVerifiedUsersSortedByDate(); return $this->render( 'Xxx:xxx.xxx.html.twig', array('verifiedUsersSortedByDate' => $verifiedUsersSortedByDate) ); You should be very carefull not to do extra work in your entities. As quoted in the doc, "An entity is a basic class that holds the data". Keep the work in your entities as basic as possible and apply all the "logic" within the entityManagers. If you don't want get lost in your code, it's best to follow this kind of format, in order (from Entity to Template) 1 - Entity. (Holds the data) 2 - Entity Repositories. (Retrieve data from database, queries, etc...) 3 - Entity Managers (Perform crucial operations where you can use some functions from your repositories as well as other services.....All the logic is in here! So that's how we can judge if an application id good or not) 4 - Controller(takes request, return responses by most of the time rendering a template) 5 - Template (render only!)
{ "pile_set_name": "StackExchange" }
Q: Trying to load opserver I downloaded opserver that I saw at SQLPass. I can't seem to do anything with it. I tried opening it with VS 2008, VS 2010 and keep getting incompatible errors. What version of VS should I be using? I am a newbie so am in real unfamiliar territory. What do I do after I download it? Are there step by step instructions anywhere? A: Opserver targets ASP.NET 4.5 for concurrency features, which I believe requires 2012 or better. The official Opserver documentation assumes that you know how to build and publish and ASP.NET MVC 4 application. Typically the challenge in building MVC is getting the right dependencies/config setup on IIS the first time. Very easy to update after that. There are many blog posts and good answers on this site on that general subject. If you want directions specific to Opserver, currently you are limited to third party blog posts such as the following: Patrick Hyatt: Setting Up StackExchange's Opserver (very useful for the config files) Danny Sorensen: Using Opserver Will It Build? (my own experience so far) If this is not familiar territory, I recommend the following: Use Visual Studio 2012 or 2013 on a machine with ASP.NET 4.5 Only enable the Opserver security file. Modify it for your IP address, or use "alladmin" to start. Build it. If it doesn't work, use StackOverflow to solve your issue. You're having trouble with ASP.NET MVC 4, not Opserver at this point. Now enable one additional config file at a time and build it again until you are done. Note, that you will not need to enable all of the config files unless your setup matches that of StackOverflow. Most of the config files are intended to be optional and left disabled.
{ "pile_set_name": "StackExchange" }
Q: Prove $\frac{f'(\xi)}{g'(\xi)}+\frac{f'(\eta)}{g'(\eta)}=0$ Let $f(x)$ is continuous in $[0,1]$, differentiable in $(a,b)$, such that $f(0)=g(0)=f(1)=0$, $g'(x)\neq0$. Prove: $\exists\xi,\eta\in(0,1),\xi<\eta,$ $$\frac{f'(\xi)}{g'(\xi)}+\frac{f'(\eta)}{g'(\eta)}=0$$ I have no idea about it, but I can post some link which I think is useful. question1 question2 question3 This is a question of a real-analysis book which named 'Mathematical analysis course'(Author:Shi Jihuai,Chang Gengzhe). Book Name:数学分析教程(Mathematical analysis course) Author: 史济怀 常庚哲 My attempt When there are two parameters in question,we can express them by a node which associated with both. And then we can remove the node by some operations.For this question, We can see the answer of I posted. I want to get a proof,and a way to solve two-parameter($\xi,\eta$) question A: By the Intermediate Value Theorem, since $g(0)=0$, $\exists t\in (0,1)$ such that $g(t)=g(1)/2$. By the Cauchy's Mean Value Theorem, $\exists \xi \in(0,t)$ such that $$\frac{f(t)}{g(t)}=\frac{f(t)-f(0)}{g(t)-g(0)}=\frac{f'(\xi)}{g'(\xi)}.$$ Again, by the same reason as before, $\exists \eta \in(t,1)$ such that $$-\frac{f(t)}{g(1)-g(t)}=\frac{f(1)-f(t)}{g(1)-g(t)}=\frac{f'(\eta)}{g'(\eta)}.$$ Then $0<\xi<\eta<1$ and $$\frac{f'(\xi)}{g'(\xi)}+\frac{f'(\eta)}{g'(\eta)}= \frac{f(t)(g(1)-2g(t))}{g(t)(g(1)-g(t))}=0.$$
{ "pile_set_name": "StackExchange" }
Q: Dar color a stacked icons en FontAwesome como podria darle color a los iconos de forma independiente, quiero que el corazon sea de color amarillo y el circulo de color rojo, pero no me da. Traté con color pero tampoco Gracias por leer .fa-circle { background: red; } .fa-heart{ background: yellow; } <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <span class="fa-stack fa-2x"> <i class="fas fa-circle fa-stack-2x"></i> <i class="far fa-heart fa-stack-1x fa-inverse"></i> </span> A: Si usas before puedes aplicar tanto background como color. Prueba: .fa-circle:before { background: red; color: blue; } .fa-heart:before { background: yellow; color: blue; } A mi me quedó así:
{ "pile_set_name": "StackExchange" }
Q: Inspect doesn't recognize win32 editable textbox I developed a win32 application (c++) and now, I want to do some automation tests using Inspect (SDK). My problem is that Inspect doesn't recognize EDIT boxes. I mean that Inspect can't distinguish their names. It can see that there are multiple EDIT boxes, but they're all named "none" which occur to be the null value. Those names are always null, even if I initialize them with the LPCTSTR lpWindowName parameter // Create an edit box hEdit = CreateWindowEx(WS_EX_CLIENTEDGE, _T("EDIT"), _T("I JUST WANT TO BE SEEN !"), WS_CHILD|WS_VISIBLE| ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL, 50, 100, 200, 100, hWnd, (HMENU)IDC_MAIN_EDIT, GetModuleHandle(NULL), NULL); I also try setting the name with the setWindowText method, but it doesn't work either. The two method does work fine with BUTTON, but doesn't work on EDIT. Does anyone as a clue? A: It's possible to set the name (or any other property of the control) by using Dynamic Annotation. Also, if it's a common control, it might be possible to set the name by adding a hidden label in the .rc file. Otherwise you'll have to use Dynamic Annotation. if you want to set one of these : -NAME -KEYBOARDSHORTCUT -DESCRIPTION -DEFAULTACTION -ROLE -VALUEMAP -STATE -ROLEMAP -HELP -STATEMAP. You'll have to use Direct Annotation or Server Annotation. But if you want to set one of these : -FOCUS -RIGHT -SELECTION -PREV -PARENT -NEXT -UP -FIRSTCHILD -DOWN -LASTCHILD -LEFT Only the Server Annotation will allow you to do it. Here's more detail about Dynamic Annotation : http://msdn.microsoft.com/en-us/windows/desktop/gg712214.aspx Here's more detail if you want to do Dynamic Annotation on custom control : http://msdn.microsoft.com/en-us/windows/cc307845.aspx
{ "pile_set_name": "StackExchange" }
Q: VB6 - converting string to double using specific culture? I am a long time C# developer and have had to look at some VB6 code lately. After some digging, we found out that, somewhere, somehow, we are storing a number as a string. Now we are reading it back and our code is not handling culture differences very well. Here is an example: Dim text as String Dim myVal as Double Set text = "1,123456" 'This sets the value of myVal to 1123456 on our system - incorrect myVal = text Set text = "1.123456" 'This sets the value of myVal to 1.123456 on our system - correct myVal = text Keeping in mind that this is VB6 and NOT VB.NET, are there any built-in methods, functions, whatever, that can convert a string to a double using a particular culture? Or at the very least, hinting to the conversion that we may be dealing with a different format? We are still digging how the value gets written and see if we can reverse engineer the process to give us a consistent result. However, our customer(s) already has(have) data in one format or the other (or both, we are checking...), so a proper conversion algorithm or implementation would be a better answer at this point. A: I've used this quick and dirty function in the past to get a double from a text. Here in Argentina, people sometimes use the point and sometimes the comma to separate decimal values, so this function is ready to accept both formats. If only one punctuation is present, it's assumed that it's the decimal separator. function ConvertDBL( texto ) dim retval, SepDecimal, SepMiles If texto = "" then texto = "0" retval = replace(trim(texto), " ", "") If cdbl("3,24") = 324 then SepDecimal = "." SepMiles = "," else SepDecimal = "," SepMiles = "." end if If InStr( Retval, SepDecimal ) > 0 then If InStr( Retval, SepMiles ) > 0 then If InStr( Retval, SepDecimal ) > InStr( Retval, SepMiles ) then Retval = replace( Retval, SepMiles, "" ) else Retval = replace( Retval, SepDecimal, "" ) Retval = replace( Retval, SepMiles, SepDecimal ) end if end if else Retval = replace( Retval, SepMiles, SepDecimal ) end if ConvertDbl = cdbl( retval ) end function
{ "pile_set_name": "StackExchange" }
Q: What is the difference between view.topAnchor and view.safeAreaLayoutGuide.topAnchor? I have been working with constraints in Swift for iOS, and the documentation does a good job of explaining things. However, one thing that has recently confused me is the difference between view.topAnchor and view.safeAreaLayoutGuide.topAnchor. When I have set constraints programmatically in my iOS app, I have found that I can use these totally interchangeably, so I can't tell what the difference between the two is. I checked out the documentation at developer.apple.com, and I haven't found anything explaining the differences. Is there any difference between the two properties? A: The main difference is with devices that has top notch screens as well as home button like iphone 11 inside your view other than physical button like iphone 8 and older. also as it says it keeps you in the safe area even while device in landscape rotation, however some designs require using top anchor.
{ "pile_set_name": "StackExchange" }