text
stringlengths
64
89.7k
meta
dict
Q: What does WebActivator do? This code was generated for me after added entity framework code-first for SQL Server CE using NuGet. They did no changes to any other file. The file SQLCEEntityFramework.cs was created and placed in App_Start folder. Does this mean it automatically gets executed or something? The same thing happened when I added Ninject for MVC 3. No code was added to the global.ascx file so I have no idea if its plug and play or I have to configure something. [assembly: WebActivator.PreApplicationStartMethod(typeof(StackTorrents.WebUI.App_Start.SQLCEEntityFramework), "Start")] A: According to: http://haacked.com/archive/2010/05/16/three-hidden-extensibility-gems-in-asp-net-4.aspx This new attribute allows you to have code run way early in the ASP.NET pipeline as an application starts up. I mean way early, even before Application_Start. This happens to also be before code in your App_code folder (assuming you have any code in there) has been compiled. To use this attribute, create a class library and add this attribute as an assembly level attribute. A common place to add this would be in the AssemblyInfo.cs class within the Properties folder. A: To clarify, it gives you a way of hooking into several application start and application shutdown events WITHOUT having to change any existing code files (previously you had to edit Globals.asax.cs). This is mostly a big deal when making packages as these events are really useful for bootstrapping Http modules and it is really difficult to write code into existing files.
{ "pile_set_name": "StackExchange" }
Q: WWW(Unity) with HTTPS on Android not working I'm using a native android plugin my team made for communication with a server, and as it uses HTTPS I use a certificate with it. Everything's fine with that, the problem is that, in Unity, when I try to use WWW with anything HTTPS, I get this error V/com.facebook.unity.FB: sending to Unity OnLoginComplete({"error":"Caught exception: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.","callback_id":"5","key_hash":"XXXXXXXX"}) I get this error in particular when trying to use the Facebook SDK to post a picture to the user's timeline. Looking at the source code, it uses Unity's WWW for the POST. If in Unity I never call my native plugin's methods, then everything works nicely. Is there any way to get around that? Somehow install another certificate? Use some different header? Any help would be great, thanks. A: Error which You are getting is standard error generated by Android when given certyficate can't be full checked. Try to validate Your certyficate with tools like: https://www.digicert.com/help/. Yours admin should fix it if its not valid. If You can't fix certificate then its needed to modify your company plugin to use custom ssl factory/trust manager for request from Android level. This thread on SO seems helpful with understanding the case: https://stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection
{ "pile_set_name": "StackExchange" }
Q: Sizeof Reports Improper Size of Type-defined Structure - C++ My application has a defined structure: typedef struct zsSysVersionMsg_tag { WORD cmd; BYTE len; } zsSysVersionMsg_t; I would expect sizeof(zsSysVersionMsg_t) to evaluate to 3. However, when I run my application it evaluates to 4. Can someone explain why this is? (I really need it to evaluate to 3.) Thanks. A: Most platforms will "align" and "pad" structures so that they begin and end exactly on a word boundary. This is done to improve memory performance. Assuming you are on Windows, you can set your own alignment. In your case, you want to align on single bytes, so do this: #pragma pack( push, 1 ) typedef struct zsSysVersionMsg_tag { WORD cmd; BYTE len; } zsSysVersionMsg_t; #pragma pack( pop )
{ "pile_set_name": "StackExchange" }
Q: Objective C NSURLConnection dosen't get response data I am creating this application, it communicates with a PHP script on my web-server. Last night it was working perfectly. But today two of the connections does not get response. I've tried the NSURL link in my browser, it works fine. Also one of the connections work, but as i said two connections does not work? - (void) getVitsTitelByID:(int)id { NSString *url = [NSString stringWithFormat:@"http://webserver.com /ivitserdk.php?function=gettitelbyid&id=%d", id]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0]; connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } connectionDidReciveData: if(connection == connectionTitelByID){ responseTitel = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } connectionDidFinishLoading: if(connection == connectionTitelByID){ titelLabel.text = responseTitel; } I've tried and debugging it. responseTitel seems to be (null). Help would be apriceated :) A: didReceiveData may be called N (several) times. save the data to a mutably data buffer (queue it up) and in didFinish read it into a string mock code: - (void) getVitsTitelByID:(int)identifier { NSString *url = [NSString stringWithFormat:@"http://webserver.com/ivitserdk.php?function=gettitelbyid&id=%d", identifier]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0]; connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self]; dataForConnectionTitelByID = [NSMutableData data]; [connectionTitelByID start]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if(!data.length) return; if(connection == connectionTitelByID) [dataForConnectionTitelByID appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { if(connection == connectionTitelByID) { id str = [[NSString alloc] initWithData:dataForConnectionTitelByID encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); dataForConnectionTitelByID = nil; connectionTitelByID = nil; } }
{ "pile_set_name": "StackExchange" }
Q: How do I get KDiff3 to auto merge with no UI? How do I get KDiff3 to automatically do a 3-way merge such that it shows no UI? Ideally, if it succeeds, it returns success, and if it can't (it needs manual merging), it returns an error code. Everything I've read seems to imply that the following should work: "c:\Program Files\KDiff3\kdiff3.exe" --auto base.txt src.txt tar.txt -o merge.txt However, it doesn't. When I run it, a message box pops up that says: Total number of conflicts: 3 Nr of automatically solved conflicts: 3 Nr of unsolved conflicts: 0 How do I get it to run without this popup, and no GUI at all if it fails? A: I figured it out. I need to add a "--cs" and "ShowInfoDialogs=0" to the command line. So this: "c:\Program Files\KDiff3\kdiff3.exe" --auto base.txt src.txt tar.txt -o merge.txt ...becomes this: "c:\Program Files\KDiff3\kdiff3.exe" --auto base.txt src.txt tar.txt -o merge.txt --cs "ShowInfoDialogs=0" ...and now it works.
{ "pile_set_name": "StackExchange" }
Q: Python - How to use .format() method with two strings? this is my first time posting here so sorry if it's not formatted correctly or in the wrong section. I'm trying to find a way to utilise the format method to place spaces between two other strings when printing but I'm not sure how this could be done. I know how to use the format method to pring the output on the right or left but this time round I have to print two strings together with spaces inbetween them. My code is similar to this: left=(len(left)+5)*'a' right=(len(right)+5)*'a' print("{:^{x}}".format(left+right, x=2*'')) So, the output I'm aiming to get would look something like this: 'aaaaa aaaaa'. Any help would be appreciated, thanks! A: Look in the docs for details, but for your example you could write print("{l}{x}{r}".format(l=left, r=right, x=2*''))
{ "pile_set_name": "StackExchange" }
Q: Can bitwise operators have undefined behavior? Bitwise operators (~, &, | and ^) operate on the bitwise representation of their promoted operands. Can such operations cause undefined behavior? For example, the ~ operator is defined this way in the C Standard: 6.5.3.3 Unary arithmetic operators The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E. On all architectures, ~0 produces a bit pattern with the sign bit set to 1 and all value bits set to 1. On a one's complement architecture, this representation correspond to a negative zero. Can this bit pattern be a trap representation? Are there other examples of undefined behavior involving simple bitwise operators for more common architectures? A: For one's complement systems, there's explicitly listed the possibility of trap values for those that do not support negative zeros in signed integers (C11 6.2.6.2p4): If the implementation does not support negative zeros, the behavior of the &, |, ^, ~, <<, and >> operators with operands that would produce such a value is undefined. Then again, one's complement systems are not exactly common; as for example GCC doesn't support any! C11 does imply that the implementation-defined and undefined aspects are just allowed for signed types (C11 6.5p4).
{ "pile_set_name": "StackExchange" }
Q: Python os module open file above current directory with relative path The documentation for the OS module does not seem to have information about how to open a file that is not in a subdirectory or the current directory that the script is running in without a full path. My directory structure looks like this. /home/matt/project/dir1/cgi-bin/script.py /home/matt/project/fileIwantToOpen.txt open("../../fileIwantToOpen.txt","r") Gives a file not found error. But if I start up a python interpreter in the cgi-bin directory and try open("../../fileIwantToOpen.txt","r") it works. I don't want to hard code in the full path for obvious portability reasons. Is there a set of methods in the OS module that CAN do this? A: The path given to open should be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory. A simple solution would be to make your path relative to the script. One possible solution. from os import path basepath = path.dirname(__file__) filepath = path.abspath(path.join(basepath, "..", "..", "fileIwantToOpen.txt")) f = open(filepath, "r") This way you'll get the path of the script you're running (basepath) and join that with the relative path of the file you want to open. os.path will take care of the details of joining the two paths. A: This should move you into the directory where the script is located, if you are not there already: file_path = os.path.dirname(__file__) if file_path != "": os.chdir(file_path) open("../../fileIwantToOpen.txt","r")
{ "pile_set_name": "StackExchange" }
Q: Concurrent Threads using same method If I spawn various Threads, and tell them all to use the same method: internal class Program { private static DoSomething() { int result = 0; Thread.Sleep(1000); result++; int ID = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Thread {0} return {1}", ID, result); } private static Main() { Thread[] threads = new Thread[50]; for (int i = 0; i < 50; i++) threads[i] = new Thread(DoSomething); foreach (Thread t in threads) t.Start(); } } Will all the Threads share the same stack? When I run the program all Threads return 1, so I guess the answer is no, but then does that mean that the CLR makes different copies of the method in memory? A: does that mean that the CLR makes different copies of the method in memory? No. It helps to understand how memory is partitioned in a .NET program. I'll skip a lot of minor implementation details to draw the Big Picture. You can subdivide memory in these categories: The garbage collected heap. Objects are stored there, you allocate storage from it with the new operator (except structs). It grows as needed, running out of it produces an OutOfMemoryException. The loader heap. Anything that's static for an AppDomain is stored there. Lots of little pieces but the important ones are storage for static variables, type information (the kind you retrieve with reflection) and just-in-time compiled code. It grows as needed, using too much of it is very hard to do. The stack. A core data structure for the processor. Not abstracting it away in C# is an important reason that C# produces fast programs. The stack stores the return address when you call a method, the arguments passed to a method and local variables of a method. By default a stack is one megabyte and cannot grow. Your program fails with this site's name if you use too much of it, a gross and hard to diagnose failure because the processor cannot continue executing code. A thread sees all these memory categories, with a twist on the last one. Every thread has its own stack. Which is above all why it is capable of running its own methods, independent of other threads. It however uses the exact same code as any other thread, the loader heap is shared. Assuming more than one thread executes the same method. And it shares the same garbage collected heap and static variables. Which makes writing threaded code hard, you have to ensure that threads don't step on objects and static variables that are also used by other threads. An important reason for the lock keyword. A: No, each thread has its own stack. And there's just one DoSomething. And each thread can access any sort of data from anywhere, whether safely that's another question. Think of DoSomething as it were just data, an integer, and each thread increments it. Now imagine that DoSomething is a function pointer, and you pass its address (an int, essentially) to each of the threads.
{ "pile_set_name": "StackExchange" }
Q: IIS UrlRewriting and Angular 7 routing I have an issue with routing atm. I want to add a sitemap to my angular application that is hosted on azure. Currently the web.config looks like this: <?xml version="1.0" encoding="utf-8"?> <!-- This configuration file is required if iisnode is used to run node processes behind IIS or IIS Express. For more information, visit: https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config --> <configuration> <system.webServer> <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support --> <webSocket enabled="false" /> <handlers> <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module --> <add name="iisnode" path="server.js" verb="*" modules="iisnode"/> </handlers> <rewrite> <rules> <!-- Do not interfere with requests for node-inspector debugging --> <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true"> <match url="^server.js\/debug[\/]?" /> </rule> <!-- First we consider whether the incoming URL matches a physical file in the /public folder --> <rule name="StaticContent"> <action type="Rewrite" url="public{REQUEST_URI}"/> </rule> <!-- All other URLs are mapped to the node.js site entry point --> <rule name="DynamicContent"> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> </conditions> <action type="Rewrite" url="server.js"/> </rule> </rules> </rewrite> <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it --> <security> <requestFiltering> <hiddenSegments> <remove segment="bin"/> </hiddenSegments> </requestFiltering> </security> <!-- Make sure error responses are left untouched --> <httpErrors existingResponse="PassThrough" /> <!-- You can control how Node is hosted within IIS using the following options: * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server * node_env: will be propagated to node as NODE_ENV environment variable * debuggingEnabled - controls whether the built-in debugger is enabled See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options --> <!--<iisnode watchedFiles="web.config;*.js"/>--> </system.webServer> </configuration> Looking at that, I thought that this line: <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> Would ignore routing and serve the physical file, but it doesn't seem to do that. Can someone help me update my web.config so that it always serves /sitemap.xml before it starts using Angular routing? A: try to add new rule <rule name="SiteMap" patternSyntax="Wildcard" stopProcessing="true"> <match url="sitemap.xml" /> <action type="Rewrite" url="/sitemap.xml" appendQueryString="false" /> </rule> here is full xml file <?xml version="1.0" encoding="utf-8"?> <!-- This configuration file is required if iisnode is used to run node processes behind IIS or IIS Express. For more information, visit: https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config --> <configuration> <system.webServer> <!-- Visit http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx for more information on WebSocket support --> <webSocket enabled="false" /> <handlers> <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module --> <add name="iisnode" path="server.js" verb="*" modules="iisnode"/> </handlers> <rewrite> <rules> <rule name="SiteMap" patternSyntax="Wildcard" stopProcessing="true"> <match url="sitemap.xml" /> <action type="Rewrite" url="/sitemap.xml" appendQueryString="false" /> </rule> <!-- Do not interfere with requests for node-inspector debugging --> <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true"> <match url="^server.js\/debug[\/]?" /> </rule> <!-- First we consider whether the incoming URL matches a physical file in the /public folder --> <rule name="StaticContent"> <action type="Rewrite" url="public{REQUEST_URI}"/> </rule> <!-- All other URLs are mapped to the node.js site entry point --> <rule name="DynamicContent"> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/> </conditions> <action type="Rewrite" url="server.js"/> </rule> </rules> </rewrite> <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it --> <security> <requestFiltering> <hiddenSegments> <remove segment="bin"/> </hiddenSegments> </requestFiltering> </security> <!-- Make sure error responses are left untouched --> <httpErrors existingResponse="PassThrough" /> <!-- You can control how Node is hosted within IIS using the following options: * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server * node_env: will be propagated to node as NODE_ENV environment variable * debuggingEnabled - controls whether the built-in debugger is enabled See https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config for a full list of options --> <!--<iisnode watchedFiles="web.config;*.js"/>--> </system.webServer> </configuration>
{ "pile_set_name": "StackExchange" }
Q: Regex: last string in quotes Given this string and PowerShell 2.0 Jrn.Grid "Control; Modal , Opening Worksets , Dialog_Revit_Partitions; Control_Revit_Partitions", "Selection" , "Rows;Shared Views, Levels, Grids;Shared Views, Levels, Grids;" I am trying to get just the last part in quotes. I started with $string -match '(["])(\\?.)*?\1' and while $matches[0] correctly returns "Control; Modal , Opening Worksets , Dialog_Revit_Partitions; Control_Revit_Partitions" $matches[-1] does not return "Rows;Shared Views, Levels, Grids;Shared Views, Levels, Grids;", and oddly $matches[1]just returns a single double quote. I also tried $string -match '(["])(\\?.)*?\1$', with the end of line anchor, and then $matches[0] returns everything in quotes. I suspect I am having an issue with testing for nested quotes, when in fact I don't want to treat them as nested, I want to treat them as a series. What am I missing, to get just the last match. And, what can I do to NOT include the quotes in the capture, just what is between them? AHA. Based on Toto's example, I added the end of line anchor and used $matches[1], thus $string -match '"([^"]+?)"$' $matches[1] and it seems to be working. I'll hope I don't run into any more complicated data that breaks it again. A: You could use: $string -match '"([^"]+?)"' then the match is in $matches[1]
{ "pile_set_name": "StackExchange" }
Q: Database.EnsureCreated not working I'm playing around with Entity Framework 7 versions listed below "EntityFramework.Core": "7.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final" My DatabaseContext class is very simple public class WorldContext : DbContext { public DbSet<Trip> Trip { get; set; } public DbSet<Stop> Stop { get; set; } public WorldContext() { Database.EnsureCreated(); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = Startup.Configuration["Data:WorldContextConnection"]; optionsBuilder.UseSqlServer(connectionString); base.OnConfiguring(optionsBuilder); } } I'm experiencing a problem when hitting the Database.EnsureCreated method in the constructor. As far as I can understand, this method is supposed to make ensure that the database is created if it does not exist, otherwise it is supposed to do nothing. When I debug through my DatabaseContext class code I hit the breakpoint set on the Database.EnsureCreated method, when execution continues the breakpoint is hit a second time (This was not expected), so the DatabaseContext constructor is entered into twice for some reason. On the second hit the following exception is thrown Even if the database exist, shouldn't the EnsureCreated method ignore it? Am I missing something here? A: Do not call ensure created in your constructor, but call it once during app start
{ "pile_set_name": "StackExchange" }
Q: Show a few columns in a stored procedure based on a parameter I have a parameter in my stored procedure called internal. If "internal" = yes then I want to display an additional 2 columns in my results. If it's no I don't want to display these columns. I can do a case statement and then I can set the column to be empty but the column name will still be returned in the results. My questions are: Is there a way not to return these 2 columns in the results at all? Can I do it in one case statement and not a separate case statement for each column? Thank you A: No, CASE is a function, and can only return a single value. And According to your comment:- The issue with 2 select statements are that it's a major complicated select statement and I really don't want to have to have the whole select statement twice. so you can use the next approach for avoid duplicate code:- Create procedure proc_name (@internal char(3), .... others) as BEGIN declare @AddationalColumns varchar(100) set @AddationalColumns = '' if @internal = 'Yes' set @AddationalColumns = ',addtionalCol1 , addtionalCol2' exec ('Select col1, col2, col3' + @AddationalColumns + 'From tableName Where .... ' ) END
{ "pile_set_name": "StackExchange" }
Q: Can I create an installer for a proprietary game? Neverwinter Nights is a game by Bioware. They have released a Linux version which is inconvenient to install. It's nothing more than copying stuff around but it can be messed up. The game files can be downloaded on their website but require your serial key to run the game. This can be bought online if you do not have the CD-version of the game (Windows only). I tried and failed in creating a .deb package (never done that before) to automate this and am now interested in using quickly to create a GUI version Ubuntu installer for Neverwinter Nights. If possible, I would link to the "buy serial key online" URL directly from the GUI installer. If I am successful I would like to see this in the Ubuntu Software Center. Having a highly popular classic RPG in there cannot hurt. I am not sure if this is prohibited by copyright laws and if I should even bother with it if it is. What do you think? A: I can think of two ways in which you can put up an application A game which is Open Source as per Open Source Initiative definition Proprietory game whose copyrights is held by you It would be worth telling how flash is installed on your computer. When you select to install the package flashplugin-nonfree the package actually downloads the flash plugin at that moment and copies the file to appropriate place. This is why this package is not present in main or universe repository I am not a lawyer, but I think you can create a small application which downloads the game and the serial key. Distributing it would be tricky. Many games want to control how their software is being distributed. They might not like that you are circumventing their distribution model. They might have ads on their download page. Even if it won't be illegal, legal department of those companies might want to clock extra hours by showing that they are working to protect the Intellectual property. You might receive a warning letter. Even worse, they might call it "voluntary copyright violation" It is more of trust. Distros know that Adobe wants flash to be installed everywhere, so Adobe won't come after them. The case of these games is not clear. My best solution would be to contact those game developers and ask them to put their games in Ubuntu Software Center. That is the safest bet.
{ "pile_set_name": "StackExchange" }
Q: JSONObject from dot seperated strings I am struggling with a specific problem, that I cannot think of correctly. The following is the problem I have a map with key value like the following, i just used strings here String key = "activate.message.success" String value = "success" String key1 = "activate.title" String value1 = "Good Title" String key2 = "activate.message.error" String value2 = "error" String key3 = "activate.message.short.poll" String value3 = "This is short poll" I need to build a json like the following { "activate":{ "message":{ "success":"success", "error":"error", "short":{ "poll":"This is short poll" } }, "title":"Good Title" } } I could not think of a proper solution for this use case and struggling for 3 hours. I thought of using recursion, but i dont how exactly i could do. Please help with this. I am using java for this, I should use generic JSONObject to solve as there is not POJO mappings. So far I have just splitted the strings using separtor and stored in an another map like the following public Map<String, Object> getJsonObjectFromKeyValueMap(Map<String, String> stringValueMap, Map<String, Object> stringObjectMap) { for (Entry entry : stringValueMap.entrySet()) { String[] keyValueArrayString = entry.getKey().toString().split("\\."); int sizeOfMap = keyValueArrayString.length; int i = 0; String concatString = ""; for (String processKey : keyValueArrayString) { if (i < sizeOfMap - 1) { concatString += processKey + "."; stringObjectMap.put(concatString, (Object) new JSONObject()); } else { concatString += processKey; stringObjectMap.put(concatString, entry.getValue()); concatString = ""; } i++; } } return stringObjectMap; } A: First, let's update your data into a proper map : Map<String, String> data = new HashMap<>(); data.put("activate.message.success", "success"); data.put("activate.title", "Good Title"); data.put("activate.message.error", "error"); data.put("activate.message.short.poll", "This is short poll"); Then, your logic is pretty close, for each node but the last, you create a new JSONObject, for the last, you insert the value. If you try to build a JSONObject instead of the map directly, you would get a pretty good result already, well somewhat of a result. The following will iterate a Map<String, String> of data. For each entry, we split the key to getting the nodes. Then, we just need to move in the json, if a node doesn't exist, we create it. Then, for the last value, create the value. public static JSONObject build(Map<String, String> data) { JSONObject json = new JSONObject(); //Iterate the map entries for (Entry<String, String> e : data.entrySet()) { String[] keys = e.getKey().split("\\."); // start from the root JSONObject current = json; for (int i = 0; i < keys.length; ++i) { String key = keys[i]; //Search for the current node try { //If it exist, do nothing current = current.getJSONObject(key); } //If it does not exist catch (JSONException ex) { //Is it the last node, create the value if (i == keys.length - 1) { current.put(key, e.getValue()); } //Not the last node, create a new JSONObject else { JSONObject tmp = new JSONObject(); current.put(key, tmp); current = tmp; //Always replace current with the last node to go deeped each iteration } } } } return json; } And the example : public static void main(String[] args) { Map<String, String> data = new HashMap<>(); data.put("activate.message.success", "success"); data.put("activate.title", "Good Title"); data.put("activate.message.error", "error"); data.put("activate.message.short.poll", "This is short poll"); JSONObject json = build(data); System.out.println(json.toString(4)); } Ouptut: {"activate": { "message": { "success": "success", "short": {"poll": "This is short poll"}, "error": "error" }, "title": "Good Title" }} Note : I used an exception to check for the existance of the key, if the map is huge, this could have some impact so you can simply use : if(current.isNull(key)){ if (i == keys.length - 1) { current.put(key, e.getValue()); } else { JSONObject tmp = new JSONObject(); current.put(key, tmp); current = tmp; } } else { current = current.getJSONObject(key); } This was created using org.json/json
{ "pile_set_name": "StackExchange" }
Q: In Lemma 4.7 of AKS, why do distinct polynomials map to distinct elements modulo h(x)? I am reading Primes is in P by Agrawal, Kayal and Saxena, and I can't understand part of the proof of Lemma 4.7 (already the subject of two questions here: PRIMES in P paper - Lemma 4.7 - why are the polynomials $X^m$ distinct in $F$? and Primes is in P, proof of hendrik Lenstra Jr. lemma). Let $\DeclareMathOperator{\ord}{ord}\ord_r(p)$ mean the order of $p$ modulo $r$, i.e. the least $k$ such that $p^k \equiv 1 \pmod r$. We have $p$ a prime and $r$ an integer, $p > r$, and a polynomial $h(x)$ which is an irreducible factor of the $r$th cyclotomic polynomial $Q_r(x)$ over the finite field $F_p$; the degree of $h(x)$ is $\ord_r(p)$. Some other numbers involved are $n$, $t$, and $\ell$; I'd hope you don't need to worry about their details. But in case you do, $n$ is a multiple of $p$ with $\ord_r(n) > \log(n)^2$, where $\log$ is the binary log; $\ell = \lfloor{\sqrt{\phi(r)}\log(n)}\rfloor$, where $\phi$ is Euler's totient function; and $t$ is the number of elements of $I := \{ (\frac{n}{p})^i p^j \mid i,j \geq 0\}$ which are distinct modulo $r$; these $t$ residues form a group $G$. Let $P$ be the set of all polynomials of the form $\prod_{a=0}^\ell (x + a)^{e_a}$, with powers $e_a \geq 0$. The statement I am confused about says that any two distinct polynomials in $P$ of degree less than $t$ map to different elements in the field $F := F_p[x]/(h(x))$. I'll reproduce the beginning of the proof. "$m$ is introspective for $f$" means $f(x)^m = f(x^m) \pmod{x^r-1,p}$. First note that since $h(x)$ is a factor of the cyclotomic polynomial $Q_r(x)$, $x$ is a primitive $r$th root of unity in $F$. We now show that any two distinct polynomials of degree less than $t$ in $P$ will map to different elements in F. Let $f(x)$ and $g(x)$ be two such polynomials in $P$. Suppose $f(x) = g(x)$ in the field $F$. Let $m \in I$. We also have $f(x)^m = g(x)^m$ in $F$. Since $m$ is introspective for both $f$ and $g$, and $h(x)$ divides $x^r − 1$, we get: \[ f(x^m) = g(x^m) \] in $F$. This implies that $x^m$ is a root of the polynomial $Q(Y) = f(Y) − g(Y)$ for every $m \in G$. Since $(m, r)=1$ ($G$ is a subgroup of $\mathbb{Z}_r^*$), each such $x^m$ is a primitive $r$th root of unity. Hence there will be $|G| = t$ distinct roots of $Q(Y)$ in $F$. However, the degree of $Q(Y)$ is less than $t$ by the choice of $f$ and $g$. This is a contradiction and therefore, $f(x) \neq g(x)$ in $F$. But, isn't $Q(Y)$ just identically zero, since $f(x) = g(x)$, so $f(Y) = g(Y)$? A: Reading through the paper suggested by Will Jagy in the comments, It is easy to determine whether a given integer is prime by Andrew Granville, seems to have clarified this. This part of AKS Lemma 4.7 is addressed in Granville's Lemma 4.3 on page 19, which tackles the contrapositive statement: If $f(x) \equiv g(x) \mod (p, h(x))$, where $f$ and $g$ in $P$ have degree less than $t$, then $f(x) \equiv g(x) \mod p$. The difference of the two polynomials is now called $\Delta(y)$, and I take it that it's understood to live in $\mathbb{F}[y]$. I think the part I was missing is the reinterpretation of $f$ and $g$ here: Rather than a sum of coefficients times powers of $x$ the element of $\mathbb{F}$ (an $r$th root of unity), we are going back to the polynomials with integer coefficients, which we can evaluate at arbitrary elements of $F$. When evaluated at the $t$ elements of $\mathbb{F}$ of the form $x^k$ for $k \in G$, $\Delta(x^k)$ is zero, so $\Delta$ must be the zero polynomial modulo $(p, h(x))$. Then it says "which implies that $\Delta(y) \equiv 0 \pmod p$ since its coefficients are independent of $x$"—that is, because all its coefficients are integers. [As a side note, I really wish people would stop saying "$f(x)$" when they just mean the polynomial $f$ itself, not an example of its output. That alone would help to make this situation clearer.]
{ "pile_set_name": "StackExchange" }
Q: Execute Script to Run on Multiple Files I have a script that I need to run on a large number of files. This is the script and how it is run: ./tag-lbk.sh test.txt > output.txt It takes a file as input and creates an output file. I need to run this on several input files, and I want a different output file for each input file. How would I go about doing this? Can I make a script (I have not much experience writing bash scripts). [edits]: @fedorqui asked: Where are the names of the input files and output files stored? There are several thousand files, each with a unique name. I was thinking maybe there is a way to recursively iterate through all the files (they are all .txt files). The output files should have names that are generated recursively, but in a random fashion. A: Simple solution: Use two folders. for input in /path/to/folder/*.txt ; do name=$(basename "$input") ./tag-lbk.sh "$input" > "/path/to/output-folder/$name" done or, if you want everything in the same folder: for input in *.txt ; do if [[ "$input" = *-tagged.txt ]]; then continue # skip output fi name=$(basename "$input" .txt)-tagged.txt ./tag-lbk.sh "$input" > "$name" done Try this with a small set of inputs somewhere where it doesn't matter when files get deleted, corrupted and overwritten.
{ "pile_set_name": "StackExchange" }
Q: Compare string with slashes I have two strings which look like this: string a = "C:\Temp\1.png" string b = "C:\Temp\1.png" Those, of course, have the same meaning. I'm looking for a way to know that they're equal. Meaning, something like: bool areEqual = false; if (a.CompareTo(b) == 0) areEqual = true; And for the example above, areEqual will be true. How can I do that? A: Use this code string a = @"C:\xxx\1.png"; string b = @"C:\xxx\1.png"; bool blnEqule = a == b;
{ "pile_set_name": "StackExchange" }
Q: DIY car phone charger I am converting a wheelchair access vehicle into a campervan. Having removed the old wheelchair ramp lift mechanism, I'm left with a couple of 12V cables in the back. I'd like to turn one of these cables into a phone charger, i.e. a simple micro-USB cable (see below). The question is, knowing that I have 12V coming through the cable, could I simply attach a DC to DC converter to reduce the voltage to 5V (which is needed by the phone), followed by the USB cable? Are there any other specifications I should check? Here's the DC-DC converter I'm thinking of using: I have only a (very) basic knowledge of electronics, so wanted to check this project seems feasible. A: I've built a car charger using one of those CPT modules, out of curiosity as much as anything. They are pretty good, cheap buck converters. The noise on the output of mine is within the spec for USB charging. It is not isolating, so 12V ground is connected to 5V ground - which can cause noise if it's plugged into the stereo with an aux jack. The tricky bit is "fast-charging" your phone. If you just provide 5V to a phone, using the power and ground wires in a USB cable, it will usually charge at 500mA. That's the same as when plugged into a PC, and it'll take a while. Most phones these days can charge at least four times that fast, if the charger supports it. They check whether the charger supports it by looking at the connection of the data wires in the USB cable, and sometimes the connection of the metal housing of the connector. There is a standard, but frustratingly many phones don't use that standard. If you have one type of phone/tablet you want to charge you can usually look up how to wire the data leads to get fast charging to work for that type. Most brands use the same pattern across all their devices, but Apple use different patterns for different devices. You can also get ICs which detect which type of device is connected and pretend to be the right type of charger, but that's quite complicated for a beginner. Or, if you want to do it the simple way, buy a charger with the fast-charging features, connect it to your cables, and hot-glue it out of sight behind some trim. Oh, and whichever way you do this, work out which fuse in the fusebox feeds those cables and swap it for something appropriate - a wheelchair lift would probably take a lot of current, where one of these modules only needs about 1.5A max.
{ "pile_set_name": "StackExchange" }
Q: Updating Basemaps in OpenLayers 3 I'm getting the sense that OpenLayers 3 does not differentiate between basemaps and other layers the way OpenLayers 2 did (OL2 Layers had a isBaseLayer property, but I'm not seeing an equivalent in OL3). I'm guessing there must be some way to set the ordering when adding a layer to a map...something like map.addLayer(newBasemap, 1); // where all other layers would have an ordering greater than 1 But when I look at the docs all I see is addLayer(layer) which places the new layer on top of the other layers. How can I ensure the new (basemap) layer is placed underneath the other layers rather than on top? A: Found an answer here at Christopher Jennison's Blog. Turns out layers can be added at a particular index with the following: map.getLayers().insertAt(1, layer); In my case in which I'm replacing the basemap that's already there I need to first remove basemap1 and then add basemap2 in its place, which I can do like this: map.removeLayer(basemap1); map.getLayers().insertAt(1, basemap2); Huzzah UPDATE: Thanks to erilem for providing a more straightforward solution, setAt, which simply replaces the layer at a given index... map.getLayers().setAt(1, basemap2);
{ "pile_set_name": "StackExchange" }
Q: Creating table with different row dimensions Let's say I got a table like this: data <- c(1,2,3,6,5,6,9,"LC","LC","HC","HC","LC","HC","ALL") attr(data,"dim") <- c(7,2) data [,1] [,2] [1,] "1" "LC" [2,] "2" "LC" [3,] "3" "HC" [4,] "6" "HC" [5,] "5" "LC" [6,] "6" "HC" [7,] "9" "ALL" Now I want to manipulate the data so it looks like this: [,"LC"] [,"HC"] [,"ALL"] [1,] "1" "3" "9" [2,] "2" "6" [3,] "5" "6" Is there a way to do this in R or is it just impossible and should I try another way of getting access to my data? A: You can get very close by using split. This returns a list with the values you wanted and you can then use lapply or any other list manipulation function: split(data[, 1], data[, 2]) $ALL [1] "9" $HC [1] "3" "6" "6" $LC [1] "1" "2" "5" If you must have the output in matrix format, then I suggest you pad the short vectors with NA: x <- split(data[, 1], data[, 2]) n <- max(sapply(x, length)) pad_with_na <- function(x, n, padding=NA){ c(x, rep(padding, n-length(x))) } sapply(x, pad_with_na, n) This results in: ALL HC LC [1,] "9" "3" "1" [2,] NA "6" "2" [3,] NA "6" "5"
{ "pile_set_name": "StackExchange" }
Q: Iphone x losing my bottom tool bar. How to set view into safe layout area? I use a wk webview and my own tool bar on my app. I have set the constraints for the top of my webview to the **safe layout area ** as described in a https://medium.com/@hassanahmedkhan/playing-it-safe-with-safe-area-layout-guide-b3f09bdc71fe and the following image: My iphone X image looks like the following with extra white space on the top and the bottom and I am missing my bottom tool bar. ** Please note the black area is simply blocked out so as not to show location. It is the typical google map. ** I want it to look like (NOTE: the bottom bar, and the proper fit - no white space as on the iphone x version.) My code that sets the size of the web frame (top portion) looks like this IS there a way to set my view into the safe layout area/frame itself? Again, I do set the constraints to the safe layout area as described in the above hyper link. What do I need to do to correct for the iphone x version? (NOTE: when I say correct I mean remove top white space remove bottom white space have MY tool bar as show in the iphone 7 version on the bottom Thank you. A: I got my tool bar to show up. I still have extra white space, yuk! If someone has any ideas on how to fix, it would be greatly appreciated. I changed my code to this: // Iphone x does not show tool bar and has extra padding so need to change UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window]; CGFloat top = 0 ; CGFloat bottom = 0 ; bool iphoneX = NO; if (@available(iOS 11.0, *)) { top = mainWindow.safeAreaInsets.top ; bottom = mainWindow.safeAreaInsets.bottom ; if (top > 0.0) { //only have on iphonex where not zero iphoneX = YES; } } if (iphoneX) { rightSizeFrame.size.height = mainWindow.frame.size.height - top - bottom ;// notice subtracting the tool bar height instead of top and bottom did not work! - ( 1*TOOLBAR_HEIGHT) ; // need the bottom to see the tool bar not sure why rightSizeFrame.origin.y = 0 ; // no top whitespace } // will this set the right size aand POSITION [[ self webView] setFrame:rightSizeFrame] ; // then stick the new webView8 into the frame _webView8 = [[WKWebView alloc] initWithFrame:self.webView.frame configuration:configuration]; I needed the height to have both the bottom and the top removed from the window frame in order for my tool bar to show. Unfortunately, like the image in my first post - I still have extra white space on top and beneath the web view. And now I have gray space at the bottom of the tool bar. It looks terrible but at least is functional. Does anyone have any ideas why the extra white and gray space? I am actually surprised that I have received no answers. Am I missing something obvious?
{ "pile_set_name": "StackExchange" }
Q: Gradually increase the probability of mutation I am implementing something very similar to a Genetic Algorithm. So you go through multiple generations of a population - at the end of a generation you create a new population in three different ways 'randomly', 'mutation' and 'crossover'. Currently the probabilities are static but I need to make it so that the probability of mutation gradually increases. I appreciate any direction as I'm a little stuck.. This is what I have: int random = generator.nextInt(10); if (random < 1) randomlyCreate() else if (random > 1 && random < 9 ) crossover(); else mutate(); Thank you. A: In your if statement, replace the hard coded numbers with variables and update them at the start of each generation. Your if statement effectively divides the interval 0 to 10 into three bins. The probability of calling mutate() vs crossover() vs randomlyCreate() depends on the size of each bin. You can adjust the mutation rate by gradually moving the boundaries of the bins. In your code, mutate() is called 20% of the time, (when random = 9 or 1), randomlyCreate() is called 10% of the time (when random = 0) and crossover() is called the other 70% of the time. The code below starts out with these same ratios at generation 0, but the mutation rate increases by 1% each generation. So for generation 1 the mutation rate is 21%, for generation 2 it is 22%, and so on. randomlyCreate() is called 1 / 7 as often as crossover(), regardless of the mutation rate. You could make the increase in mutation rate quadratic, exponential, or whatever form you choose by altering getMutationBoundary(). I've used floats in the code below. Doubles would work just as well. If the mutation rate is what you're most interested in, it might be more intuitive to move the mutation bin so that it's at [0, 2] initially, and then increase its upper boundary from there (2.1, 2.2, etc). Then you can read off the mutation rate easily, (21%, 22%, etc). void mainLoop() { // make lots of generations for (int generation = 0; generation < MAX_GEN; generation++) { float mutationBoundary = getMutationBoundary(generation); float creationBoundary = getCreationBoundary(mutationBoundary); createNewGeneration(mutationBoundary, creationBoundary); // Do some stuff with this generation, e.g. measure fitness } } void createNewGeneration(float mutationBoundary, float creationBoundary) { // create each member of this generation for (int i = 0; i < MAX_POP; i++) { createNewMember(mutationBoundary, creationBoundary); } } void createNewMember(float mutationBoundary, float creationBoundary) { float random = 10 * generator.nextFloat(); if (random > mutationBoundary) { mutate(); } else { if (random < creationBoundary) { randomlyCreate(); } else { crossover(); } } } float getMutationBoundary(int generation) { // Mutation bin is is initially between [8, 10]. // Lower bound slides down linearly, so it becomes [7.9, 10], [7.8, 10], etc. // Subtracting 0.1 each generation makes the bin grow in size. // Initially the bin is 10 - 8 = 2.0 units wide, then 10 - 7.9 = 2.1 units wide, // and so on. So the probability of mutation grows from 2 / 10 = 20% // to 2.1 / 10 = 21% and so on. float boundary = 8 - 0.1f * generation; if (boundary < 0) { boundary = 0; } return boundary; } float getCreationBoundary(float creationBoundary) { return creationBoundary / 8; // fixed ratio }
{ "pile_set_name": "StackExchange" }
Q: How to load all scripts on a website So I have just set up a Nivo slider, although this has now resulted in the rest of the scripts from not working. I am unable to edit where the nivo slider loads, as it is a plugin, but I need to force those scripts to load before the websites, otherwise, no posts show up? I am at a loss on how to do this and its the last thing i need to do inregards to this website.. so desperate to get it over and done with. haha Here is the page in question: http://hobhob.co.uk/whmag/ Thanks! A: Assuming you're an administrator on your WordPress site, you can edit the plugin using the plugin editor. I would recommend to look for how the Nivo slider calls its JS files by searching for the wp_enqueue_script function as that is the recommended way for loading JS files. Also, most plugin developers should take into account other JS files in a WordPress environment when developing a plugin, so the problem may not necessarily be with the slider plugin, but some other JS file that you're loading. Using process of elimination, try disabling plugins one by one and see if any others are causing problems. Good luck!
{ "pile_set_name": "StackExchange" }
Q: Question on existential sentences A sentence is called existential if it is of the form $\exists x_1 \ldots \exists x_n \ \phi(x_1, \ldots, x_n)$, where $\phi$ is quantifier free. We know that (see Chang-Keisler "Model Theory", Proposition 5.2.2) Theorem. If every existential sentence that holds in $\mathfrak{A}$ also holds in $\mathfrak{B}$, then $\mathfrak{A}$ is isomorphically embeddable in some elementary extension of $\mathfrak{B}$. Suppose that we have a theory $T$ such that all its models agree on existential sentences. By the previous theorem, starting with two models $\mathfrak{A}, \mathfrak{B} \models T$, we can prove that for any $n > 0$, $\mathfrak{A}$ is $n$-sandwiched by model $\mathfrak{B}$. To see this, notice that since $\mathfrak{B} \models T$ and all models of $T$ agree on existential sentences, we have that $\mathfrak{B}$ can be isomorphically embedded in some elementary extension $\mathfrak{A}_0$ of $\mathfrak{A}$. This means that $\mathfrak{B} \subseteq \mathfrak{A}_0$. Now $\mathfrak{A}_0 \models T$, since $\mathfrak{A} \models T$ and $\mathfrak{A} \prec \mathfrak{A}_0$. So $\mathfrak{A}_0$ can be isomorphically embedded in some elementary extension $\mathfrak{B}_1$ of $\mathfrak{B}$. So we have $\mathfrak{B} \subseteq \mathfrak{A}_0 \subseteq \mathfrak{B}_1$. We can go on like this for infinitely many steps. Is this argument wrong? If not, does this mean that every theory $T$ such that all its models agree on existential sentences, is also $\Pi_2$ (and actually even $\Pi_{2n}$) complete? Doesn't ZFC satisfy the above condition as $T$? Note : Theorem (added). (Change-Keisler Proposition 5.2.5) If there are models $\mathfrak{A}', \mathfrak{B}'$ such that $\mathfrak{B} \subseteq \mathfrak{A}' \subseteq \mathfrak{B}'$, $\mathfrak{B} \prec \mathfrak{B}'$ and $\mathfrak{A} \prec \mathfrak{A}'$, then every $\Pi_2$ sentence holding in $\mathfrak{A}$ also holds in $\mathfrak{B}$. A: I see a problem with your argument. When you say that $\mathfrak A_0$ can be embedded in an elementary extension of $\mathfrak B$, it means that there is an elementary extension $\mathfrak B_1$ of $\mathfrak B$ and an embedding $f : \mathfrak A_0 \to \mathfrak B_1$. Then you say that we can identify $\mathfrak A_0$ with $f(\mathfrak A_0)$ and get $\mathfrak B \subseteq \mathfrak A_0 \subseteq \mathfrak B_1$. The problem is that you don't know what $f$ does to $\mathfrak B$. In other words $f(\mathfrak B)$ might not be an elementary substructure of $\mathfrak B_1$.
{ "pile_set_name": "StackExchange" }
Q: Find vertices pointing to common vertex In a directed graph I'm interested in finding pairs of vertices pointing towards a common vertex. More in detail, from an adjacency matrix I want to derive a matrix where a positive entry denotes that the vertices represented by the entry's row and column both point to a common vertex. For example, a graph with the following adjacency matrix: $$ \left[\begin{matrix} 0 & 1 & 0 & 1 \\ 1 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ \end{matrix}\right], $$ would result in the following matrix: $$ \left[\begin{matrix} 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ \end{matrix}\right]. $$ Since vertex 2 and 4 points to vertex 3 and vertex 1 and 3 points to vertex 4. (Or with the diagonal as ones if one does not need unique vertices in the pairs.) I'm thinking that there must be a simple matrix algebra solution to this, similar to using powers of the adjacency matrix to find walks. My intuition tells me: $$ \mathbf{A}\mathbf{A}^T $$ would do the trick, where $\mathbf{A}$ is the adjacency matrix. (In this case with a single vertex allowed to form a pair). While every example I've tested works out well, I cannot prove it will work in general. So I'm wondering: will it? A: Yes, you're correct (nice guess!) I find it a bit easier to visualize the $(i,j)$-entry of $AA^T$ as the standard inner product of rows $i$ and $j$ of $A$. Since all entries of $A$ are non-negative, you will got a positive value if and only if there is a column $k$ so that both entries in coordinates $(i,k)$ and $(j,k)$ are positive, i.e., there is a $k$ so that $(i,k)$ and $(j,k)$ are directed edges in the graph. So in your example, this occurs for $i=1$ and $j=3$ (at $k=4$), and also for $i=2$ and $j=4$ (at $k=3$), which of course is what you found.
{ "pile_set_name": "StackExchange" }
Q: Nesting columns under a new header column in a DataFrame I have a time series DataFrame df1 with prices in a ticker column, from which a new DataFrame df2 is created by concatenating df1 with 3 other columns sharing the same DateTimeIndex, as shown: Now I need to set up the ticker name "Equity(42950 [FB])" to become the new header and to nest the 3 other columns under it, and to have the ticker's prices replaced by the values in the "closePrice" column. How to achieve this in Python? A: pd.MultiIndex: d = pd.DataFrame(np.arange(20).reshape(5,4), columns=['Equity', 'closePrice', 'mMb', 'mMv']) arrays = [['Equity','Equity','Equity'],['closePrice', 'mMb','mMv']] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples) df = pd.DataFrame(d.values[:, 1:], columns=index) df Equity closePrice mMb mMv 0 1 2 3 1 5 6 7 2 9 10 11 3 13 14 15 4 17 18 19
{ "pile_set_name": "StackExchange" }
Q: Continuous creation of bitmaps leads to memory leak I have a thread that continuously generates bitmaps and takes a screenshot of another program's window. Now, I have a pictureBox on my form, and that's constantly being updated with the bitmaps generated. Here's the code I have in the thread: Bitmap bitmap = null; while (true) { if (listBoxIndex != -1) { Rectangle rect = windowRects[listBoxIndex]; bitmap = new Bitmap(rect.Width, rect.Height); Graphics g = Graphics.FromImage(bitmap); IntPtr hdc = g.GetHdc(); PrintWindow(windows[listBoxIndex], hdc, 0); pictureBox1.Image = bitmap; g.ReleaseHdc(hdc); } } As you can see, this leads to a memory leak, because of the continuous call to new Bitmap(rect.Width, rect.Height). I've tried adding "bitmap.Dispose()" to the bottom of the while loop, but that leads to the pictureBox's image also being disposed, which makes a giant red X in place of the actual image. Is there any way I can dispose of "bitmap" without disposing of the pictureBox image? A: You're also "leaking" the Graphics object. Try this: while (true) { if (listBoxIndex != -1) { Rectangle rect = windowRects[listBoxIndex]; Bitmap bitmap = new Bitmap(rect.Width, rect.Height); using (Graphics g = Graphics.FromImage(bitmap)) { IntPtr hdc = g.GetHdc(); try { PrintWindow(windows[listBoxIndex], hdc, 0); } finally { g.ReleaseHdc(hdc); } } if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } pictureBox1.Image = bitmap; } }
{ "pile_set_name": "StackExchange" }
Q: Bind for taking out melee wep in TF2? I'd like a bind to take out my melee.This is mainly for powerjack efficiency, but it would help for market gardener. A: I think by default your '3' key is bound to execute 'slot3' which simply brings up your third weapon in mostly every source game and, in TF2's case it is always the melee. If you're unsure how to bind however, open your developer console (needs to be enabled in Keyboard/Mouse Settings > Advanced) and enter: bind "3" "slot3" Replacing '3' with whatever you'd like to press. This can also be done with slot1, slot2, slot4 and slot5 for all classes, including things like the Spy's sapper and disguise kit, along with Engineer's Build and Destruction PDA. Hope this helped you out.
{ "pile_set_name": "StackExchange" }
Q: Create or update function of realm framework not working in iOS I am using the Realm framework for iOS and I'm trying to create multiple objects in an array from a parse query, but keeping in check that there are none that are repeated in the local realm. let lastSyncDate = NSUserDefaults.standardUserDefaults().objectForKey("com.fridge.sync.last") as NSDate let query = PFQuery(className: "Category", predicate: NSPredicate(format: "updatedAt > %@", lastSyncDate)) query.findObjectsInBackgroundWithBlock { (results, error) -> Void in if error != nil { return } if results.isEmpty { return } let realm = RLMRealm.defaultRealm() /*realm.transactionWithBlock({ () -> Void in for remoteCategory in results as [PFObject] { let category = Category() category.name = remoteCategory["name"] as String category.image = NSData() realm.addObject(category) } })*/ /*realm.beginWriteTransaction() for remoteCategory in results as [PFObject] { let category = Category() category.name = remoteCategory["name"] as String category.image = NSData() realm.addObject(category) } realm.commitWriteTransaction()*/ } I also used the creatorupdate version but it still doesn't save any of the objects and for some reason I can't debug anything of what is heppening inside of the realm code. The category model is like this: class Category: RLMObject { dynamic var categoryId: String = "" dynamic var name: String = "" dynamic var image: NSData = NSData() var stores: [Store] { return linkingObjectsOfClass(Store.className(), forProperty: "category") as [Store] } override class func primaryKey() -> String { return "categoryId" } } Any idea of what could possibly be going wrong is greatly appreciated. Thanks in advance A: It doesn't look like you are setting the categoryID property on your objects. This would cause all of them to use the same primary key and overwrite the same object when using createOrUpdate To debug and step into the Realm code you will probably need to build from source.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap navbar dropdown does not open The dropdown menu in the navbar which build by bootstrap does not open. Do you have any solutions? here is the code: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!--JQuery.min.js------------> <script src="http://code.jquery.com/jquery.min.js"></script> <!--JQuery.min.js------------> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="style.css" rel="stylesheet"> </head> A: If you still having the issue put http://code.jquery.com/jquery.min.js before <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>in head. Like this: <head> ----- ----- ---- <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!--JQuery.min.js------------> <script src="http://code.jquery.com/jquery.min.js"></script> <!--JQuery.min.js------------> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> Hope this help you.!!
{ "pile_set_name": "StackExchange" }
Q: Calling parent method with multiple inheritance I have the following contract definition: contract MyToken is StandardToken, Ownable { ... function transfer(address _to, uint256 _value) public returns (bool){ require(...); // would like to call StandardToken's transfer function here } } I've tried doing: function transfer(address _to, uint256 _value) public StandardToken(_to, _value) returns (bool) { but that didn't work: TypeError: Referenced declaration is neither modifier nor base class. A: Your contract 'MyToken' is a child of 'StandardToken', it inherits the 'transfer' function. You do not need to define 'transfer' because you can already use it. If you want to override the 'transfer' function, you can read about it here.
{ "pile_set_name": "StackExchange" }
Q: Publish a zip file to Nexus (Maven) with Gradle Say you have a PL file you want to upload to Nexus with Gradle. How would such a script look like. group 'be.mips' version = '1.4.0-SNAPSHOT' In settings.gradle --> rootProject.name = 'stomp' And let's say that the pl file is in a subdirectory dist (./dist/stomp.pl). Now I want to publish this stomp.pl file to a nexus snapshot repository. As long as you go with Java, then Gradle (just like Maven) works like a charm. But there's little documentation found what to do if you have a DLL, or a ZIP, or a PL (Progress Library). A: I publish such artifacts for a long time. For example, ZIP archives with SQL files. Let me give you an example from real project: build.gradle: apply plugin: "base" apply plugin: "maven" apply plugin: "maven-publish" repositories { maven { url defaultRepository } } task assembleArtifact(type: Zip, group: 'DB') { archiveName 'db.zip' destinationDir file("$buildDir/libs/") from "src/main/sql" description "Assemble archive $archiveName into ${relativePath(destinationDir)}" } publishing { publications { mavenJava(MavenPublication) { artifact source: assembleArtifact, extension: 'zip' } } repositories { maven { credentials { username nexusUsername password nexusPassword } url nexusRepo } } } assemble.dependsOn assembleArtifact build.dependsOn assemble publish.dependsOn build gradle.properties: # Maven repository for publishing artifacts nexusRepo=http://privatenexus/content/repositories/releases nexusUsername=admin_user nexusPassword=admin_password # Maven repository for resolving artifacts defaultRepository=http://privatenexus/content/groups/public # Maven coordinates group=demo.group.db version=SNAPSHOT
{ "pile_set_name": "StackExchange" }
Q: menubar's sliding effect and tabs not appear I want when pointing from one menu to another menu, the menu looked like a sliding board. i can show that after downloaded at apycom.com, beside that, i have a jquery-ui tabs in input.php. the problem comes after i have included that menubar. menubar's sliding effect not show and also the tabs.. why it happens? A: From what I understand of your question, this is not possible in pure CSS. However, it's possible with the addition of javascript. Check out the "accordion" effect on google. jQuery has a nice implementation.
{ "pile_set_name": "StackExchange" }
Q: Need advice on microcontroller to switch relay on/off I am trying to connect an OMRON G2RL-2A DPST 12 VDC relay (G2RL relay datasheet) to my PICAXE 20x2 microcontroller. I also have a ULN2803A relay driver (ULN2803A datasheet). I managed to get the microcontroller to work quite well, so I don't have a problem with it. The question is this: The ULN2803 does not have a V+ pin, so does that mean it does not require power? It only has a GND pin, which I believe should be connected to a GND (probably the GND of the microcontroller?) Now, I think I have to connect an output of the PICAXE 20x2 to an input of ULN2803. After this, where should I connect the respective output of the ULN2803 on the relay? Also do I have to use a 12 VDC power for my relay? Or maybe I can use the same 5 V power of my microcontroller? If not, where should I connect this 12 V on the relay? Sorry for total noob questions, I hope you can guide me. UPDATE I can not still make this circuit to work properly. Here is the work I have done so far, please have a look. The problem is, if I connect ULN2803 pin 10 to +12 V or GND, the relays either dont work or just lock the current state. Where should I connect ULN2803 pin 10? A: V+ goes through the relay, into the collector of the darlington pair inside the driver, then down to ground. A second V+ connection to pin 10 acts as a 'flywheel' diode to stop back-emf. Connect GND to ground (anywhere), one of the outputs to the relay, and the other side of the relay to +12V. The logic '1' signal is enough to power the base of the darlington pair to turn it on/off. It needs no power supply of its own. Here is the circuit built on breadboard. The connectors along the top are: Black: Common ground Yellow: +5V Blue: +3.3V Green: +12V Red: -12V
{ "pile_set_name": "StackExchange" }
Q: Australian Skilled Independent Visa - How can I prove I have been employed in my nominated skilled occupation I am planning to apply for the Skilled Independent (Subclass 189) visa in the next few years. The Australian immigration page writes that one might get plus points if the applicant has been working in his/her nominated skilled occupation or in an occupation closely related to it. I have no doubt that if the applicant makes such a statement, he/she has to be able to support it with evidence. My question is - how can this be proven? In my specific case, I don't want my employer to know about my intentions of moving there until it is absolutely necessary. Is there any way of providing evidence of my employment without involving my employer? As a related question, what if I get a new job meanwhile, before applying for the visa? If the only way of proving my employment is to provide papers from my employer then do I have to contact all my previous employers so that the total duration of working in the nominated occupation adds up for the necessary X years? A: Yes, they need a reference letter from your employer detailing your skills so as to match them with a list of standard skills required for your nominated skilled occupation. If you cannot provide such a letter from the employer, a statutory declaration from your manager on a non-judicial paper is also accepted. Additionally you are required to provide payslips, bank statements, tax statements, employment contracts, etc. to further evidence the employment. You cannot make these statements yourself. It has to be either your employer stating these in a reference letter on their letter head or your manager/ supervisor as a statutory declaration. You get points for work experience in your occupation. The more the work experience, the more points you earn. Therefore, you will need this documentation from all your ex-employers/ ex-managers as well (unless you don't want more employment points). A: As an addition to @kpatil answer I would like to stress how important it is to have reference letters in required standard... Below you will find two examples one that got accepted other rejected ... Successful: Failed: I suggest you make forms for each company that look like former example. You then take originals to Australian embassy for notarization.
{ "pile_set_name": "StackExchange" }
Q: How configurable is the "more than {n} answers" alert box? We're considering asking that the trigger for this be lowered from 30 on IPS to something else, which is shown to be possible in the post that introduces it. There is some concern regarding some of the text on the popup: Specifically, the last sentence: Also, please note that you can click the edit link on any of these answers to improve them. This is absolutely true on Stack Exchange and editing to improve answers is certainly something that everyone should be willing to do... but on sites like Interpersonal Skills where answers tend to be very personal, it can feel intrusive to have people add information to an answer. If we decide to change the quantity of answers that trigger this popup, is it possible to remove this? A: Quick note on this threshold: while the default is 30, it can be lowered all the way to 0 if desired (which would generate this warning if at least one answer had already been posted). Note that this setting controls one other feature: for questions that exceed the threshold, all comments are hidden by default unless they score 1 or more; there's currently no way to separate these two bits of functionality, so if you opt to reduce the answer threshold you'll have to accept fewer comments shown by default as well. Oh, such a shame, I know, I know... As for the bit about editing: the message isn't configurable at all. Editing is a fundamental part of how these sites are designed to be used; while it's true that some topics (and some communities) do tend to be more possessive of their work than others, the rationale for allowing editing remains valid across all sites: these posts are intended to outlast their authors, and allowing them to be improved and maintained is critical to this end. The last thing any question needs is dozens of answers each existing solely to provide a small correction to a previous answer; if IPS (or any other site) is headed in that direction, we might as well shutter it and direct folks to a PHPBB forum (and the year 2006). As always, respect the original author - but if an author asserts that their work should never be edited, gently suggest to them that they may be happier somewhere else on the Internet.
{ "pile_set_name": "StackExchange" }
Q: Data Entities Add Range quit working Like the title suggests I have a small program that has been running in production for the last 3 months. Last week it started to error out on an AddRange line with this error message: "Message=Keyword not supported: 'file'." And nothing in the inner exception. Here is the offending function where I can no longer get to the SaveChanges() line. private static void SaveToDB(List<MarketNew> inMarketNews) { proxy.MarketNews.AddRange(inMarketNews); proxy.SaveChanges(); } cheers bob edit- If I try to manually add them one at a time I still receive the following exception. System.ArgumentException was caught HResult=-2147024809 Message=Keyword not supported: 'file'. Source=System.Data StackTrace: at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext](TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) at System.Data.Entity.Infrastructure.SqlConnectionFactory.CreateConnection(String nameOrConnectionString) at System.Data.Entity.Internal.LazyInternalConnection.Initialize() at System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() at System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() at System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() at System.Data.Entity.Internal.Linq.InternalSet`1.AddRange(IEnumerable entities) at System.Data.Entity.DbSet`1.AddRange(IEnumerable`1 entities) at GetMarketNews.Program.SaveToDB(List`1 inMarketNews) in e:\Tableau\Custom Utilities\MarketNews\GetMarketNews\GetMarketNews\Program.cs:line 195 InnerException: A: The exception indicates that there is a problem with your connection string. While the program itself may not have been changed in months, can you confirm that the config file (or however you set your connection string) has not been changed? If you still can't find it from this, I would suggest you check out the value of the connection string at runtime (e.g. put a breakpoint on the AddRange line, and look at proxy.Database.ConnectionString). I suspect you'll find the "file" keyword in the connection string.
{ "pile_set_name": "StackExchange" }
Q: Trying to duel boot linux/windows with each OS on a different HD I'll try to do my best to explain the situation. So I want to boot linux/windows, but duel boot not just boot from the current hd. Something I noticed when I went into the BIOS settings. I'm not sure if this is something that is causing this issue or what, but I can only one have one of the HD in the boot priority list at a time. I have to go to boot options and go to Hard Drive BBS Priorities to switch to the other hard drive. Now when I switch the other one can't be in the main Boot Priority list. I have no clue as to why it is doing this. I was told by a friend and through some research a "grub" screen should appear when I boot. What is a grub screen and could the reason above be why I don't see it? A: The last time I installed ubuntu with windows it gave an option for dual boot. It would flash on the screen and allow you to choose which operating system to start. I believe you have an installation issue. Try reinstalling ensure you choose the dual boot options. All else fails you can load ubuntu on a USB drive and run it from there.
{ "pile_set_name": "StackExchange" }
Q: How do i arranged by reading two text files using bash? I have a two text files text cat A.txt 10,1,1,"ABC" 10,1,2,"ABC" 10,1,3,"baba" 10,2,1,"asd" 10,2,2,"dkkd" cat B.txt 10,1,2,"S1" 10,2,1,"S2" 10,2,2,"S3" I want contents of file B.txt should appear above the matched from A.txt Here i need to compare the three numbers which are separated by commas. say (10,1,2) of A.txt and (10,1,2) of B.txt if they found equal then it add to above How do i get this output and save to another file using bash 10,1,1,"ABC" 10,1,2,"S1" 10,1,2,"ABC" 10,1,3,"baba" 10,2,1,"S2" 10,2,1,"asd" 10,2,2,"S3" 10,2,2,"dkkd" A: Just sort the files using the first three fields. Because you prefer lines from B.txt in front of A.txt, I used -s, --stable option to disable last-resort sorting, hoping for sort to pick the first line it reads. So by specifying the first file to be B.txt, I hope it will places B.txt lines in front. sort -s -t, -k1,3 B.txt A.txt will output: 10,1,1,"ABC" 10,1,2,"S1" 10,1,2,"ABC" 10,1,3,"baba" 10,2,1,"S2" 10,2,1,"asd" 10,2,2,"S3" 10,2,2,"dkkd"
{ "pile_set_name": "StackExchange" }
Q: How to fetch images, css, js from cache (with http status 200 (cache) not 304) I have web page which refers large number of JS, Images files. when teh page is loaded second time, 304 requests goes to the server. I would like to get http 200 (cache) status for cached object rather than 304. I am using asp.net 4, iis 7. Setting the Expiry header is not working, it still sends 304 requests. I want http status 200 (cache). Please let me know if there is any technique for this. A: You've said that setting the expiry doesn't help, but it does if you set the right headers. Here's a good example: Google's library hosting. Here are the (relevant) headers Google sends back if you ask for a fully-qualified version of a library (e.g., jQuery 1.7.2, not jQuery 1., or jQuery 1.7.): Date:Thu, 07 Jun 2012 14:43:04 GMT Cache-Control:public, max-age=31536000 Expires:Fri, 07 Jun 2013 14:43:04 GMT (Date isn't really relevant, I just include it so you know when the headers above were generated.) There, as you can see, Cache-Control has been set explicitly with a max-age of a year, and the Expires header also specifies an expiration date a year from now. Subsequent access (within a year) to the same fully-qualified library doesn't even result in an If-Modified-Since request to the server, because the browser knows the cached copy is fresh. This description of caching in HTTP 1.1 in RFC 2616 should help.
{ "pile_set_name": "StackExchange" }
Q: WordPress login screen database issue My WordPress login page at mysite.com/wp-login.php is giving me a cannot connect to 127.0.0.1 error. The site works, and other WordPress admin pages are available, like upgrade.php. I've done some googling, tried some of the suggestions here: http://wordpress.org/support/topic/error-establishing-a-database-connection-112 But to no avail. Admin has been working for weeks and nothing has been changed. Everything also looks correct in config.php. The site is on AN Hosting, and I logged into the phpMyAdmin on the cPanel and everything seems to be in order with the database I have very little experience with database issues and MySQL, so I am a little flummoxed. A: Same problem. AN Hosting is blocking you. They are blocking any attempt to login on some of their shared servers. I changed wp-login.php page to a new address, and corrected all references in the WordPress folder. Now everything works fine. However, it will only work until the next update. AN Hosting says they are doing this only temporarily because they've been facing some type of attack on WordPress logons. If you ask me this is very lame. They need to resolve this issue. Call them! I will also call them again and complain.
{ "pile_set_name": "StackExchange" }
Q: What is a word or term for extreme questioning? Could someone tell me please the word for when someone reports a crime, but under extreme questioning they change their story as they are made to doubt the other persons intentions and relents and changes their story to what the interrogator wants to hear? There is a particular word or paraphrase which describes the coercive questioning that leads a victim to change their story. I saw it on a crime programme a while back – but I can't remember the phrase used. The show I saw was based on a young lady who was raped whilst at a college party in the USA – she went to the police and they basically said, well were you dragged into the room – NO. Did you go into the room of your own free will – YES. The coercive questioning actually made the girl doubt that she had actually had unconsenting sex in the first place – so she was charged with lying under oath and sent to prison. A: browbeat intimidate (someone), typically into doing something, with stern or abusive words. Google top hit used a witness under cross-examination as the example: a witness is being browbeaten under cross-examination Alternative gaslight to cause (a person) to doubt his or her sanity through the use of psychological manipulation Usually it involves more than just talking, but talking quickly and sternly, and forcing yes-or-no answers is a form of psychological manipulation; and leading a witness to question their assertions is a doubt to sanity, so it fits.
{ "pile_set_name": "StackExchange" }
Q: STL map composite #include <iostream> #include <algorithm> #include <climits> #include <map> #include <unordered_map> using namespace std; int main() { std::map<int, std::unordered_map<std::pair<int, int>, int>> region; region[0].insert(make_pair(make_pair(1, 1), 1)); return 0; } I am writing the above code and it don't work as expected, How can I fixed it? The error is " error C2064: term does not evaluate to a function taking 1 arguments" A: There is no specialization of std::hash for std::pair, so it can't be used as a key for std::unordered_map unless you provide a custom hash function.
{ "pile_set_name": "StackExchange" }
Q: How to print one word at a time on one line? I want to write code which allows me to print a word out and then it disappears and the next word prints. For example, if I have "Hello World!," the program should print "Hello" then the word disappears and then "World!" prints and then disappears. I should be able to change the speed of the printing words as well. Currently I was able to figure out how to print characters at a certain speed, but how do I print words one by one? import time import sys def print_char(s): for c in s: sys.stdout.write( '%s' % c ) sys.stdout.flush() time.sleep(0.1) print_char("hello world") A: Try this: #!/usr/bin/env python3 import sys import time data = "this is a sentence with some words".split() max_len=max([len(w) for w in data]) pad = " "*max_len for w in data: sys.stdout.write('%s\r' % pad) sys.stdout.write("%s\r" % w) sys.stdout.flush() time.sleep(0.4) print Example, just for the fun of it
{ "pile_set_name": "StackExchange" }
Q: Change Data Type from String to Long in Realm Android using RealmMigration final RealmObjectSchema customerSchema = schema.get("Customer"); customerSchema.removeField("creditPeriod") .addField("creditPeriod", Long.class); Above is the code i used for realm migration. I have deleted the already existing field which was previously string and then added the same field changing its data type in migration code and also in Pojo.class A: Below I just mentioned a example for migrating the field type from String to int using the example mentioned in the comment by @christian-melchior public class DataMigration implements RealmMigration { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { RealmSchema schema = realm.getSchema(); ...... // Modify your check according to your version update. if(oldVersion == 1) { // Below I am going to change the type of field 'id' from 'String' to 'int' // Get Schema of a Particular Class. Change --Testing-- with the respected pojo class name RealmObjectSchema schema = schema.get("Testing"); // Add a new temporary field with the new type which you want to migrate. 'id_tmp' is a temporary integer field. schema.addField("id_tmp", int.class); // Set the previous value to the new temporary field schema.transform(new RealmObjectSchema.Function() { @Override public void apply(DynamicRealmObject obj) { // Implement the functionality to change the type. Below I just transformed a string type to int type by casting the value. Implement your methodology below. String id = obj.getString("id"); obj.setInt("id_tmp", Integer.valueOf(id)); } }); // Remove the existing field schema.removeField("id"); // Rename the temporary field which hold the transformed value to the field name which you insisted to migrate. schema.renameField("id_tmp", "id"); oldVersion++; } ...... } } Don't forgot to update the schema version and refer the above migration class instance in the RealmConfiguration instance of realm.
{ "pile_set_name": "StackExchange" }
Q: List of default modules that come along with python 2.x installation I have a project in my mind, for which i am planning to use python for implementation. Before I start, i am looking for a comprehensive list of all modules which come with a standard python2.x (python2.7) installation so that I can figure out what all can be done without installing a single dependency and later add dependencies accordingly according to the needs. Is there any online list available or any other way to find this list. A: The Python 2.7 library reference has a list, and with documentation of all of them.
{ "pile_set_name": "StackExchange" }
Q: method must be compatible with interface method I have an interface that defines a method charge(), the first parameter is required and the second one is optional, and my layout looks something like this: interface Process{ public function charge($customerProfileId, $paymentProfileId = null); // Other items } abstract class CardProcessor implements Process{ // Some methods & properties are here } class Authorize extends CardProcessor{ public function charge($customerProfileId, $paymentProfileId){ // Process the card on profile } } When I load the file (even when I am not executing charge()) I get the following error: PHP Fatal error: Declaration of src\processors\CardProcessors\Authorize::charge() must be compatible with src\interfaces\Process::charge($customerProfileId, $paymentProfileId = NULL) in /home/processor/src/processors/CardProcessors/Authorize.php on line 19" What is the reason for this? It looks right to me... A: interface Process { public function charge($customerProfileId, $paymentProfileId); // Other items } abstract class CardProcessor implements Process { // Some methods & properties are here public abstract function charge($customerProfileId, $paymentProfileId); } class Authorize extends CardProcessor { public function charge($customerProfileId, $paymentProfileId = null) { // Process the card on profile } } Added method signature to abstract class CardProcessor as suggested by @Dev Mode Took implementation out of interface ( var = null ) and put it in the concrete class.
{ "pile_set_name": "StackExchange" }
Q: nokogiri gem installation error I know there are a lot of questions about this gem but no answer has worked for me. When I run in SSH gem install nokogiri I get this error: Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0... OK Running patch with /home/user58952277/.gem/ruby/1.9.3/gems/nokogiri-1.6.2.1/ports/patches/libxml2/0001-Fix-parser-local-buffers-size-problems.patch... Running 'patch' for libxml2 2.8.0... ERROR, review 'tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0/patch.log' to see what happened. *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. My host told me that all libs are installed. Here are the full logs after executing the install nokogiri command: Building native extensions. This could take a while... Building nokogiri using packaged libraries. Building libxml2-2.8.0 for nokogiri with the following patches applied: - 0001-Fix-parser-local-buffers-size-problems.patch - 0002-Fix-entities-local-buffers-size-problems.patch - 0003-Fix-an-error-in-previous-commit.patch - 0004-Fix-potential-out-of-bound-access.patch - 0005-Detect-excessive-entities-expansion-upon-replacement.patch - 0006-Do-not-fetch-external-parsed-entities.patch - 0007-Enforce-XML_PARSER_EOF-state-handling-through-the-pa.patch - 0008-Improve-handling-of-xmlStopParser.patch - 0009-Fix-a-couple-of-return-without-value.patch - 0010-Keep-non-significant-blanks-node-in-HTML-parser.patch - 0011-Do-not-fetch-external-parameter-entities.patch ************************************************************************ IMPORTANT! Nokogiri builds and uses a packaged version of libxml2. If this is a concern for you and you want to use the system library instead, abort this installation process and reinstall nokogiri as follows: gem install nokogiri -- --use-system-libraries If you are using Bundler, tell it to use the option: bundle config build.nokogiri --use-system-libraries bundle install However, note that nokogiri does not necessarily support all versions of libxml2. For example, libxml2-2.9.0 and higher are currently known to be broken and thus unsupported by nokogiri, due to compatibility problems and XPath optimization bugs. ************************************************************************ ERROR: Error installing nokogiri: ERROR: Failed to build gem native extension. /opt/rubies/ruby-1.9.3/bin/ruby extconf.rb Building nokogiri using packaged libraries. checking for iconv.h... yes checking for iconv_open() in iconv.h... yes Building libxml2-2.8.0 for nokogiri with the following patches applied: - 0001-Fix-parser-local-buffers-size-problems.patch - 0002-Fix-entities-local-buffers-size-problems.patch - 0003-Fix-an-error-in-previous-commit.patch - 0004-Fix-potential-out-of-bound-access.patch - 0005-Detect-excessive-entities-expansion-upon-replacement.patch - 0006-Do-not-fetch-external-parsed-entities.patch - 0007-Enforce-XML_PARSER_EOF-state-handling-through-the-pa.patch - 0008-Improve-handling-of-xmlStopParser.patch - 0009-Fix-a-couple-of-return-without-value.patch - 0010-Keep-non-significant-blanks-node-in-HTML-parser.patch - 0011-Do-not-fetch-external-parameter-entities.patch ************************************************************************ IMPORTANT! Nokogiri builds and uses a packaged version of libxml2. If this is a concern for you and you want to use the system library instead, abort this installation process and reinstall nokogiri as follows: gem install nokogiri -- --use-system-libraries If you are using Bundler, tell it to use the option: bundle config build.nokogiri --use-system-libraries bundle install However, note that nokogiri does not necessarily support all versions of libxml2. For example, libxml2-2.9.0 and higher are currently known to be broken and thus unsupported by nokogiri, due to compatibility problems and XPath optimization bugs. ************************************************************************ Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0... OK Running patch with /home/user58952277/.gem/ruby/1.9.3/gems/nokogiri-1.6.2.1/ports/patches/libxml2/0001-Fix-parser-local-buffers-size-problems.patch... Running 'patch' for libxml2 2.8.0... ERROR, review 'tmp/x86_64-unknown-linux-gnu/ports/libxml2/2.8.0/patch.log' to see what happened. *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/opt/rubies/ruby-1.9.3/bin/ruby --help --clean --use-system-libraries --enable-static --disable-static --with-zlib-dir --without-zlib-dir --with-zlib-include --without-zlib-include=${zlib-dir}/include --with-zlib-lib --without-zlib-lib=${zlib-dir}/lib --enable-cross-build --disable-cross-build /home/user58952277/.gem/ruby/1.9.3/gems/mini_portile-0.6.0/lib/mini_portile.rb:279:in `block in execute': Failed to complete patch task (RuntimeError) from /home/user58952277/.gem/ruby/1.9.3/gems/mini_portile-0.6.0/lib/mini_portile.rb:271:in `chdir' from /home/user58952277/.gem/ruby/1.9.3/gems/mini_portile-0.6.0/lib/mini_portile.rb:271:in `execute' from extconf.rb:282:in `block in patch' from extconf.rb:279:in `each' from extconf.rb:279:in `patch' from /home/user58952277/.gem/ruby/1.9.3/gems/mini_portile-0.6.0/lib/mini_portile.rb:108:in `cook' from extconf.rb:253:in `block in process_recipe' from extconf.rb:154:in `tap' from extconf.rb:154:in `process_recipe' from extconf.rb:419:in `<main>' A: 2020 April 6th Update: macOS Catalina 10.15 gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/libxml2/ macOS Mojave 10.14 gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/libxml2/ macOS High Sierra 10.13 gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/libxml2/ macOS Sierra 10.12: gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/libxml2/ OS X El Capitan 10.11 gem install nokogiri -- --use-system-libraries=true --with-xml2-include=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/ Consider to add sudo if you don't have permission. For some reason Apple’s Yosemite version of OSX does not have a system accessible installation of libxml2. Nokogiri requires this in order to compile and luckily Xcode has a version of libxml2 bundled with it — we just need to specify it when installing the gem. It’s important to get Nokogiri installed correctly because as of right now Rails 4.2.1.rc4 automatically attempts to install it and you will feel pain. Checkout this post for more info. A: Finally, the problem was caused by nokogiri itself by shipping it's own libxml2 that's incompatible with some systems. So to install nokogiri I had to tell it that it should use the system libraries. I installed it manually by: gem install nokogiri -v 1.6.2.1 -- --use-system-libraries And it worked well. Other answers didn't solve it. A: I ran into this same problem, because of an unlisted build dependency. When I found the tmp directory in question: find ~/.rbenv/ -name patch.log It said: sh: patch: command not found Fixed that with a simple: sudo yum install -y patch
{ "pile_set_name": "StackExchange" }
Q: Programmatically change datelimit in JQUERY calendar control I seem to be having a problem setting the dateLimit of the JQuery calendar control, programatically. When the page initially load, I setup the calendar control like so: $('#dashboard-report-range').daterangepicker({ opens: (App.isRTL() ? 'right' : 'left'), startDate: moment($('#hidLatestData_Date').val()).add('days', -6), endDate: moment($('#hidLatestData_Date').val()),//.add('days', 1), minDate: '01/01/2012', maxDate: moment($('#hidLatestData_Date').val()),//.add('days', 2), dateLimit: { days: 6 }, showDropdowns: false, showWeekNumbers: true, timePicker: false, timePickerIncrement: 1, timePicker12Hour: true, ranges: { 'Today': [moment(), moment().add('days', 0)], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1).add('days', 0)], 'Last 7 Days': [moment().subtract('days', 6), moment()]//, //'Last 30 Days': [moment().subtract('days', 29), moment()], //'This Month': [moment().startOf('month'), moment().endOf('month')], //'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, buttonClasses: ['btn'], applyClass: 'blue', cancelClass: 'default', format: 'DD/MM/YYYY', separator: ' to ', locale: { applyLabel: 'Apply', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom Range', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 } } On the page, I have a drop down list. If a specific selection is made, I want to change the dateLimit value to 1, rather than 6. I have tried a bunch of different options, but nothing seems to be working for me. Any help would be greatly appreciated. I am actually having to change the start time too, but the code for (below) works 100% correctly. $("#dashboard-report-range").datepicker('option', { startDate: new Date(hidEndDate)}); These are the options I have tried, plus others I cannot even remember anymore: $("#dashboard-report-range").datepicker('option', { dateLimit: "days:1"}); $("#dashboard-report-range").datepicker('option', { dateLimit: { "days":"1"}}); $("#dashboard-report-range").datepicker('option', dateLimit: { "days":"1"}); $("#dashboard-report-range").datepicker('option', dateLimit: "days:1"); $("#dashboard-report-range").datepicker('option', dateLimit, "days:1"); $("#dashboard-report-range").datepicker('option', "dateLimit", "days:1" ); A: You can try following: $("#dashboard-report-range").datepicker('option', "dateLimit.days", "1" ); Update 1: You can access datarangepicker data in following manner: var drp = $('#dashboard-report-range').data('daterangepicker'); drp.dateLimit.days = 1; Update 2: You can also update properties in following manner: drp.ranges['Today'] = [moment(), moment().add('days', 1)] Here is updated jsFiddle: http://jsfiddle.net/pvskz78d/3/
{ "pile_set_name": "StackExchange" }
Q: ASP.NET MVC export html table to excel not working I have this method here: [Authorize] [HttpPost] [ValidateInput(false)] public void ExportCostMatrixExcel(string GridHtmlExcel, string GridCommunityExcel) { Response.ClearContent(); Response.ClearHeaders(); Response.BufferOutput = true; Response.ContentType = "application/excel"; Response.AddHeader("Content-Disposition", "attachment; filename=Reliquat.xlsx"); Response.Write(GridHtmlExcel); Response.Flush(); Response.Close(); Response.End(); } This takes me html table and converts it over to an Excel spreadsheet, when I try to open the file, I get this error message: Excel cannot open the file 'Reliquat.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file. Why is this happening, you can see GridHtmlExcel here on the link below, its an HTML table with colspans, is the colspans messing it up? https://jsfiddle.net/2nyjhpaz/3/ A: In essence it looks like you're merely dumping the contents into a file and just renaming it to an XLSX. However, that extension follows a specific XML-based schema, and that's why it doesn't play well. You have a few options: Find a library that can do this for you - initial searches list a few but they're often fickle little beings. Use something like HTML Agility Pack to parse the HTML into a usable format and write it into an excel file. You might have to create an excel file manually, possibly using the Office Interop stuff. If the excel format itself isn't that much of an issue, you could choose to write a CSV file instead (and can be opened by excel), using CSV Helper - but you'd still have to parse the HTML.
{ "pile_set_name": "StackExchange" }
Q: Change "Implement interface" template in Visual Studio I'm constantly using the "Implement interface" shortcut in Visual Studio 2008. My "problem" is that i want Visual Studio to use the String-alias instead of string in every instance. Since i'm forced to use String instead of string this would save me a great ammount of time. For example, i want the following: public Catalogue(String url) { } instead of public Catalogue(string url) { } Is this possible? Where do I find these templates? A: You cannot change the templates used during refactorings. Templates that you can change are available in %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE. Specifically, most of the CSharp ones for blank files and such are in %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp Maybe the person forcing you to use "String" would change their ways if they realized how much time this wasted. I personally don't understand this... The IDE uses "string", and not "String" in all generated code - so by forcing a non-standard "standard" your team is inviting inconsistency. People can debate about which is better until they're blue in the face - but as you point out, using "String" is a pain in the ass.
{ "pile_set_name": "StackExchange" }
Q: Good websites/books for geometry exercises? I'm looking for exercises similar to those seen on putnam exams or olympiad exams, such as finding the area of polygons inscribed other polygons, finding certain angles, etc. A: I like Go-geometry, which covers the basics up to IMO level. I'm not too certain what you would consider Putnam Geometry, in part because the undergraduate competitions don't focus heavily on Euclidean Geometry techniques, but have more to do with calculus ideas.
{ "pile_set_name": "StackExchange" }
Q: Printing a 2D-array into "squares" I'm trying to learn how to work with 2D-array and I can't seem to understand how to print them correctly. I want to print them in a "square" like 5x5 but all I get is one line. I've tried both WriteLine and Write and changed some of the variables in the loops but I get either an error or not the result I want to have. The code is supposed to print out a 5x5 with a random sequence of 15 numbers in each column. I get the correct numbers out of it, it's only the layout that is wrong. static void Main(string[] args) { Random rnd = new Random(); int[,] bricka = new int[5, 5]; int num = 0; int num1 = 1; for (int i = 0; i < bricka.GetLength(1); i++) { num += 16; for (int j = 0; j < bricka.GetLength(0); j++) { bricka[j, i] = rnd.Next(num1, num); } num1 += 16; } for (int i = 0; i < bricka.GetLength(0); i++) { for (int j = 0; j < bricka.GetLength(1); j++) { Console.Write(bricka[i, j]+ " " ); } } Console.ReadKey(); } This is my print, I would like to have the the 12 under the 8 and 14 under the 12 and so on. http://i.imgur.com/tfyRxf1.png A: You need to call WriteLine() after each line, so that each line is printed on a separate line: for (int i = 0; i < bricka.GetLength(0); i++) { for (int j = 0; j < bricka.GetLength(1); j++) { Console.Write(bricka[i, j]+ " " ); } Console.WriteLine(); } That would be one way of doing it, anyway.
{ "pile_set_name": "StackExchange" }
Q: $\lim\limits_{x\to\infty}\frac{(x+7)^2\sqrt{x+2}}{7x^2\sqrt{x}-2x\sqrt{x}}$ Determine $$\lim\limits_{x\to\infty}\frac{(x+7)^2\sqrt{x+2}}{7x^2\sqrt{x}-2x\sqrt{x}}.$$ Multiplying and dividing by $\sqrt{x}$ yields $$\frac{(x+7)^2\sqrt{x^2+2x}}{7x^3-2x^2}$$ where I would like to approximate the squareroot for sufficiently large $x$ with $$\frac{(x+7)^2\sqrt{x^2+2x+1}}{7x^3-2x^2}=\frac{(x+7)^2(x+1)}{7x^3-2x^2}=\frac{x^3(49/x^3+63/x^2+15/x+1)}{x^3(7-2/x)}\longrightarrow 1/7.$$ Can anyone confirm that my approximation is valid and does anyone know how to solve this in a more "usual" way like I did? A: Hint: A standard thing to do is to divide top and bottom by $x^2\sqrt{x}$. The new top is $$\left(1+\frac{7}{x}\right)^2 \sqrt{1+\frac{2}{x}},$$ and its behaviour for large $x$ is clear. The new bottom is $7$ plus something tiny. Remark: In the solution given in the OP, $\sqrt{x^2+2x}$ was replaced by $x+1$. True, this is fine, the change is indeed small. But if we are doing things formally, the replacement leaves a gap in the argument.
{ "pile_set_name": "StackExchange" }
Q: Initialize a hash in the inject method to prevent a value being nil I am trying to compile all the values for a given hash key in a list of hashes. I have the following which works. [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}].inject({}) do |hash, item| item.each do |key, value| hash[key] = [] if hash[key].nil? hash[key] << value end hash end Here is the result which is great: {:a=>[1, 4, 7], :b=>[2, 5, 8], :c=>[3, 6, 9]} My question: is there a more elegant way to initializing the hash so I don't need to check for the nil case in the following line? hash[key] = [] if hash[key].nil? I have tried Hash.new(0) as the default for the inject method but it doesn't work. I'm sure there is a more elegant way to do this. Thanks. A: Yes, you can do Hash.new { |hash, key| hash[key] = [] } to make values empty arrays by default. A: Solutions You can use each_with_object : array = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}] empty_hash = Hash.new{ |h, k| h[k] = [] } hash = array.each_with_object(empty_hash) do |small_hash, hash| small_hash.each do |k, v| hash[k] << v end end p hash #=> {:a=>[1, 4, 7], :b=>[2, 5, 8], :c=>[3, 6, 9]} A shorter, but more unusual version is here : hash = array.each_with_object(Hash.new{ [] }) do |small_hash, hash| small_hash.each {|k, v| hash[k] <<= v } end p hash #=> {:a=>[1, 4, 7], :b=>[2, 5, 8], :c=>[3, 6, 9]} Both return {:a=>[1], :b=>[2]} for [{a: 1}, {b: 2}], as the OP specified. <<= ? hash[k] <<= v is a weird (and probably inefficient) trick. It is equivalent to : hash[k] = (hash[k] << v) The assignment is needed because the hash default hasn't been properly initialized, and a new array is being generated for every hash lookup, without being saved as a value : h = Hash.new{ [] } p h[:a] << 1 #=> [1] p h[:a] #=> [] p h[:a] <<= 1 #=> [1] p h[:a] #=> [1]
{ "pile_set_name": "StackExchange" }
Q: Condition on degrees for existence of a tree Here is what I need to prove: Let $d_1,d_2,...,d_n$ be a sequence of natural numbers (>0). Show that $d_i$ is a degree sequence of some tree if and only if $\sum d_i = 2(n-1)$. I know that: 1. for any graph $\sum_{v \in V}\ deg(v) = 2e$; 2. for any tree $e=v-1$. From 1 and 2 it follows that for any tree $\sum_{v \in V}\ deg(v) = 2(v-1)$. If I understand it correctly, this is only a half of the proof ($\rightarrow$), isn't it? Any hints on how to prove it the other way? Edit (induction attempt): $n=1$, we have $d_1 = 2(1-1) = 0$ and $d_1$ is a degree sequence of a tree. Let's assume the theorem holds for all $k<n$. So we know that $d_1 + d_2 + ... + d_{n-1} = 2(n-2) $ and that it's a degree sequence of a tree. In order to add one vertex to this tree, so that it remains a tree we only can add a vertex of degree one (we connect it to any existing vertex with a single edge). By doing this our new sequence is $1,d_1,...,d_j+1,...,d_{n-1}$, where $j$ is the vertex to which we attached the new vertex (it's degree increments). Clearly this sums to $2(n-1)$. Is this proof correct or am I missing the point? A: Hints for the other way round: Do you know about mathematical induction? Can every $d_i$ be $\gt 1$? A: From your fact (1) and the hypothesis $\sum d_i = 2(n-1)$, you know $e = n - 1$. You need now only prove that any connected graph with $n - 1$ edges is a tree. EDIT - Since you are going down an alternate path, I have a new suggestion. Order the $d_i$ so that $d_1 \leq d_2 \leq \ldots \leq d_n$. Construct a tree with degree sequence $d_2, \ldots, d_n$. You know $\sum_{i \neq 1} d_i = 2(n - 2)$ (why?). Now try to construct your tree with degree sequence $d_1, \ldots, d_n$. You have to be careful about how you add in your vertex with degree $d_1$ so that it remains a tree, but this can be done. EDIT - The above is incorrect. The idea remains to add in a vertex of degree $1$ to a tree with a specific degree sequence related to $d_1, \ldots, d_n$. But $\sum_{i \neq 1} d_i = 2n - 3$, so we cannot claim $d_2, \ldots, d_n$ is a degree sequence of a tree by the inductive hypothesis. Of course, when we add in the vertex of degree $1$, we alter the degree of another vertex, right?
{ "pile_set_name": "StackExchange" }
Q: Find child of div with particular text I have a box, a div, and inside there are three children, displayed as three different words... --------- | Red | Green | Blue -------- Anyways, I want change the text of Red to the color red. However, I do not know how to access this particular child. I tried... $("#target :contains("Red")").children().css("color", "red"); However this changes all of them to red. I am clearly not using contains properly. A: Try css pseudo elements #target > div:nth-child(1){color:red} #target > div:nth-child(2){color:green} #target > div:nth-child(3){color:blue} DEMO jQuery solution $( "#target div:contains('Red')" ).css( "color", "red" ); You need to refer the child div which contains the specific text. DEMO Jquery
{ "pile_set_name": "StackExchange" }
Q: Как группировать массив данных в JavaScript Есть массив данных в JavaScript. Надо группировать их по свойству. Например, есть массив сотрудников: employees = [ { id: 111, name: 'Ivan', salary: 5000, date: '2020-01-01' }, { id: 222, name: 'Oleg', salary: 3000, date: '2020-01-01' }, { id: 111, name: 'Ivan', salary: 5000, date: '2020-01-01' }, { id: 333, name: 'Anya', salary: 3000, date: '2020-01-02' }, { id: 444, name: 'Arman', salary: 5000, date: '2020-01-01' } ] Теперь их надо группировать, типа: obj = { '2020-01-01' : { 111: { "salary": 5000 }, } } A: Если по двум параметрам группировать, то можно так. Если больше, то переписал бы в рекурсивное построение дерева с последующим заполнением. let employees = [{ id: 111, name: 'Ivan', salary: 5000, date: '2020-01-01' }, { id: 222, name: 'Oleg', salary: 3000, date: '2020-01-01' }, { id: 111, name: 'Ivan', salary: 5000, date: '2020-01-01' }, { id: 333, name: 'Anya', salary: 3000, date: '2020-01-02' }, { id: 444, name: 'Arman', salary: 5000, date: '2020-01-01' } ]; let groupResult = employees.reduce((obj, item) => { obj[item.date] = obj[item.date] || {}; (obj[item.date][item.id] = obj[item.date][item.id] || []).push({ id: item.id, name: item.name, date: item.date, salary: item.salary }); return obj; }, {}); console.log(groupResult);
{ "pile_set_name": "StackExchange" }
Q: Pause application in QML when app is in background Symbian I want to know of any pure QML way to find out whether the application is in the background or not and then accordingly stop or play music. In meego the alternate way to do is through the PlatformWindow Element but it does not exist in Symbian QML. Help needed please A: Finally I got it working :) and i did it though Qt way... here are the steps 1) Create a class MyEventFilter class myEventFilter : public QObject { bool eventFilter(QObject *obj, QEvent *event) { switch(event->type()) { case QEvent::WindowActivate: emit qmlvisiblechange(true); qDebug() << "Window activated"; bis_foreground=true; return true; case QEvent::WindowDeactivate: emit qmlvisiblechange(false); qDebug() << "Window deactivated"; bis_foreground=false; return true; default: return false; } } void dosomething(); private: int something; public: bool bis_foreground; Q_OBJECT public slots: Q_INVOKABLE QString checkvisibility() { if (bis_foreground==true) return "true"; else return "false"; } signals: void qmlvisiblechange(bool is_foreground); }; 2) Then in main.cpp include this file include the class and add setContext propery like this context->setContextProperty("myqmlobject", &ef); 3) in qml file call it like this: Item { id: name Connections { target:myqmlobject onQmlvisiblechange: { if(is_foreground) { //dont do anything... } else { playSound.stop() } } } } Enjoy :)
{ "pile_set_name": "StackExchange" }
Q: Psexec commands to remotely delete files in a few computers and looping of txt file Hi I am New to scripting . I have to remotely execute a PSEXEC command to delete al files in a certain drive in a few computers. I do have a TXT file with every ip address of all the computers. Is there a way to use PSEXEC to cmd command all the computers to delete the folders by executing every command for every IP in my txt file? currently i am using this line whereby i need to manually enter the ip address in the command line for eg . PsTools>PsExec.exe \ 1.1.1.1 , 1.1.1.2 cmd /c rmdir /S /Q D:\ A: FOR /F %%i IN (FileWithEveryIP.txt) DO PSEXEC \\%%i CMD /C DIR folderToDelete Use %i instead of %%i if you run it from command prompt window instead of batch file. Replace DIR with RMDIR /S /Q if it works.
{ "pile_set_name": "StackExchange" }
Q: Not working xpath in selenium The first xpath is working whereas the second not: First: "//*[@id='j_idt46:j_username']"; Second: "//*[contains(@id,'username']"; Why? A: To what could be figured out of the information provided, the way you are using contains is possibly inappropriate : As mentioned by @TuringTux - //*[contains(@id,'username')] could be the possible change if the same lined goes as it is in your code. Also a good practice to follow in //*[contains(@id,'username')] , would be to replace * by an element type in html. And lastly there could be chances when you are trying to access elements using //*[contains(@id,'username')], you may be ending up getting a list of these similar WebElements while you might be trying to access only a single at the same time.
{ "pile_set_name": "StackExchange" }
Q: Set Theoretic Definition of Complex Numbers: How to Distinguish $\mathbb{C}$ from $\mathbb{R}^2$? I have spent some time looking for a rigorous, set-theoretic definition of the complex numbers. I have read the book Elements of Set Theory by Herbert Enderton (1977) which does an excellent job of constructing numbers from sets including the natural numbers, integers, and rational numbers, but stops at the real numbers. So far, I have only found two comparable constructions of complex numbers The set of all $2 \times 2$ matrices taking real-valued components The set of all ordered pairs taking real-valued components I favor the second construction better, because I feel it has a stronger geometric interpretation because of its similarities to Euclidean vector spaces. That is, define \begin{equation*} \mathbb{C}=\{(x,y):x,y \in \mathbb{R}\}, \end{equation*} which also is exactly how the Euclidean plane, $\mathbb{R}^2$, is defined. This leads me to my question. With $\mathbb{C}$ defined exactly the same as how one defines $\mathbb{R}^2$, how does one distinguish the elements of these two sets? For example, how does one distinguish the ordinary vector $(0,1) \in \mathbb{R}^2$ from what we define to be $i$, namely the number $i=(0,1) \in \mathbb{C}$, when they are set-theoretically identical? In set theory, these two very different "numbers" -- the vector $(0,1)$ and the number $i$ -- are exactly the same set! Thanks for your thoughts! A: If you define the set $\mathbb{C}$ as $\mathbb{R}^2$, then you obviously cannot distinguish these sets. This follows from the reflexivity of the = symbol in set theory: if $a=a$ then $a$ "is" $a$. The difference is that you have a defined multiplication in $\mathbb{C}$. In other words, the difference is hidden in the structure with which you endow the set, not in the underlying sets. I appologize if this looks like a stupid or trivial answer and if I'm missing something deep. A: Consider these two ordered sets: $(\{0,1\},<)$ where $<$ is the usual order, $0<1$. $(\{0,1\},\prec)$ where $\prec$ is the discrete order, $1\nprec 0$ and $0\nprec1$. How do you distinguish between $0$ in the first and in the second? It's the same set, $\{0,1\}$! And indeed you cannot distinguish between them. If it's the same set, then it's the same set. Period. But $\Bbb C$ and $\Bbb R^2$ have additional structure, they are not just sets. They have addition, multiplication, and so on defined on them. How do you distinguish between $0$ in the first order and in the second, you don't.? How distinguish between the two ordered sets? They are different ordered sets, one is linear and the other is not. If you define $\Bbb C$ as a field whose underlying set is $\Bbb R^2$, and you can do that, then you do not distinguish $(0,1)$ from $i$. They are defined to be the same object. But you distinguish $\Bbb C$ and $\Bbb R^2$ by the fact they have different multiplication defined on them, one is a field and the other is a ring with zero divisors. Of course, you can define $\Bbb C$ as a quotient of $\Bbb R[x]$ instead, which gives a completely different underlying set.
{ "pile_set_name": "StackExchange" }
Q: Canceling an ngFormControl event firing I have a ngFormControl for a search field, which I have subscribed to as follows: this.searchTerm.valueChanges .debounceTime(400) .distinctUntilChanged() .switchMap(searchTerm => this.locationSearchService.search(searchTerm)) .subscribe(items => { doSomethingPartiallyInteresting() }) In certain circumstances I want to cancel the .valueChanges event firing. Does anyone know if this is impossible? A: Perhaps you could leverage the filter operator for this: this.searchTerm.valueChanges .debounceTime(400) .distinctUntilChanged() .filter(() => { // <------------ return !(this.address === 'don't handle this address'); }) .switchMap(searchTerm => this.locationSearchService.search(searchTerm)) .subscribe(items => { doSomethingPartiallyInteresting() })
{ "pile_set_name": "StackExchange" }
Q: How can i list the subscribed/registered consumers using spring kafka? I'm spring-kafka version 2.2.7-RELEASE to write the kafka Listeners (as consumers) and trying understand if we have any option in spring-kafka to directly list all the subscribed/registered consumers with the details like the consumer group, consumer lag offset etc? A: The current 2.2.x version is 2.2.10. If you are using Spring Boot: @Bean public ApplicationRunner runner(KafkaAdmin admin, ConsumerFactory<String, String> cf) { return args -> { Consumer<String, String> consumer = cf.createConsumer("group", "clientId", ""); try (AdminClient client = AdminClient.create(admin.getConfig())) { Collection<ConsumerGroupListing> groups = client.listConsumerGroups() .all() .get(10, TimeUnit.SECONDS); groups.forEach(group -> { Map<TopicPartition, OffsetAndMetadata> map = null; try { map = client.listConsumerGroupOffsets(group.groupId()) .partitionsToOffsetAndMetadata() .get(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } Map<TopicPartition, Long> endOffsets = consumer.endOffsets(map.keySet()); map.forEach((tp, off) -> { System.out.println("group: " + group + " tp: " + tp + " current offset: " + off.offset() + " end offset: " + endOffsets.get(tp)); }); }); } finally { consumer.close(); } }; } If you are not using Spring Boot, use AdminClient.create() to create an admin, create a consumer, and do the same.
{ "pile_set_name": "StackExchange" }
Q: Back arrow is not converting to hamburger icon I am using Android Studio 3.1.4 with Kotlin. I created a new project choosing NavigationDrawer template. I added two fragments MainFragment and SecondFragment to Mainactivity. When activity is started, MainFragment is shown, then I called SecondFragment by clicking Camera item from NavigationDrawer. When I pressed back button, It goes to MainFragment but ActionBar still showing Back Arrow instead of hamburger. Previously I worked on a project with android.support.v4.widget.DrawerLayout and all things were working fine. Below is my MainActiviy Code: import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.app_bar_main.* class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) showMainFragment() val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() nav_view.setNavigationItemSelectedListener(this) } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val itemId = item.itemId if (itemId == android.R.id.home) { onBackPressed() } when (item.itemId) { R.id.action_settings -> return true else -> return super.onOptionsItemSelected(item) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. when (item.itemId) { R.id.nav_camera -> { // Handle the camera action val fragment = SecondFragment() val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.fragment_container, fragment, "OK") fragmentTransaction.addToBackStack(null) fragmentTransaction.commit() } R.id.nav_gallery -> { } R.id.nav_slideshow -> { } R.id.nav_manage -> { } R.id.nav_share -> { } R.id.nav_send -> { } } drawer_layout.closeDrawer(GravityCompat.START) return true } private fun showMainFragment(){ val fragment = MainFragment() val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.fragment_container, fragment) fragmentTransaction.commit() } } MainFragment Code: import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.support.v7.app.AppCompatActivity import kotlinx.android.synthetic.main.app_bar_main.* // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * */ class MainFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment var view : View = inflater.inflate(R.layout.fragment_main, container, false) return view } SecondFragment Code: import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" class SecondFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view : View = inflater!!.inflate(R.layout.fragment_surah, container, false) (activity as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true) val toolbar = activity!!.findViewById<android.support.v7.widget.Toolbar>(R.id.toolbar) (activity as AppCompatActivity).setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_material) return view } } A: hamburger is not showing because of this - val toolbar = activity!!.findViewById(R.id.toolbar) (activity as AppCompatActivity).setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_material) To handle back button and hamburger both, add following code in your activity .- supportFragmentManager.addOnBackStackChangedListener(android.support.v4.app.FragmentManager.OnBackStackChangedListener { if (supportFragmentManager.getBackStackEntryCount() > 0) { supportActionBar?.setDisplayHomeAsUpEnabled(true); // show back button toolbar?.setNavigationOnClickListener(View.OnClickListener { onBackPressed() }) } else { //show hamburger supportActionBar?.setDisplayHomeAsUpEnabled(false); toogle.syncState(); toolbar?.setNavigationOnClickListener(View.OnClickListener { drawer.openDrawer(GravityCompat.START); }) setTitle(resources.getString(R.string.app_name)) } }) And Remove following code from your Second Fragment- (activity as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true) val toolbar = activity!!.findViewById<android.support.v7.widget.Toolbar>(R.id.toolbar) (activity as AppCompatActivity).setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_material)
{ "pile_set_name": "StackExchange" }
Q: Converting to a decimal without rounding I have a float number, say 1.2999, that when put into a Convert.ToDecimal returns 1.3. The reason I want to convert the number to a decimal is for precision when adding and subtracting, not for rounding up. I know for sure that the decimal type can hold that number, since it can hold numbers bigger than a float can. Why is it rounding the number up? Is there anyway to stop it from rounding? Edit: I don't know why mine is rounding and yours is not, here is my exact code: decNum += Convert.ToDecimal((9 * 0.03F) + 0); I am really confused now. When I go into the debugger and see the output of the (9 * 0.03F) + 0 part, it shows 0.269999981 as float, but then it converts it into 0.27 decimal. I know however that 3% of 9 is 0.27. So does that mean that the original calculation is incorrect, and the convert is simply fixing it? Damn I hate numbers so much lol! A: What you say is happening doesn't appear to happen. This program: using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { float f = 1.2999f; Console.WriteLine(f); Decimal d = Convert.ToDecimal(f); Console.WriteLine(d); } } } Prints: 1.2999 1.2999 I think you might be having problems when you convert the value to a string. Alternatively, as ByteBlast notes below, perhaps you gave us the wrong test data. Using float f = 1.2999999999f; does print 1.3 The reason for that is the float value is not precise enough to represent 1.299999999f exactly. That particular value ends up being rounded to 1.3 - but note that it is the float value that is being rounded before it is converted to the decimal. If you use a double instead of a float, this doesn't happen unless you go to even more digits of precision (when you reach 1.299999999999999) [EDIT] Based on your revised question, I think it's just expected rounding errors, so definitely read the following: See "What Every Computer Scientist Should Know About Floating-Point Arithmetic" for details. Also see this link (recommended by Tim Schmelter in comments below). Another thing to be aware of is that the debugger might display numbers to a different level of precision than the default double.ToString() (or equivalent) so that can lead to you seeing slightly different numbers. Aside: You might have some luck with the "round trip" format specifier: Console.WriteLine(1.299999999999999.ToString()); Prints 1.3 But: Console.WriteLine(1.299999999999999.ToString("r")); Prints 1.2999999999999989 (Note that sneaky little 8 at the penultimate digit!) For ultimate precision you can use the Decimal type, as you are already doing. That's optimised for base-10 numbers and provides a great many more digits of precision. However, be aware that it's hundreds of times slower than float or double and that it can also suffer from rounding errors, albeit much less.
{ "pile_set_name": "StackExchange" }
Q: Estilos API POI Tengo : CellStyle style = sheet.getWorkbook().createCellStyle(); HSSFCell cell = row.createCell((short)number); cell.setCellValue(text) cell.setCellStyle(style); Me gustaria que el fondo sea de color gris por ejemplo A: Lo que tienes que hacer es: CellStyle style = sheet.getWorkbook().createCellStyle(); //cambiar el fondo style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); style.setFillPattern(CellStyle.SOLID_FOREGROUND); HSSFCell cell = row.createCell((short)number); cell.setCellValue(text) cell.setCellStyle(style);
{ "pile_set_name": "StackExchange" }
Q: Can I create a CollectionProperty of brushes? I want to create a collection property with certain sculpt brushes. Can this be done? I tried: WindowManager.coll = CollectionProperty(type=bpy.types.Brush) But I'm getting errors: TypeError: CollectionProperty(...) expected an RNA type derived from ID Exception in module register(): '/home/antoni4040/Documents/blender-2.79-linux-glibc219-i686/2.79/scripts/addons/Advanced_Brushes/__init__.py' Traceback (most recent call last): File "/home/antoni4040/Documents/blender-2.79-linux-glibc219-i686/2.79/scripts/modules/addon_utils.py", line 350, in enable mod.register() File "/home/antoni4040/Documents/blender-2.79-linux-glibc219-i686/2.79/scripts/addons/Advanced_Brushes/__init__.py", line 23, in register registerBrushSelectionPanel() File "/home/antoni4040/Documents/blender-2.79-linux-glibc219-i686/2.79/scripts/addons/Advanced_Brushes/Brush_Menu/Brush_Menu.py", line 120, in registerBrushSelectionPanel WindowManager.coll = CollectionProperty(type=bpy.types.Brush) ValueError: bpy_struct "WindowManager" registration error: coll could not register Any ideas? Thanks A: Make a PropertyGroup with a brush type member. Can use a pointer property to point to an ID type, in this case a brush. brush = bpy.props.PointerProperty(type=bpy.types.Brush) import bpy # Assign a collection class SceneSettingItem(bpy.types.PropertyGroup): name = bpy.props.StringProperty(name="Test Prop", default="Unknown") brush = bpy.props.PointerProperty(type=bpy.types.Brush) bpy.utils.register_class(SceneSettingItem) bpy.types.Scene.brushes = \ bpy.props.CollectionProperty(type=SceneSettingItem) print("Adding All Brushes") for brush in bpy.data.brushes: my_item = bpy.context.scene.brushes.add() my_item.name = brush.name my_item.brush = brush Python console check after running script above. >>> C.scene.brushes['Twist'].brush bpy.data.brushes['Twist']
{ "pile_set_name": "StackExchange" }
Q: C# WPF: webbrowser modal dialog close from win32 app I am curious as to if this is even possible, but basically what I need is when opening a System.Windows.Forms.WebBrowser Modal Dialog from a WPF application I need to catch a value passed back from the page to WPF and keep a window up or close it based on the value that I return. Is this even possible or am I going to have to about in a different way? Thanks, Andrew A: surely is possible, just create the dialog, register an event handler for a custom event you have created in your second form and show it as modal, then inside your form you do what you need to do and when something happens you fire the event the main form has registered to, in the custom EventArgs class used in your event you can pass the value main form needs to get. from the main form you check the value and you do nothing or close the popup....
{ "pile_set_name": "StackExchange" }
Q: Single Website Directory / Multiple IIS Websites (Multiple web.config files) I have inherited some very old asp code. I need to resolve a design problem because of it, described below. I have 3 customers... Foo, Bar and Baz. I have a folder called... c:\WebSites\Site.v15.07 I have 3 websites in IIS defined as... Website.Foo Website.Bar Website.Baz They all point to the 15.07 directory. There are 3 other folders called... c:\WebConfigurations\Foo c:\WebConfigurations\Bar c:\WebConfigurations\Baz ... which all contain client specific files for each of the 3 sites. Uploaded images etc. Each of the 3 customers has their own database that the website sits on. I need to set (ideally, using a web.config) the connection string for each of the 3 sites. If I put this in the web.config in the root of the website directory, they will all share the same setting. Is there a way of adding the settings/web.config in IIS at the "website" level so that each site can be set differently? A: Put only the common configuration in Web.config in the application folder. When the application is first loading, programmatically load the client-specific config file from the respective folder and programmatically merge the info into the configuration info in memory. Example of programmatically editing configuration info in memory: Change a web.config programmatically with C# (.NET) var configuration = WebConfigurationManager.OpenWebConfiguration("~"); var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings"); section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=..."; In your case you'll want to make two calls to WebConfigurationManager.OpenWebConfiguration, one to open the application config and once to load the client configuration. Then copy data from client config to the in-memory application config (don't call Save() per the referenced question--that's a different use case).
{ "pile_set_name": "StackExchange" }
Q: How to read only date from sql server 2008? DECLARE @temp TABLE ( iLeadID INT , Title VARCHAR(MAX) , AlertDate DATETIME ) DECLARE @iLeadID INT DECLARE @getiLeadID CURSOR SET @getiLeadID = CURSOR FOR SELECT iLeadID FROM LeadsContracts OPEN @getiLeadID FETCH NEXT FROM @getiLeadID INTO @iLeadID WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO @temp SELECT @iLeadID , 'Disclosure' , CONVERT(VARCHAR, dtDisclosure, 101) 'Date' FROM LeadsContracts WHERE iLeadID = @iLeadID AND dtDisclosure IS NOT NULL INSERT INTO @temp SELECT @iLeadID , 'Due Diligence' , CONVERT(VARCHAR, dtDueDiligence, 101) 'Date' FROM LeadsContracts WHERE iLeadID = @iLeadID AND dtDueDiligence IS NOT NULL INSERT INTO @temp SELECT @iLeadID , 'Finance Appraisals' , CONVERT(VARCHAR, dtFinanceAppraisals, 101) 'Date' FROM LeadsContracts WHERE iLeadID = @iLeadID AND dtFinanceAppraisals IS NOT NULL INSERT INTO @temp SELECT @iLeadID , sFreeTextCustom1 , CONVERT(VARCHAR, dtFreeTextDate1, 101) 'Date' FROM LeadsContracts WHERE iLeadID = @iLeadID AND dtFreeTextDate1 IS NOT NULL INSERT INTO @temp SELECT @iLeadID , sFreeTextCustom2 , CONVERT(VARCHAR, dtFreeTextDate2, 101) 'Date' FROM LeadsContracts WHERE iLeadID = @iLeadID AND dtFreeTextDate2 IS NOT NULL FETCH NEXT FROM @getiLeadID INTO @iLeadID END CLOSE @getiLeadID DEALLOCATE @getiLeadID SELECT * , ( CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sEmail FROM UserAccount objUA WHERE EXISTS ( SELECT iUserID FROM GroupAgent WHERE iUserID = objUA.iUserID AND iGroupID = t1.GroupID AND btAdminFlg = ( (1) ) ) ) ELSE '' END ) AS AdminEmail FROM ( SELECT * , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sFirstName + ' ' + sLastName FROM Lead WHERE iLeadID = objTemp.iLeadID ) ELSE '' END AS LeadName , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sEmail FROM Lead WHERE iLeadID = objTemp.iLeadID ) ELSE '' END AS LeadEmail , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 iUserID FROM AssignLeadUser WHERE iLeadID = objTemp.iLeadID ) ELSE '' END AS AgentID , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sFirstName + ' ' + sLastName FROM UserAccount WHERE iUserID = ( SELECT iUserID FROM AssignLeadUser WHERE iLeadID = objTemp.iLeadID ) ) ELSE '' END AS AgentName , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sEmail FROM UserAccount WHERE iUserID = ( SELECT iUserID FROM AssignLeadUser WHERE iLeadID = objTemp.iLeadID ) ) ELSE '' END AS AgentEmail , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 iGroupID FROM AssignLeadUser WHERE iLeadID = objTemp.iLeadID ) ELSE '' END AS GroupID , CASE WHEN 1 = 1 THEN ( SELECT TOP 1 sName FROM [Group] WHERE iGroupID = ( SELECT iGroupID FROM AssignLeadUser WHERE iLeadID = objTemp.iLeadID ) ) ELSE '' END AS GroupName FROM @temp objTemp ) AS t1 ORDER BY AlertDate ASC it gives me an output of 2013-04-04 00:00:00.000 in the AlertDate column I want to get only the date (no time) like this: 2013-04-04" in the AlterDate column. Could anybody please help me to advice some query or update my code? Thanks in advance A: You can use the date type instead of datetime declare @temp Table ( iLeadID int, Title varchar(Max), AlertDate date )
{ "pile_set_name": "StackExchange" }
Q: For loop to repeat 20 times in sql statement I am using below but getting error, what is wrong in this code : declare begin for i in 1..20 loop execute immediate 'update table IMP_BACKUP set name='XYZ' where status='INVALID''; end loop; end; / A: Declare variable i as declare i number(2); begin for i in 1..20 loop execute immediate 'update table IMP_BACKUP set name=''XYZ'' where status=''INVALID'''; end loop; end; /
{ "pile_set_name": "StackExchange" }
Q: Java generics - ensure static method is implemented I'm using generics like this: public class MyList<T>. Is there any way to ensure that the class represented by T implements a certain static method? A: No, even without generics there is never a way to ensure a class implements a static method. You can, however, create a generic static method. public static <T> List<T> makeSingletonList(T item) { ArrayList<T> result = new ArrayList<T>(); result.add(item); return result; }
{ "pile_set_name": "StackExchange" }
Q: How to access an element in an array, within an array, within another array...in JavaScript I'm trying to call an element in an array, that is in another array, that is in yet another array. for example.... var a1 = ["1","2","3"]; var a2 = ["4","5","6"]; var a3 = ["7","8","9"]; var a4 = ["10","11","12"]; var b1 = ["a1","a2"]; var b2 = ["a3","a4"]; var c = ["b1","b2"]; var x = c[0]; console.log(x); The answer is x = b1 How can I define the var x = c[0] b1[1] a2[2] so that the answer would be 6? A: What you want are nested arrays. var a1 = ["1","2","3"]; var a2 = ["4","5","6"]; var a3 = ["7","8","9"]; var a4 = ["10","11","12"]; var b1 = [a1,a2]; var b2 = [a3,a4]; var c = [b1,b2]; var x = c[0][1][2]; console.log(x);
{ "pile_set_name": "StackExchange" }
Q: Is it possible to interject your own audio once the ios media library has taken over? I am wondering if it would be possible to insert your own audio once the ios media library has taken over in an app? Example: Playing a piece of audio after every song that says the number of songs you've listened to that day. I know that because its a framework there is only so many things they let you do. A: This should be doable. To start, you can add your class as an observer of the MPMusicPlayerControllerNowPlayingItemDidChangeNotification to be informed when the song in the iPod library changes. From there, you can tell the iPod library to pause, play your track, and then resume music playback afterwards. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someSel:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil]; [[MPMusicPlayerController iPodMusicPlayer] pause]; // play your sound [[MPMusicPlayerController iPodMusicPlayer] play];
{ "pile_set_name": "StackExchange" }
Q: Using awk to extract a column containing spaces I'm looking for a way to extract the filename column from the below output. 2016-02-03 08:22:33 610540 vendor_20160202_67536242.WAV 2016-02-03 08:19:25 530916 vendor_20160202_67536349.WAV 2016-02-03 08:17:10 2767824 vendor_20160201_67369072 - cb.mp3 2016-02-03 08:17:06 368928 vendor_20160201_67369072.mp3 One of the files has spaces in the name which is causing issues with my current commmand awk '{print $4}' How would I treat a column with spaces as a single column? A: awk to the rescue! $ awk '{for(i=4;i<NF;i++) printf "%s", $i OFS; printf "%s", $NF ORS}' file vendor_20160202_67536242.WAV vendor_20160202_67536349.WAV vendor_20160201_67369072 - cb.mp3 vendor_20160201_67369072.mp3 or alternatively, $ awk '{for(i=5;i<=NF;i++) $4=$4 OFS $i; print $4}' file if your file format is fixed perhaps using the structure is a better idea $ cut -c36- file vendor_20160202_67536242.WAV vendor_20160202_67536349.WAV vendor_20160201_67369072 - cb.mp3 vendor_20160201_67369072.mp3
{ "pile_set_name": "StackExchange" }
Q: How to align div inside page content in jQuery-Mobile? I have a div inside jQuery-Mobile page div like this: http://jsfiddle.net/UFOcode/gtXzb/1/ <div data-role="page" data-pagination="1"> <div data-role="content"> <div class="iBorder"> </div> </div> </div> I want to align class iBorder at left side and expand its size to screen frame. I don't know why always have small gap on left and right This is some trying CSS .iBorder{ height: 300px; width: auto; margin: 0; background-color: brown; top: 0; left: 0; } and this is screen shot Please help to to justify iBorder div and expand its size. Thanks! A: It seems that .ui-content is adding the extra padding, so there are two options. Override jQuery UI CSS: .ui-content { padding: 0px !important; } Change HTML markup, to avoid using .ui-content: <div data-role="page" data-pagination="1"> <div class="iBorder">...</div> </div>
{ "pile_set_name": "StackExchange" }
Q: series leds powered with a 6v 4.5ah battery I'm running 48 leds with a 6v 4.5AH lead acid battery, there are 24 leds connected in parallel each parellel line has got 2 leds making them 48 leds. the leds are standard 5mm 25cd white leds with 3.2Vf. please i need to know the total current and watt of the leds and how long the battery would last. please ignore the green led color on the attached proteus schematic, the illustration is to show how the leds are arranged. A: Generally speaking, running two identical loads in parallel doubles the current, while keeping the same voltage. Running those loads in series doubles the voltage, but maintaining the same current. So, what you're looking at here is, based on the comment you provided: Each serial "substring" of two LEDs will drive at full power when they are provided with 6.4V and 20mA, or 128mW. Because you have 24 substrings, your power consumption is simply $$N \cdot P_{d(string)}$$, so 24 * 128mW = 3.072W. Stated in terms of voltage and current, this gives 6.4V at 480mA. You can go about getting the (ideal/naïve) operation time from the battery through a number of ways. The first is to round down the 6.4V string voltage to 6.0V, your battery voltage (sealed-lead acid?), and then divide 4,500mA by the current consumption. This would give 9.3 hours. The second is to multiply the battery voltage and current to get the energy capacity in watt-hours (Wh), and then divide that by the power consumption to pull out the running time. This gives 8.8 hours, because it uses a number based on the full Vf of the LED, not the maximum voltage the battery can supply. There are two big problems with these methods, hence the requests for access to datasheets in your comments. The first is that the current consumption, call it If, of an LED depends on the Vf. Obviously, your battery cannot supply any more voltage than what it is rated for (or, at least you should be designing with that restriction), so your If @ 6.0V is going to be less than what it would be at 6.4V. The datasheet is needed because it keeps a graph of forward voltage and forward current as one (usually voltage) changes. The second big problem is that a battery is not an ideal voltage source; as it depletes, the rail voltage (and current availability) of your circuit will also drop, affecting the current draw (and thus the power consumption) of the LEDs. Because of this, actual runtime might be significantly different than those "eyeball" estimates above.
{ "pile_set_name": "StackExchange" }
Q: Animation on back key pressed I want to add an out animation when the back key is pressed, before it actually goes back. Right now I just have the animation playing inside of the override method for the back key. It doesn't play the animation fully though. Is there a way to cancel the back event and add it to the animation completion event? Or what is the best way to achieve this? A: Try this: protected override void OnBackKeyPress( System.ComponentModel.CancelEventArgs e ) { if( NavigationService.CanGoBack() ) { // Cancel the navigation e.Cancel = true; //Create the storyboard Storyboard anim = new MyCoolAnimation(); // Hook an on complete handler EventHandler handler = null; handler = ( s, e ) => { // Navigate backward NavigationService.GoBack(); anim.Completed -= handler; }; anim.Completed += handler; // Start the storyboard anim.Begin(); } }
{ "pile_set_name": "StackExchange" }
Q: CSS Selector not working as expected when SVG present I have this JS Fiddle that works well, making my custom title display on mouseover and hide on mouseout. The problem I am having when transporting it to real world environment is that the ~ tilde selector doesn't work anymore. Is there another way to do this? My .message div is at very end of page ( as I had to close SVG tags first ), so I know the + plus selector won't work. I realized that the real problem on my webpage as opposed to the fiddle is that my button class items are svg elements and while the tilde targeting works properly if the two elements are non svg, it doesn't work properly if one element is svg and the other isn't. I added an svg element of the same class "button" to the Fiddle to demonstrate this issue. If anyone can show me how to properly target this, I will be most grateful. JS Fiddle Here .button:hover ~ .message { opacity: 1; transition: opacity .6s ease-in; -moz-transition: opacity .6s ease-in; -webkit-transition: opacity .6s ease-in; } A: Am I missing something? Is there a reason you can't just apply class="button" to the SVG? It seems to achieve what you are after. Demo here Update Instead of trying to achieve the message show with pure CSS, just use a little extra jQuery. Add a class to the message element when you mouseover "button". $('.message').addClass("visible-message"); Then remove it again when you mouseout. Demo here
{ "pile_set_name": "StackExchange" }
Q: Django, listing the query-set of connected Models I would like to list all conversations of a User. As seen from picture below, Conversation Model is not Directly connected to the User table. This is a freelancer site project, where users can register as workers to do jobs posted by users. The result I want is: my_conversations = User.Conversation.all() I'm adding this picture, since it paints everything that I will summarise below. Let's images I have 2 users, one of which is a registered worker. Then it looks as follows: **Users** id Name ... 1 John 2 Bob **Worker** id user_id ... 1 2 John posted some job. We add 1 new entry to the JOB table. **Job** id title user_id 1 Help me design a database 1 This is a M-to-M relationship (worker can apply for many jobs and one job can have many workers), we define a new table where job_has_worker. For each job_has_worker, there should be a way to communicate between worker and job poster. Now what I would like Django to do is load all conversations the user who is logged in e.g. load a list of my conversations for the jobs I posted. Views - My Posted Jobs User = request.user Jobs = User.job_set.all() Views - My Conversations, This is what I need User = request.user Jobs = User.job_set.all() for job in Jobs: # load conversations converstation = job.converstation_set.all() # also somehow append this to all conversations Views - Messages First I need to get conversation id Messages = Conversation.get(pk=pk).message_set.get_all() I'm going to add some security with if loops e.g. if request.user.id not in message.sender || message.receiver return false EDIT: Models.py class Worker(models.Model): user = OneToOneField(User) class Conversation(models.Model): #What to here? #Job_Has_Worker = ForeignKey(Job, Worker) class Message(models.Model): body = models.TextField(max_length=500, blank=False) sender = models.IntegerField() receiver = models.IntegerField() conversation = models.ForeignKey(Conversation) class Job(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField(max_length=500, blank=False) workers = models.ManyToManyField(Worker) A: Without the relationship fields that involve Conversation I can't completely answer this, but here's an example using Job: # All jobs for a given user: Jobs.objects.filter(workers__user=request.user) Your listed example of User.job_set.all() won't work, User doesn't have a direct relation to Job so it won't have a job_set attribute. Assume Conversation is declared using a ForeignKey on the job/worker m2m implicit through model: class Conversation(models.Model): job_worker = ForeignKey(Job.workers.through) (Credit to How can I use the automatically created implicit through model class in Django in a ForeignKey field? for the syntax to reference the implicit through model.) Then something like this should work to get conversations: Conversation.objects.filter(job_worker__worker__user=request.user).distinct() Or this to get messages: Messages.objects.filter(conversation__job_worker__worker__user=request.user).distinct() You can use the through argument to your ManyToManyField to get a nicer name for the intermediate model than Job.workers.through, of course. You can also walk back from an instance, as you were heading towards with user.job_set.all() - it would have to be user.worker.job_set.all() to start, and you'd want to check to ensure that the user has a non-empty worker first, but because job_set is itself a manager that returns querysets of jobs that's a bit more cumbersome to work with for this indirect a relation. some_worker.job_set.filter(...) is clearer than Job.objects.filter(worker=some_worker, ...), though, so it depends on the circumstances.
{ "pile_set_name": "StackExchange" }
Q: How to set image position inside tag to be on top-left corner while text is on the left-bottom I have two pawns and I want to set them on the top-left corner while the text (cell number) is on left-bottom. This is what I have: This is what I want to have: CSS: td { width: 80px; height: 80px; text-align: left; vertical-align: bottom; border: 1px solid black; } .soldiers { width:20px; height:20px; } HTML: <tr> <td class="oddCellBorder" row="0" col="0">57 <img src="Resources/images/player_2.png" class="soldiers"> <img src="Resources/images/player_1.png" class="soldiers"> </td> <td class="evenCellBorder" row="0" col="1">58</td> <td class="oddCellBorder" row="0" col="2">59</td> <td class="evenCellBorder" row="0" col="3">60</td> <td class="oddCellBorder" row="0" col="4">61</td> <td class="evenCellBorder" row="0" col="5">62</td> <td class="oddCellBorder" row="0" col="6">63</td> <td class="evenCellBorder" row="0" col="7">64</td> </tr> A: Wrap the number in a span and position it at the bottom, and vertical-align: top; everything else. td { position: relative; vertical-align: top; width: 80px; height: 80px; text-align: left; border: 1px solid black; } td span { position: absolute; bottom: 0; } <table> <tr> <td> <span>57</span> <img src="http://placehold.it/20x20/ff6a00/ff6a00" alt="" /> <img src="http://placehold.it/20x20/fb235e/fb235e" alt="" /> </td> </tr> </table>
{ "pile_set_name": "StackExchange" }
Q: R: Rename or copy dataframe and naming it as defined in a vector I want to create a new dataframe from an existing one and naming it as defined in a vector: I have a dataset with many different questions, and to go through the dataset a bit quicker, I have developed a list of generic functions that can be called upon. For each question, I define the specific values, such as can be seen below. In the second part, I more or less create a clean dataset for the question, which is saved as a dataframe called 'questionid'. Because that variable is overwritten with each question, I want to create a duplicate of this dataframe and call it as specified under 'questionname' (in this case "A1"). I find it very difficult to find easy ways to do that. I hope someone can help me. # Specify vectors and variables question <- "Would you recommend edX to a friend of you?" questionname <- "A1" edXid <- "i4x-DelftX-ET3034TUx-problem-b3d30df864ca41ffa0170e790f01a783_2_1" clevels <- c("0 - Not at all likely", "1", "2", "3", "4", "5 - Neutral", "6", "7", "8", "9", "10 - Extremely likely") csvname <- paste(questionname, ".csv", sep="") pngname <- paste(questionname, ".png", sep="") # Run code questionid <- subset(allDatasolar, allDatasolar[,3]==edXid, select = -c(X,question)) questionid <- questionid[-grep("dummy", questionid$answer), ] questionid <- droplevels(questionid) # as.name(questionname) <- as.data.frame(questionid) # does not work questionid$answer <- factor(questionid$answer, ordered=TRUE, levels=clevels) write.csv(data.frame(summary(questionid$answer)), file = csvname) png(file = pngname, width = 640) barchart(questionid$answer, main = question, xlab = "", col='lightblue') dev.off() A: You're looking for assign >question = "What do you need?" >questionname = "A1" > >questionid = data.frame(question, x="minimal working example") > >assign(questionname, questionid) > >A1 question x 1 What do you need? minimal working example Assign takes a string (or a character variable, in this case) as the first argument and makes an object with that name that is a copy of whatever is in the second argument. In this case, you can feel free to keep over-writing the questionid data frame, but you will be making copies along the way based on your "questionname" variable value.
{ "pile_set_name": "StackExchange" }
Q: How to import notebook from local machine to Azure Databricks portal? How to import notebook from local in Azure Databricks? I have sample notebook in DBC format on my local machine and I need to import via Notebook Rest API. curl -n -H "Content-Type: application/json" -X POST -d @- https://YOUR_DOMAIN/api/2.0/workspace/import <<JSON { "path": "/Users/[email protected]/new-notebook", "format": "SOURCE", "language": "SCALA", "content": "Ly8gRGF0YWJyaWNrcyBub3RlYm9vayBzb3VyY2UKcHJpbnQoImhlbGxvLCB3b3JsZCIpCgovLyBDT01NQU5EIC0tLS0tLS0tLS0KCg==", "overwrite": "false" } JSON Refer this doc They are given as destination file path but not mention about source file path instead they given as content. But How could I add the source file to import notebook? A: If you have a DBC file then the format needs to be DBC and language is ignored. Also, the content property needs to be the DBC file bytes Base64 encoded, per the docs: The content parameter contains base64 encoded notebook content If using bash you could simply do base64 notebook.dbc
{ "pile_set_name": "StackExchange" }
Q: Android SSHJ exception upon connect() - "KeyFactory ECDSA implementation not found" I'm trying to open an SSH client session from my Android app. Trying to connect to a device on the local network (a Raspberry Pi). I'm using the SSHJ library version 0.10.0. It fails on the ssh.connect() call, with a TransportException which is ultimately caused by a NoSuchAlgorithmException. Refer exception tree below. SSHClient ssh = new SSHClient(new AndroidConfig()); Session session = null; try { //ssh.loadKnownHosts(); // Exception thrown on this line ssh.connect("192.168.1.109", 22); // Doesn't reach below ssh.authPassword("user", "password"); session = ssh.startSession(); } catch (net.schmizz.sshj.transport.TransportException ex) { ; } Exception tree: net.schmizz.sshj.transport.TransportException net.schmizz.sshj.common.SSHException net.schmizz.sshj.common.SSHRuntimeException java.security.GeneralSecurityException: java.security.NoSuchAlgorithmException: KeyFactory ECDSA implementation not found java.security.NoSuchAlgorithmException: KeyFactory ECDSA implementation not found Other system info: SSHJ library : v0.10.0 Android device : Galaxy Note 3 running Android 4.4.2 I used the maven dependency support in Android Studio to bring in the SSHJ JAR and it pulled in the following three libraries in addition to the SSHJ v0.10.0 jar... bouncy castle... bcpkix-jdk15on-1.50.jar bcprov-jdk15on-1.50.jar logging.... slf4j-api-1.7.7.jar Don't have a clue where to start with this exception ... any suggestions appreciated! Thanks. UPDATE: 31-Oct-2014 As suggested by LeeDavidPainter, I included the SpongyCastle 1.51.0 JAR and added this line at the top: Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); I'm now getting a different exception on the same line: net.schmizz.sshj.transport.TransportException net.schmizz.sshj.common.SSHException net.schmizz.sshj.common.SSHRuntimeException java.security.GeneralSecurityException: java.security.spec.InvalidKeySpecException: key spec not recognised java.security.spec.InvalidKeySpecException: key spec not recognised Also note I tried the following line as well, with the same result: Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); I have another app on my phone which is basically doing exactly what I want to achieve - its called RaspberryPiController - it connects to your RPi over SSH with username and password auth. This works fine, so it would seem its not a network issue. A: Android ships with a cut down version of BouncyCastle which does not include the ECDSA algorithms. So even though you include the full version in your class path, the Android runtime version will be picked up and used. You may want to look at http://rtyley.github.io/spongycastle/ which was created to get around this, its a repackaged version of Bouncycastle that can be installed as a separate JCE provider in Android. Just install it as the default JCE provider before you try to connect with SSHJ (untested). Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); A: Couldn't get anywhere with this issue in SSHJ, so decided to give JSch a try which offers the same functionality. Its available as a maven repo as well - I used jsch version 0.1.51 ('com.jcraft:jsch:0.1.51'). It worked first time with this code fragment; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import java.io.ByteArrayOutputStream; import java.util.Properties; JSch jsch = new JSch(); com.jcraft.jsch.Session session = null; String result = ""; try { session = jsch.getSession("user", "192.168.1.109", 22); session.setPassword("password"); // Avoid asking for key confirmation Properties prop = new Properties(); prop.put("StrictHostKeyChecking", "no"); session.setConfig(prop); session.connect(); // SSH Channel ChannelExec channel = (ChannelExec)session.openChannel("exec"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); channel.setOutputStream(stream); // Execute command channel.setCommand("ls -ltr"); channel.connect(1000); java.lang.Thread.sleep(500); // this kludge seemed to be required. channel.disconnect(); result = stream.toString(); } catch (JSchException ex) { String s = ex.toString(); System.out.println(s); } catch (InterruptedException ex) { String s = ex.toString(); System.out.println(s); } finally { if (session != null) session.disconnect(); } It feels like a more robust implementation when using it compared to SSHJ - or this impression might be caused by them selecting quite conservative timeouts. For example, if the target device is switched off, the session.connect() call will, by default, keep trying to connect for something like 20 seconds before giving up.
{ "pile_set_name": "StackExchange" }
Q: Django Rest Framework ManyToMany field ordering I've got the following models: class BusStop(m.Model): street_name = m.CharField(max_length=255) class Meta: ordering = ['street_name'] ... class Carrier(m.Model): name = m.CharField(max_length=255) ... class CarrierStop(m.Model): bus_stop = m.ManyToManyField(BusStop, related_name='carrier_stop_fk') carrier = m.ForeignKey(Carrier, on_delete=m.CASCADE, related_name='test_carrier_fk') I made the serializer: class CarrierStopSerializer(serializers.ModelSerializer): carrier = serializers.StringRelatedField() bus_stop = serializers.StringRelatedField(many=True) class Meta: model = CarrierStop fields = ['id', 'carrier', 'bus_stop'] I've got some objects of BusStop models and serializer gives representation like this: [ { "id": 1, "carrier": "Fremiks", "bus_stop": [ "Armii Krajowej", "Kino Lot 01", "Kosynierów I 02" ] } ] bus_stop field from CarrierStopSerializer returns bus stops ordered by name. I want to order it by id in intermediate table carrierstop_bus_stop created by Django ManyToMany field. I know that i should use SerializerMethod field instead of StringRelatedField(or PrimaryKeyRelatedField, doesn't matter) but I'm not sure how to do this exactly. A: Use SerializerMethodField as class CarrierStopSerializer(serializers.ModelSerializer): carrier = serializers.StringRelatedField() bus_stop = serializers.SerializerMethodField(read_only=True) def get_bus_stop(self, model): return [bus_stop.__str__() for bus_stop in model.bus_stop.all().order_by('id')] class Meta: model = CarrierStop fields = ['id', 'carrier', 'bus_stop']
{ "pile_set_name": "StackExchange" }
Q: PowerBuilder: Check record and insert into SQL table if not available I am fairly new to PowerBuilder Classic 12. I need to check whether a record is available and if not insert from a textbox. I would probably need a DataStore since someone suggested a preference to SQL statements. Thanks. this code is behaving funny, please where is the problem? at one time it works but running the program again it accepts a data that has already been inserted. the program is not giving any error but i can see the same data stored in the table. string id, idno idno=trim(sle_idno.text) if idno="" then messagebox("EMPTY","Enter a record") return end if SELECT employee.idnumber INTO :id FROM employee ; if idno=id then messagebox("AVAILABLE","Record available") return end if INSERT INTO employee ( idnumber ) VALUES ( :idno ) ; A: You are looking for Merge. I will explain it using an example. Just send the values in Database via Stored Proc? and use following technique. Sample DDL CREATE TABLE Employee ( EmployeeID INTEGER PRIMARY KEY, EmployeeName VARCHAR(15) ) CREATE TABLE EmployeeSalary ( EmployeeID INTEGER , EmployeeSalary INTEGER ) Sample DML For Employee INSERT INTO Employee VALUES(1,'SMITH') INSERT INTO Employee VALUES(2,'ALLEN') INSERT INTO Employee VALUES(3,'JONES') INSERT INTO Employee VALUES(4,'MARTIN') INSERT INTO Employee VALUES(5,'JAMES') Sample DML For EmployeeDetails INSERT INTO EmployeeSalary VALUES(1,23000) INSERT INTO EmployeeSalary VALUES(2,25500) INSERT INTO EmployeeSalary VALUES(3,20000) Merge Query MERGE EmployeeSalary AS stm USING (SELECT EmployeeID,EmployeeName FROM Employee) AS sd ON stm.EmployeeID = sd.EmployeeID WHEN MATCHED THEN UPDATE SET stm.EmployeeSalary = stm.EmployeeSalary + 12 WHEN NOT MATCHED THEN INSERT(EmployeeID,EmployeeSalary) VALUES(sd.EmployeeID,25000); References First Reference Second Reference Third Reference Fourth Reference
{ "pile_set_name": "StackExchange" }
Q: Get the name of snapshot from property using zfs get It would like to know if it's possible to get the name of snapshot from any property. For example, I created a property called :uuid with the value c98fdd32-8a76-4bcf-a509-d298291f85f5 If it's possible to get the name of this snapshot using the property and its value? A: Yes, it is possible. Short answer: Use zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}' Long answer/explanation: You can query any ZFS property of any dataset (file system, volume, or snapshot): zfs get :uuid <dataset> If you call it recursively with -r without a dataset, you will get all valid datasets: zfs get -r :uuid To reduce it only to datasets of snapshot type, use -t: zfs get -r -t snapshot :uuid Then you can only display the columns you want with -o, in this case the name and value columns: zfs get -r -t snapshot -o name,value :uuid To further work with the data, you need remove the headers with -H and display numbers as exact values with -p: zfs get -Hpr -t snapshot -o name,value :uuid This includes all values, even non-set ones (-), so you need to further filter the output (for example with awk): If you just want a specific snapshot name (print every first column/name for each line where the second column/value is the specific string): zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 == "c98fdd32-8a76-4bcf-a509-d298291f85f5") print $1}' If you want all results except the empty ones (all without -): zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}' If you want to just have the basename, you can then further split first and second column by @ (which is the delimiter between file system and snapshot name): zfs get -Hpr -t snapshot -o name,value :uuid | awk '{if ($2 != "-") print $1}' | awk -F"@" '{print $1}'
{ "pile_set_name": "StackExchange" }
Q: Get current frame of video in javascript / jquery I am playing video using the html video tag. While playing video I want the current frame of the video not "currentTime" using jquery or javascript. I am able to get the current frame by doing the calculation of the fps of video and currentTime, but it is not giving the exact frame number. Any ideas how I can fix this? A: Please check out below demo. Only one thing is you have to assign a frameRate of video. External Js will manage all thing and you can get Frame number easily. var currentFrame = $('#currentFrame'); var video = VideoFrame({ id : 'video', frameRate: 29.97, callback : function(frame) { currentFrame.html(frame); } }); $('#play-pause').click(function(){ ChangeButtonText(); }); function ChangeButtonText(){ if(video.video.paused){ video.video.play(); video.listen('frame'); $("#play-pause").html('Pause'); }else{ video.video.pause(); video.stopListen(); $("#play-pause").html('Play'); } } <script src="https://rawgit.com/allensarkisyan/VideoFrame/master/VideoFrame.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="frame"> <span id="currentFrame">0</span> </div> <video height="180" width="100%" id="video"> <source src="http://www.w3schools.com/html/mov_bbb.mp4"></source> </video> <div id="controls"> <button id="play-pause">Play</button> </div> A: Image of the current frame: function captureVideo(video) { var canvas = document.createElement("canvas"); canvas.width = video.videoWidth; canvas.height = video.videoHeight; var canvasContext = canvas.getContext("2d"); canvasContext.drawImage(video, 0, 0); return canvas.toDataURL('image/png'); } Current time: var frameAfterSeek = Math.floor(_video.currentTime); A: I found cause of that problem. I was compressing my video therefore while compressing, fps gets reduced that's why I was not able to get correct fps. Now I'm able to get the with difference of 1-2 frames, but that's ok. Thanks for your help guys.
{ "pile_set_name": "StackExchange" }
Q: How do I write search algorithm in c sharp? I am writing simple program that will assist me to configure and sort out my files.I want the algorithm to search for matching string or text that the user inputs in the search box like windows search index , Google,or any other search engines.I doesn't have to be complex,just simple.you can show me by example or direct me to the appropriate resource. A: https://support.microsoft.com/sv-se/kb/303974 Has some information that will get you going. Edit: string[] files = Directory.GetFiles("C:\\", "*.dll"); This line will search through all files in c:\ for a file thats ending with .dll Now you want it to search through all files that starts with something then youd have to run "yourstring*". In your example case, you only remember the starting "tes". Directory.GetFiles("C:\\", "tes*"); This line will search for a file starting with the filename "tes" You can also use Directory.GetDirectories("C:\\"); to get all directories in c:\ and if you want then, loop through those directories with the same method to find all the subdirectories, then search for your file in all of those directories.
{ "pile_set_name": "StackExchange" }
Q: Android Custom ListView with ArrayAdapter possible? I have a prefilled DB in Assets, that will be copied and opened after App start. I have a activity who Displays the Column Name with rawQuery Cursor c = database.rawQuery("SELECT _id, Name from DB ORDER BY Name ASC", null); ArrayList<String> values = new ArrayList<String>(); while (c.moveToNext()) { values.add(c.getString(c.getColumnIndex("Name"))); } c.close(); and starts onItemClick a new intent who Displays the other colums (new activity get "Name" variable with i.putExtra) private void getSQLData() { Bundle extras = getIntent().getExtras(); String Name = extras.getString("Name"); DataBaseHelper myDbHelper = new DataBaseHelper(null); myDbHelper = new DataBaseHelper(this); SQLiteDatabase database = myDbHelper.getWritableDatabase(); ListView lv = (ListView)findViewById(R.id.listView1); Cursor c = database.rawQuery("SELECT * from DB WHERE Name='"+Name+"' ORDER BY Name ASC", null); ArrayList<String> values = new ArrayList<String>(); while (c.moveToNext()) { values.add(c.getString(c.getColumnIndex("Name"))); values.add(this.getString(R.string.x) + (c.getString(c.getColumnIndex("x"))+" "+this.getString(R.string.x)+":")); values.add((c.getString(c.getColumnIndex("y")) + this.getString(R.string.y) + " " + this.getString(R.string.y))); } c.close(); ArrayAdapter<String> NamenDetails = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values); } lv.setAdapter(NamenDetails); } I get all SQL datas I need, but in the Default View. But I Need it customized like for exmaple : I tried many many tutorials with custom listview and simplecursoradapter but I think all be defeated by the ArrayListString. I hope anyone can help me I get frustrated.. Thanks! A: This is an example of listview with its single row having two textviews. This the thing you wanted: CustomListView.java: package com.customlistview; import java.util.ArrayList; import resources.PlacesListAdapter; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; public class CustomListView extends Activity { /** Called when the activity is first created. */ private ArrayList<String> mPlacesData1 = new ArrayList<String>(); private ArrayList<String> mPlacesData2 = new ArrayList<String>(); PlacesListAdapter mPLAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPlacesData1.clear(); mPlacesData2.clear(); mPlacesData1.add("ICD1"); mPlacesData2.add("SubTitle1"); mPlacesData1.add("ICD2"); mPlacesData2.add("SubTitle2"); mPlacesData1.add("ICD3"); mPlacesData2.add("SubTitle3"); mPlacesData1.add("ICD4"); mPlacesData2.add("SubTitle4"); mPlacesData1.add("ICD5"); mPlacesData2.add("SubTitle5"); mPlacesData1.add("ICD6"); mPlacesData2.add("SubTitle6"); mPlacesData1.add("ICD7"); mPlacesData2.add("SubTitle7"); mPlacesData1.add("ICD8"); mPlacesData2.add("SubTitle8"); ListView listView = (ListView) findViewById(R.id.listview); mPLAdapter = new PlacesListAdapter(CustomListView.this, mPlacesData1, mPlacesData2); listView.setAdapter(mPLAdapter); } } PlaceListAdapter.java: package resources; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.customlistview.R; public class PlacesListAdapter extends BaseAdapter { // private Context mContext; private LayoutInflater mInflater; private ArrayList<String> AL_id_text = new ArrayList<String>(); private ArrayList<String> AL_text = new ArrayList<String>(); public PlacesListAdapter(Context c, ArrayList<String> AL_name_time, ArrayList<String> AL_name_time1) { mInflater = LayoutInflater.from(c); // mContext = c; this.AL_id_text = AL_name_time; this.AL_text = AL_name_time1; } public int getCount() { return AL_id_text.size(); } public Object getItem(int position) { return AL_id_text.get(position); } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.place_row, null); holder = new ViewHolder(); holder.txt_maintext = (TextView) convertView .findViewById(R.id.txt_maintext); holder.txt_mtext = (TextView) convertView .findViewById(R.id.txt_mtext); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.txt_maintext.setText(AL_id_text.get(position)); holder.txt_mtext.setText(AL_text.get(position)); return convertView; } static class ViewHolder { TextView txt_maintext; TextView txt_mtext; } } activity_main.xml: <?xml version="1.0" encoding="UTF-8"?> -<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ListView android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/listview"> </ListView> </LinearLayout> place_row.xml: <?xml version="1.0" encoding="UTF-8"?> -<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> -<LinearLayout android:orientation="vertical" android:layout_height="70dip" android:layout_width="match_parent" android:id="@+id/lin_main"> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="@+id/txt_maintext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="5dip" android:textColor="#fff"/> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="@+id/txt_mtext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="15dip" android:textColor="#fff"/> </LinearLayout> <ImageView android:layout_height="3dip" android:layout_width="match_parent" android:background="#0000ff"/> </LinearLayout> This is an example. You can make necessary edits to achieve what you want.
{ "pile_set_name": "StackExchange" }
Q: Listen to Livereload.js event to reload ajax contents "not the whole page" here is my configuration: I have a remote site, say something.com where "some" page contents are dynamically loaded from localhost, with an ajax call to a node local server. Remote site listens to grunt-watch server too, and reloads the whole page using livereload.js. Every change on local files force the page to reload, page who re-injects the code from my localhost. And this is smooth. Next step could be to listen to livereload events, and reload not the whole page, but just reinject the code via a new ajax call. Is it possible ? I didn't found this kind of event in the doc, there's something, but is about connection established/interrupted. Any idea ? Thanks :) A: The livereload docs themselves include the following statement: Would love, but doesn't seem possible: live JS reloading An alternative is to use the webpack dev server which does support this functionality, via Hot Module Replacement.
{ "pile_set_name": "StackExchange" }
Q: Spinner in android with fragment I am having the problem using the spinner in android! Can anyone tell me out? My code in ListViewFragment is public class ListViewFragment extends Activity implements OnItemSelectedListener { public void ListViewFragments (){} private String[] state = { "Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "HoneyComb", "IceCream Sandwich", "Jellybean", "kitkat"}; Spinner spinnerOsversions; TextView selVersion; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); System.out.println(state.length); selVersion = (TextView) findViewById(R.id.selVersion); spinnerOsversions = (Spinner) findViewById(R.id.osversions); ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state); adapter_state .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerOsversions.setAdapter(adapter_state); spinnerOsversions.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { spinnerOsversions.setSelection(position); String selState = (String) spinnerOsversions.getSelectedItem(); selVersion.setText("Selected Android OS:" + selState); } @Override public void onNothingSelected(AdapterView<?> arg0) { } similarly in fragment_list.xml <TextView android:id="@+id/selVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/osversions" android:layout_marginLeft="10dp" android:layout_marginTop="20dp" /> <Spinner android:id="@+id/osversions" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below=@+id/textView2" android:layout_marginTop="38dp" /> and where i get error is in MainActivity.java Fragment fragment = null; switch (position) { case 0: fragment = new HomeFragment(); break; case 1: fragment = new ListViewFragment(); break; case 2: fragment = new StyleFragment(); break; case 3: fragment = new DatabaseFragment(); break; case 4: fragment = new PrefsFragment(); break; case 5: fragment = new WebViewFragment(); break; case 6: fragment = new WebServiceFragment(); break; case 7: fragment = new RssReaderFragment(); break; default: break; } The error message is: Description Resource Path Location Type Type mismatch: cannot convert from ListViewFragment to Fragment MainActivity.java /Nagarik Sahayata/src/com/yogeshojha/nagarikshayata line 235 Java Problem A: Take a look at your code here: ListViewFragment extends Activity ==> your ListViewFragment extends the Activity class and not a Fragment! ==> rethink what you want to do. Should ListViewFragment actually be a Fragment or an Activity? Anyhow, you can't just squeeze an Activity into a Fragment like this: fragment = new ListViewFragment();
{ "pile_set_name": "StackExchange" }
Q: VB.net 2010 - IndexOutOfRange from datagridview when refreshing dataset I have a datagridview on a form that is bound to a table in a dataset from another class. I use a data adapter to .Fill a table in that dataset and the grid displays the data fine. Works fine. On my form I have a textbox the user can type in that will will pass a parameter to the storedprocedure used to fill this table. So on startup the textbox will have "%" in it. and then the user can type in "F%" and get everything that starts with an "F" So when that textbox changes I launch an async refresh (.BeginInvoke) to do my refresh. The table gets populated with the reduced number of records (I check ds.table(0).rows.count and it is correct) But the datagridview then starts throwing datagridview.dataerror events. "System.IndexOutofRangeException : Index # does not have a value" It looks like the dataset is getting filled correctly and not having any issues, but the datagrid is not liking this update. The index out of range error is so common that I'm not finding what I need through searches. Thanks in advance! :) A: Well, find the error. Take out the BeginInvoke and do it synchronous. See if that fixes it. If not, leave it out until you're sure you have no other problems. @roadie has a good comment on resetting the SelectedRow There are similar ways to enforce the update. Like .. bindingSource.DataSource = null; bindingSource.DataSource = myTable;
{ "pile_set_name": "StackExchange" }
Q: Running selenium with Javascript on Node.js I am a noob to Javascript so apologies if my question is very trivial. I am trying to run a selenium test that was wrote in Javascript. As I usually do, I just want to start with something simple and work from there. In my script I am just trying to load Google using chromedriver. var webdriver = require("selenium-webdriver"); var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build(); driver.get("http://www.google.com"); On the CLI I navigate to the directory where the Test.js file is saved in and I run the command node Test.js. I always get this error in response; C:\Selenium\node_modules\selenium-webdriver\_base.js:104 vm.runInContext(opt_srcText, closure, src); ^ SyntaxError: Unexpected token ) at goog.loadModuleFromSource_ (C:\Selenium\node_modules\selenium-webdriver\l at Object.goog.loadModule (C:\Selenium\node_modules\selenium-webdriver\lib\g at C:\Selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1:6 at Object.Context.closure.goog.retrieveAndExecModule_ (C:\Selenium\node_modu at <anonymous>:1:6 at Context.closure.closure.vm.createContext.CLOSURE_IMPORT_SCRIPT (C:\Seleni at Object.goog.importScript_ (C:\Selenium\node_modules\selenium-webdriver\li at Object.goog.importModule_ (C:\Selenium\node_modules\selenium-webdriver\li at Object.goog.writeScripts_ (C:\Selenium\node_modules\selenium-webdriver\li at Object.goog.require (C:\Selenium\node_modules\selenium-webdriver\lib\goog I originally ran this code on my Windows machine and when I was getting that error I put it down to Windows and Node.js no agreeing and tried it on my Mac. Still no luck as I was getting the exact same response. On both machines I have node and npm installed. Previous to executing the tests I ran the command npm install selenium-webdriver and I also added chromedriver to my PATH. I have no idea what I am doing wrong so if anyone can point me in the right direction, it'd be very much appreciated. A: Turns out the version of node I was using was too old. Thanks to @Louis for your help in reaching this solution. What I did was uninstall node and re-installed it with the latest version. I would imagine upgrading would work too.
{ "pile_set_name": "StackExchange" }
Q: create sorted vector of content of two binary search trees in sorted order You are given two binary search trees, the goal is produce a sorted array of elements containing elements from both the trees. I wanted to know if there is a simpler approach, and if the use of boost variant is justified in the code. The code uses a stack to iterate over the binary search tree. The stack maintains the state for pre-order traversal of the tree. #include <iostream> #include <stack> #include <boost/range/irange.hpp> #include <boost/variant.hpp> #include <random> #include <algorithm> using namespace std; using boost::irange; using boost::variant; struct Node { Node(Node* l, Node* r, int v):left(l), right(r), val(v) { } Node* left; Node* right; int val; }; typedef variant<Node*, int> stkElemT; typedef stack<stkElemT> bstStkT; //from variant extract the pointer if valid otherwise NULL struct stkElemVisitorNode : public boost::static_visitor<Node*> { Node* operator()(const int& val) const { return NULL; } Node* operator()(Node*& ptr) const { return ptr; } }; //from variant extract the integer value if valid otherwise -1 struct stkElemVisitorInt : public boost::static_visitor<int> { int operator()(const int& val) const { return val; } int operator()(Node*& ptr) const { return -1; } }; //expand left most path of top node. void fillPathStkRecurse(bstStkT& bstStk) { stkElemT topE = bstStk.top(); Node* topN = boost::apply_visitor(stkElemVisitorNode(), topE); if(topN != NULL) // { bstStk.pop(); if (topN->right) bstStk.push(topN->right); bstStk.push(topN->val); if (topN->left) { bstStk.push(topN->left); } fillPathStkRecurse(bstStk); } else{ return; //top node is not a pointer but value } } int getTopVal(const bstStkT& bstStk) { assert(!bstStk.empty()); stkElemT topE = bstStk.top(); int val = boost::apply_visitor(stkElemVisitorInt(), topE); return val; } void incrBstStk(bstStkT& bstStk) { if(bstStk.empty()) return; int topVal = getTopVal(bstStk); assert(topVal != -1); bstStk.pop(); if(!bstStk.empty()) fillPathStkRecurse(bstStk); //expand till child node return; } Node* create_tree(vector<int>& vals, int start, int end) //end excluded { if(end==start) return new Node(NULL, NULL, vals[start]); if(end == start + 1) { Node* curr = new Node(NULL, NULL, vals[start]); curr->right = new Node(NULL, NULL, vals[start+1]); return curr; } int mid = floor((start + end)/2.0); Node* left = create_tree(vals, start, mid-1); Node* right = create_tree(vals, mid+1, end); Node* curr = new Node(left, right, vals[mid]); return curr; } vector<int> merge_bst(Node* root1, Node* root2) { vector<int> res; bstStkT bstStk1; bstStk1.push(root1); fillPathStkRecurse(bstStk1); bstStkT bstStk2; bstStk2.push(root2); fillPathStkRecurse(bstStk2); while(1) { //cout<<"stk sizes = "<<bstStk1.size()<<" "<<bstStk2.size()<<endl; if(bstStk1.empty() && bstStk2.empty()) break; int val1 = numeric_limits<int>::max(); if(!bstStk1.empty()) val1 = getTopVal(bstStk1); int val2 = numeric_limits<int>::max(); if(!bstStk2.empty()) val2 = getTopVal(bstStk2); if(val1 < val2)//consume bstStk1 { res.push_back(val1); incrBstStk(bstStk1); } else { res.push_back(val2); incrBstStk(bstStk2); } } return res; } int main(int argc, char** argv) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> uid5k(0, 1000); // distribution in range [1, 6] int n = 10000; for(auto k: irange(0, 10000)) { vector<int> inVec1; for(auto i: irange(0, n)) inVec1.push_back(uid5k(rng)); sort(inVec1.begin(), inVec1.end()); Node* root1 = create_tree(inVec1, 0, n-1); vector<int> inVec2; for(auto i: irange(0, n)) inVec2.push_back(uid5k(rng)); sort(inVec2.begin(), inVec2.end()); Node* root2 = create_tree(inVec2, 0, n-1); vector<int> merged_vec(inVec1.begin(), inVec1.end()); merged_vec.insert(end(merged_vec), begin(inVec2), end(inVec2)); sort(begin(merged_vec), end(merged_vec)); auto res = merge_bst(root1, root2); assert(res == merged_vec); } return 0; } A: Design If you are going to do this the C++ way then you should be using standard algorithms. A tree is a type of container; so you should be able to get an iterator to logically pass over each element in the container. As a result I would expect the code to look like this: Tree one; Tree two; // Add data to one and two here. std::vector<int> result; result.reserve(one.size() + two.size()); // There is a standard algorithm to combine two sorted containers. // So I would expect you to use that. Which means your // Tree structure should support an iterator concept. std::merge(std::begin(one), std::end(one), std::begin(two), std::end(two), std::back_inserter(result)); So looking at your code I see struct Node { Node* left; Node* right; int val; }; What I would actually expect to see is: class Tree { struct Node { Node* left; Node* right; int val; }; class Iterator { public: using value_type = int; using pointer = int*; using reference = int&; using difference_type = std::ptrdiff_t; using iterator_category = std::forward_iterator_tag; Iterator(); // end() Iterator(Node*); // begin() int const& operator*(); Iterator operator++(); Iterator operator++(int); bool operator==(Iterator const& rhs) const; bool operator!=(Iterator const& rhs) const; }; Node* root; std::size_t size; public: Tree(); void insert(int val); using iterator = void; // can't modify a BST using const_iterator = Iterator; const_iterator begin() const {return Iterator(root);} const_iterator cbegin() const {return Iterator(root);} const_iterator end() const {return Iterator();} const_iterator cend() const {return Iterator();} bool empty() const; std::size_t size() const; }; Code Review Now that I have shown what I would expect, let's have a look at what you wrote. Don't use the using namespace X expression. Doing this is bad practice. You are asking for trouble in the long run. For details see: Why is “using namespace std” considered bad practice? using namespace std; Even doing the below can be dangerous (though less than above). If you are going to do this don't do it at file scope: try and restrict the scope by doing it inside a function. using boost::irange; using boost::variant; Both of these are bad habits. So, even for small projects, you should resist doing this. Habits are hard to break and you may do it accidentally when it actually matters. The reason the "Standard" namespace is called "std" is so that the prefix std:: did not impose a large burden. Constructor Using brace list In this type of simple case: struct Node { Node(Node* l, Node* r, int v):left(l), right(r), val(v) { } Node* left; Node* right; int val; }; You don't actually need to define a constructor. You can use brace initialization to initialize all the members (without needing a constructor). Node x = new Node {nullptr, nullptr, 3}; User Defined Types Its normal to use an initial capitol letter to define "User Defined Types" (while functions and variables have an initial lower case letter). Now this is a common convention, but not universal (so you can take it or leave it). But using this convention does help. One of the big things about C++ is the type information. Being able to distinguish types from objects is really useful (so its a convention I follow). typedef variant<Node*, int> stkElemT; // I would use StkElemT (see next rule) typedef stack<stkElemT> bstStkT; // I would use BstStkT (see next rule) Self Documenting Code Writing self documenting code is critical to writing maintainable code. This basically means writing function and type names that explain exactly what they do. typedef variant<Node*, int> stkElemT; // I would use StackElement typedef stack<stkElemT> bstStkT; // I would use SearchTreeStack Comments I actually like your comments (I usually hate people's comments). These are actually useful. So keep this up. //from variant extract the pointer if valid otherwise NULL struct stkElemVisitorNode : public boost::static_visitor<Node*> //from variant extract the integer value if valid otherwise -1 struct stkElemVisitorInt : public boost::static_visitor<int> //expand left most path of top node. void fillPathStkRecurse(bstStkT& bstStk) { } BST and Balanced BST A BST (binary search tree) does not need to be balanced. You go to extensive lengths to make sure the tree you build is balanced. I think this is overkill. A simple BST is easier to build. Node* create_tree(vector<int>& vals, int start, int end) //end excluded Begin/End In C++ it is more traditional for the end iterator to be one past the end. Your code it marks the actual last element. Its a valid choice. But not traditional C++ (so you should mention it in the comment. You try but I am not sure its clear). I would also encourage you to try it using the traditional method; in my opinion it will make the code easier. Node* create_tree(vector<int>& vals, int start, int end) //end excluded Prefer nullptr over NULL return new Node(NULL, NULL, vals[start]); In C++11 we introduced nullptr which is a type safe NULL.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to add more than one link to a question when marked as Duplicate? A question on How to remove the white border of polygons using QGIS was asked yesterday, and I voted to close the question as a duplicate to another question that has an answer. However, sometimes there are more than one question that can be linked to the OP as exact duplicate, but with a better solution. But since we only have to provide one link as a duplicate question to the OP, I added another solution in the comment. I understand that duplicate means an exact question asked two times (with different phrasing, of course), but sometimes it has more than one possible solution. Is there a way to add more than one link to an OP when marked/voted as Duplicate? In other words, can the system be expanded to give more than one option when adding a link to a related question. A: As far as I know the only time you will ever see more than one duplicate to a question is when it's reviewers have differing opinions as to which is more appropriate. Each reviewer is expected to choose the one question that they think represents the same question having been asked before. To enable a single reviewer to choose more than one duplicate would need an enhancement request to succeed at the site-wide Meta Stack Exchange rather than here. However, I would not expect such a request to be successful. If it is difficult to choose which previous question of earlier candidates represents a duplicate I think it is a sure sign that more editing to focus the questions involved in the dilemma or trilemma facing you is needed. This appears to be the same question that you are asking, asked previously at Meta Stack Exchange: Allow same user to add multiple links as possible duplicates
{ "pile_set_name": "StackExchange" }
Q: View Controllers in cocoa When you instantiate a new view controller is it faster to create the objects present within, in code like [UIButton buttonWithType:] and [self.view addSubView:] or by loading them from a nib/xib file. A: Earlier the first way was definitely faster, but with iOS 4 and UINib caching it depends on how often do you hit the cache.
{ "pile_set_name": "StackExchange" }
Q: Como cambiar el Font del texto de la barra de títulos en Android Quisiera saber como cambiar el font de la barra de títulos, tengo esto: y me gustaria obtener este, título de 2 líneas y tamaño diferente A: Ubícate en la parte del Toolbar en el .MainActivty y haz lo siguiente. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Buzón de entrada"); toolbar.setSubtitle("todas las cuentas"); setSupportActionBar(toolbar); solo tendrías que agregar: toolbar.setSubtitle("todas las cuentas"); espero que te haya servido.
{ "pile_set_name": "StackExchange" }