text
stringlengths
64
81.1k
meta
dict
Q: How to implement friction in a physics engine based on "Advanced Character Physics" I have implemented a physics engine based on the concepts in the classic text Advanced Character Physics by Thomas Jakobsen. Friction is only discussed very briefly in the article and Jakobsen himself notes how "other and better friction models than this could and should be implemented." Generally how could one implement a believable friction model on top of the concepts from the mentioned article? And how could the found friction be translated into rotation on a circle? I do not want this question to be about my specific implementation but about how to combine Jakobsens ideas with a great friction system more generally. But here is a live demo showing the current state of my engine which does not handle friction in any way: http://jsfiddle.net/Z7ECB/embedded/result/ Below is a picture showing and example on how collision detection could work in an engine based in the paper. In the Verlet integration the current and previous position is always stored. Based on these a new position is calculated. In every frame I calculate the distance between the circles and the lines. If this distance is less than a circles radius a collision has occurred and the circle is projected perpendicular out of the offending line according to the size of the overlap (offset on the picture). Velocity is implicit due to Verlet integration so changing position also changes the velocity. What I need to do know is to somehow determine the amount of friction on the circle and move it backwards parallel to the line in order to reduce its speed. A: You should take a look at Mathias Mueller et all's "position based dynamics" paper. It's basically the same as Jacobsons' paper and he might give you more info about friction. http://www.matthiasmueller.info/publications/posBasedDyn.pdf They state that friction is basically damping the particle's velocity in the plane of the collision by some scalar value. Note that this doesn't give you any coulomb friction effects (the amount of momentum into the collision doesn't affect the magnitude of the friction force) but you might be able to get that by considering the particle's velocity into the collision plane.
{ "pile_set_name": "StackExchange" }
Q: align list items content at the same level What this the best way to accomplish the following? using tabular ? i dont want to use \hfill and pushing them to the end of the line. • list-item i want this • longggg-item and this to be aligned • another-item at the same level auto in a more general way • some text i want this same here • another text and this to be at the same here • not the same length same level after let say seconde level here A: Something like this? \documentclass{article} \newcommand\mybullet{{\tiny\raise0.5ex\hbox{\textbullet}\ }} % custom-size "bullet" \begin{document} \noindent \begin{tabular}{@{\mybullet}ll} list-item & i want this\\ longgg-item & and this to be aligned\\ another-item & at the same level auto\\ \end{tabular} \bigskip\noindent \begin{tabular}{@{\mybullet}lll} some text & i want this & same here\\ some other text & and this to be at the & same here\\ not the same length & same level after let say & seconde level here\\ \end{tabular} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Using an ImmutableJS Object as the React Component State I am trying to use ImmutableJS to help maintain state in a React component. I can use it just fine if the state contains an immutable object. But, if the entire state is an immutable object, then it fails whenever I try to setState() with an error that says TypeError: this.state.get is not a function. Below is a minimal example to reproduce the error. Every time the increment button is pushed, the count variable should be incremented and re-rendered. Please help me understand why this approach does not work. Thanks! import React from 'react'; import { Map as ImmutableMap } from 'immutable' class App extends React.Component { constructor (props) { super(props) this.state = ImmutableMap({ count: 0 }) // entire state is immutable } increment () { const newCount = this.state.get('count') + 1 this.setState(prevState => prevState.set('count', newCount)) } render() { return ( <div> { this.state.get('count') } // produces error after setState() <button onClick={this.increment.bind(this)}>Increment</button> </div> ); } } export default App; A: See this part of the docs. When you call setState(), React merges the object you provide into the current state. So after setState you'll be left with an empty object. Here's another related resource: https://github.com/facebook/immutable-js/wiki/Immutable-as-React-state Note that state must be a plain JS object, and not an Immutable collection, because React's setState API expects an object literal and will merge it (Object.assign) with the previous state. In the current version of the code, the actual merging of the state occcurs in ReactUpdateQueue.js within the getStateFromUpdate function with the following line: // Merge the partial state and the previous state. return Object.assign({}, prevState, partialState);
{ "pile_set_name": "StackExchange" }
Q: Join cell value into one cell when matches exist I have this four columns Handle Title Images Joined Images Dalmas HG Dalmas HG http://4b1e4d.jpg http://4b1e4d.jpg,http://ee78e4.jpg, http://7390f6.jpg Dalmas HG http://ee78e4.jpg Dalmas HG http://7390f6.jpg Klyftig Klyftig http://7390f6.jpg Klyftig http://8ffa40.jpg Klyftig http://f1627e.jpg Klyftig http://f21eda.jpg Klyftig http://6001d2.jpg Then I would like to join the images if they have the same handle. But I cannot find out the riddle on how to. This is how I'm trying to solve it DALMAS =if(A2=B2,JOIN(",", C2:C4),IFERROR(VLOOKUP(C2:C,3,FALSE))) KLYFTIG =if(A5=B5,JOIN(",", C5:C9),IFERROR(VLOOKUP(C2:C,3,FALSE))) Returns : http://4b1e4d.jpg,http://ee78e4.jpg, http://7390f6.jpg But that means that i manually needs to change the index when I getting to the next handle. Any ideas on how to solve this more dynamically? I have this spreadsheet that have the formulas. Google Sheet A: I made a copy of your sheet here. This formula seems to work, and should work for up to about 5,000 images? maybe more. depends on how many sets there are. it uses what I (and some others) call a Query() "smush". It's a sort of a trick using the query header parameter to join a whole bunch of data together by column. =ARRAYFORMULA(TRANSPOSE(SUBSTITUTE(TRIM(QUERY(IF(TRANSPOSE(D2:D)=VLOOKUP(ROW(A2:A),FILTER({ROW(A2:A),A2:A},A2:A<>""),2),B2:B&CHAR(10),),,9^9)),CHAR(10),",")))
{ "pile_set_name": "StackExchange" }
Q: windows application to get battery status of connected android phone Is there any way get the battery status of android phone (Samsung Galaxy SIII specificaly) connected to you PC in your C#.NET windows application which is running on your PC?? Thanks in advance. I think we have to take help of samsung mobile phone driver for this. A: Take a look at the AndroidLib.dll Library. Dan has a Class that will handle device battery level reporting with the device booted in normal boot(i.e. Normal rom bootup) Main thread for AndroidLib http://forum.xda-developers.com/showthread.php?t=1512685 For Documentation about AndroidLib http://www.regawmod.com/software/windows/androidlib/current/documentation/index.html // Example Code using AndroidLib.dll private void button1_Clicked(object sender, EventArgs e) { string serial; android = AndroidController.Instance; android.UpdateDeviceList(); serial = android.ConnectedDevices[0]; device = android.GetConnectedDevice(serial); // this will give the label lblsomelabel the Value of the device battery level. lblsomelabel.Text = device.Battery.Level.ToString(); lblsomelabel.Text += "%"; } using a form with a button named button1 And a Label named lblsomelabel You will get the Connected Devices serial and then associate it with device. the library then can be called to pull the battery level as indicated. Hope this helps. Dan's Github has examples of his code in use as well as you can look at the git hub to better understand his calls.
{ "pile_set_name": "StackExchange" }
Q: Thom's seminal cobordism paper in English? In Quelques proprietes globales des varietes differentiables, Thom classifies unoriented manifolds up to cobordism. I've been struggling a bit to understand this paper, and while Stong's cobordism notes have helped a bit, I was wondering if an English translation (of the entire paper or just parts) exists. Thank you in advance. A: An English translation of this paper is included in the first volume of the "Topological Library", edited by Novikov and Taimanov. See the following website : http://www.worldscibooks.com/mathematics/6379.html By the way, Thom's paper is rather hard to read. There are alternative expositions (often with somewhat easier proofs) of various pieces of it in various places. What portion in particular is giving you trouble? A: An English translation is also available online here: http://math.mit.edu/~hrm/kansem/thom-some-global-properties.pdf
{ "pile_set_name": "StackExchange" }
Q: Can we achieve 'Filtering on Examples' based on karate.env Can we achieve 'Filtering on Examples' that we have on Jbehave Sample below: * def request = { item: '#(item)' } Examples: |karate.env: |item | |@dev |778983-110833-110834| |@qa |848079-419456-419457| What we need to achieve is: Karate DSL to execute the tests in Examples table based on the current value of karate.env Karate must create a request = { item: '778983-110833-110834' } if i run tests in dev environment & { item: '848079-419456-419457' } if i run tests in qa. I was unable to achieve this by using karate.env property but achieved it using the tags, please refer to example below: Feature: Background: * url 'https://reqres.in/api' * configure headers = { 'Content-Type': 'application/json'} Scenario Outline: * def reqJson = { "name": "name", "job": "<item>"} And path 'users' And request reqJson When method post Then status 201 And match response.job == '<item>' @dev Examples: | item | | 111| @qa Examples: | item | | 222| Triggering on commandline for environment=qa : mvn test -Dcucumber.options="--tags @qa" Triggering on commandline for environment=dev : mvn test -Dcucumber.options="--tags @dev" Please let me know if there is any other way of achieving it since i wanted to use karate.env property. A: I think you are looking for this: https://github.com/intuit/karate#tags-and-examples A little-known capability of the Cucumber / Gherkin syntax is to be able to tag even specific rows in a bunch of examples ! You have to repeat the Examples section for each tag. The example below combines this with the advanced features described above. Scenario Outline: examples partitioned by tag * def vals = karate.tagValues * match vals.region[0] == '<expected>' @region=US Examples: | expected | | US | @region=GB Examples: | expected | | GB | EDIT: for those landing here trying to do this, I suggest another approach, you can call a feature like this: * call read('foo-' + karate.env + '.feature') Remember, Karate can read from JSON (or CSV) files and you can use that to drive Examples: https://github.com/intuit/karate#dynamic-scenario-outline And finally, I don't recommend this much - but if you want to achieve the logic to NOT run a test for a particular karate.env value, you can do this via karate.abort(): * if (karate.env == 'prod') karate.abort() Just add that line just after the Scenario: and the test will be skipped when needed.
{ "pile_set_name": "StackExchange" }
Q: How to display emails in an angular app like it gets displayed in an email client I am currently trying to develop a web app to display EMails to the user. It is important for me that the emails get displayed like they get in an email client (e.g. gmail). I use the gmail api to import emails to my database then I get the messageparts from the emails into my angular app. The problem is that I am not able to display html emails with the propert styling. It seems like html tags get used correclty but the original styling seems to be lost I am using angular 7, and spring boot. To collect the Emails I use the gmail api and import them into a postgresql database. I tried to use iframes so my app styling doesn't get in the way of the email styling but it gets displayed the same way. How I prepare the emails private String getMessageContent(Message message) { StringBuilder stringBuilder = new StringBuilder(); try { if(message.getPayload().getParts() != null) { handleEmailMainContent(message.getPayload().getParts(), stringBuilder); byte[] bodyBytes = Base64.decodeBase64(stringBuilder.toString()); return new String(bodyBytes, "UTF-8"); } else { return ""; } } catch (UnsupportedEncodingException e) { System.out.println("UnsupportedEncoding: " + e.toString()); return message.getSnippet(); } } private void handleEmailMainContent(List<MessagePart> messageParts, StringBuilder stringBuilder) { for (MessagePart messagePart : messageParts) { switch (messagePart.getMimeType()) { case "text/plain": handleMimeTypeTextPlain(messagePart, stringBuilder); break; case "text/html": handleMimeTypeTextHtml(messagePart, stringBuilder); break; default: break; } } } Note: selectedEmail.mainContent is the String I build above Example The content inside mainContent are phishing emails I try to collect and display. The example is a html email I try to display. I ommited the links and most of the spam content. ---------- Forwarded message --------- Von: emailaddress Date: Fr., 10. Mai 2019 um 22:06 Uhr Subject: Name, Give mom the gifts she wants To: emailaddress image Become part of the Heally family on Facebook link ! - LET'S TALK Celebraing Mom ... Moms run the world. They literally give us life, take on one of the hardest roles, and do it all without an end to their workday or any time off. While moms deserve to be celebrated year-round, Mother’s Day is a special time to make sure they know they’re loved and appreciated. LEARN MORE link Looking for CBD only Products? PROMO CODE: SAVECBD20 link CBD 20% OFF link Give mom gifts that she actually wants. Shop the Marketplace -ommited SPAM- You are receiving this email because you or your medical provider have registered for a Heally account. Unsubscribe link Copyright (C) 2019 Heally Inc. All rights reserved. Unsubscribe own Example I tried to send a minimalistic html email to myself containing this content: *dummy* <div dir="ltr"><i>dummy</i></div> and it worked just fine. Maybe the problem is an external class which does not get displayed/loaded and/or not exported by the gmail api How I tried to display it <mat-card> <mat-card-title> Current Email </mat-card-title> <mat-card-content [innerHTML]="selectedEmail.mainContent"> </mat-card-content> </mat-card> I want to display emails like they get displayed in gmail instead I was only able to display plain text and basic styling through html tags. I don't understand at which of my steps the styling gets lost or if I do not correctly display the emails. A: Angular security Blocks dynamic rendering of HTML and other scripts. You need to bypass them using DOM Sanitizer. Read more here : Angular Security DO below changes in your code : // in your component.ts file //import this import { DomSanitizer } from '@angular/platform-browser'; export class TestComponent{ public htmlData :any ; // in constructor create object constructor( ... private sanitizer: DomSanitizer ... ){ } someMethod(){ /* this method must be called after getting the value of selectedEmail.mainContent from service */ this.htmlData = this.sanitizer.bypassSecurityTrustHtml(selectedEmail.mainContent); // this line bypasses angular security } } And in compoenent.html <div [innerHtml]="htmlData"> </div> Here is the working StackBlitz : Working Demo
{ "pile_set_name": "StackExchange" }
Q: How do i use this class in the main function? Dictionaries and indexers (Collections) I am trying to add entries in dictionary array list but i don't know which arguments to set in the People Class in the main function. public class People : DictionaryBase { public void Add(Person newPerson) { Dictionary.Add(newPerson.Name, newPerson); } public void Remove(string name) { Dictionary.Remove(name); } public Person this[string name] { get { return (Person)Dictionary[name]; } set { Dictionary[name] = value; } } } public class Person { private string name; private int age; public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } } using this seem to give me error static void Main(string[] args) { People peop = new People(); peop.Add("Josh", new Person("Josh")); } Error 2 No overload for method 'Add' takes 2 arguments A: This peop.Add("Josh", new Person("Josh")); should be this var josh = new Person() // parameterless constructor. { Name = "Josh" //Setter for name. }; peop.Add(josh);//adds person to dictionary. The class People has the method Add which only takes one argument: a Person object. The Add on the people class method will take care of adding the it to the dictionary for you and supplying both the name (string) argument and the Person argument. Your Person class only has a parameterless constructor, which means that you need to set your Name in the setter. You can do this when you instantiate the object like above.
{ "pile_set_name": "StackExchange" }
Q: Custom keyboard primaryCode from onPress is always zero Here is my problem. I have a custom keyboard that I am dynamically adding keys to but anytime I try to catch the keys being pressed I don't catch anything useful. The only callback that gets triggered is onPress and it is supposed to have the keys primaryCode as an argument. The problem is that this primary is always 0 even if I try to change it when I create the key. How can I get the primaryCode to reflect the primary code of the key that was pressed? Here is my keyboard.xml <Keyboard xmlns:android="http://schemas.android.com/apk/res/android" android:keyWidth="25%p" android:keyHeight="10%p"> </Keyboard> This is where I generate my keyboard keys, which works great. My keyboard looks exactly how it is supposed to. Keyboard.Row row = new Row(this); for (int i = 0; i < labels.size(); i++) { Keyboard.Key key = new Keyboard.Key(row); key.label = labels.get(i); key.text = labels.get(i); key.codes = new int[] { 'c' }; key.width = keyWidth; key.height = keyHeight; this.getKeys().add(key); } And I register for the listener in my fragment. keyboardView.setOnKeyboardActionListener(this); A: The problem was that I didn't have stub rows and keys in my keyboard.xml file. After adding them the issue was resolved.
{ "pile_set_name": "StackExchange" }
Q: Did Desmond Tutu criticize African missionaries for stealing land? The following quote has been widely attributed to Desmond Tutu: When the missionaries came to Africa, they had the Bible and we had the land. They said “let us close our eyes and pray.” When we opened them, we had the Bible, and they had the land. Examples of the attribution: Tumblr Homelands Productions Afhir Europe - misspelling his name, and describing him as an 'African novelist'. Think Exist Scots Independent, attributing the source as The Observer. The Guardian Desmond Tutu is an outspoken activist, but this sentiment seems unlikely coming from a former Archbishop and Primate of the Anglican church. None of the attributions I found suggested when and where he uttered these words. The quote has also been attributed to Jomo Kenyatta, former Prime Minister and then President of Kenya. I am unfamiliar with him, and the attribution might be apocryphal, but it seems a little more plausible, at least. A: Wikiquote mentions this. As quoted in Desmond Tutu: A Biography (2004) by Steven Gish, p. 101; this is a joke Tutu has used, but variants of it exist which are not original to him. So he didn't make it up, but he did say it. He may not have meant it completely seriously. On the other hand he may have thought it humourous way of presenting a significant truth. Being a Christian doesn't automatically mean you approve of everything other Christians do. Here is an extract from the book, giving more context. Before [Tutu] left for the Nobel Prize Ceremony in Oslo, Norway, he spoke at the Waldorf-Astoria Hotel in New York City, and told one of his favorite stories. "When the missionaries came to Africa, they had the Bible and we had the land. They said “let us close our eyes and pray.” When we opened them, we had the Bible, and they had the land."
{ "pile_set_name": "StackExchange" }
Q: Getting number of characters in a unicode string in python How can I get the number of codepoints in a string which may contain unicode characters 3 byte long. https://unicode-table.com/ For example for "I❤U" I would like to get 3. Doing len(str) returns the number of bytes, so for the above example I would get 5. A: Try to decode it in python2: "I❤U".decode('utf-8') Output: u'I\u2764U' then len("I❤U".decode('utf-8')), it will be 3
{ "pile_set_name": "StackExchange" }
Q: Tkinter is opening new windows when running a function in a thread Hi all I am using python 2.7.15 and tkinter. It is a simple GUI with some buttons. Once a button is pressed I need to start a function in a thread (I do not need to open any new windows). What is happening is for each thread a new GUI copy of the program is opened. Is there any way to start a function (that does some calculations) without popping up a new copy of the Tkinter gui? I am making a thread like this: thread = Process(target=functionName, args=(arg1, arg2)) thread.start() thread.join() EDIT: here is some code to reproduce. As you can see, all I am interested in below "sample" is to run one function. Not to clone the whole program. from Tkinter import * from multiprocessing import Process window = Tk() window.title("Test threadinng") window.geometry('400x400') def threadFunction(): sys.exit() def start(): thread1 = Process(target=threadFunction) thread2 = Process(target=threadFunction) thread1.start() thread2.start() thread1.join() thread2.join() btn = Button(window, text="Click Me", command=start, args=()) btn.grid(column=1, row=1) window.mainloop() Thank you. A: Since the child process will inherit resource from parent process, that means it will inherit tkinter from parent process. Put the initialization of tkinter inside if __name__ == '__main__' block may solve the problem: from tkinter import * from multiprocessing import Process import time def threadFunction(): print('started') time.sleep(5) print('done') def start(): thread1 = Process(target=threadFunction) thread2 = Process(target=threadFunction) thread1.start() thread2.start() thread1.join() thread2.join() if __name__ == '__main__': window = Tk() window.title("Test threadinng") window.geometry('400x400') btn = Button(window, text="Click Me", command=start) btn.grid(column=1, row=1) window.mainloop()
{ "pile_set_name": "StackExchange" }
Q: How can I make MdiChild forms be in tabs in C#? I have a MDIparent Forma and which has some mdichild forms in it. Can you help me some how put the mdichilds in Tabs like google chrome , firefox , IE , Opera ... A: There's a good article on MDI forms with TabControls here: http://www.codeproject.com/KB/cs/MDITabBrowsing.aspx
{ "pile_set_name": "StackExchange" }
Q: Azure toolkit is not working I am trying to deploy a Spring Boot app to Azure using IntelliJ, I started with their formal tutorial about deploying a web app : https://docs.microsoft.com/en-us/java/azure/intellij/azure-toolkit-for-intellij-create-hello-world-web-app I downloaded the toolkit and followed the tutorial step by step , but after I choose the "Run on web app" in the Azure option, no dialog box shows and nothing happens. I don't understand where is the problem, any help ? Thank you A: I have successfully created a Hello World web app for Azure using IntelliJ: I would suggest you to check whether you have missing any prerequisites mentioned in this article. Once you have Installed Azure Toolkit for IntelliJ, you should restart IntelliJ and create a new project.
{ "pile_set_name": "StackExchange" }
Q: Permission error when saving a document I've workflow application using 8 xpages. It was working fine upto this moment and all of sudden when saving new document for any xpage, it started giving the following error: Unexpected runtime error The runtime has encountered an unexpected error. Error source Page Name:/XpNew.xsp Exception Error saving data source document1 Could not save the document 44F2A NotesException: Notes error: You cannot update or delete the document(s) since you are not listed as an allowable Author for this document Even though I've manager access to the database. It is also weird that it started giving error on test and production server. I also ran compact with -c and still the same issue. Ran Fixup and still same issue. A: In this situation, since it appears to be a core Notes exception and not anything at the XSP layer, I'd look into ACLs first. Are you manager by way of being in a group? And if so, has that group changed in any way recently, or is it specified in a secondary Directory referenced via Directory Assistance? I've had situations where the HTTP task just sort of "forgets" group membership from a secondary Directory until I restart it. Another potential source of trouble could be the "Maximum Internet name and password" field on the database's ACL's Advanced tab - if that's set to Author, it will override whatever your real access is. As a troubleshooting step, I'd make an XPage with this in a computed text item: database.queryAccess(session.getEffectiveUserName()); That should return your numeric access level. Additionally, to check on the first paragraph's theory, you could add a Form or Page with a computed value of: @UserNamesList That will give you a list of all effective names, groups, and roles for the current user in the current database.
{ "pile_set_name": "StackExchange" }
Q: Paypal, how do I find out when someone makes a purchase? In General: C# Server Getting transactions from hosted items Type: Shopping Cart Type: Subscriptions Data: Custom field Callbacks? Not web I am setting up a Minecraft server and require purchases to be recognised as soon as possible, is there a way to get callbacks when purchases are made and if there isn't - how would I get payment history? List Payment Resources has been a complete waste of my time looking into for this topic as it finds transactions with the API but I can't see any other parts in which I could find transactions from the generated hosted buttons. Does anyone know of where to get this information and with better documentation - as so far PayPal has been the worst API to work with. A: Before using IPN, choose a payment product which gives you immediate response when a payment is made. For example, you may choose Express Checkout with Classic API (https://developer.paypal.com/webapps/developer/docs/classic/express-checkout/gs_expresscheckout/) or Payment with REST API (https://developer.paypal.com/webapps/developer/docs/api/#payments). They both return immediate response when the payment is made, and you will immediately know if the payment is successful. In this case IPN works as a secondary means of notification, and it also serves other purposes: disputes, chargebacks, etc. But yes, IPN can be used if you have to choose Website Payments Standard, meaning the Buy Now button, Shopping Cart button, Subscription button, etc.
{ "pile_set_name": "StackExchange" }
Q: Rank of the matrices I want to ask, if rank of matrix with right side (Ab=3), is greater than the rank of the matrix without it (A=2) does it mean that matrix does not have solution? Thanks A: Yes, to determine whether there are no solutions, a unique solution or infinite many solutions, use the following conditions : $1)$ The matrix $A$ and the matrix emerging by concatenating $A$ and $b$ must have the same rank. If this is not the case, there is no solution. If it is the case, then continue with $2)$ $2)$ If the rank of the matrix $A$ is equal to the number of unknowns, the solution is unique, otherwise there are infinite many solutions.
{ "pile_set_name": "StackExchange" }
Q: How to compare a session variable with a string in C#? i edited the question it still does not work, the user writes appendix then press OK in Login, nothing happens here is the login (vb.net) Partial Class login Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Session("passcode") = TextBox1.Text Response.Redirect("Default.aspx") End Sub End Class and here is the default page C# public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["passcode"] == "appendix") { Response.Write("OK !"); } else { Response.Redirect("login.aspx"); } } } A: You probably mean Session["passcode"] == "Appendix" In C# (unlike VB), == is the equality operator and = is the assignment operator.
{ "pile_set_name": "StackExchange" }
Q: Jquery .load() doesn't seem to be working in firefox I've tried to find the answer to this by searching through Stackoverflow, and I've found a lot of closely related answers, but none seem to give me quite what I'm looking for. Most are much more complicated scenarios and just don't apply. Anyhow, what I'm doing is calling to a certain page of my site using the url, and then as well identifying a specific element on the page to be loaded into another div #getter. This script works flawlessly in IE and Chrome, but I'm having no luck at all with Firefox. Any ideas? Here is the code: <script> $("#getter").load("http://$domain/member/?show=feed .content"); </script> A: Try this code (with out domain): <script> $("#getter").load("/member/?show=feed .content"); </script>
{ "pile_set_name": "StackExchange" }
Q: Compile PHP into Static Binary I need to run a php script on a system with a somewhat broken PHP install. Rather than trying to workaround the issues I want to just package my code with it's own PHP binary (I can execute an executable). I want to just have a simple php binary that has all the modules I need compiled in. My general process is: ./configure --enable-static --enable-cli --disable-all This gives me a php binary with no extensions. From here I can add the extensions I need. For example to add curl and json support ./configure --enable-static --enable-cli --disable-all --with-curl --enable-json This seems to work well generally. My script needs libxml support for interacting with AWS. So I added --enable-libxml --enable-simplexml to the configure command. When I copy the binary to the remote machine it gets an error when trying to use the XML library that looks like: /usr/lib/x86_64-linux-gnu/libxml2.so.2: version `LIBXML2_2.9.0' not found Obviously it is dynamically linking to libxml2. I take this to mean that while the PHP extension is statically compiled into PHP, the library that the PHP extension is using is not. Running ldd confirms this: $ ldd sapi/cli/php linux-vdso.so.1 => (0x00007fff05cf3000) libcrypt.so.1 => /lib64/libcrypt.so.1 (0x00007f3c69f82000) libresolv.so.2 => /lib64/libresolv.so.2 (0x00007f3c69d68000) libcurl.so.4 => /lib64/libcurl.so.4 (0x00007f3c69afc000) librt.so.1 => /lib64/librt.so.1 (0x00007f3c698f4000) libm.so.6 => /lib64/libm.so.6 (0x00007f3c695ed000) libdl.so.2 => /lib64/libdl.so.2 (0x00007f3c693e8000) libnsl.so.1 => /lib64/libnsl.so.1 (0x00007f3c691cf000) libxml2.so.2 => /lib64/libxml2.so.2 (0x00007f3c68e66000) libz.so.1 => /lib64/libz.so.1 (0x00007f3c68c4f000) libc.so.6 => /lib64/libc.so.6 (0x00007f3c68890000) libfreebl3.so => /lib64/libfreebl3.so (0x00007f3c6860f000) libidn.so.11 => /lib64/libidn.so.11 (0x00007f3c683db000) libssh2.so.1 => /lib64/libssh2.so.1 (0x00007f3c681b1000) libssl3.so => /lib64/libssl3.so (0x00007f3c67f72000) libsmime3.so => /lib64/libsmime3.so (0x00007f3c67d44000) libnss3.so => /lib64/libnss3.so (0x00007f3c679fc000) libnssutil3.so => /lib64/libnssutil3.so (0x00007f3c677d0000) libplds4.so => /lib64/libplds4.so (0x00007f3c675cb000) libplc4.so => /lib64/libplc4.so (0x00007f3c673c6000) libnspr4.so => /lib64/libnspr4.so (0x00007f3c67188000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f3c66f6a000) libgssapi_krb5.so.2 => /lib64/libgssapi_krb5.so.2 (0x00007f3c66d20000) libkrb5.so.3 => /lib64/libkrb5.so.3 (0x00007f3c66a40000) libk5crypto.so.3 => /lib64/libk5crypto.so.3 (0x00007f3c6680a000) libcom_err.so.2 => /lib64/libcom_err.so.2 (0x00007f3c66606000) liblber-2.4.so.2 => /lib64/liblber-2.4.so.2 (0x00007f3c663f7000) libldap-2.4.so.2 => /lib64/libldap-2.4.so.2 (0x00007f3c661a4000) /lib64/ld-linux-x86-64.so.2 (0x00007f3c6a1d7000) liblzma.so.5 => /lib64/liblzma.so.5 (0x00007f3c65f7f000) libssl.so.10 => /lib64/libssl.so.10 (0x00007f3c65d12000) libcrypto.so.10 => /lib64/libcrypto.so.10 (0x00007f3c6592b000) libkrb5support.so.0 => /lib64/libkrb5support.so.0 (0x00007f3c6571c000) libkeyutils.so.1 => /lib64/libkeyutils.so.1 (0x00007f3c65518000) libsasl2.so.3 => /lib64/libsasl2.so.3 (0x00007f3c652fa000) libselinux.so.1 => /lib64/libselinux.so.1 (0x00007f3c650d6000) libpcre.so.1 => /lib64/libpcre.so.1 (0x00007f3c64e6f000) As you can see there are many libraries that are dynamically linked to my php binary. I am guessing it was generally working because my target system had a lot of these same libraries but not the libxml library. So my question is, how do I make a completely static binary with no dependencies on shared libraries. I realize this will make my executable bigger but it would also mean I can package my php executable with the code and it will work on any 64-bit linux machine. A: I have found a solution although it's a bit messier than I would like. I am leaving the libxml as a shared object and just including it with my code package and using the LD_LIBRARY_PATH environment variable so that it loads my shared library objects instead of the ones installed on the system. Ideally I would like just a single binary file but this solution works. It also has the slight advantage of using the system libraries if those are suitable (i.e. my code package doesn't have to include all the shared libraries). But I would still be interested in knowing if there is a way to compile a completely static php binary.
{ "pile_set_name": "StackExchange" }
Q: Get name of bluetooth device on the Devices and Printers window I know there are questions out there referring to gathering the friendly name of a device on the Device Manager but I cannot do this as the device is simply referred to as "Stardard Serial over Bluetooth link (COM)" and I have many virtual ports with the same reference. I want the name of the device as shown on the Devices and Printers window on: I'm doing this in C# and currently just getting a list of available COM ports on the system and selecting the one I know from memory. A: I managed to get it to work using 32Feet.Net. You can search for a device by doing BluetoothClient client = new BluetoothClient(); devices = client.DiscoverDevicesInRange(); foreach (BluetoothDeviceInfo d in devices) { items.Add(d.DeviceName); } This will give a list of the friendly names you see on the Devices and Printers window rather than "Standard serial over Bluetooth Link". If you want the COM port like me or any other piece of information then you can simply do a WMI query such as System.Management.ManagementObjectSearcher Searcher = new System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort"); foreach (System.Management.ManagementObject Port in Searcher.Get()) { //your comparison or code here }
{ "pile_set_name": "StackExchange" }
Q: std::string::reserve not being honored to create std::string of exact capacity I am trying to allocate strings of exact capacity. This is being done to save on memory. The size of strings to be created is variable, but known before hand. I am trying to use reserve, but the capacity not honored and over-allocation is taking place. std::string str; str.reserve(21); str = "12345678901234567890"; std::cout << "size: " << str.size() << "\n"; std::cout << "length: " << str.length() << "\n"; std::cout << "capacity: " << str.capacity() << "\n"; The output of the above is as follows: size: 20 length: 20 capacity: 30 max_size: 9223372036854775807 I know that reserve is a non-binding request as described here Is there some method to ensure that strings of exact size are allocated. A: In short: No, there isn't. You can precisely control the size of a string, but not its capacity. C++ puts no restriction on what capacity implementations should take -- the implementation can choose whatever that (it thinks) is efficient. Only the size is fixed. P.S. Several tens of bytes are usually not considered a waste of memory. STL containers are designed for a compromise between time efficiency and space efficiency. A: You can use the following : std::string str; str = "12345678901234567890"; str.shrink_to_fit(); The output is as follows: size: 20 length: 20 capacity: 20
{ "pile_set_name": "StackExchange" }
Q: What happens with toInt() I currently start to learn Kotlin and I was making this code val a = "1" val b = a[0] val c = b.toInt() println(c) When I run the code, the result is 49. What really happened? Because I think the result will be 1. A: a is a String, which is a CharSequence. That is why you can access a[0] in the first place. a.get(0) or a[0] then returns a Char. Char on the other hand returns its character value when calling toInt(), check also the documentation of toInt(). So your code commented: val a = "1" // a is a String val b = a[0] // b is a Char val c = b.toInt() // c is (an Int representing) the character value of b If you just want to return the number you rather need to parse it or use any of the answers you like the most of: How do I convert a Char to Int? (one simple way being b.toString().toInt()).
{ "pile_set_name": "StackExchange" }
Q: Last Man Standing - closed form equation I wrote a matlab code inorder to find the last man standing for the problem given here. Problem: n people are standing in a circle with gun in their hands. 1 kills 2, 3 kills 4, 5 kills 6 and so on (circularly) till we are left with only one person. Who will be the last person alive. function N = lastManStanding(n) while length(n) ~= 1 if mod(length(n),2) == 0 for ii = 1:length(n)/2 a(ii) = [ii*2]; end n(a) = []; a = []; end if mod(length(n),2) == 1 for jj = 1:floor(length(n)/2) b(jj) = [jj*2]; end n(b) = []; n = circshift(n,[0,1]); b = []; end end N = n; What this code basically does is it takes a range array (1,....,n) as input and returns the last remaining index. I was wondering if there exists a closed form equation to solve this or if the above code can be simplified further. UPDATE Find the updated code below function N = lastManStanding(n) while length(n) ~= 1 if mod(length(n),2) == 0 n(2:2:end) = []; else mod(length(n),2) == 1 n(2:2:end) = []; n = circshift(n,[0,1]); end end N = n; A: Closed form solution: If you plot the "survivor" index i for n = 1:100 using your script, you will see a sawtooth shaped function which falls back to 1 for every n = 2^k, where k being integer values. Which means that at those points mod(n, 2^k) = 0. You can find 2^k to be the next minor multiple of 2 of n. Hence k is: k = floor(log2(n)); In between the edges of the function where n > 2^k the function rises with 2 * mod(n, 2^k). Since the function has an offset of 1 we can thus write the closed form solution as: i = 2 * mod(n, 2^k) + 1; or inline: i = 2 * mod(n, 2.^floor(log2(n))) + 1; The plot: UPDATE: This problem is also known as the Josephus problem. You can find a more general and mathematically rigorous derivation here: https://en.wikipedia.org/wiki/Josephus_problem. A: You can also solve this problem without loop, in a more mathematical way: %for n in [1,inf[ lastManStanding = mod(n,2.^floor((log(n)/log(2))))*2+1; As suggested by wolfie you can also use directly the function log2 lastManStanding = mod(n,2.^floor(log2(n)))*2+1; The function mod can deal with vector, so n can be a vector.
{ "pile_set_name": "StackExchange" }
Q: Bind click events to dynamically created html content I've got the following jQuery command to bind the click event when the specific element is dynamically created. $(".bill-remove-icon").live("click", function(){ $(this).parent().hide('slide',function(){$(this).parent().remove()}); }); But this code gives a firebug error : TypeError: $(...).live is not a function What am I doing wrong here? if this code is wrong, pls suggest a better method to bind events to dynamically created elements. A: Live is deprecated, you have to use delegation with .on(): $(document).on("click", ".bill-remove-icon", function(){ $(this).parent().hide('slide',function(){$(this).parent().remove()}); });
{ "pile_set_name": "StackExchange" }
Q: AngularJS and Play Framework model binding and templates I was wondering if anyone has figured out a good way to bind the model between Play Framework and AngularJS. For example you hit a URL and the page is generated by Play Framework using templates on the server-side for a given Person object. Now you want to use AngularJS to enable rich user experience and use that Person object within the JavaScript/AngularJS templates on the client-side. One way of doing this would be to make another Ajax call from AngulraJS and populate the JS model. This seem redundent with the first call to generate the page for that Person object. Another way would be to do something like this: person = @Html(FrontEnd.personToJSON(thisPersonObject)); But then you need to set the person object within the $scope. Moreover this seems like a hack since the whole object is in JSON format, will be placed inside the html page. I know there is better ways to architect this web app for example using SPA design where Play is just a service layer with a clean API for data retrieval and manipulation. This will enable you to do MVC strictly on the client-side. Any thoughts? A: Angular was designed to be one single page application, so you should avoid trying to bootstrap the page already with data. Instead, you should provide a restful API with your framework and use angular's resources or some alternative (e.g.: restangular) to receive and send data from the server. To sum up: Your application/site should only communicate with your framework using the an api. A: What you proposed is a viable approach with AngularJS. Another solution would be to run the javascript code on the server side, and then send the output to the browser (Similar to Airbnb's Rendr). However, nothing like this exists that I know of for AngularJS. It might not be possible because of the way the scopes are handled. With the bootstrapped javascript object approach, it's simple and you avoid visiting the server twice. So, Construct your app as a SPA client that consumes a REST API. Using server-side templating, render an extra javascript object with the data you want to bootstrap and include it on the page (or another js file). On the front-end, transfer the data from this bootstrapped javascript object into your $resource model. See this similar question with AngularJS and Rails. How to bootstrap data as it it were fetched by a $resource service in Angular.js For SEO, use this AngularJS SEO guide [1]. This guide was mentioned by AngularJS engineers at Google I/O [2]. [1] http://www.yearofmoo.com/2012/11/angularjs-and-seo.html [2] http://www.youtube.com/watch?feature=player_detailpage&v=HCR7i5F5L8c#t=2238
{ "pile_set_name": "StackExchange" }
Q: How to choose the row from a numpy's array for which a specific column's value is the largest? Given an array of a particular shape (m, n), I'd like to choose the whole row (or find its index) for which a specific's column value is the largest. Consider the array below. I'd like to find the row where a value of the second column is the largest. The biggest value of the second columns is 0.795, so I should return [0.21212121, 0.795]. array([[-3. , 0.5 ], [-2.93939394, 0.5 ], [-2.87878788, 0.5 ], [ 0.21212121, 0.795 ], [ 0.27272727, 0.785 ], [ 0.33333333, 0.785 ], [ 0.39393939, 0.77 ], [ 2.93939394, 0.5 ], [ 3. , 0.5 ]]) I have achieved the desired result in the following way: best_result = np.max(acc_m[:, 1]) row_with_best_res = acc_m[acc_m[:, 1] == best_result] where acc_m is the name of the array. The presented solution works, but I can't believe that there's no fancier, pythonic way to do this. A: Using np.argmax() In your case row_with_best_res = acc_m[acc_m[:, 1].argmax()]
{ "pile_set_name": "StackExchange" }
Q: DELETE request on a link in laravel 5.4 I am trying to hit a route I made to make a delete HTTP request in laravel view when user clicks on 'Delete' button, but it won't work. I've read it should be done with forms in laravel. Here is my code: <form action="/admin/pages/delete/{{ $section->id }}" method="post"> {{ method_field('delete') }} <button class="btn btn-sm" type="submit">Delete</button> </form> What is a proper way to handle this? It shows me an error in the console, Bootbox: 'please specify a message' whenever I click on the button. Route definition inside admin group: Route::delete('/pages/delete/{id}', 'PagesController@delete')->name('pages.delete'); A: I believe you are missing the csrf token in the form. You can add {{ csrf_field() }} just after your form starts. Visit this link for knowing more about csrf
{ "pile_set_name": "StackExchange" }
Q: Integrality of a certain quantity $\sum_{i =1}^n a_{\lfloor \frac{n}{i}\rfloor }=n^{10}, $ Problem :A sequence $a_1,a_2,\dots$ satisfy $$ \sum_{i =1}^n a_{\lfloor \frac{n}{i}\rfloor }=n^{10}, $$ for every $n\in\mathbb{N}$. Let $c$ be a positive integer. Prove that, for every positive integer $n$, $$ \frac{c^{a_n}-c^{a_{n-1}}}{n} $$ is an integer. I try : Note that the required proposition is true if both $a_n\geqslant n$ and $\phi (n)\mid a_n-a_{n-1}$ is true for all positive integer $n>1$. From the condition given, we get that $a_1=1$ and \begin{align*} (n+1)^{10}-n^{10}-1& =\sum_{j=1}^{n}{\left( a_{\lfloor \frac{n+1}{j}\rfloor }-a_{\lfloor \frac{n}{j}\rfloor }\right) }\\ & =\sum_{\substack{j\mid n+1 \\1\leqslant j<n+1}}{\left( a_{\frac{n+1}{j}} -a_{\frac{n+1}{j}-1} \right) } \\ & =\sum_{\substack{d\mid n+1 \\d>1}}{ (a_d-a_{d-1})} . \end{align*} Following work I can't A: You are in the right direction. Differencing yields $$\begin{eqnarray} n^{10} - (n-1)^{10} &=& a_1 +\sum_{1\leq i \leq n-1} (a_{\lfloor \frac{n}{i}\rfloor }-a_{\lfloor \frac{n-1}{i}\rfloor })\\ &=&a_1 + \sum_{i|n, i<n} (a_{\frac{n}{i} }-a_{\frac{n}{i}-1 })\\ &=&a_1 + \sum_{i|n, i>1} (a_{i }-a_{i-1 }) = \sum_{i|n} (a_{i }-a_{i-1 }) \end{eqnarray}$$ if we let $a_0 = 0$. Define $b_n = a_n - a_{n-1}$ and $p(n) = n^{10} - (n-1)^{10}$. By Mobius inversion formula, (see https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula) we have $$ b_n = \sum_{j|n} p(j)\mu(\frac{n}{j}). $$ What we show first is that $\phi(n) $ divides each $b_n$ for all $n\geq 1.$ To this end, we show the following claim: for each $r\geq 0$, $\sum_{j|n} j^r\mu(\frac{n}{j})$ has $\phi(n)$ as its factor. Proof goes like this. Let $$c_n = \sum_{j|n} j^r\mu(\frac{n}{j}).$$ Observe that $c_1 = 1$, hence $\phi(1) | c_1$. We first show $\phi(n)|c_n$ for $n = p^k$ where $p$ is a prime. This follows easily since $$ c_{p^k} = p^{rk} - p^{r(k-1)}, $$ and $$ \phi(p^k) = p^k - p^{k-1}. $$ (Note that $x-y | x^r - y^r$.) Next we show that $c_n$ is multiplicative, that is, for $p,q$ such that $(p,q)=1$, it holds that $c_{pq} = c_pc_q$. This also follows easily from $$\begin{eqnarray} c_{pq} &=&\sum_{j|pq} j^r\mu(\frac{pq}{j}) \\ &=& \sum_{n|p, m|q} (nm)^r\mu(\frac{pq}{nm})\\ &=&\sum_{n|p, m|q} n^r\mu(\frac{p}{n})\cdot m^r\mu(\frac{q}{m})\\ &=& \sum_{n|p} n^r\mu(\frac{p}{n})\cdot \sum_{m|q}m^r\mu(\frac{q}{m})\\ &=& c_p\cdot c_q. \end{eqnarray}$$ Since $\phi(n)$ is also multiplicative, these two facts prove the claim. So far we've shown that for every monomial $j^r$, it holds that $\phi(n) |\sum_{j|n} j^r\mu(\frac{n}{j})$. Thus it holds for any polynomial with integer coefficients, and especially for $p(j)$. This shows $$ \phi(n) \:|\: b_n = \sum_{j|n} p(j)\mu(\frac{n}{j}), $$ as we wanted. It remains to show $a_n \geq n$. Assume $c\cdot j^{10} \leq a_j \leq j^{10}$ for $j=1,2,\ldots,n-1$ for some $0<c<1$. Then we have $$\begin{eqnarray} a_n &=& n^{10} - \sum_{2\leq i \leq n} a_{\lfloor \frac{n}{i}\rfloor }\\ &\geq & n^{10} - n^{10}\sum_{2\leq i \leq n} \frac{1}{i^{10}} \\ &\geq & n^{10} (1-\sum_{2\leq i <\infty} \frac{1}{i^{10}}), \end{eqnarray}$$ and $a_n \leq n^{10}$. If we let $c = 1-\sum_{i=2}^{\infty}\frac{1}{i^{10}}\in (0.99,1)$, then by induction hypothesis, it holds for every $n\in \mathbb{N}$ once if we prove it for $n=1$. But this is obviously true, since $a_1 = 1$. Finally, we see that $$ a_n \geq c\cdot n^{10} \geq (c\cdot 2^9)\cdot n >500n $$ for all $n\geq 2$, establishing $a_n \geq n$.
{ "pile_set_name": "StackExchange" }
Q: How to solve the Cumulative Traveling Salesman Problem using or-tools in python? The objective of the Cumulative Traveling Salesman Problem (CTSP) is to minimize the sum of arrival times at customers, instead of the total travelling time. This is different than minimizing the overall time of travel. For example, if one has unlimited vehicles (# vehicles is the same as # of locations) and the objective is to minimize the overall time to locations, one would send one vehicle per location, for it is the fastest way to satisfy said demands. One can see that the or-tools routing module focuses mainly on minimizing the overall travel time (not the time to locations). Is there a way to solve the CTSP, and, even better, have a balance (maybe using weights) between minimizing time to locations vs. minimizing travelling time? Let me show an analytical example. Let's say we have a depot (0) and two customers (1 and 2). Let's consider the following time matrix: [[0, 10, 20], [10, 0, 15], [20, 15, 0]] Let's assume we have a number of vehicles equal to the number of locations (2 vehicles). Let's consider the following two situations: Objective 1: if we want to minimize overall travel time The solution is 0 -> 1 -> 2 -> 0 (one vehicle is used), where: travel time is 45. 0 -> 1: 10 + 1 -> 2: 15 + 2 -> 0: 20 = 10 + 15 + 20 = 45. locations time is 35. For location 1: 0 -> 1: 10. For location 2 (note that we have to pass through location 1): 0 -> 1: 10 + 1 -> 2: 15. In summation, we have: 10 + 10 + 15 = 35. Objective 2: if we want to minimize time to locations The solution is 0 -> 1 -> 0 and 0 -> 2 -> 0 (two vehicles are used), where: travel time is 60. For vehicle 1: 0 -> 1: 10 + 1 -> 0: 10. For vehicle 2: 0 -> 2: 20 + 2 -> 0: 20. In summation, we have 10 + 10 + 20 + 20 = 60. locations time is 30. For location 1: 0 -> 1: 10. For location 2 (note that we do not have to pass through location 1): 0 -> 2: 20. In summation, we have: 10 + 20 = 30. So... Can this be done? Can one solve the CTSP (objective 2)? Is it possible to have an objective function such that we could balance both of these objectives (i.e. min alpha * overall_travel_time + beta * time_to_locations, such that alpha and beta are weights). Python code is much appreciated. Thank you! Working code for objective 1: minimizing the overall travel time """Vehicles Routing Problem (VRP).""" from __future__ import print_function from ortools.constraint_solver import pywrapcp def create_data_model(): """Stores the data for the problem.""" data = {} data['time_matrix'] = [ [0, 10, 20], [10, 0, 15], [20, 15, 0] ] data['num_vehicles'] = 2 data['depot'] = 0 return data def print_solution(data, manager, routing, solution): """Prints solution on console.""" max_route_time = 0 for vehicle_id in range(data['num_vehicles']): index = routing.Start(vehicle_id) plan_output = 'Route for vehicle {}:\n'.format(vehicle_id) route_time = 0 while not routing.IsEnd(index): plan_output += ' {} -> '.format(manager.IndexToNode(index)) previous_index = index index = solution.Value(routing.NextVar(index)) route_time += routing.GetArcCostForVehicle( previous_index, index, vehicle_id) plan_output += '{}\n'.format(manager.IndexToNode(index)) plan_output += 'time of the route: {}\n'.format(route_time) print(plan_output) max_route_time = max(route_time, max_route_time) print('Maximum of the route times: {}'.format(max_route_time)) def main(): """Solve the CVRP problem.""" # Instantiate the data problem. data = create_data_model() # Create the routing index manager. manager = pywrapcp.RoutingIndexManager( len(data['time_matrix']), data['num_vehicles'], data['depot']) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) # Create and register a transit callback. def time_callback(from_index, to_index): """Returns the time between the two nodes.""" # Convert from routing variable Index to time matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['time_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(time_callback) # Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() # Solve the problem. solution = routing.SolveWithParameters(search_parameters) # Print solution on console. if solution: print_solution(data, manager, routing, solution) if __name__ == '__main__': main() Results for the above code Route for vehicle 0: 0 -> 0 time of the route: 0 Route for vehicle 1: 0 -> 1 -> 2 -> 0 time of the route: 45 Maximum of the route times: 45 A: This is a heuristic approach to the problem you describe using OR tools. Consider a procedure in which you “guess” what the maximum route duration is (across all routes), and will find this in a binary search fashion. Your guess, $G$, is between $L$ and $U$, and for a particular iteration, set it to $G=\frac{U+L}{2}$. At iteration 0, $L=0$and $U=\texttt{max duration vrp}$ (45 in your example). Now add a constraint to the problem using routing.AddDimension() that says that routes should have a duration less or equal to $G$. If the problem is feasible, then $U=G$ and update $G$. Otherwise, $L=G$ and update $G$. You do this until the $L$ and $U$ are arbitrarily close. Note that every time you update $G$, you need to update the constraint you added to the routing object (or create a new object from scratch).
{ "pile_set_name": "StackExchange" }
Q: Why these 2 dots frequently occur in dog's eyebrows? Do it serve/served any advantage? It has been wonder me, in spite of so-many variations in color-patterns in dogs; these 2 dots (1 on each eyebrow) remains frequently occurring. Dog-1 Dog-1 close up. this one has a white dot. photographed from Kolkata. this one is from Uttarakhand, Western Himalayas. Also has white dots. I've seen brown dots too, which I have not photographed, so I cite an example from internet (wikimedia: ) Now, my question is; why are these 2 dots are so conserved? Is it associated with some conserved region of a chromosome? or maybe it has/ had served any purpose or advantage (such as recognition or nonverbal communication or to mislead their prey since if the prey think of them as eyes; then they would miss the gazing direction of actual eye) so that it was selected by nature? Some sort of wolves too have similar paired-spots, so could I guess that once upon a time certain ancestor of all dogs and wolves contained these paired dots? PS. I've not found helpful discussion about that dots. From this webpage it seems to me, it is being called false-white black and tan atat genotype. Don't know have i understood correct or not... A: I suspect but can't prove that these markings are not adaptive, but are accidents or epiphenomena of the general genetic system that determines coat colour. On the one hand, an Australian Broadcasting Corporation documentary claims that canid eyebrows are adapted for social interaction: they have specialized muscles (which are not present in other carnivorous mammals such as cats), and ... One study showed foxes who hunt alone had about half the facial expressions of wolves who work in packs. In fact, in wolves and dingoes, the eyebrows are often even a different colour, exaggerating the movement. (they don't give any primary references). On the other hand (supporting my guess) a lot of the evolution of these colour patterns seems to have occurred after domestication. These markings (not the eyebrow spots in particular) seem to be called tan points: Red (tan) appears as pips above the eyes, on the sides of the muzzle extending to the cheeks, as pips on the cheeks, on the front of the neck just below the head, as two triangular patches on the front of the chest, on the lower legs and feet (and inside of the legs), and as a patch underneath the tail (and sometimes along the bottom edge of the tail too). (I don't know whether eyebrow contrast in animals that aren't strictly brown/black is caused by the same genes ...) A PhD thesis by Dayna Dreger (some material published in Journal of Heredity 2013:104(3):399–406 doi:10.1093/jhered/est012) The black-and-tan phenotype, associated with the at allele, is a predominantly eumelanistic phenotype, with phaeomelanin restricted to distinct regions on the lower limbs, cheeks, eyebrows, chest, and around the anus. (p. 7) Genome wide association study analysis, fine mapping, and sequence analysis identified a 16 bp tandem duplication in intron 5 of the hnRNP-Associated with Lethal Yellow (RALY) gene that segregates with the black-and-tan phenotype, versus saddle tan, in Basset Hounds and Pembroke Welsh Corgis. In breeds that never have the saddle tan phenotype, but frequently have the black-and-tan phenotype, the RALY duplication does not segregate with black-and-tan. This, together with further genotype analysis, suggests a gene interaction of ASIP, MC1R, DEFB103, RALY, and an additional modifier gene is required for expression of saddle tan or black-and-tan. (p. ii) Neither the coyote nor 9 of the 10 wolves had the RALY duplication and the tenth atypical wolf was heterozygous (+/dup) (Table 5.1), suggesting that the lack of the duplication is the ancestral or wild-type allele (+). It follows then that the saddle tan phenotype is ancestral to the black-and-tan phenotype, despite the relatively limited number of breeds that currently express the saddle tan phenotype, making black-and-tan a modification of the saddle tan phenotype. The popularity of the black-and-tan phenotype across breeds and breed types is likely explained by artificial selection for the striking black-and-tan phenotype over that of saddle tan. Since the saddle tan pattern is found primarily in terriers, scent hounds, and a small number of herding breeds, this finding may also shed light on the development and relation of modern dog breeds, hinting at common ancestors between breed types. A: I can't attest to the purpose of these "eye spots". But they do seem to be rather atavistic in nature. My last dog had them even though neither of his parents sported eye spots. I've seen them on other mixed breeds, completely unrelated to the breeds my dog derived from, whose owners reported none in the parents. This suggest an early origin and a possible selective advantage. There are "eye spots" on the wings of some butterflies and moths. Textbook explanations state these deter predators by giving them the impression they are looking at a larger, possibly predatory, animal. Not that that exactly applies here. If the spots were more largely separated than the eyes, it might be an argument for making the dog appear larger which might minimize conflicts with other predators. Maybe this idea still works if the eyespots look like larger eyes and convey a perception of a larger animal. A: Dogs are actually not prey animals and are pretty high up on the food chain, so the theory that the eye dots are "decoy eyes" doesn't make a whole lot of sense. Realistically speaking, dogs are pack animals, and use several parts of their body to interact and 'converse' with other dogs. One of these body parts are the eyes. Like humans, dogs can widen and narrow their eyes to show emotion. The eye dots simply accentuate these movements, aiding greatly in pack conversation while hunting. Besides that, they're just plain cute.
{ "pile_set_name": "StackExchange" }
Q: Jquery validate plugin -submitHandler set as default to work across multiple forms? I was trying to build this validation module using JQuery Validate Plugin, working across multiple forms. So, I decided to put the common functions/rules in the jQuery.validator.setDefaults() method that the plugin provides. So, only the success function of the plugin needs to be in different places. $("#myForm").validate( success: function(label){ window.location = someURL; } ); SubmitHandler was one of them (in the setDefaults method), and it doesn't seem to be working. I'm getting the default page on clicking submit, if the form is invalid. Is there a return false or preventDefault() kind of a thing for submitHandler()? $.validator.setDefaults({ submitHandler: function(form){ var url = $(form).attr('action') ; var data = $(form).serialize()+'&ajax_validation=1'; $.ajax({ url: url, data: data, type: 'POST', success: function(response) { //something } }); } }); Can anybody help? Somebody who has tried to deal with multiple forms using jQuery validate plugin? Help will be appreciated. Let me know if elaboration needed. A: Add a return false at the end of the submitHandler callback to prevent the default form action. $.validator.setDefaults({ submitHandler: function(form) { var url = $(form).attr('action') ; var data = $(form).serialize()+'&ajax_validation=1'; $.ajax({ url: url, data: data, type: 'POST', success: function(response) { //something } }); return false; // <-- add this line } }); DEMO: http://jsfiddle.net/SySGN/1/ Edited jsFiddle with OP's inline class rules. Still working the same. EDIT 2: I just noticed the content of your success function. $("#myForm").validate( success: function(label){ window.location = someURL; // <-- WHY?! } ); What are you trying to do with that? When exactly do you think success fires? Why would you try to load a new URL in the middle of validating the form? Quote OP: "I'm getting the default page on clicking submit, if the form is invalid" That's because as soon as you fill in the first field, success fires and redirects the page to someURL. How do you expect the user to finish filling in the form if you change to a new page before he's done? success is simply a callback function that fires to show the label whenever an element passes validation. It was designed for things like placing icons next to successfully filled in fields and such. The success callback function, as per jQuery Validate docs: If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like “ok!”. You're already submitting the form with .ajax(), so reloading the page at any point in the process defeats the whole purpose of .ajax(). I cannot even suggest alternative code since I can't imagine what you're trying to do. All I can say is that you'd only use the submitHandler callback to fire code upon submit after the whole form passes validation. Is it possible you got jQuery Validate success confused with .ajax() success? The latter is already inside the .ajax() which is inside your submitHandler. However, again, .ajax() allows you to submit data without reloading the page, so a redirect to another page makes the .ajax() totally pointless.
{ "pile_set_name": "StackExchange" }
Q: Generate padding bytes for a structure by nesting it in a union I was going through this question to reaffirm my understanding of structure padding.I have a doubt now. When I do something like this: #include <stdio.h> #define ALIGNTHIS 16 //16,Not necessarily union myunion { struct mystruct { char a; int b; } myst; char DS4Alignment[ALIGNTHIS]; }; //Main Routine int main(void) { union myunion WannaPad; printf("Union's size: %d\n\ Struct's size: %d\n", sizeof(WannaPad), sizeof(WannaPad.myst)); return 0; } Output: Union's size: 16 Struct's size: 8 should I not expect the struct to have been padded by 8 bytes? If I explicitly pad eight bytes to the structure, the whole purpose of nesting it inside an union like this is nullified. I feel that declaring a union containing a struct and a character array the size of the struct ought to be but isn't, makes way for a neater code. Is there a work-around for making it work as I would like it? A: should I not expect the struct to have been padded by 8 bytes? No, as the struct mystruct is seen/handled on its own. The char had been padded by 3 sizeof (int) -1 bytes to let the int be properly aligned. This does not change, even if someone, somewhere, sometimes decides to use this very struct mystruct inside another type.
{ "pile_set_name": "StackExchange" }
Q: CSS Equal Height Columns - Ugh! Again? Right, worst question in the history of web design. Who cares, just choose an option. So my question is like this... What is the best answer to be standards compliant and (backwards) browser compatible? jQuery used for layout which is supposed to be reserved for css and html OR Negative margin, extra containers , or other hacks or bloat? Already spent too much time on this but looking for the "professional" way to do it. EDIT: Here is a code example using Alexander's method. A: Usually I use pure css/html solution which works in 99% cases: I have a parent div with background-repeat on 'Y' axe. The general structure is going to be like this : html: <div id="container" class="clearfix"> <div class="LeftPane"></div> <div class="CenterPane"></div> <div class="RightPane"></div> </div> css: #container{ background:url(imagePath) 0% repeat y; } for background image you can apply image for the borders, or everything else what can make users to think that all 3 blocks have the same height
{ "pile_set_name": "StackExchange" }
Q: Did Miki really never bully Shoko? When Shoya confronts Miki in the story to ask whether she told anyone about him bullying Shoko, Miki makes the claim that she never once badmouthed Shoko, and that she always told Shoya to stop. Miki is portrayed as manipulative, but Shoya also admits that he might not remember things correctly: Miki is right... I probably altered my memories to make myself feel better. (Volume 5, page 112) Could this be a case of an unreliable narrator? Can Miki's claim be validated? A: Points For Miki: Having reread the first volume, Miki's claim actually does have a great deal of credence. She is often seen helping Shoko, informing her on page 80 when the teacher calls on Shoko, and showing her which question the teacher asked on page 69. Bonus points for copying the homework assignment for Naoka when Shoko's questioning caused her to miss what the teacher said (this helps Shoko, albeit indirectly). Additionally Miki does, in fact, tell Shoya to knock it off several times: Stop goofing off, boys! (Volume 1, page 100, after Shoya dumps a dustpan on Shoko outside) This happens after Shoya dumps a dustpan on Shoko, who is outside the window. See? I told you to knock it off! (Volume 1, Page 106) Miki says this after Shoya injures Shoko by pulling on her hearing aid apparatus. Notably, her alleged first call to "knock it off" is suspiciously missing from the narrative. Miki also attempts to shield Shoko from harm in several instances. First, when Naoka rudely asks Shoko whether she can speak Japanese, Miki says, Haha... That's not a nice way to put it. (Volume 1, page 73) When Shoko asks for clarification for what Naoka said, Miki writes in Shoko's notebook, changing the question to "Do you have a nickname?" Second, Miki is present when Shoko sees the mean messages written on the chalkboard by Shoya and friends. It's unclear if the message is actually communicated to Shoko since she's deaf, but Miki says, It's awful, isn't it? I mean, really...(Volume 1, page 97) In cases where her friends are badmouthing Shoko, it is actually true that Miki does not participate. Rather, she gives diplomatic replies, such as "I know, right?" and "I know what you mean." (Volume 1, pages 105 and 80). She acknowledges her friends' grievances against Shoko, but does not levy any of her own. Shoya is also shown to be, to a degree, oblivious to the people around him, lending credence to the idea that he might not be the most reliable narrator. When he's doing his daredevil stunts, his two friends show a declining interest in continuing, but Shoya doesn't notice, and it hits him like a brick wall when they outright tell him they don't want to keep jumping off bridges. In high school, he puts mental X's over everyone's faces, further showing that he doesn't pay attention to other people. Since the first volume is almost entirely told from Shoya's perspective, a case might be made that any memories in the narrative he has of Miki being mean to Shoko are fabricated or exaggerated. Thus one wonders whether Shoya's claim on Volume 1, page 124 can be trusted: And if you count insults, the girls badmouthed her more than anyone! Especially Miki and Naoka! Naoka, certainly. But Shoya may just be lumping Miki in because she was part of the conversation. Points Against Miki: Probably the most damaging point against Miki is her friendship with Naoka, who is definitively known to have bullied Shoko. In spite of this, Miki defends Naoka to the teacher, saying Naoka did more than anyone to keep Shoya in line on page 123. It is possible that Miki just willfully looked the other way when Naoka was bullying Shoko, or, less likely, that she was unaware of the worse offenses Naoka perpetrated. But her strong association with Naoka does lead credence to the idea that she also badmouthed Shoko, even if there is no instance in the manga of this happening. Secondly, Miki may have been present at the aforementioned blackboard incident when Shoya and friends were writing the messages. On page 95, there is a panel showing the legs of several characters. One pair of socks does resemble Miki's. If so, then this quote would be attributed to her: When you get in trouble, I had nothing to do with this! (Volume 1, page 95) She seems to be trying to discourage them, so it's unlikely she took part directly. On the other hand, this means she could have erased the messages before Shoko saw them. Thirdly, Miki laughed at the Shoya's joke on page 102 about Shoko being deaf because they forgot to write the sutras on her ears. Initially, she does give Shoya a disapproving look, but after the teacher laughs, she laughs too. She even contributes clarification on the joke, saying, "Hoichi the Earless?", and thus giving it her stamp of approval (in her defense, as an honor student, she likely couldn't resist classical/literary allusions). Conclusion: I suspect that Miki really was doing her best to help Shoko. Her classmates did have legitimate grievances against Shoko, so Miki likely didn't know what to do or who to side with as the class turned increasingly hostile. She didn't stick out her neck for Shoko, so as to keep a target from being put on her, but she did her best to moderate in an impossible situation that could not be handled by children. However, there is a great deal of ambiguity to the character in the story, and I invite everyone to review the character's words and actions and come to their own conclusion.
{ "pile_set_name": "StackExchange" }
Q: How to check if there's nothing to be committed in the current branch? The goal is to get an unambiguous status that can be evaluated in a shell command. I tried git status but it always returns 0, even if there are items to commit. git status echo $? #this is always 0 I have an idea but I think it is rather a bad idea. if [ git status | grep -i -c "[a-z]"> 2 ]; then code for change... else code for nothing change... fi any other way? update with following solve, see Mark Longair's post I tried this but it causes a problem. if [ -z $(git status --porcelain) ]; then echo "IT IS CLEAN" else echo "PLEASE COMMIT YOUR CHANGE FIRST!!!" echo git status fi I get the following error [: ??: binary operator expected now, I am looking at the man and try the git diff. ===================code for my hope, and hope better answer====================== #if [ `git status | grep -i -c "$"` -lt 3 ]; # change to below code,although the above code is simple, but I think it is not strict logical if [ `git diff --cached --exit-code HEAD^ > /dev/null && (git ls-files --other --exclude-standard --directory | grep -c -v '/$')` ]; then echo "PLEASE COMMIT YOUR CHANGE FIRST!!!" exit 1 else exit 0 fi A: An alternative to testing whether the output of git status --porcelain is empty is to test each condition you care about separately. One might not always care, for example, if there are untracked files in the output of git status. For example, to see if there are any local unstaged changes, you can look at the return code of: git diff --exit-code To check if there are any changes that are staged but not committed, you can use the return code of: git diff --cached --exit-code Finally, if you want to know about whether there are any untracked files in your working tree that aren't ignored, you can test whether the output of the following command is empty: git ls-files --other --exclude-standard --directory Update: You ask below whether you can change that command to exclude the directories in the output. You can exclude empty directories by adding --no-empty-directory, but to exclude all directories in that output I think you'll have to filter the output, such as with: git ls-files --other --exclude-standard --directory | egrep -v '/$' The -v to egrep means to only output lines that don't match the pattern, and the pattern matches any line that ends with a /. A: The return value of git status just tells you the exit code of git status, not if there are any modifications to be committed. If you want a more computer-readable version of the git status output, try git status --porcelain See the description of git status for more information about that. Sample use (script simply tests if git status --porcelain gives any output, no parsing needed): if [ -n "$(git status --porcelain)" ]; then echo "there are changes"; else echo "no changes"; fi Please note that you have to quote the string to test, i.e. the output of git status --porcelain. For more hints about test constructs, refer to the Advanced Bash Scripting Guide (Section string comparison). A: If you are like me, you want to know if there are: 1) changes to existing files 2) newly added files 3) deleted files and specifically do not want to know about 4) untracked files. This should do it: git status --untracked-files=no --porcelain Here's my bash code to exit the script if the repo is clean. It uses the short version of the untracked files option: [[ -z $(git status -uno --porcelain) ]] && echo "this branch is clean, no need to push..." && kill -SIGINT $$;
{ "pile_set_name": "StackExchange" }
Q: MySQL - Need to search URL table for URLs containing a specified word I have a table of URLs, and I need to find any URLs that contain a keyword, such as "fogbugz" or "amazon". If the keyword appears anywhere in the URL, I'd like it to be a result. Right now, I'm trying: SELECT url FROM url WHERE url LIKE '%keyword%' Which is predictably slow, even when url is indexed. I'm open to alternative methods for indexing this quickly, including scripting methods. I was thinking about going through each URL, splitting it up by "/" then "_ or -" characters, and storing those in a separate url2keyword table. With this method, a URL like: "http://www.foo.com/directory/article-name" would have "foo" "directory" "article" "name" as its keywords. Just an idea. Of course, if there's a simpler way to do this in MySQL, or in general, I'd prefer that. I'd like your suggestions on this matter! Thanks. A: You can try full text search (http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html). The disadvantage is that you will get approximate results as well, so you will probably have to run another pass over the results to pick out the ones you do and don't want.
{ "pile_set_name": "StackExchange" }
Q: Rails 4: Specified Unicorn in Procfile, but Webrick is executed I am using Rails 4.0.1 and I want to run unicorn as my web server, but when I execute rails s, Webrick is used instead (the unicorn gem is in my Gemfile, so it can't be that). This is my Procfile: worker: bundle exec rake jobs:work web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb And this is the unicorn.rb file: worker_processes 2 timeout 30 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end What is going on? Thanks! A: rails server doesn't use your Procfile; that's for foreman. Start your application with foreman instead: bundle exec foreman start If you want rails server to use Unicorn as well, you can include the unicorn-rails gem. A: I am adding this as a general help article to those that have landed here because of a related search on Google. If you want to run Unicorn then add this in your project Gemfile # Use unicorn as the app server gem 'unicorn' gem 'unicorn-rails' Then in your terminal run bundle install You will then get something like this in your terminal that shows that you are now using Unicorn. => Booting Unicorn => Rails 4.0.0 application starting in development on http://0.0.0.0:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server I, [2014-10-24T18:39:41.074259 #32835] INFO -- : listening on addr=0.0.0.0:3000 fd=8 I, [2014-10-24T18:39:41.074399 #32835] INFO -- : worker=0 spawning... I, [2014-10-24T18:39:41.075407 #32835] INFO -- : master process ready I, [2014-10-24T18:39:41.076712 #32836] INFO -- : worker=0 spawned pid=32836 I, [2014-10-24T18:39:41.237335 #32836] INFO -- : worker=0 ready Additional Reading Unicorn Rails Deploying to Heroku with Unicorn
{ "pile_set_name": "StackExchange" }
Q: Keeping determine digits in Append to process The end of my code is written as below. Ignoring the inefficient role of Append, I want to have very simple set of values as for example: {0.70, 0.091, 0.3032},{0.70, 0.094, 0.2933},{0.70, 0.097, 0.2840}..... But when I copy and paste whole (below code) in another notebook to save them for being protected from unintentional events, unfortunately I encounter to However, I don't have problem with this copied format but I want to have no messy output. For example same as {0.70, 0.091, 0.3032},{0.70, 0.094, 0.2933},{0.70, 0.097, 0.2840}..... Code . . . AppendTo[whole, {x, y, Round[n,0.0001]}]; , {y, 0.001, 2.0, 0.003}]; , {x, 0, 2, 0.05}] A: Since your Target is to save them for being protected from unintentional events I propose a different strategy, but check first, NumberForm NumberMarks Machine‐Precision Numbers vals = RandomReal[{-1, 1}, {12, 3}] NB copied as Plain Text {{0.768526,0.981104,-0.384388},{0.177151,0.378702,0.537739},{0.338071,0.100119,0.548224},{-0.374293,0.472408,-0.102244},{-0.217492,0.445251,-0.913405},{-0.465784,-0.00326553,0.756313},{0.416133,-0.669428,0.371823},{0.906655,-0.0154896,-0.0677684},{0.31712,0.991293,-0.369311},{0.107006,-0.600543,0.987313},{0.77811,-0.566304,0.745197},{-0.242659,-0.987115,-0.368953}} first = SetPrecision[vals, 4] {{0.7685,0.9811,-0.3844},{0.1772,0.3787,0.5377},{0.3381,0.1001,0.5482},{-0.3743,0.4724,-0.1022},{-0.2175,0.4453,-0.9134},{-0.4658,-0.003266,0.7563},{0.4161,-0.6694,0.3718},{0.9067,-0.01549,-0.06777},{0.3171,0.9913,-0.3693},{0.1070,-0.6005,0.9873},{0.7781,-0.5663,0.7452},{-0.2427,-0.9871,-0.3690}} second = NumberForm[vals, 2] {{0.77,0.98,-0.38},{0.18,0.38,0.54},{0.34,0.1,0.55},{-0.37,0.47,-0.1},{-0.22,0.45,-0.91},{-0.47,-0.0033,0.76},{0.42,-0.67,0.37},{0.91,-0.015,-0.068},{0.32,0.99,-0.37},{0.11,-0.6,0.99},{0.78,-0.57,0.75},{-0.24,-0.99,-0.37}} first {{0.7685,0.9811,-0.3844},{0.1772,0.3787,0.5377},{0.3381,0.1001,0.5482},{-0.3743,0.4724,-0.1022},{-0.2175,0.4453,-0.9134},{-0.4658,-0.003266,0.7563},{0.4161,-0.6694,0.3718},{0.9067,-0.01549,-0.06777},{0.3171,0.9913,-0.3693},{0.1070,-0.6005,0.9873},{0.7781,-0.5663,0.7452},{-0.2427,-0.9871,-0.3690}} second {{0.77,0.98,-0.38},{0.18,0.38,0.54},{0.34,0.1,0.55},{-0.37,0.47,-0.1},{-0.22,0.45,-0.91},{-0.47,-0.0033,0.76},{0.42,-0.67,0.37},{0.91,-0.015,-0.068},{0.32,0.99,-0.37},{0.11,-0.6,0.99},{0.78,-0.57,0.75},{-0.24,-0.99,-0.37}} Export you values to Export["00_1.m", vals] 00_1.m Get your values << "00_1.m" {{0.768526,0.981104,-0.384388},{0.177151,0.378702,0.537739},{0.338071,0.100119,0.548224},{-0.374293,0.472408,-0.102244},{-0.217492,0.445251,-0.913405},{-0.465784,-0.00326553,0.756313},{0.416133,-0.669428,0.371823},{0.906655,-0.0154896,-0.0677684},{0.31712,0.991293,-0.369311},{0.107006,-0.600543,0.987313},{0.77811,-0.566304,0.745197},{-0.242659,-0.987115,-0.368953}} And format your Data {{0.77,0.98,-0.38},{0.18,0.38,0.54},{0.34,0.1,0.55},{-0.37,0.47,-0.1},{-0.22,0.45,-0.91},{-0.47,-0.0033,0.76},{0.42,-0.67,0.37},{0.91,-0.015,-0.068},{0.32,0.99,-0.37},{0.11,-0.6,0.99},{0.78,-0.57,0.75},{-0.24,-0.99,-0.37}}
{ "pile_set_name": "StackExchange" }
Q: Angular 2 routing displays both the component I have a login component and mainpage component in angular 2. when i logged in and try to navigate to main page, both login and mainpage component are coming in same page. my app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { Appmainpage } from './mainpage.component'; import { RouterModule, Routes } from '@angular/router'; const appRoutes: Routes = [ {path: 'login', component: AppComponent}, { path: 'mainpage', component: Appmainpage} ]; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot(appRoutes) ], declarations: [ AppComponent, Appmainpage ], bootstrap: [ AppComponent ] }) export class AppModule { } my app.component.ts import { Component } from '@angular/core'; import { Login } from './login'; import { Router } from '@angular/router'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'my-app', template: ` <router-outlet> </router-outlet> `, }) export class AppComponent { constructor(public _router: Router, private route: ActivatedRoute){} model = new Login(null, null) uname:any; pwd:any; ulogin() { if (this.model.uname == "NP13310" && this.model.pwd == "pandi") { console.log("sucess"); this._router.navigate(['../mainpage'], { relativeTo: this.route}); } } } my mainpage.component.ts which displays the main page import { Component } from '@angular/core'; import { AppComponent } from './app.component'; import { RouterModule, Routes } from '@angular/router'; @Component({ templateUrl: 'app/mainp.component.html' }) export class Appmainpage { } A: The AppComponent is the root of your app. It displays everything in the router-outlet. You should create an other component for Login.
{ "pile_set_name": "StackExchange" }
Q: XMPP with Java Asmack library and X-FACEBOOK-PLATFORM I've intentionally copy-pasted this question dont be angry for duplicate. There are several unclear moments for me in the topic: 1) xmpp.login(apiKey + "|" + sessionKey, sessionSecret, "Application"); sessionKey is the second part of the access token. If the token is in this form, AAA|BBB|CCC, the BBB is the session key But my access token looks like: BAADcfjCWMLABAIyzRSZA69eAtA9Dr3EQVlXA8Ql6rr5odDWxNYZCHhssiaar8S0gaPLZAm1ZBKCqWO3QFegJPR39hT0JR5ZCyIP1AJZC19qh9mFAExUd9KDjJ05yjE3IUZD so I cant see any "second part"... 2) sessionSecret is obtained using the old REST API with the method auth.promoteSession. To use it, it's needed to make a Http get to this url: https://api.facebook.com/method/auth.promoteSession?access_token=yourAccessToken Despite of the Facebook Chat documentation says that it's needed to use your application secret key, only when I used the key that returned that REST method I was able to make it works. To make that method works, you have to disable the Disable Deprecated Auth Methods option in the Advance tab in your application settings. I've read here that REST is deprecated and We will not be supporting this method in the Graph API. What should I do? I'm using only Graph API. Is there any other way to get sessionSecret? Thanks! A: I tested this one and it worked for me . First of all Edit your SASLXFacebookPlatformMechanism class . Copy and paste this code . package com.facebook.android; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import org.apache.harmony.javax.security.auth.callback.CallbackHandler; import org.apache.harmony.javax.security.sasl.Sasl; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.sasl.SASLMechanism; import org.jivesoftware.smack.util.Base64; import android.util.Log; public class SASLXFacebookPlatformMechanism extends SASLMechanism { private static final String NAME = "X-FACEBOOK-PLATFORM"; private String apiKey = ""; private String accessToken = ""; /** * Constructor. */ public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication) { super(saslAuthentication); } @Override protected void authenticate() throws IOException, XMPPException { getSASLAuthentication().send(new AuthMechanism(NAME, "")); } @Override public void authenticate(String apiKey, String host, String accessToken) throws IOException, XMPPException { if (apiKey == null || accessToken == null) { throw new IllegalArgumentException("Invalid parameters"); } this.apiKey = apiKey; this.accessToken = accessToken; this.hostname = host; String[] mechanisms = { "DIGEST-MD5" }; Map<String, String> props = new HashMap<String, String>(); this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this); authenticate(); } @Override public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException { String[] mechanisms = { "DIGEST-MD5" }; Map<String, String> props = new HashMap<String, String>(); this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh); authenticate(); } @Override protected String getName() { return NAME; } @Override public void challengeReceived(String challenge) throws IOException { byte[] response = null; if (challenge != null) { String decodedChallenge = new String(Base64.decode(challenge)); Map<String, String> parameters = getQueryMap(decodedChallenge); String version = "1.0"; String nonce = parameters.get("nonce"); String method = parameters.get("method"); String composedResponse = "method=" + URLEncoder.encode(method, "utf-8") + "&nonce=" + URLEncoder.encode(nonce, "utf-8") + "&access_token=" + URLEncoder.encode(accessToken, "utf-8") + "&api_key=" + URLEncoder.encode(apiKey, "utf-8") + "&call_id=0" + "&v=" + URLEncoder.encode(version, "utf-8"); response = composedResponse.getBytes(); } String authenticationText = ""; if (response != null) { authenticationText = Base64.encodeBytes(response); } // Send the authentication to the server getSASLAuthentication().send(new Response(authenticationText)); } private Map<String, String> getQueryMap(String query) { Map<String, String> map = new HashMap<String, String>(); String[] params = query.split("\\&"); for (String param : params) { String[] fields = param.split("=", 2); map.put(fields[0], (fields.length > 1 ? fields[1] : null)); } return map; } } Then use this method in your activity class from where you want to login to facebook. private void testLogin(){ ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222); config.setSASLAuthenticationEnabled(true); config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled); xmpp = new XMPPConnection(config); SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class); SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0); Log.i("XMPPClient", "Access token to " + mFacebook.getAccessToken()); Log.i("XMPPClient", "Access token to " + mFacebook.getAppId()); Log.i("XMPPClient", "Access token to " + mFacebook.getAccessToken()); try { xmpp.connect(); Log.i("XMPPClient", "Connected to " + xmpp.getHost()); } catch (XMPPException e1) { Log.i("XMPPClient", "Unable to " + xmpp.getHost()); e1.printStackTrace(); } try { xmpp.login(PreferenceConnector.APP_ID, mFacebook.getAccessToken()); getRoster(xmpp); } catch (XMPPException e) { e.printStackTrace(); } }
{ "pile_set_name": "StackExchange" }
Q: How to get html rows where text boxes , select boxes values have been changed I have a web form having multiple rows in HTML table. When I click Submit, it's updating all the rows ( passing input values of all the rows to the stored procedure parameter ). All I want is to pass and update only those rows where input values are changed. My HTMl Source: <html> <head> <title> Dashboard:</title> <script language="JavaScript"> var gAutoPrint = true; // Tells whether to automatically call the print function function printSpecial() { if (document.getElementById != null) { var html = '<HTML>\n<HEAD>\n'; if (document.getElementsByTagName != null) { var headTags = document.getElementsByTagName("head"); if (headTags.length > 0) html += headTags[0].innerHTML; } html += '\n</HE>\n<BODY>\n'; var printReadyElem = document.getElementById("printReady"); if (printReadyElem != null) { html += printReadyElem.innerHTML; } else { alert("Could not find the printReady function"); return; } html += '\n</BO>\n</HT>'; var printWin = window.open("","printSpecial"); printWin.document.open(); printWin.document.write(html); printWin.document.close(); if (gAutoPrint) printWin.print(); } else { alert("The print ready feature is only available if you are using an browser. Please update your browswer."); } } function validate() { //alert('here'); var elements = document.getElementById("frmDtls").elements ; var val = [] ; var flag = true; var x = -1; var y = 0; if(flag == true) { document.frmDtls.hfrom.value = 'Updt' ; document.frmDtls.method = "post" ; document.frmDtls.action = "samepage.asp" ; document.frmDtls.submit(); // alert("Record has been Updated Successfully!"); //window.location.href = window.location.href; // location.reload(); } // alert(flag); } </script> </head> <body background="Images/Notebook.jpg"> <div align="center"> <center> <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111"> <tr> <td width="100%" align="center"> <img border="0" src="Axalta Coating Systems Logo.jpg" width="1200" height="60"></td> </tr> </table> <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%"> <tr> <td width="100%" bgcolor="#C0C0C0" align="center"><b> <font face="Times New Roman" size="4"> CYCLE TIMES and UNITS for UPDATING </font></b>&nbsp; </TD> </tr> </table> <div id="printReady"> <div align="center" id="formdiv"><center> <form id="frmDtls" name="frmDtls"> <!--<form id="frmDtls" name="frmDtls" target="MyFrame">--> <iframe id="MyFrame" name="MyFrame" style="display:none;"></iframe> <input type="hidden" name="hfrom" value = ""> <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%"> <tr> <td width="70%" bgcolor="#C0C0C0" align="center"><b> <font face="Times New Roman" size="5">SELECTED DUAL CODE DETAILS </font></b>&nbsp;</td> <td width="13%" align="Middle" valign = "Middle" bgcolor="#FFFF00"> <input type="button" name='update' value = 'Update' onclick='validate();'> </TD> <td width="17%" bgcolor="#C0C0C0" align="Center"> <b><font face="Times New Roman" size="2"> LATEST POSTING DATE / TIME 2/13/2019 7:09:20 AM</font></b>&nbsp; </TD> </tr> </table> <table BORDER="1" CELLSPACING="1" CELLPADDING="1" style="font-weight: normal; letter-spacing: normal; text-align: left; width:100%;"> <tr align="center"> <th><small><small><span style="color:darkgreen;font-weight:bold">Profile ID</small></small></th> <th><WIDTH="200"><small><small><span style="color:green;font-weight:bold">DUAL CODE</small></small></th> <th><small><span style="color:darkgreen;font-weight:bold">Description</small></th> <th><small><span style="color:darkgreen;font-weight:bold">R/D Material?</small></th> <th><small><small><span style="color:darkgreen;font-weight:bold">Process Step Name</small></small></th> <th><small><small><span style="color:darkgreen;font-weight:bold">Process Step Sequence</small></small></th> <th><small><small><span style="color:darkgreen;font-weight:bold">FROM Event Status</small></small></th> <th><small><small><span style="color:darkgreen;font-weight:bold">TO Event Status</small></small></th> <th><small><small><span style="color:darkblue;font-weight:bold">Current CYCLE TIME</small></small></th> <th><small><small><span style="color:darkred;font-weight:bold">Updated CYCLE TIME</small></small></th> <th><small><small><span style="color:darkblue;font-weight:bold">Cycle Time Units</small></small></th> <th><small><small><span style="color:darkred;font-weight:bold">Updated Units</small></small></th> <th><small><small><span style="color:darkblue;font-weight:bold">Comments</small></small></th> </tr> <tr> <td><input type="Hidden" name="l_enteredpartialdualcode" value="" > </td> <td><input type="Hidden" name="l_selecteddualcodes" value="1026-FD195, 1143-01427" > </td> <td><input type="Hidden" name="l_selectedprocessstepnames" value="" > </td> <td><input type="Hidden" name="l_selectedgbtindicato" value="Both" > </td> <td><input type="Hidden" name="l_multipledualcodess" value="" > </td> </tr> <TR align=center><TD Width=90 Height=3 nowrap ><B>1</B></TD><TD Width=90 Height=3 nowrap ><B>1026-FD195</B></TD><TD WIDTH=200 Height=3><small><small><B>1026-FD195 E500546 DARK GRAY WBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>Load_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>2</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>LDGS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>LDGC </B></small></small></TD><TD WIDTH=70 Height=3><B>6</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_1_2' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' >3</option><option value = '4' >4</option><option value = '5' >5</option><option value = '6' selected>6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_1_2" value="test1" > </B></small></small></TD> <TR align=center><TD Width=90 Height=3 nowrap ><B>1</B></TD><TD Width=90 Height=3 nowrap ><B>1026-FD195</B></TD><TD WIDTH=200 Height=3><small><small><B>1026-FD195 E500546 DARK GRAY WBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>Test_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>4</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>TSTS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>TSTC </B></small></small></TD><TD WIDTH=70 Height=3><B>6</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_1_4' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' >3</option><option value = '4' >4</option><option value = '5' >5</option><option value = '6' selected>6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_1_4" value="" > </B></small></small></TD> <TR align=center><TD Width=90 Height=3 nowrap ><B>1</B></TD><TD Width=90 Height=3 nowrap ><B>1026-FD195</B></TD><TD WIDTH=200 Height=3><small><small><B>1026-FD195 E500546 DARK GRAY WBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>FILL_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>6</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>FLGS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>FLGC </B></small></small></TD><TD WIDTH=70 Height=3><B>4</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_1_6' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' >3</option><option value = '4' selected>4</option><option value = '5' >5</option><option value = '6' >6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_1_6" value="test1" > </B></small></small></TD> <TR align=center><TD Width=90 Height=3 nowrap ><B>2</B></TD><TD Width=90 Height=3 nowrap ><B>1143-01427</B></TD><TD WIDTH=200 Height=3><small><small><B>1143-01427 E450552 TITANIUM SBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>Load_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>2</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>LDGS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>LDGC </B></small></small></TD><TD WIDTH=70 Height=3><B>3</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_2_2' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' selected>3</option><option value = '4' >4</option><option value = '5' >5</option><option value = '6' >6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_2_2" value="" > </B></small></small></TD> <TR align=center><TD Width=90 Height=3 nowrap ><B>2</B></TD><TD Width=90 Height=3 nowrap ><B>1143-01427</B></TD><TD WIDTH=200 Height=3><small><small><B>1143-01427 E450552 TITANIUM SBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>Test_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>4</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>TSTS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>TSTC </B></small></small></TD><TD WIDTH=70 Height=3><B>6</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_2_4' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' >3</option><option value = '4' >4</option><option value = '5' >5</option><option value = '6' selected>6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_2_4" value="test" > </B></small></small></TD> <TR align=center><TD Width=90 Height=3 nowrap ><B>2</B></TD><TD Width=90 Height=3 nowrap ><B>1143-01427</B></TD><TD WIDTH=200 Height=3><small><small><B>1143-01427 E450552 TITANIUM SBPR</B></small></small></TD><TD WIDTH=30 Height=3><small><small><B></B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>FILL_Cycle</B></small></small></TD><TD WIDTH=100 Height=3><small><small><B>6</B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>FLGS </B></small></small></TD><TD WIDTH=90 Height=3><small><small><B>FLGC </B></small></small></TD><TD WIDTH=70 Height=3><B>6</B></TD><TD WIDTH=70 Height=3><small><small><B><Select name = 'DDSQ_2_6' font-size=1><option value = '1' >1</option><option value = '2' >2</option><option value = '3' >3</option><option value = '4' >4</option><option value = '5' >5</option><option value = '6' selected>6</option><option value = '7' >7</option><option value = '8' >8</option><option value = '9' >9</option><option value = '10' >10</option><option value = '11' >11</option><option value = '12' >12</option><option value = '13' >13</option><option value = '14' >14</option><option value = '15' >15</option><option value = '16' >16</option><option value = '17' >17</option><option value = '18' >18</option><option value = '19' >19</option><option value = '20' >20</option><option value = '21' >21</option><option value = '22' >22</option><option value = '23' >23</option><option value = '24' >24</option><option value = '-1' >Clear</option></Select></B></small></small></TD> <TD WIDTH=70 Height=3 nowrap><small><small><B> Hours </B></small></small></TD><TD WIDTH=70 Height=3><small><small><B></B></small></small></TD> <td WIDTH=100 Height=3><small><small><B><input type="text" name="txt_2_6" value="test2" > </B></small></small></TD> </table> </form> </center> </div> </div> <p><small><small><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; End of Report.</strong></small></small></p> <p align="center"><strong><big><big>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</big></big></strong></p> </body> </html> Run code snippetExpand snippet Template is here : Web Page Template Currently I am trying to append all the row id's with ';' separated on textbox OnChange event in javascript and store it in variable and then pass only these id's to my sql query but I am not able to figure out how to do that. Is there any way you guys can help me out with?. My HTML : <input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;" > function onChangeTest(textbox){ alert("Value is " + textbox.value + "\n" + "Old Value is " + textbox.oldvalue + "\n" + "Name is " + textbox.name); } A: If I got your question correctly, I think this should work. but If you can add some code, or explain what do you want to do with the row IDs, I can help more function submitTable(){ var rows_ids = []; $('#content-table .new-value').each(function(){ var old_value = parseInt($(this).parent().find('.old-value').text()); var new_value = parseInt($(this).find('input.desired-input').val()); if(old_value !== new_value){ rows_ids.push($(this).parent().attr('id')); // use this as you want, it containes the id for the changed rows. // you have the changes value in new_value, so you also can use it. } }); console.log(rows_ids); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="content-table"> <tr id="1"> <td>STG</td> <td class="old-value">4</td> <td class="new-value"><input type="text" name="txt_1_2" value="4" class="desired-input"></td> </tr> <tr id="2"> <td>LDG</td> <td class="old-value">3</td> <td class="new-value"><input type="text" name="txt_2_5" value="3" class="desired-input"></td> </tr> <tr id="3"> <td>FLG</td> <td class="old-value">6</td> <td class="new-value"><input type="text" name="txt_3_6" value="6" class="desired-input"></td> </tr> <tr id="4"> <td>FLG</td> <td class="old-value">7</td> <td class="new-value"><input type="text" name="txt_4_3" value="7" class="desired-input"></td> </tr> </table> <button type="button" name="button" onclick="submitTable()">Submit</button> EDIT: if you mean that you want to store the old value in the same input you can use the data- attribute to do so... then the code should look like this function submitTable(){ var rows_ids = []; $('#content-table .desired-input').each(function(){ var old_value = parseInt($(this).data('old-value')); var new_value = parseInt($(this).val()); if(old_value !== new_value){ rows_ids.push($(this).closest('tr').attr('id')); // use this as you want, it containes the id for the changed rows. // you have the changes value in new_value, so you also can use it. } }); console.log(rows_ids); } and you need to add data-old-value="..." to your input <input type="text" name="" value="7" class="desired-input" data-old-value="7"> EDIT2: based on your comment, you can use .split to split the name on _ and then get the id that you want, for the name format that you mentioned it should be at index 1,, the js code should look like function submitTable(){ var ids = []; $('#content-table .desired-input').each(function(){ var old_value = parseInt($(this).data('old-value')); var new_value = parseInt($(this).val()); if(old_value !== new_value){ ids.push($(this).attr('name').split('_')[1]); } }); console.log(ids); }
{ "pile_set_name": "StackExchange" }
Q: Question deleted without a trace and without notice? I'm somewhat annoyed that one of my questions just vanished like it never existed. Shouldn't there at least be some kind of notification in my account left? And why not keep questions that don't have an answer, yet? The question was related to quantum scars - a relatively recent research topic, which might not be so popular among the Copenhagen orthodoxy... Censorship? I managed to find it in my bookmarks but nowhere else! Here it is: Relation between 't Hooft's deterministic QM and Gutzwillers trace formula? A: Your question was asked thirteen months ago. In that time it was viewed by thirty-three people, of whom zero voted postively or negatively. It was automatically deleted by the roomba after a year as an "abandoned question." Forgotten questions are deleted without notice by design --- it helps them stay forgotten. In the future, consider What should I do if no one answers my question? Note that your question has now been undeleted by a moderator. A: OP's zero score question without answers was automatically deleted after 1 year. See also this related meta post. It is a deliberate SE design not to inform users of deletions. I manually undeleted OP's question.
{ "pile_set_name": "StackExchange" }
Q: Translate XSL files with PHP and gettext Is it possible to translate XSL files using PHP and gettext? I'm building a web application where most of the user interface code is in XSL files. I'm using PHP gettext to translate PHP pages and an app called Poedit to translate the texts. All this works very well! I would need a way to translate the XSL files too, preferably so that Poedit can find the texts from the XSL files. Is this possible? Should I perhaps consider another approach for translating XSL files? A: You can use any PHP function within XSL template: <xsl:value-of select="php:function( 'gettext' , 'Term to translate' )" /> You just need to register namespace: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"> And allow to use php functions: $style = DOMDocument::load( $template ); $processor = new XSLTProcessor(); $processor->registerPHPFunctions(); $processor->importStylesheet( $style ); See This
{ "pile_set_name": "StackExchange" }
Q: How to make a conditional request with NSManagedObjectContext? I'm new to NSManagedObjectContext. I have created an entity Link in my app, which contains a NSString *url. At some point of my app, I need to insert a new Link in my base, so I simply do this : Link *link = [NSEntityDescription insertNewObjectForEntityForName:@"Link" inManagedObjectContext:self.managedObjectContext]; link.url = myUrl; But before doing this, I want to check if there is not already a Link in my base with the same url. And I have no idea of how to do so... what should I do? EDIT : to retrieve data from the base I'm using this method from a tool I found on the web: // Fetch objects with a predicate +(NSMutableArray *)searchObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate *)predicate andSortKey:(NSString*)sortKey andSortAscending:(BOOL)sortAscending andContext:(NSManagedObjectContext *)managedObjectContext { // Create fetch request NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; // If a predicate was specified then use it in the request if (predicate != nil) [request setPredicate:predicate]; // If a sort key was passed then use it in the request if (sortKey != nil) { NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; } // Execute the fetch request NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; // If the returned array was nil then there was an error if (mutableFetchResults == nil) NSLog(@"Couldn't get objects for entity %@", entityName); // Return the results return mutableFetchResults; } I would like to know how to use it. Thanks for your help. A: The method you provided just searches for a NSManagedObject that matches the attributes in the NSManagedObjectContext and if one exists, it returns it. But, what you need to implement is called the Find-or-Create pattern, which is discussed in the Core Data programming guide. Basically, you search for an object matching specific criteria and if it exists that object is returned. If that object does not exist you create it. Core Data Programming Guide E.g. + (NSString *)entityName { return NSStringFromClass([Link class]); } + (instancetype)findUsingPredicate:(NSPredicate *)predicate withContext:(NSManagedObjectContext *)context { Link * entity; // Setup the fetchRequest NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[[self class] entityName]]; fetchRequest.predicate = predicate; // Credit: @Martin R [fetchRequest setFetchLimit:1]; // Execute the fetchRequest NSError *error = nil; NSArray * matchingLinks = [context executeFetchRequest:fetchRequest error:&error]; // MatchingLinks will only return nil if an error has occurred otherwise it will return 0 if (!matchingLinks) { // handle error // Core data returns nil if an error occured NSLog(@"%s %@", __PRETTY_FUNCTION__, [error description]); } else if ([matchingLinks count] <= 0) { // if the count <= 0, there were no matches NSLog(@"%s Not found", __PRETTY_FUNCTION__); } else { // A link with a url that matches the url in the dictionary was found. NSLog(@"%s Found", __PRETTY_FUNCTION__); entity = [matchingLinks lastObject]; } return entity; } + (instancetype)findUsingPredicate:(NSPredicate *)predicate orCreateWithContext:(NSManagedObjectContext *)context { Link * entity = [[self class] findUsingPredicate:predicate withContext:context]; if (!entity) { entity = [[self class] createWithContext:context]; } return entity; } + (isntancetype)createWithContext:(NSManagedObjectContext *)context { return [[self class] alloc] initWithContext:context]; } - (instancetype)initWithContext:(NSManagedObjectContext *)context { Link * entity = [NSEntityDescription insertNewObjectForEntityForName:[[self class] entityName] inManagedObjectContext:context]; return entity; } USE CASE: NSString * url = @"http://www.mylink.com"; NSPredicate * predicate = [NSPredicate predicateWithFormat:@"url = %@", url]; Link * link = [Link findUsingPredicate:predicate orCreateWithContext:self.managedObjectContext]; link.url = url;
{ "pile_set_name": "StackExchange" }
Q: Nietzsche aphorism about happiness - interpretation THE DANGER IN HAPPINESS.--"Everything now turns out best for me, I now love every fate:--who would like to be my fate?" From Beyond Good and Evil. I wondered if anyone could share some wisdom about this. In order to keep this from being removed for opinion-based, any interpretation should be backed by some credible reference or body of work. My personal take is that he is pointing to the dangers of self-centered happiness, but I couldn’t find any other reference outside of my own head. In fact, when searching for any insight on any of his aphorisms in Beyond Good and Evil, I find the resources available painfully limited, especially given the vast amount available on other Nietzsche work. Essentially, my request is for an explanation of the above quote or for a reference to an explanation. A: Actually, this is quite easy to understand, especially if you take slightly bigger excerpt from Chapter 4 like bellow. As usual in his works, Nietzsche is fighting against spirit of content, seeking of peace, slave mentality, priestly morality of obeying (monk morality), modesty, humility . It is well known that Nietzsche was seeking road to Übermensch. For Nietzsche (and for Übermensch) life was a struggle to improve himself and gain more power (Will to power). Therefore, for Nietzsche, happiness was not to have easy life, life without struggle ("Everything now turns out best for me") and to stoically accept and be content with anything ("I now love every fate"). Instead, happiness was to have passion and strength to meet life's obstacles and overcome them, thus becoming better. It is compatible with his famous maxim What does not kill me makes me stronger. THE DISAPPOINTED ONE SPEAKS--"I listened for the echo and I heard only praise". We all feign to ourselves that we are simpler than we are, we thus relax ourselves away from our fellows. A discerning one might easily regard himself at present as the animalization of God. Discovering reciprocal love should really disenchant the lover with regard to the beloved. "What! She is modest enough to love even you? Or stupid enough? Or--or---" THE DANGER IN HAPPINESS.--"Everything now turns out best for me, I now love every fate:--who would like to be my fate?" Not their love of humanity, but the impotence of their love, prevents the Christians of today--burning us. The pia fraus is still more repugnant to the taste (the "piety") of the free spirit (the "pious man of knowledge") than the impia fraus. Hence the profound lack of judgment, in comparison with the Church, characteristic of the type "free spirit"--as ITS non-freedom.
{ "pile_set_name": "StackExchange" }
Q: Why are honeypots not widely deployed? From what I understand honeypots in addition to honey tokens are meant to prevent malicious insiders. Given recent high profile cases involving malicious insiders (Snowden), why are honeypots not deployed more frequently? Is it because honeypots are not easy to deploy? Or is it because that it is not very effective? A: Honeypots are "Security by Obscurity" when employed to catch insiders. Once it is known what the honeypot is, it is no longer effective. On the other hand, honeypots employed to catch external users who have gained insider access can be very useful (I use them all the time). In this case, you can publicize the existence of the honeypot to internal users so that any activity on the honeypot is suspicious. Legal issues scare people away (read HexTitan's link), honeypots can generate large numbers of false positives (making them potentially expensive to manage), and they need to be carefully designed so that they do not become an attacker's asset. All these issues combined have come up when I suggest employing honeypots in my organizations. I have successfully countered the arguments, but the resistance has always been huge. In short: the term "honeypot" is a broad term, and confusion and ambiguity as a result of the vagueness result in resistance from management to use honeypots, in general.
{ "pile_set_name": "StackExchange" }
Q: change with column that is updated based on is null Hi I have an update query where if one field is null then I want value goes to another field here is an example of what I would like to do: UPDATE Table SET CASE WHEN Column1 is NULL THEN Column2 = @Update ELSE Column1 = @Update END; Now this does not work as I get an error on the word case but is there a way to do what I am try to accomplish? I know it could be done if I used two update statements with a where but was wondering if it could be done in one query? A: You are using incorrect syntax for CASE in SQL statements. CASE must return an expression, it cannot contain a statement in pure SQL. update Table Set Column1 = Case when Column1 is NULL Then NULL Else @Update END, Column2 = Case when Column1 is NULL Then @Update Else Column2 END
{ "pile_set_name": "StackExchange" }
Q: Extracting numbers from the string using regex I am trying to extract the number 4 and 3 from the string /ab/cd__my__sep__4__some__sep__3. I am trying with regex but not sure how would I do this. I wrote the following code, but it just prints out __my__sep__4__some__sep__3 #include <stdio.h> #include <regex.h> #include <string.h> #include <stdlib.h> int main() { char* s = "/ab/cd__my__sep__4__some__sep__3"; regex_t regex; int reti = regcomp(&regex,"__my__sep__([0-9]+)",REG_EXTENDED); if(reti!=0) { exit(-1); }else { regmatch_t match[2]; reti = regexec(&regex, s, 2, match, 0); if(reti == 0) { char *v = &s[match[1].rm_so]; ssize_t fl; sscanf(v, "%zu", &fl); printf("%s",v); }else { printf("else"); } } } How could I extract the numbers 4 and 3 ? A: match[0] refers to the part of the text matched by the entire pattern. match[1] is the match corresponding to the first capture (parenthesized subpattern). Note that &s[match[1].rm_so] gives you a pointer to the start of the capture, but if you print the string at that point, you will get the part of the string starting at the beginning of the capture. In this case, that doesn't really matter. Since you're using sscanf to extract the integer value of the captured text, the fact that the substring isn't terminated immediately doesn't matter; it's not going to be followed by a digit, and sscanf will stop at the first non-digit. But in the general case, it's possible that it will not be so easy to identify the end of the matched capture, and you can use one of these techniques: If you want to print the capture, you can use a computed string width format: (See Note 1.) printf("%.*s\n", match[1].rm_eo - match[1].rm_so, &s[match[1].rm_so]); If you have strndup, you can easily create a dynamically-allocated copy of the capture: (See Note 2.) char* capture = strndup(&s[match[1].rm_so], match[1].rm_eo - match[1].rm_so); As a quick-and-dirty hack, it is also possible to just insert a NUL terminator (assuming that the searched string is not immutable, which means that it cannot be a string literal). You'll probably want to save the old value of the following character so that you can restore the string to it's original state: char* capture = &s[match[1].rm_so]; char* rest = &s[match[1].rm_eo]; char saved_char = *rest; *rest = 0; /* capture now points to a NUL-terminated string. */ /* ... */ /* restore s */ *rest = saved_char; None of the above is really necessary in the context of the original question, since the sscanf as written will work perfectly if you change the start of the string to scan from match[0] to match[1]. Notes: In the general case, you should test to make sure that a capture was actually found before trying to use its offset. The rm_so member will be -1 if the capture was not found during the regex search That doesn't necessarily mean that the search failed, because the capture could be part of an alternative not used in the match. Don't forget to free the copy when you no longer need it. If you don't have strndup, it's pretty easy to implement. But watch out for the corner cases.
{ "pile_set_name": "StackExchange" }
Q: Junit test not working correctly with Math.pow It's might be a trivial question as I'm just a beginner in programming. The task is to write a code that raises array's elements to a third power for the following Junit test case: @Test public void testCubeArray() { FirstSteps firstSteps = new FirstSteps(); int[] array1 = {1, 2, 3, 0}; firstSteps.cube(array1); int[] arrayResult1 = {1, 8, 27, 0}; assertArrayEquals(arrayResult1, array1); int[] array2 = {100, 200, 3, 10}; firstSteps.cube(array2); int[] arrayResult2 = {1000000, 8000000, 27, 1000}; assertArrayEquals(arrayResult2, array2); } My code is like thatpublic void cube(int[] array) { for (int i = 0; i <= array.length; i++) { int result = (int)Math.pow(i,3); } The test is failed with the result 2 instead of 8. What have I done wrong? A: The problem is very simple here (don't be scared of the long answer, it's interesting!) firstSteps.cube(array1); You're passing an array instance to the cube method, that's fine. However public void cube(int[] array) { for (int i = 0; i <= array.length; i++) { int result = (int)Math.pow(i,3); } } You're not touching the input array, you're not even using it. See (int)Math.pow(i,3); You're passing the counter variable i to the pow method instead of array[i]. Also, you're assigning the pow result to a limited scope local variable, which means the result variable will continually be re-created with a new initial value but no real usefulness. Another problem is here i <= array.length This will cause an ArrayIndexOutOfBoundsException, as you'll lookup an index greater than the one available in array. Remember that indexes starts at 0! What you can do, for example, is assign the Math.pow result to the original array for (int i = 0; i < array.length; i++) { array[i] = (int) Math.pow(array[i], 3); } Because as you know, arrays are passed by refence, and the elements inside it will be updated for everyone having a reference to it. Now, this int[] array1 = {1, 2, 3, 0}; firstSteps.cube(array1); int[] arrayResult1 = {1, 8, 27, 0}; assertArrayEquals(arrayResult1, array1); will work : ) Olivier Grégoire suggested in the comments to add an intermediate step between modifying the input array (which is what you're doing now, and which is usually not a good choice as it can lead to unexpected side effects) and using the Stream library. See comments, and remember the logic is the same as using the Stream solution below, just not in a functional manner. public int[] cube(final int[] array) { // Initialize a new array, with the same size as the input one, // to hold the computed value. We will return this array instead // of modifying the inputted one. final int[] powResult = new int[array.length]; for (int i = 0; i < array.length; i++) { powResult[i] = (int) Math.pow(array[i], 3); } return powResult; } You can now use this as // We use array1 only as input final int[] array1 = {1, 2, 3, 0}; final int[] powResult = firstSteps.cube(array1); int[] arrayResult1 = {1, 8, 27, 0}; // We use the returned powResult for comparison, // as array1 has not been touched. assertArrayEquals(arrayResult1, powResult); As an addition, I'd like to introduce you a version using a functional approach. public int[] cube(final int[] array) { return IntStream.of(array) .map(v -> (int) Math.pow(v, 3)) .toArray(); } Here we do not touch the array input array, but we create a new, modified copy, using a Stream. That is the array becomes an int flow, and we can examine each element of that flow. .map(v -> (int) Math.pow(v, 3)) If you keep programming you'll probably arrive to the conclusion that this solution is a lot better.
{ "pile_set_name": "StackExchange" }
Q: Sending message from child to parent iframe Well I am trying to do a simple task. Sending a message from parent window to iframe and from iframe to parent. index.js (parent) window.onload = function() { //Get Audio node let audio = document.getElementsByTagName('audio')[0]; //Get iframe node let iframe = document.getElementsByTagName('iframe')[0]; iframe.contentWindow.postMessage('Parent To Child', '*'); window.addEventListener('message', messagesHandler); } function messagesHandler(ev) { console.log(ev.data); } menu.js window.onload = function() { window.parent.postMessage('Child to parent', '*'); window.addEventListener('message', messagesHandler); } function messagesHandler(ev) { console.log(ev.data); } I am able to send messages from parent to child but not the other way around. Any clues?? A: Your parent load handler gets called after the iframe load handler. This leaves the postMessage sent from the child frame not handled. From the MDN docs: The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. You need to do the postMessages at a time that you are sure the listeners are already registered. While you know that the child listener will be available before the parent load event, it still would be good practice to implement in a generic way and not depend on this order, so that you could use the same framework code, regardless if you are in parent or a child frame. Another recommendation would be to not do things on the window load event, as it may fail to trigger in some situations. A better choice is DOMContentLoaded.
{ "pile_set_name": "StackExchange" }
Q: What are some helpful and free UX tools for eye-tracking and mouse-tracking, etc I am looking into ways to gain more insight for how people use the tools I build. Short of having a physical user group for a/b testing, are there some faster and cheaper solutions out there such as tools to gauge eye tracking or mouse tracking, or whatever else can give effective insight into the user's experience? Also, is using mechanical-turk-like solutions helpful for UX? Thanks! A: I've used click heat before: http://www.labsmedia.com/clickheat/index.html It is a self hosted, open source, PHP based heatmap system you can use for free. It works well for click tracking. As far as eye tracking goes, unless you have hardware, you are looking at mouse hover tracking. I think clicktail has it. You could use the mechanical turk as well, but I have no experience with it. Another option could be one of the pay for testing sites out there. A quick google turns up: http://www.usertesting.com/, http://www.feedbackarmy.com/, etc... I've seen ones where they record what the person is saying, and the actions they are taking and they can be effective for a nice usability overview.
{ "pile_set_name": "StackExchange" }
Q: Button action preventing parallel execution? I couldn't find a better title, so I'll jump straight to the example! There is this long list of slow jobs to be executed in a parallel way, at the press of a button: DynamicModule[{dispatch, list, doStuff}, list = Range[8]; dispatch[] := ParallelMap[(Pause[0.5]; Print@{$KernelID, #}) &, list]; Button["Go", dispatch[] , Method -> "Queued"] ] This works as expected, with every kernel printing it's job and ID. As soon as I start modularizing code, things break: DynamicModule[{dispatch, list, doStuff}, list = Range[8]; doStuff[a_] := (Pause[0.5]; Print@{$KernelID, a}); dispatch[] := ParallelMap[doStuff, list]; Button["Go", dispatch[] , Method -> "Queued"] ] This executes sequentially using only the main kernel (ID 0). I've tried distributing definitions, contexts and even sharing variables, but the closest I've gotten to parallelization was the following: DynamicModule[{dispatch, list, doStuff, doSlowStuff}, list = Range[8]; doSlowStuff[] := Pause[0.5]; doStuff[a_] := (doSlowStuff[]; Print@{$KernelID, a}); dispatch[] := ParallelMap[doStuff, list]; dispatch[]; (*This call is correctly executed in parallel*) Button["Go", dispatch[] , Method -> "Queued"] ] The "inline" dispatch[] call is correctly executed (using all kernels) even with the added nested definition of doSlowStuff, but the button's dispatch[] still executes sequentially on kernel 0. What am I missing? A: It might be that this is due to dispatch, list and doStuff being completely owned by the frontend, since you wrapped them in a DynamicModule. Frontend variables cannot be shared between kernels. When you localize them in a Module, and therefore keep them as kernel variables, it works: Module[{dispatch, list, doStuff}, list = Range[8]; doStuff[a_] := (Pause[0.5]; Print@{$KernelID, a}); dispatch[] := ParallelMap[doStuff, list]; Button["Go", dispatch[], Method -> "Queued"]] (* {4,1} {3,3} {2,5} {1,7} {4,2} {3,4} {2,6} {1,8} *) It is possible to accomplish this task in a DynamcModule: DynamicModule[{dispatch, doSlowStuff, list = Range[6]}, doSlowStuff[x_] := (Pause[0.1]; x^2); dispatch[] := ParallelMap[Print[{$KernelID, doSlowStuff[#]}] &, list]; Button["Go", SetSharedFunction[doSlowStuff, dispatch]; dispatch[]] ] (* {4,1} {3,9} {2,25} {1,36} {4,4} {3,16} *) The local frontend variables dispatch and doSlowStuff are linked to kernel variables in the context FE`. It seems that these variables are not automatically distributed over the sub kernels, so we have to use SetSharedFunctions. When this is done outside the button, the kernel variables and not the frontend variables are distributed. Since the kernel variables are removed when the evaluation of the DynamicModule is completed, that will not work. So SetSharedFunctions must be used inside the button.
{ "pile_set_name": "StackExchange" }
Q: Flipping a slice with a for loop logic error So I am trying to write a method that takes two slices, flips both of them and then gives them to each other. Ex. s1 = {1,2,3,4,5} s2 = {6,7,8,9,10} Should return: s1 = {10,9,8,7,6} s2 = {5,4,3,2,1} Here is my code: package main import( "fmt" ) func main(){ f:= [5]int{1,2,3,4,5} h:= [5]int{6,7,8,9,10} var sliceF []int = f[0:5] var sliceH []int = h[0:5] fmt.Println(reverseReverse(sliceF,sliceH)) } func reverseReverse(first []int, second []int) ([]int, []int){ //creating temp arrays to hold the traversed arrays before swapping. var tempArr1 []int = first var tempArr2 []int = second //count is used for counting up the tempArrays in the correct order in the For loops var count int= 0 //goes through the first array and sets the values starting from the end equal to the temp array //which increases normally from left to right. for i :=len(first)-1; i>=0;i--{ tempArr1[count] = first[i] fmt.Println(i) count++ } count =0 //same as first for loop just on the second array for i :=len(second)-1; i>=0;i--{ tempArr2[count] = second[i] count++ } //trying to replace the values of the param arrays to be equal to the temp arrays first=tempArr2 second = tempArr1 //returning the arrays return first,second } When run here is the output: 4 3 2 1 0 [10 9 8 9 10] [5 4 3 4 5] *Not I included a print statement in the for loop to check if the index is decreasing properly. I understand there are better ways to do this but for proof of concept I want to use a for loop. Any help appreciated. I am new to go and tend to have java habits so I assume somehow my problem is related to that. A: This can be done much simpler by realizing there's no need to actually swap the individual elements. Instead, reverse each array and swap their order. Much simpler! func reverseReverse( a, b []int ) ([]int, []int) { return reverse(b), reverse(a) } func reverse( a []int ) []int { end := len(a) - 1 // Allocate a new array slice of the same length to copy to. ret := make( []int, len(a) ) // Copy each element of a into ret, reversed. for i := range a { ret[end-i] = a[i] } return ret } With that revelation, there's little need for the very specialized reverseReverse function. Swap the order yourself. fmt.Println(reverse(sliceH), reverse(sliceF)) Note that if you just want to take a slice of an array, it's sufficient to write sliceH []int := h[:] without specifying the start and end. The start is assumed to be 0 and the end is the end. Also note there's no need to declare the type, := takes care of that for you. Even better, you can declare and initialize them directly. sliceF:= []int{1,2,3,4,5} sliceH:= []int{6,7,8,9,10}
{ "pile_set_name": "StackExchange" }
Q: A universal cross-platform way (mobile) to show alerts to a user I have a task to create a client application which can show notifications to a user with a high probability of notifications being noticed. The application should work on Android (2.0+)/iOS/WP. Here is the use case: The user starts the Application and performs some Action. Then he switches to the home screen/another application. The response to the Action makes the Application to issue a notification. The notification is noticed by the user disregarding of what another application (or home screen) he uses on his mobile device at the moment. There is no requirement for the application to be a native app or to be a web browser-based mobile app. The notification could be a sound or a vibration on the device, but I know that accessing the vibrations from within a browser is still tricky. Here are my research results of making universal sound/vibro notification mechanism so far: it seems that making a mobile device vibrate from a browser works only in mobile Firefox (no iOS, no WP); the support of the audio html5 tag is still experimental, it doesn't work on each and every browser/device; the sound alert from this example works only in mobile Firefox (asks for a plugin to play an mp3 sound), the Android browser just remains silent. So, the question is: Is there any way to force a user of a mobile device (Android 2.0+/iOS/WP) to view a notification from a mobile application? Is the only way to do this is to write a native app for each mobile platform? A: I would propose PhoneGap for that particular problem. Among other things it features cross-platform alert, sound and vibrator notifications. Only quirk for Windows Phone 7 is that the Cordova lib includes a generic beep file that is used. You should consult the Notification reference page to make sure if it can help you.
{ "pile_set_name": "StackExchange" }
Q: Print writer format I have a list with several objects each containing three strings, how should I format the output (in outfile.format()) to make it look like in the sample output below? public void save() { try { PrintWriter outfile = new PrintWriter (new BufferedWriter (new FileWriter("reg_out.txt"))); for (int i = 0; i < list.size(); i++) { outfile.format("???", list.get(i).getLastName(), list.get(i).getFirstName(), list.get(i).getNumber()); } outfile.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Sample output in reg_out.txt: Allegrettho Albert 0111-27543 Brio Britta 0113-45771 Cresendo Crister 0111-27440 A: try this outfile.printf("%-20s%-20s%-20s%n", list.get(i).getLastName(), list.get(i).getFirstName(), list.get(i).getNumber()); see java.util.Formatter API for details
{ "pile_set_name": "StackExchange" }
Q: Remove all #div id from domtree with class .selected How to remove all divs with id #divs with class .something with vanilla javascript. For example: function removeEl() { var removeEl = document.querySelectorAll('.selected'); if (removeEl.length > 0) { for (var i = 0; i < removeEl.length; i++) { var elem = document.getElementById("box1"); elem.remove(); } } } This will delete all div box1 but I want to delete all box1 with class .selected A: Simply use: for (var i = 0; i < removeEl.length; i++) { removeEl[i].remove(); } You already selected all elements which you want to remove. So it's not necessary to select it again with a given id.
{ "pile_set_name": "StackExchange" }
Q: Any Cassandra operation require node to be down? Is there are any Cassandra related operations that would require node to be down (so this node is not available for read and write)? Thanks A: If you want to alter the sstables which store data via the sstable2json or json2sstable tools the cluster shouldn't be running.
{ "pile_set_name": "StackExchange" }
Q: Kendo UI ListView Drag - Drop I have two Kendo UI ListViews. I am able to get the list of available options to load and display values. I am also able to get the drag functionality to work. The issue is the drop functionality of the destination. I can get the second ListView to register as a dropTarget, but I cannot determine how to add the draggable to the destination ListView. Here is the relevant code: var groupDataSource = getReadGroupsDataSourceFor(2819); try { var readgroups = $("#availableReadGroups").kendoListView({ selectable: "single", navigatable: false, template: "#if(!IsSelectedGroup) {# <div style='font-size:13px;padding-left:5px;padding-top:5px;'>${GroupName}</div>#} else {# <div class=\"k-state-selected\" style=\"font-size:13px;padding-left:5px;padding-top:5px;\" aria-selected=\"true\">${GroupName}</div> #}#", dataSource: groupDataSource }); var selectedGroups = $("#selectedGroupsValues").kendoListView({ selectable: "single", navigatable: false, template: "#if(!IsSelectedGroup) {# <div style='font-size:13px;padding-left:5px;padding-top:5px;'>${GroupName}</div>#} else {# <div class=\"k-state-selected\" style=\"font-size:13px;padding-left:5px;padding-top:5px;\" aria-selected=\"true\">${GroupName}</div> #}#", }); readgroups.kendoDraggable({ filter: "div[role=option]", hint: function (row) { return row.clone(); } }); selectedGroups.kendoDropTarget({ drop: function (e) { var lvObject= selectedGroups.data(); lvObject.kendoListView.dataSource.add(e.draggable); } }); } catch (err) { alert(err); } A: I finally came up with an answer and got it to work in IE and FireFox on my machine; I couldn't get this solution to work in jsFiddle, though, and I can't figure out why. Here is the code: selectedGroups.kendoDropTarget({ drop: function (e) { var lvObject= selectedGroups.data(); lvObject.kendoListView.dataSource.add(readgroups.data("kendoListview").dataSource.getByUid(e.draggable.hint.data().uid)); } }); The hint property apparently contains the jQuery object which in turn has a data method. When you execute the data method, the only thing returned is an object with the property uid. Using this, you can search the dataSource of the draggable's origin for the data item. The data item is what you want to supply to the add method of the destination's dataSource.
{ "pile_set_name": "StackExchange" }
Q: Overloading generic event handlers in Scala If I define the following generic event handler trait Handles[E <: Event] { def handle(event: E) } with event type's like this trait Event { } class InventoryItemDeactivated(val id: UUID) extends Event; class InventoryItemCreated(val id: UUID, val name: String) extends Event; how do I then make a single class that implements event handlers for each of these events ?. I tried: class InventoryListView extends Handles[InventoryItemCreated] with Handles[InventoryItemDeactivated] { def handle(event: InventoryItemCreated) = { } def handle(event: InventoryItemDeactivated) = { } } but Scala complains that a trait cannot be inherited twice. I found this answer which hints at a solution, but it seams to require multiple classes (one for each handler). Is this really the only way or is there then some other Scala construct I can use to make a single class implement multiple generic event handlers (i.e. using case classes, manifests or some other fancy construct) ?. A: I don't know of a way to do it in one class (except by making Event an ADT and defining handle to accept a parameter of type Event. But that would take away the kind of typesafety you seem to be looking for). I'd suggest using type-class pattern instead. trait Handles[-A, -E <: Event] { def handle(a: A, event: E) } trait Event { ... } class InventoryItemDeactivation(val id: UUID) extends Event class InventoryItemCreation(val id: UUID, val name: String) extends Event class InventoryListView { ... } implicit object InventoryListViewHandlesItemCreation extends Handles[InventoryListView, InventoryItemCreation] = { def handle(v: InventoryListView, e: InventoryItemCreation) = { ... } } implicit object InventoryListViewHandlesItemDeactivation extends Handles[InventoryListView, InventoryItemDeactivation] = { def handle(v: InventoryListView, e: InventoryItemDeactivation) = { ... } } def someMethod[A, E <: Event](a: A, e: E) (implicit ev: InventoryListView Handles InventoryItemCreation) = { ev.handle(a, e) ... } A: What's the advantage of two separate handle methods? def handle(rawEvent: Event) = rawEvent match { case e: InventoryItemCreated => ... case e: InventoryItemDeactivated => ... }
{ "pile_set_name": "StackExchange" }
Q: How to GET RID of the iFRAME on Azure that wraps my website I uploaded via FTP this is driving me NUTS! I have a website I built that's on AZURE. I built it in NETBEANS 8.2 like I do with EVERY SITE since 2011. I uploaded to AZURE via FILEZILLA with no issue. When I got to login, BOOM! I get this error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) It's because of AZURE WRAPPING MY SITE with TWO IFRAMES!!! Whiskey Tango Foxtrot??? When I'm on my 1and1 DEDICATED SERVER and NOT a VIRTUALIZED AZURE SERVER, I have ZERO PROBLEMS and no IFRAMES! PLEASE SOMEONE TELL ME HOW TO GET RID OF THIS ANNOYANCE??? UPDATE: BRANDO, here's the config on Azure for Virtual Directories. It's pretty straight forward and I get an iFRAME!!! Azure "IS" doing this!!]1 A: Azure web app will not add any codes to your html page.It is just a host platform. www.thingblugrow.com/www.thingblu.com <--- custom domain, add the frameset testappinnovyt.azurewebsites.net/thingbluapp.azurewebsites.net <--- azure web site doesn't add the frameset So this issue is not related with azure web app. So I guess the frame set is added by your custom domain company server or you set the frame by code at some other place(by js) not the azure. I suggest you could try to connect with your custom domain support and could follow this article to bind the custom domain with your azure web app.
{ "pile_set_name": "StackExchange" }
Q: Group width when elements at negative coordinates <s:Group id="g1"> <s:Group id="g2" width="100" x="-40"/> </s:Group> I have a group that contains elements placed at negative coordinate values. I would like to get the total width of the group including parts of elements placed at negative values. In the example above g1.width returns 60 (100-40) but i like to get the value 100. In the example bellow g3.width returns 0 and still i like to get the value 100. How can I do this. I have debugged the application and no property of g1 or g3 is 100. I get the values I want if I use the Box class instead but how do I get the values i want with the Group class? <s:Group id="g3"> <s:Group id="g4" width="100" x="-150"/> </s:Group> This is an simplified example. I have many child elements in the real application so i can't just use the width of the child element. A: Try using contentHeight and contentWidth property on the container.
{ "pile_set_name": "StackExchange" }
Q: How to delete attachment from list item in sharepoint using client object model? The AttachmentCollection object does not have any delete method. How can i do it? A: AttachmentCollection class does not expose any methods for deleting attachments, but you could utilize Attachment.DeleteObject method to delete an Attachment from a collection. The following example demonstrates how to delete all attachments in list item: public static void DeleteAttachmentFiles(ClientContext context, string listTitle,int listItemId) { var list = context.Web.Lists.GetByTitle(listTitle); var listItem = list.GetItemById(listItemId); context.Load(listItem, li => li.AttachmentFiles); context.ExecuteQuery(); listItem.AttachmentFiles.ToList().ForEach(a => a.DeleteObject()); context.ExecuteQuery(); }
{ "pile_set_name": "StackExchange" }
Q: What SQL injection syntax should I send in payload of rest API to test it properly We are creating a API automation suite and we need to write/test sql injection testcase. I have use SQLMAP for same to test my api for sql-injection. Now I need to send some parameter in my test script to test these testcases. I have tried syntax like:- or 1=1 '1' ='1' ' OR ''=' What other I can try. Do it work with JSON Payload POST request as well or should I tried this for GET request only. please suggest a good approach so that I can accomplish my task correctly A: You could start by using one of the several collections of SQL Injection and XSS payload strings hosted on GitHub. For example: SQL/XSS Injection Strings. If you want a serious testing for vulnerabilities you should use a prooven penetration testing framework like Kali Linux or a SQL Injection tool.
{ "pile_set_name": "StackExchange" }
Q: How can i read csv in Python tkinter at the same time? I have some questions to you. My first question is I read csv file with import_csv_data function but before I read the data although I have made definition like "global df" it says df is not defined. If I create a df like df = pd.DataFrame(Columns=["X","Y"]) , this time OptionMenu show X and Y. If i want to show columns of my DataFrame i need to remove df = pd.DataFrame(Columns=["X","Y"]) and then i need to run code again. And i have one questiong connected with this question is when i read csv file, to see last df i need to close Window. So i want to read csv file and i want the program to memorize at the same time. The second question is when i changed the SelectedValue on OptionMenu i want to get the SelectedValue -selected column name- and show on tk.Button(Drop Column + SelectedValue) < in short i want to get the column name on OptionMenu and show the name on Button at the same time. Third question is i can not fit button or text or label to Frame. It is limitting me i have added a photo that describe that question.[Here is image url. > https://ibb.co/wrkcdfK ] Thank you. def _quit(): root.quit() # stops mainloop root.destroy() # this is necessary on Windows to prevent # Fatal Python Error: PyEval_RestoreThread: NULL tstate def option_changed(*args): global SelectedValue SelectedValue = selection.get() print(SelectedValue) def hello(): print("hello!") def import_csv_data(): global v global df global a csv_file_path = askopenfilename() print(csv_file_path) v.set(csv_file_path) df = pd.read_csv(csv_file_path) a = csv_file_path def removenans(): print("Merhaba") print(df.head()) df = pd.read_csv(csv_file_path) def plotthefigure(): df.dropna(inplace=True,axis=0) df.Sex = [1 if i=="female" else 0 for i in df.Sex] plt.figure(figsize=[6,5]) plt.plot(range(len(df["Sex"])),df["Sex"]) plt.title("Age vs Sex") # Plot window name plt.gcf().canvas.set_window_title("Plot Frame") #Switching Frames def raise_frame(frame): frame.tkraise() # Opening new window def aboutmenudef(): window = tk.Toplevel(root) def printdf(): tk.Label(MainFrame,textvariable=df.head()).grid(row=6, columnspan=7, sticky='WE',padx=5, pady=5, ipadx=5, ipady=5) root = tk.Tk() root.wm_title("Machine Learning Implementer") # FRAMES # # MainFrame = Frame(root) AboutFrame = Frame(root) HelpFrame = Frame(root) # for frame in (MainFrame,AboutFrame,HelpFrame): frame.grid(row=0, column=0, sticky=NSEW) v = tk.StringVar() entry = tk.Entry(MainFrame, textvariable=v).grid(row=0, column=1, ipadx=100) head = tk.StringVar() tk.Label(MainFrame,textvariable=head).grid(row=3, columnspan=2, sticky='WE',padx=5, pady=5, ipadx=5, ipady=5) tk.Label(AboutFrame, text="About Us").grid(row=0,column=0) tk.Label(MainFrame,text="File Path").grid(row=0, column=0) mainlabel = Label(MainFrame,text="DF Columns").grid(row=5, column=0) ###---------------------- BUTTON ----------------------### tk.Button(MainFrame, text=" Read CSV ", command=removenans).grid(row=1, column=0) tk.Button(MainFrame, text=" Drop Column\n "+SelectedValue, command=removenans).grid(row=2, column=0) tk.Button(MainFrame, text="Remove NaN Values", command=removenans).grid(row=3, column=0) tk.Button(MainFrame, text=" Print Head of DF ", command=printdf).grid(row=4, column=0) tk.Button(MainFrame, text=" Scale Parameters ", command=printdf).grid(row=10, column=0) tk.Button(MainFrame, text="Plot the Graph", command=plotthefigure).grid(row=0, column=2) ###---------------------- CHECKBOX ----------------------### var = IntVar() c = Checkbutton(root,text="Independent",variable = var) c.grid(row=3, column=3) c.config(state=DISABLED) ###---------------------- MENU & TOOLBARS ----------------------### menubar = Menu(root) # FILE MENU # filemenu = Menu(menubar,tearoff=0) filemenu.add_command(label="Open CSV File", command=import_csv_data) #filemenu.add_command(label="Save", # command=hello) filemenu.add_separator() filemenu.add_command(label="Exit", command=_quit) menubar.add_cascade(label=" File ", menu=filemenu) # MENU PLOT SECTION # plotmenu = Menu(menubar,tearoff=0) plotmenu.add_command(label="Open Plot", command=hello) #plotmenu.add_separator() plotmenu.add_command(label="Close Program", command=_quit) menubar.add_cascade(label=" Plot ", menu=plotmenu) # HELP # helpmenu = Menu(menubar,tearoff=0) helpmenu.add_command(label="Help Index", command=hello) menubar.add_cascade(label=" Help ", menu=helpmenu) # ABOUT # aboutmenu = Menu(menubar,tearoff=0) aboutmenu.add_command(label="About", command=lambda:raise_frame(AboutFrame)) menubar.add_cascade(label=" About ", menu=aboutmenu) root.config(menu=menubar) # OPTION MENU # selection = StringVar(MainFrame) selection.set("-") # default value selection.trace("w", option_changed) w = OptionMenu(MainFrame, selection, *df.columns).grid(row=2, column=1) # root.geometry("800x550") raise_frame(MainFrame) root.mainloop() A: For the first question i have created a new button named Read Csv, so after i have browsed the csv data i read it with a button. For second question i couldnt do this. But i have found something about label with label.config then you can change the value with a def function that you connected with a button for example. For the last question, i guess it was about the root.geometry() i have changed it to root.geometry("1200x800") and i have defined it on the top one section below of root = Tk() .... If you have any questions about tkinter you can ask.
{ "pile_set_name": "StackExchange" }
Q: Question regarding condition of perpendicularity Let $ax^2+2hxy+by^2=0$ be the equation of two straight lines passing through the origin. We know that the angle between these two straight lines is given by, $$\arctan \dfrac{2\sqrt{h^2-ab}}{a+b}$$ The condition for perpendicularity is given by $$a+b=0$$ Is it not illogical? Since we already know (and in fact can prove) that division by $0$ is undefined, how can we define the $\arctan$ of an undefined quantity? A: I think this statement is sloppy, so you are making a good point. What is should be said is that either the lines are perpendicular, for which the test is $a+b=0$, or the lines are not perpendicular, in which case the smaller of the two angles made by the two intersecting lines is given by the formula you give.
{ "pile_set_name": "StackExchange" }
Q: jQuery calculating price not working (correctly) $(function() { var base_price = 0; CalculatePrice(); $(".math1").on('change', function(e) { CalculatePrice(); }); function CalculatePrice() { var base_cost = base_price; $('.math1').each(function() { base_cost += $(this).find('option:selected').data("price"); }); $("#price").text(base_cost.toFixed(2)*32); } }); The script will look at all data-price of the selected option and does this: data-price (of select 1) + data-price (of select 2) But it need to do this: data-price (of select 1) * data-price (of select 2) It will return a standard value for example: 2 person room = $32, 2 2 person rooms = $64 (correctly) 4 person room = $64, 2 4 person rooms = $96 (must be + 64 instead of 32 so will return $128) 6 persoon room = $128, 2 6 person rooms= $160 (must be +128 so will return $256) fiddle: http://jsfiddle.net/5HkEh/3/ Note: this doesn't work base_cost *= $(this).find('option:selected').data("price"); A: Set base_price = 1 Then change your += to *=
{ "pile_set_name": "StackExchange" }
Q: How to get the Selected rows based on Multiple Column Values Name Value Base 0 Type 0 Serialized 1 C4 0 c5 0 I am getting the Above values by having following query. Select T2.Name,Convert(Bit,T2.Value) from [Table1] T1 join [Table2] T2 with(nolock) on T1.Id = T2. Id where T1.SID= 'DDXRS' But I need the rows whose Name is either Base,Type or Seralized? I tried creating temp Table but could not get to the result. A: You just need to include your desired results in the filter: Select T2.Name,Convert(Bit,T2.Value) from [Table1] T1 join [Table2] T2 with(nolock) on T1.Id = T2. Id where T1.SID= 'DDXRS' AND T2.Name IN ('Base', 'Type', 'Serialized')
{ "pile_set_name": "StackExchange" }
Q: good dictionary type for wxwidgets What would be a good dictionary type to use with wxWidgets? Is there such a type somewhere in the framework? Should I just stick with arrays? I've tried unordered_map but giving me errors with the wxString type. #include <unordered_map> std::unordered_map<wxString,int>mapsi; mapsi={ {"first",1}, {"second",2}, }; errors: In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h: In ins tantiation of 'struct std::__detail::_Hash_code_base<wxString, std::pair<const w xString, int>, std::__detail::_Select1st, std::hash<wxString>, std::__detail::_M od_range_hashing, std::__detail::_Default_ranged_hash, true>': d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1402:10 : required from 'struct std::__detail::_Hashtable_base<wxString, std::pair<con st wxString, int>, std::__detail::_Select1st, std::equal_to<wxString>, std::hash <wxString>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_ha sh, std::__detail::_Hashtable_traits<true, false, true> >' d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable.h:174:11: requ ired from 'class std::_Hashtable<wxString, std::pair<const wxString, int>, std:: allocator<std::pair<const wxString, int> >, std::__detail::_Select1st, std::equa l_to<wxString>, std::hash<wxString>, std::__detail::_Mod_range_hashing, std::__d etail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail: :_Hashtable_traits<true, false, true> >' d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\unordered_map.h:100:18: required from 'class std::unordered_map<wxString, int>' E:\bootsi\New folder\TEST.cpp:96:34: required from here d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1070:12 : error: invalid use of incomplete type 'struct std::hash<wxString>' struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1070:12 : error: invalid use of incomplete type 'struct std::hash<wxString>' struct _Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H2, ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1082:53 : error: invalid use of incomplete type 'struct std::hash<wxString>' using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1082:53 : error: invalid use of incomplete type 'struct std::hash<wxString>' using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; ^ E:\bootsi\New folder\TEST.cpp: In constructor 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map(std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type, const hasher&, const key_equal&, const allocator_type &) [with _Key = wxString; _Tp = int; _Hash = std::hash<wxString>; _Pred = std::e qual_to<wxString>; _Alloc = std::allocator<std::pair<const wxString, int> >; std ::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type = unsigned int; std: :unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::hasher = std::hash<wxString>; s td::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::key_equal = std::equal_to<wx String>; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::allocator_type = s td::allocator<std::pair<const wxString, int> >]': E:\bootsi\New folder\TEST.cpp:96:34: error: invalid use of incomplete t ype 'std::unordered_map<wxString, int>::hasher {aka struct std::hash<wxString>}' std::unordered_map<wxString,int>mapsi; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'std::unordered_map<wxString, int>::hasher {aka struct std: :hash<wxString>}' struct hash; E:\bootsi\New folder\TEST.cpp:96:34: note: when instantiating default argument for call to std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unord ered_map(std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type, const h asher&, const key_equal&, const allocator_type&) [with _Key = wxString; _Tp = in t; _Hash = std::hash<wxString>; _Pred = std::equal_to<wxString>; _Alloc = std::a llocator<std::pair<const wxString, int> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type = unsigned int; std::unordered_map<_Key, _Tp, _Hash, _ Pred, _Alloc>::hasher = std::hash<wxString>; std::unordered_map<_Key, _Tp, _Hash , _Pred, _Alloc>::key_equal = std::equal_to<wxString>; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::allocator_type = std::allocator<std::pair<const wxSt ring, int> >] std::unordered_map<wxString,int>mapsi; ^ E:\bootsi\New folder\TEST.cpp: At global scope: E:\bootsi\New folder\TEST.cpp:149:19: error: expected constructor, dest ructor, or type conversion before ';' token CreateStatusBar(); ^ E:\bootsi\New folder\TEST.cpp:150:15: error: expected constructor, dest ructor, or type conversion before '(' token SetStatusText("Welcome to wxWidgets!"); ^ E:\bootsi\New folder\TEST.cpp:151:1: error: expected declaration before '}' token } ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h: In ins tantiation of 'std::__detail::_Hash_code_base<_Key, _Value, _ExtractKey, _H1, _H 2, std::__detail::_Default_ranged_hash, true>::_Hash_code_base(const _ExtractKey &, const _H1&, const _H2&, const std::__detail::_Default_ranged_hash&) [with _Ke y = wxString; _Value = std::pair<const wxString, int>; _ExtractKey = std::__deta il::_Select1st; _H1 = std::hash<wxString>; _H2 = std::__detail::_Mod_range_hashi ng]': d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1463:65 : required from 'std::__detail::_Hashtable_base<_Key, _Value, _ExtractKey, _Eq ual, _H1, _H2, _Hash, _Traits>::_Hashtable_base(const _ExtractKey&, const _H1&, const _H2&, const _Hash&, const _Equal&) [with _Key = wxString; _Value = std::pa ir<const wxString, int>; _ExtractKey = std::__detail::_Select1st; _Equal = std:: equal_to<wxString>; _H1 = std::hash<wxString>; _H2 = std::__detail::_Mod_range_h ashing; _Hash = std::__detail::_Default_ranged_hash; _Traits = std::__detail::_H ashtable_traits<true, false, true>]' d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable.h:828:24: requ ired from 'std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::_Hashtable(std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::size_type, const _H1&, const _H2&, const _Hash&, const _Equal&, const _ExtractKey&, const alloca tor_type&) [with _Key = wxString; _Value = std::pair<const wxString, int>; _Allo c = std::allocator<std::pair<const wxString, int> >; _ExtractKey = std::__detail ::_Select1st; _Equal = std::equal_to<wxString>; _H1 = std::hash<wxString>; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; _Traits = std::__detail::_ Hashtable_traits<true, false, true>; std::_Hashtable<_Key, _Value, _Alloc, _Extr actKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::size_type = unsigned i nt; std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::allocator_type = std::allocator<std::pair<const wxStrin g, int> >]' d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable.h:397:26: requ ired from 'std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::_Hashtable(std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::size_type, const _H1&, const key_equal&, const allocator_type&) [with _Key = wxString; _Value = std::pair<const wxString, int>; _Alloc = std::allocator<std::pair<const wxString , int> >; _ExtractKey = std::__detail::_Select1st; _Equal = std::equal_to<wxStri ng>; _H1 = std::hash<wxString>; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_reha sh_policy; _Traits = std::__detail::_Hashtable_traits<true, false, true>; std::_ Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPol icy, _Traits>::size_type = unsigned int; std::_Hashtable<_Key, _Value, _Alloc, _ ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, _Traits>::key_equal = std::e qual_to<wxString>; std::_Hashtable<_Key, _Value, _Alloc, _ExtractKey, _Equal, _H 1, _H2, _Hash, _RehashPolicy, _Traits>::allocator_type = std::allocator<std::pai r<const wxString, int> >]' d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\unordered_map.h:142:35: required from 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_ma p(std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type, const hasher&, const key_equal&, const allocator_type&) [with _Key = wxString; _Tp = int; _Has h = std::hash<wxString>; _Pred = std::equal_to<wxString>; _Alloc = std::allocato r<std::pair<const wxString, int> >; std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type = unsigned int; std::unordered_map<_Key, _Tp, _Hash, _Pred, _ Alloc>::hasher = std::hash<wxString>; std::unordered_map<_Key, _Tp, _Hash, _Pred , _Alloc>::key_equal = std::equal_to<wxString>; std::unordered_map<_Key, _Tp, _H ash, _Pred, _Alloc>::allocator_type = std::allocator<std::pair<const wxString, i nt> >]' E:\bootsi\New folder\TEST.cpp:96:34: required from here d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1099:63 : error: invalid use of incomplete type 'struct std::hash<wxString>' : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hash table.h:35:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\unordered _map:47, from E:\bootsi\New folder\TEST.cpp:9: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\hashtable_policy.h:1099:63 : error: invalid use of incomplete type 'struct std::hash<wxString>' : __ebo_extract_key(__ex), __ebo_h1(__h1), __ebo_h2(__h2) { } ^ In file included from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basi c_string.h:3033:0, from d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\string:52 , from D:/build/wxWidgets-3.0.1/include/wx/stringimpl.h:66, from D:/build/wxWidgets-3.0.1/include/wx/unichar.h:15, from D:/build/wxWidgets-3.0.1/include/wx/strvararg.h:22, from D:/build/wxWidgets-3.0.1/include/wx/string.h:46, from D:/build/wxWidgets-3.0.1/include/wx/memory.h:15, from D:/build/wxWidgets-3.0.1/include/wx/object.h:19, from D:/build/wxWidgets-3.0.1/include/wx/wx.h:15, from E:\bootsi\New folder\TEST.cpp:5: d:\build\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\functional_hash.h:58:12: e rror: declaration of 'struct std::hash<wxString>' struct hash; A: There is always wxHashMap WX_DECLARE_STRING_HASH_MAP( int, // type of the values myMapType); // name of the class myMapType myMap; myMap["test"]=321; To use wxString in a unordered_map, you will need to provide a hash function for wxString. It might be simpler to use std::wstring. So you have the choices: Use wxHashMap which provides support for wxString immediately, but not for all the latest C+11 goodness. Use unordered_map with a home brewed wxString hash function. Use unordered_map with std::wstring. You will have to convert between wxString and std::wstring, but will get complete support for C++11 Wait of wxWidgets v3.1.0 I recommend option #3, for now
{ "pile_set_name": "StackExchange" }
Q: Find 2 or more criteria in the same elements of an array in MongoDB I have a json data structure as follow: "_id" : { Inst_Id: 1119689706 }, "items" : [ { "Token" : "Let", "Lemma" : "let", "POS" : "VERB" }, { "Token" : "'s", "Lemma" : "-PRON-", "POS" : "PRON" }, { "Token" : "face", "Lemma" : "face", "POS" : "VERB" }, { "Token" : "it", "Lemma" : "-PRON-", "POS" : "PRON", } ] My items are basically fields which have arrays of token of sentences (e.g. "Let's face it inside.) How can I search for 2 or more criteria inside the same item of an array? I have tried $elemMatch but it only matches elements across arrays and not inside one array. For example, I want to look for a sentence for which the token is "face" AND the POS is "VERB" at the same time. A: $elemMatch is the way : db['01'].find( {items:{$elemMatch:{Token:"face",POS:"VERB"}}} ) will return whole document. To return only matching array elements, add the same to projection part of query : db['01'].find( {items:{$elemMatch:{Token:"face",POS:"VERB"}}}, {items:{$elemMatch:{Token:"face",POS:"VERB"}}} ) will return { "_id" : { "Inst_Id" : 1119689706.0 }, "items" : [ { "Token" : "face", "Lemma" : "face", "POS" : "VERB" } ] }
{ "pile_set_name": "StackExchange" }
Q: Trying to submit a form on other server using curl() I've searched a lot of forums as well as here @ stackoverflow but I cant make my script submit the form. I can see other people mangage to make this work but not myself. Nothing updates/changes on the page. RESULT Array ( [url] => http://xxxxxxx.nu/login/index.php' [content_type] => text/html; charset=iso-8859-1 [http_code] => 404 [header_size] => 145 [request_size] => 467 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.01751 [namelookup_time] => 0.001108 [connect_time] => 0.004769 [pretransfer_time] => 0.005047 [size_upload] => 264 [size_download] => 214 [speed_download] => 12221 [speed_upload] => 15077 [download_content_length] => 214 [upload_content_length] => 264 [starttransfer_time] => 0.017168 [redirect_time] => 0 [certinfo] => Array ( ) [redirect_url] => ) 0- This is my attempt <? $www = "http://xxxxxxxxxxxxxxxxxx.se/index.php"; //create array of data to be posted $post_data['mandag_1'] = 'måndag 1'; $post_data['tisdag_1'] = 'tisdag 1'; $post_data['onsdag_1'] = 'onsdag 1'; $post_data['torsdag_1'] = 'torsdag 1'; $post_data['fredag_1'] = 'fredag 1'; $post_data['week'] = '4'; $post_data['food'] = 'y'; $post_data['usersettings'] = 'y'; $post_data['status'] = '1'; $post_data['adress'] = 'Falugatan'; $post_data['stad'] = 'Falun'; $post_data['old_menu'] = '1'; $post_data['menysort'] = '1'; $post_data['telefon'] = '023'; $post_data['hemsida'] = ''; $post_data['epost'] = ''; $post_data['changepassword'] = ''; $post_data['oldpass'] = ''; $post_data['newpass1'] = ''; $post_data['newpass2'] = ''; $post_data['lunchinfo'] = ''; //traverse array and prepare data for posting (key1=value1) foreach ( $post_data as $key => $value) { $post_items[] = $key . '=' . $value; } //create the final string to be posted using implode() $post_string = implode ('&', $post_items); //create cURL connection $curl_connection = curl_init('http://xxxxxxxxxxx.nu/login/index.php'); //set options curl_setopt($curl_connection, CURLOPT_POST, 1); curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); //set data to be posted curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); //perform our request $result = curl_exec($curl_connection); //show information regarding the request print_r(curl_getinfo($curl_connection)); echo curl_errno($curl_connection) . '-' . curl_error($curl_connection); //close the connection curl_close($curl_connection); echo '<br>TTT'.$post_string; ?> Below is how the form looks like on the remote page <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Lunchguide.nu</title> <link rel="stylesheet" type="text/css" href="../style.css?19972" /> <link rel="stylesheet" type="text/css" href="login.css?90004" /> <script type="text/javascript" src="//use.typekit.net/srs7uku.js"></script> <script type="text/javascript">try{Typekit.load();}catch(e){}</script> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <script src="../js/showSingleMap.js"></script> <link rel="stylesheet" type="text/css" media="only screen and (max-width: 1220px) and (min-width: 1px), only screen and (max-device-width: 1220px)" href="../style-1220.css?67124" /> <link rel="stylesheet" type="text/css" media="only screen and (max-width: 920px) and (min-width: 1px), only screen and (max-device-width: 920px)" href="../style-940.css?8540" /> <link rel="stylesheet" type="text/css" media="only screen and (max-width: 620px) and (min-width: 1px), only screen and (max-device-width: 620px)" href="../style-620.css?89448" /> <meta name="viewport" content="width=device-width" /> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="style-ie.css" /> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <script type="text/javascript" src="../js/showhide.js"></script> <script type="text/javascript" src="../js/jquery.placeholder.js"></script> <div id='container'> <div id='header'> <a id="logo" href="index.php"><img src="../img/header_logo_02_2x.png"/></a> <a id="title" href="index.php"><img src="../img/header_title_02_x2.png"/></a> <div class="smallclear"></div> <div id="settingspanel" class="slidingDiv"> <a href="logout.php"> <div class="logout"><img src="../img/logout.png" /></div> </a> <div class="clear"></div> </div> <div id="holder"> <div id='single' style='margin-top:20px;'><form enctype='multipart/form-data' action='' method='POST'><div class='heading'><div class='left'><h3>Lägg till/ändra menyer</h3></div><div class='weekover'><div class='left'><span>Vecka </span><a href='#' id='4' class='active populatedWeek'>4</a><a href='#' id='5' class=''>5</a><a href='#' id='6' class=''>6</a><a href='#' id='7' class=''>7</a><a href='#' id='8' class=''>8</a><a href='#' id='9' class=''>9</a><a href='#' id='10' class=''>10</a><a href='#' id='11' class=''>11</a><a href='#' id='12' class=''>12</a><a href='#' id='13' class=''>13</a></div></div><input type='submit' class='submit' value='Spara meny' /></div><div class='weekunder'><div class='heading'><div class='left'><span>Vecka </span><a href='#' id='4' class='active populatedWeek'>4</a><a href='#' id='5' class=''>5</a><a href='#' id='6' class=''>6</a><a href='#' id='7' class=''>7</a><a href='#' id='8' class=''>8</a><a href='#' id='9' class=''>9</a><a href='#' id='10' class=''>10</a><a href='#' id='11' class=''>11</a><a href='#' id='12' class=''>12</a><a href='#' id='13' class=''>13</a></div></div></div><div class='day' style='background-color:#fff;'> <h4>Måndag 20/1</h4><p>Maträtt 1 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='1' name='mandag_1' autocomplete='off'>...</textarea><p>Maträtt 2 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='2' name='mandag_2' autocomplete='off'></textarea><p>Maträtt 3 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='3' name='mandag_3' autocomplete='off'></textarea><div class='clear'></div></div><div class='day' style='background-color:#fff;'> <h4>Tisdag 21/1</h4><p>Maträtt 1 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='4' name='tisdag_1' autocomplete='off'></textarea><p>Maträtt 2 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='5' name='tisdag_2' autocomplete='off'></textarea><p>Maträtt 3 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='6' name='tisdag_3' autocomplete='off'></textarea><div class='clear'></div></div><div class='day' style='background-color:#fff;'> <h4>Onsdag 22/1</h4><p>Maträtt 1 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='7' name='onsdag_1' autocomplete='off'></textarea><p>Maträtt 2 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='8' name='onsdag_2' autocomplete='off'></textarea><p>Maträtt 3 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='9' name='onsdag_3' autocomplete='off'></textarea><div class='clear'></div></div><div class='day' style='background-color:#fff;'> <h4>Torsdag 23/1</h4><p>Maträtt 1 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='10' name='torsdag_1' autocomplete='off'></textarea><p>Maträtt 2 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='11' name='torsdag_2' autocomplete='off'></textarea><p>Maträtt 3 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='12' name='torsdag_3' autocomplete='off'></textarea><div class='clear'></div></div><div class='day' style='background-color:#fff;'> <h4>Fredag 24/1</h4><p>Maträtt 1 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='13' name='fredag_1' autocomplete='off'></textarea><p>Maträtt 2 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='14' name='fredag_2' autocomplete='off'></textarea><p>Maträtt 3 - <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>60</span></p><textarea tabindex='15' name='fredag_3' autocomplete='off'></textarea><div class='clear'></div></div> <input type='hidden' name='week' value='4' /> <input type='hidden' name='food' value='y' /> <script type="text/javascript"> $(".day textarea").keyup(function () { var maxchars = 60; var tlength = $(this).val().length; if(tlength>maxchars) { $(this).css("background-color","#fcc").fadeOut(10).fadeIn(10).fadeOut(10).fadeIn(10); $(this).val($(this).val().substring(0, maxchars)); } var tlength = $(this).val().length; var remain = maxchars - parseInt(tlength); $(this).prev('p').find('span').next().html(remain); }); $("textarea").focusout(function () { $(this).css("background-color","#fff"); }); $("textarea").keydown(function (evt) { if (evt.keyCode == 13) { iname = $(this).val(); if (iname !== 'Submit'){ var fields = $('input:text,input:checkbox,select,textarea'); var index = fields.index( this ); if ( index > -1 && ( index + 1 ) < fields.length ) { fields.eq( index + 1 ).focus(); } return false; } } }); $(document).ready(function() { $.ajaxSetup ({ cache: false }); $( ".left a" ).click(function() { pos = $(this).attr('id'); $.ajax({ type:"POST", url: "", data: { week:pos, aq:'1' }, context: document.body, success: function(s,x){ $(this).html(s); } }); }); $( ".day textarea" ).each(function( i ) { var tlength = $(this).val().length; $(this).prev('p').find('span').next().html(60-tlength); }); }); </script></div><div id='single'> <div class='heading'> <div class='left'> <h3>Restauranginställningar</h3> </div> <input type='submit' class='submit' value='Spara inställningar' /> </div> <div id="sidebar"> <img src='../img/logo/falun/xxxxxxxxxx.png' /> <h3>xxxxxxxxx</h3> </div> <div id="singleholder"> <div class="menuitem"> <input type="text" id="adress" name="adress" value="Falugatan 3" /> <p>Gatuadress</p> <input type="button" value='Visa gatuadress på karta' onclick="getAdress();" /> <div id='map-canvas'></div> <script>initialize('60.606424, 15.62957');</script><p style='margin-top:3px;font-family: arial;'><span style='font-size:12px;font-style:italic;'>Stämmer inte kartmarkören? Flytta på den!</span></p> <input type="hidden" name="latlong" value="" /> </div> <!-- HÄR KANSKE MAN SKULLE KUNNA GÖRA NÅGON SORTS DROPDOWN <p>Lunchtider:</p> <input name='lunchtider' value='' size='41' /> --> <div class="menuitem"> <input type="text" name='pris' value='89' style='width:18px;' /> <p>Lunchpris</p> <p>Lunchinformation <span class='remainingChars'>Återstående tecken: </span><span class='remainingChars'>70</span></p> <textarea id="lunchinfo" name='lunchinfo'>Inkl salladsbuffe, bröd kaffe kaka, pris 85 kr. Avhämtning 79 kr. månd-fred 11.00-14.00. Välkommen!</textarea> <input type='hidden' name='usersettings' value='y' /> <p>Typ av meny</p> <input class='radiobtn' type='radio' name='menysort' value='1' checked /><p>Ny meny varje vecka</p><input class='radiobtn' type='radio' name='menysort' value='2'/><p>Fast veckomeny</p><input class='radiobtn' type='radio' name='menysort' value='3'/><p>Samma meny alla dagar</p> </div> <input type='hidden' name='old_menu' value='1' /> <div class="menuitem"> <input type="text" name='telefon' value='xxxxxxxxxxxx' /> <p>Telefon</p> <input type="text" name='hemsida' value='http://www.xxxxxxxxxxxxxxxxxxxx.se' /> <p>Hemsida</p> <input type="text" name='epost' value='' /> <p>E-postadress</p> <input type="checkbox" class='radiobtn' id="changepassword" name='changepassword' value='y' /> <p>Jag vill byta mitt lösenord</p> <input id="password" type='password' name='oldpass' disabled="disabled" value='' /> <p>Gammalt lösenord</p> <input id="password" type='password' name='newpass1' disabled="disabled" value='' /> <p>Nytt lösenord</p> <input id="password" type='password' name='newpass2' disabled="disabled" value='' /> <p>Upprepa nytt lösenord</p> <input type='hidden' name='stad' value='Falun' /> <input type='hidden' name='status' value='1' /> </div> </form> </div> <script> $('input[type=file]').change(function(e){ $(".upload").css("background-color", "green"); $(".upload").css("color", "white"); $(".upload span").text("Ny logotyp vald"); }); $('#changepassword').change(function(){ $('.menuitem #password').each(function(i) { if($(this).prop('disabled')) { $(this).prop('disabled', false); } else { $(this).prop('disabled', true); } }); }); var tlength = $("#lunchinfo").val().length; $("#lunchinfo").prev('p').find('span').next().html(70-tlength); $("#lunchinfo").keyup(function () { var maxchars = 70; var tlength = $(this).val().length; if(tlength>maxchars) { $(this).css("background-color","#fcc").fadeOut(10).fadeIn(10).fadeOut(10).fadeIn(10); $(this).val($(this).val().substring(0, maxchars)); } var tlength = $(this).val().length; var remain = maxchars - parseInt(tlength); $("#lunchinfo").prev('p').find('span').next().html(remain); }); $("textarea").focusout(function () { $(this).css("background-color","#fff"); }); getAdress = function(){ var adress=$("#adress").val(); var stad= "Falun"; initialize(adress+", "+stad); } </script></div> <div class="clear"></div> </div> </div> <div id="footer"> <p><img src="../img/mittmedialogo.png" width="140px"></p> </div> <script> $( "#menu1 .selectable" ).click(function() { var option = $(this).html(); window.location.href = 'index.php#'+option; $('#menu1 .active').removeClass('active').addClass('selectable'); $(this).removeClass('selectable').addClass('active'); $('.stad').html(option); }); </script> <script> $('input, textarea').placeholder(); </script> <!-- /Placeholder IEfix --> </body> </html> A: Seems like you haven't set this cURL Parameter.. curl_setopt($curl_connection, CURLOPT_POST, 1);
{ "pile_set_name": "StackExchange" }
Q: How to change mobile device screen size in Unity for testing? For an experiment I need to be able to dynamically adjust the screen size of my device. I'm using a Nexus 5 (5") and want to fake the screensize to 2", 3", 4",.. See images: Is this possible using Unity? I'm aware that I can easily place some planes right in front of my camera, but I'm looking for a proper solution. A: In the editor's Game view, you can set the size that you'll see when you hit Play. Across the top of that view are buttons for screen resolution; the far left side has setting for screen size, and the right side has Maximize on Play. A: You should set the camera background color to black and make your game play in the specified area and then programmatically change the settings of camera like size etc. You can find more information on how to play with camera here: http://docs.unity3d.com/ScriptReference/Camera.html
{ "pile_set_name": "StackExchange" }
Q: Jquery update rails variable I have a ruby on rails site and in that I have a variable called @number. The variable uses a api to grab a number and then displays it. The problem is that it only updates once every refresh. I need it to update every 10 seconds and I believe that it can be done in jquery/ajax. I have tried looking online but havent found anything similar or with rails. Thanks. A: If you have something like this in your template: Hi you have <div id="my_number"><%= @number %></div> here? one way to update that number would be to send an ajax request like this var number = $("#my_number").value(); // get current number as displayed in template // send the number to the server $.ajax({ url: your_controller/check_number, // your controller data: number, // data success: success, dataType: "script" // not 100% sure here might need to google }); In your controller you could have a "check_number" action: def check_number @old_number = params[:number] // number from the template @new_number = update_my_number // not sure what or how your number changes respond_to do |format| format.js // render your js.erb template end end and finally in your js.erb template something like this: <% if @old_number != @new_number %> $("#my_number").value(<%= @new_number %>); // of course you can also do this in controller and just update everytime <% end %> and call for the x (5 seconds in this case) seconds per call just wrap it in: window.setInterval(function(){ // call me here }, 5000); // ms EDIT: I assumed with api you meant something you have control over (your rails app), if that is not the case, you just need to hook into the success callback in the ajax method and update the variable with jquery.
{ "pile_set_name": "StackExchange" }
Q: Removing table row after Ajax success I have a table that will display images stored in a DB as well as some other information. I have a column that has a link that the user can click to delete the image, this works fine however when the user does this I also want to remove the row that the user selects to remove but I can't seem to get it to work. function removeSectionPhoto(image, section_id) { if(confirm("Are you sure you want to delete this image?") == true) { $.ajax({ type: "POST", url: "remove_section_photo.php", data: 'image='+image+'&sectionID='+section_id, success: function(data){ //this is supposed to remove the row but currently doesnt work $("#"+$(this).data("remove-row")).remove(); } }); } } The table rows are being output from PHP, this is what one of the table rows looks like: echo "<tr id='fac_sec_photo_row". $imageRowCount ."'>"; echo "<td><a><img class='section_photo' src='" . $sectionPhotoRow['photo'] . "' alt='Section Photos' height='50' width='50'</a></td>"; echo "<td><input type='text' id='photoDesc' name='photoDesc[]' value='" . $sectionPhotoRow['photo_desc'] . "'</td>"; echo "<td><input type='file' id='new_section_photo' name='new_section_photo[]' onchange='displaySecImage(this)'></td>"; echo "<td><a href='#' class='removeImageRow' data-remove-row='fac_sec_photo_row". $imageRowCount . "' onClick='removeSectionPhoto(\"". $sectionPhotoRow['photo'] ."\", \"". $facilitySecId ."\")'>Remove</a></td>"; echo "</tr>"; What am I doing wrong, how can I remove the selected table row? A: All right. I see part of the issue. You are mixing vanilla javascript with jquery. Jquery does a LOT behind the scenes that hides what javascript doesn't do. Since you are using a vanilla onclick inline on the element, this will likely refer to window, not the element that is being clicked on (I know, confusing). Jquery uses the function.prototype.apply method to re-map this to the target element. Javascript doesn't. But all is not lost, and there is an easy fix. The easiest of which is to just pass in $imageRowCount to your function as well. Then you can simply reference the id directly. function removeSectionPhoto(image, section_id, row_id) { if(confirm("Are you sure you want to delete this image?") == true) { $.ajax({ type: "POST", url: "remove_section_photo.php", data: 'image='+image+'&sectionID='+section_id, success: function(data){ //this is supposed to remove the row but currently doesnt work $("#"+row_id).remove(); } }); } } And then: echo "<td><a href='#' class='removeImageRow' onClick='removeSectionPhoto(\"{$sectionPhotoRow['photo']}\", \"{$facilitySecId}\", \"fac_sec_photo_row{$imageRowCount}\")'>Remove</a></td>"; Another option would be to pass in this to the function call in the onclick='removeSectionPhoto(this, ...etc...)' which would give your first argument (or whatever argument number you pass it in) a reference to that variable. Then $(ele).closest('tr').remove() would work. Really though, you shouldn't mix vanilla js with jquery. Just use jquery to query for the elements and use it's event handlers and this wouldn't have been an issue (well, you still need to map this to self).
{ "pile_set_name": "StackExchange" }
Q: vb.net how to show list of data with variable column widths? I have a situation where I'm trying to fill a listview (or other control) with data from an ADODB recordset in a windows form. The problem is most rows will have several columns, but some rows will only have 1 column. I am trying to create a POS solution where some lines can be comments. example output (simplified for brevity): line 1: [quantity1], [item1], [item1 description], [item1 price] line 2: [comment1] line 3: [quantity2], [item2], [item2 description], [item2 price] line 4: [quantity3], [item3], [item3 description], [item3 price] line 5: [comment2] I would like the comment rows to span the entire width of the control. It is my understanding that a listview will not allow variable column widths like this. Is there a control in vb.net windows forms that will allow this type of formatting? Or is there any other way of achieving this visual output? A: I finally found a custom datagridview control here from viblend that works great. I'm still finding the ropes with the new control, but I'm able to merge rows on the fly through the following code: Imports VIBlend.WinForms.DataGridView Imports VIBlend.Utilities Public Class Form1 Private Sub Form1_Shown(sender As System.Object, e As System.EventArgs) Handles MyBase.Shown With viDataGridView1 .AutoGenerateColumns = True 'dt is a pre-defined dataTable variable .DataSource = dt .ColumnsHierarchy.AutoResize() 'dataTable has 9 columns, first and last columns should be invisible 'unless the row is a designated row for comments .ColumnsHierarchy.Items(0).Width = 0 'this column contains string comment, empty string for non-comment rows .ColumnsHierarchy.Items(8).Width = 0 'this column contains boolean flag [isComment] .AllowCellMerge = True .Refresh() End With End Sub Private Sub viDataGridView1_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) _ Handles viDataGridView1.Paint Dim colItem As HierarchyItem With viDataGridView1 For Each rowItem In .RowsHierarchy.Items colItem = .ColumnsHierarchy.Items(8) 'column with boolean flag If .CellsArea.GetCellValue(rowItem, colItem).Equals(True) Then 'this is a comment line colItem = .ColumnsHierarchy.Items(0) .CellsArea.SetCellSpan(rowItem, colItem, 1, 7) End If Next End With End Sub End Class
{ "pile_set_name": "StackExchange" }
Q: Should a nonresident US citizen get SSN I am married to a woman who holds dual citizenship for both the US and Israel where we actually live. Our entire life is in Israel with no assets in the US at all (later on I will buy some American shares, as I want to invest in some S&P ETFs). She only has a US passport but doesn't have an SSN. Should she get an SSN? As I understand, once you have an SSN, you are supposed to pay taxes for both the US AND the country you actually live in. What benefits do we have from getting an SSN and what are the downsides? A: The US taxes all global income of all US citizens. It doesn't matter where you live, work, or die, or if you ever set foot in the US - if you are a US citizen, you are taxed. That means every US citizen with income is required to file his taxes (unless he makes less than the (current=2020) limit of $ 12 200per person) - and for that you need an SSN or an ITIN. Note that the tax liability might well be zero every year: if a US citizen pays taxes in another country for his income, and the US has a no-double-tax agreement with that country, the tax already paid is deducted from the US taxes due (which might and often does result in 0 or less). I don't know if Israel has such an agreement with the US, but I would think they do. Btw, you can buy shares of US companies or ETFs of them, without buying them in the US - most country's providers offer that. No need to open an account remotely in the Us.
{ "pile_set_name": "StackExchange" }
Q: Найти количество элементов массива, меньших заданного числа В, и произведение четных элементов Есть код который считает произвидение выше указаного пользователем b (то есть числа ниже b игнорируются), нужно чтобы только четные числа перемножались, которые соответственно выше b. Затем вывести количество этих самых четных. int main(int argc, char* argv[]) { setlocale(LC_ALL, "RUS"); float b; cout << "Число b: "; cin >> b; int n; cout << "Кол-во элементов n: "; cin >> n; float* a = new float[n]; float result = 1; int count = 0; for (int i(0); i < n; i++) { cout << "a[" << i << "] = "; cin >> a[i]; if (a[i] > b && a[i %2]) { result *= a[i]; count++; } } if (count == 0) result = 0; cout << result << endl; delete[] a; } A: Вообщем ничего сложного просто запутался немного, решил в итоге. #include <iostream> #include <locale.h> /* Для русского языка */ using namespace std; int main(int argc, char* argv[]) { setlocale(LC_ALL, "RUS"); float b; cout << "Число b: "; cin >> b; int n; cout << "Кол-во элементов n: "; cin >> n; int* a = new int[n]; float result = 1; int count = 0; for (int i(0); i < n; i++) { cout << "a[" << i << "] = "; cin >> a[i]; if (a[i] > b && a[i] % 2 == 0) { result *= a[i]; count++; } } if (count == 0) result = 0; cout <<"Произвидение чисел: " << result << endl << "Количество парных чисел выше "<<b<< " :" << count << endl; delete[] a; }
{ "pile_set_name": "StackExchange" }
Q: Discover JPA annotated classes when using Spring 3+Hibernate JPA I have a web application using the Spring 3 + Hibernate JPA stack. I would like to know if there is a way to have Hibernate to automatically discover @Entity annotated classes, so that I don't have to list them in the persistence.xml file. My @Entity annotated classes "live" in a separate jar, located in the WEB-INF/lib of my web application. This is a snippet from my Spring configuration file: <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="mypersistence"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true"/> <property name="generateDdl" value="true"/> <property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/> </bean> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/> <property name="url" value="jdbc:derby://localhost:1527/library;create=true"/> <property name="username" value="app"/> <property name="password" value="app"/> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> A: You can put the persistence.xml file inside the jar where your entities live. Don't need to specify anything then, it works automagically. A: you can also specify your @Entity annotated classes in applicationContext.xml like this <property name="packagesToScan"> <list> <value>com.vattikutiirf.nucleus.domain</value> <value>com.vattikutiirf.nucleus.domain.generated.secondtime</value> </list> </property>
{ "pile_set_name": "StackExchange" }
Q: Parse SOAP Message to c# classes I am trying to parse SOAP message to c# classes, however I am not getting any errors but still data from SOAP message is not mapped to classes. SOAP MESSAGE: <?xml version="1.0" encoding="UTF-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"> <soap:Body> <mes:dataSaving xmlns:mes="http://message.test.testing.fi/" soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <prdoductType>test product</prdoductType> <action>save</action> <priority>1</priority> <timestamp>27.09.2017 09:12:34274000000</timestamp> <message priority="1" messageTimestamp="27.09.2017 09:12:34274000000"> <![CDATA[<TestData><test>HOSTPITAL_1</test></TestData>]]> </message> </mes:dataSaving> </soap:Body> C# Classes: namespace Xml2CSharp { [XmlRoot(ElementName = "message")] public class Message { [XmlAttribute(AttributeName = "priority")] public string Priority { get; set; } [XmlAttribute(AttributeName = "messageTimestamp")] public string MessageTimestamp { get; set; } [XmlText] public string Text { get; set; } } [XmlRoot(ElementName = "dataSaving", Namespace = "http://message.test.testing.fi/")] public class DataSaving { [XmlElement(ElementName = "prdoductType")] public string PrdoductType { get; set; } [XmlElement(ElementName = "action")] public string Action { get; set; } [XmlElement(ElementName = "priority")] public string Priority { get; set; } [XmlElement(ElementName = "timestamp")] public string Timestamp { get; set; } [XmlElement(ElementName = "message")] public Message Message { get; set; } [XmlAttribute(AttributeName = "mes", Namespace = "http://www.w3.org/2000/xmlns/")] public string Mes { get; set; } [XmlAttribute(AttributeName = "encodingStyle", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public string EncodingStyle { get; set; } } [XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public class Body { [XmlElement(ElementName = "dataSaving", Namespace = "http://message.test.testing.fi/")] public DataSaving DataSaving { get; set; } } [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public class Envelope { [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] public Body Body { get; set; } [XmlAttribute(AttributeName = "soap", Namespace = "http://www.w3.org/2000/xmlns/")] public string Soap { get; set; } [XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2000/xmlns/")] public string Xsd { get; set; } [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")] public string Xsi { get; set; } } } Code to parse SOAP to classes: /// <summary> /// Converts a SOAP string to an object /// </summary> /// <typeparam name="T">Object type</typeparam> /// <param name="soapMsg">SOAP string</param> /// <returns>The object of the specified type</returns> public T SOAPToObject<T>(string soapMsg) { try { var rawXML = XDocument.Parse(soapMsg); using (var reader = rawXML.CreateReader(System.Xml.Linq.ReaderOptions.None)) { var ser = new XmlSerializer(typeof(T)); return (T)ser.Deserialize(reader); } } catch (Exception ex) { throw; } } Code does not throw any error, however properties of DataSaving class are still null. A: Make the name space empty in the attribute [XmlRoot(ElementName = "dataSaving", Namespace = "")] public class DataSaving { [XmlElement(ElementName = "prdoductType")]
{ "pile_set_name": "StackExchange" }
Q: Best way to extend existing website functionality while maintaining the functionality of base libraries? I have an existing site build in c# 3.5 using asp.net mvc 1. There is a section of the site that requires additional behaviour. Basically there is a need to configure an object that is in one of the base libraries to have extended features. If these extended features have been specified on the object, then additional content/functionality should be exposed within the details page of this object. In terms of extending my object with new functionality I was thinking of using the decorator pattern, creating an extendedobject with additional properties etc which I could persist to another database table. I would manage all of this within an extensions library. My problems start at the controller/view level. All of the controller actions have already been written and are in the base library that I do not want to modify. I can make minor modifications to these - however, no breaking changes can be introduced, and all existing functionality should be maintained as the library is used elsewhere. I can however, create as many new controllers/services as I like. To makes things more complicated, this extended functionality is not required for all of the existing objects within the site. The client will need to be able choose to convert certain instances of these objects to the extended type when viewing the details page for the object. This makes my details page very messy. I now need to figure out if the object has been extended already, and if not show the controls which allows the user to convert it to the extended type. If the object has been extended then I will have to display out all it's extended content out onto the page. This would be oki if the functionality was isolated to a specific section of the page (yay, one renderaction!), but the extended content will be output throughout various parts of the page. It seems messy doing a load of different renderactions everywhere, which should only output different content based on whether it is an extended object or not. I half considered doing a single ajax query, and then dynamically rendering each of the sections using javascript when the details page has loaded. I don't want to break or change the existing libraries governing the base functionality of this site. What is the best way to approach this type of problem? A: Could you create an interface matching the existing functionality. Then implement the interface with the new functionality and use a factory to load whichever one is required. I do realise this is a code change though but the new functionality could be in a separate project and the factory and interface wont be a massive change to the code. just a thought
{ "pile_set_name": "StackExchange" }
Q: Create a string from uint32/16_t and then parse back the original numbers I need to put into a char* some uint32_t and uint16_t numbers. Then I need to get them back from the buffer. I have read some questions and I've tried to use sprintf to put them into the char* and sscanf get the original numbers again. However, I'm not able to get them correctly. Here's an example of my code with only 2 numbers. But I need more than 2, that's why I use realloc. Also, I don't know how to use sprintf and sscanf properly with uint16_t uint32_t gid = 1100; uint32_t uid = 1000; char* buffer = NULL; uint32_t offset = 0; buffer = realloc(buffer, sizeof(uint32_t)); sprintf(buffer, "%d", gid); offset += sizeof(uint32_t); buffer = realloc(buffer, sizeof(uint32_t) + sizeof(buffer)); sprintf(buffer+sizeof(uint32_t), "%d", uid); uint32_t valorGID; uint32_t valorUID; sscanf(buffer, "%d", &valorGID); buffer += sizeof(uint32_t); sscanf(buffer, "%d", &valorUID); printf("ValorGID %d ValorUID %d \n", valorGID, valorUID); And what I get is ValorGID 11001000 ValorUID 1000 What I need to get is ValorGID 1100 ValorUID 1000 I am new in C, so any help would be appreciated. A: buffer = realloc(buffer, sizeof(uint32_t)); sprintf(buffer, "%d", gid); offset += sizeof(uint32_t); buffer = realloc(buffer, sizeof(uint32_t) + sizeof(buffer)); sprintf(buffer+sizeof(uint32_t), "%d", uid); This doesn't really make sense, and will not work as intended except in lucky circumstances. Let us assume that the usual CHAR_BIT == 8 holds, so sizeof(uint32_t) == 4. Further, let us assume that int is a signed 32-bit integer in two's complement representation without padding bits. sprintf(buffer, "%d", gid) prints the decimal string representation of the bit-pattern of gid interpreted as an int to buffer. Under the above assumptions, gid is interpreted as a number between -2147483648 and 2147483647 inclusive. Thus the decimal string representation may contain a '-', contains 1 to 10 digits and the 0-terminator, altogether it uses two to twelve bytes. But you have allocated only four bytes, so whenever 999 < gid < 2^32-99 (the signed two's complement interpretation is > 999 or < -99), sprintf writes past the allocated buffer size. That is undefined behaviour. It's likely to not crash immediately because allocating four bytes usually gives you a larger chunk of memory effectively (if e.g. malloc always returns 16-byte aligned blocks, the twelve bytes directly behind the allocated four cannot be used by other parts of the programme, but belong to the programme's address space, and writing to them will probably go undetected). But it can easily crash later when the end of the allocated chunk lies on a page boundary. Also, since you advance the write offset by four bytes for subsequent sprintfs, part of the previous number gets overwritten if the string representation (excluding the 0-termnator) used more than four bytes (while the programme didn't yet crash due to writing to non-allocated memory). The line buffer = realloc(buffer, sizeof(uint32_t) + sizeof(buffer)); contains further errors. buffer = realloc(buffer, new_size); loses the reference to the allocated memory and causes a leak if realloc fails. Use a temporary and check for success char *temp = realloc(buffer, new_size); if (temp == NULL) { /* reallocation failed, recover or cleanup */ free(buffer); exit(EXIT_FAILURE); } /* it worked */ buffer = temp; /* temp = NULL; or let temp go out of scope */ The new size sizeof(uint32_t) + sizeof(buffer) of the new allocation is always the same, sizeof(uint32_t) + sizeof(char*). That's typically eight or twelve bytes, so it doesn't take many numbers to write outside the allocated area and cause a crash or memory corruption (which may cause a crash much later). You must keep track of the number of bytes allocated to buffer and use that to calculate the new size. There is no (portable¹) way to determine the size of the allocated memory block from the pointer to its start. Now the question is whether you want to store the string representations or the bit patterns in the buffer. Storing the string representations has the problem that the length of the string representation varies with the value. So you need to include separators between the representations of the numbers, or ensure that all representations have the same length by padding (with spaces or leading zeros) if necessary. That would for example work like #include <stdint.h> #include <inttypes.h> #define MAKESTR(x) # x #define STR(x) MAKESTR(x) /* A uint32_t can use 10 decimal digits, so let each field be 10 chars wide */ #define FIELD_WIDTH 10 uint32_t gid = 1100; uint32_t uid = 1000; size_t buf_size = 0, offset = 0; char *buffer = NULL, *temp = NULL; buffer = realloc(buffer, FIELD_WIDTH + 1); /* one for the '\0' */ if (buffer == NULL) { exit(EXIT_FAILURE); } buf_size = FIELD_WIDTH + 1; sprintf(buffer, "%0" STR(FIELD_WIDTH) PRIu32, gid); offset += FIELD_WIDTH; temp = realloc(buffer, buf_size + FIELD_WIDTH); if (temp == NULL) { free(buffer); exit(EXIT_FAILURE); } buffer = temp; temp = NULL; buf_size += FIELD_WIDTH; sprintf(buffer + offset, "%0" STR(FIELD_WIDTH) PRIu32, uid); offset += FIELD_WIDTH; /* more */ uint32_t valorGID; uint32_t valorUID; /* rewind for scanning */ offset = 0; sscanf(buffer + offset, "%" STR(FIELD_WIDTH) SCNu32, &valorGID); offset += FIELD_WIDTH; sscanf(buffer + offset, "%" STR(FIELD_WIDTH) SCNu32, &valorUID); printf("ValorGID %u ValorUID %u \n", valorGID, valorUID); with zero-padded fixed-width fields. If you'd rather use separators than a fixed width, the calculation of the required length and the offsets becomes more complicated, but unless the numbers are large, it would use less space. If you'd rather store the bit-patterns, which would be the most compact way of storing, you'd use something like size_t buf_size = 0, offset = 0; unsigned char *buffer = NULL, temp = NULL; buffer = realloc(buffer, sizeof(uint32_t)); if (buffer == NULL) { exit(EXIT_FAILURE); } buf_size = sizeof(uint32_t); for(size_t b = 0; b < sizeof(uint32_t); ++b) { buffer[offset + b] = (gid >> b*8) & 0xFF; } offset += sizeof(uint32_t); temp = realloc(buffer, buf_size + sizeof(uint32_t)); if (temp == NULL) { free(buffer); exit(EXIT_FAILURE); } buffer = temp; temp = NULL; buf_size += sizeof(uint32_t); for(size_t b = 0; b < sizeof(uint32_t); ++b) { buffer[offset + b] = (uid >> b*8) & 0xFF; } offset += sizeof(uint32_t); /* And for reading the values */ uint32_t valorGID, valorUID; /* rewind */ offset = 0; valorGID = 0; for(size_t b = 0; b < sizeof(uint32_t); ++b) { valorGID |= buffer[offset + b] << b*8; } offset += sizeof(uint32_t); valorUID = 0; for(size_t b = 0; b < sizeof(uint32_t); ++b) { valorUID |= buffer[offset + b] << b*8; } offset += sizeof(uint32_t); ¹ If you know how malloc etc. work in your implementation, it may be possible to find the size from malloc's bookkeeping data.
{ "pile_set_name": "StackExchange" }
Q: need help accessing variable inside inner class for loop I am having problem accessing the variable int i inside the inner class Code: public class OnColumnSelectPanel { JFrame jFrame; JPanel mainJPanel; //JPanel jPanel1; //JTextField jTextField; //JButton jButton; //JComboBox jComboBox []; MigLayout layout; MigLayout frameLayout; //column names ColumnNames cn = new ColumnNames(); List<String> listedColumnNames = cn.getColumnNames(); String columnNames[] = listedColumnNames.toArray(new String[0]); public OnColumnSelectPanel(int n) { //jPanel1 = new JPanel(); jFrame = new JFrame("Create Structure of Columns"); // mainJPanel = new JPanel(); layout = new MigLayout("flowy", "[center]rel[grow]", "[]10[]"); frameLayout = new MigLayout("flowx", "[center]rel[grow]", "[]10[]"); //mainJPanel.setLayout(new BoxLayout(mainJPanel, BoxLayout.X_AXIS)); //MigLayout mainJPanelLayout = new MigLayout("flowy", "[]rel[grow]", "[]5[]"); // declare & initialize array JPanel jPanel[] = new JPanel[n]; JComboBox jComboBox[] = new JComboBox[n]; JButton jButton[] = new JButton[n]; final int num = 0; for (int i = 0; i < n; i++) { //assign array jComboBox[i] = new JComboBox(columnNames); jButton[i] = new JButton("add Sub Heading"); jPanel[i] = new JPanel(); System.out.println("Loop number: " + i); jButton[i].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { for (int j = 0; j < n; j++) { if (j <= n) { jComboBox[j] = new JComboBox(columnNames); jPanel[j].add(jComboBox[j]); jFrame.revalidate(); } else { JOptionPane.showMessageDialog(null, "You have exceeded your limit"); } } } }); //set layout jPanel[i].setLayout(layout); //jPanel[i].setPreferredSize(new Dimension(50, 400)); //mainJPanel.setLayout(mainJPanelLayout); jFrame.setLayout(frameLayout); System.out.println(" height " + jPanel[i].getHeight()); jPanel[i].add(jComboBox[i], new CC().newline()); //jPanel.add(jTextField); jPanel[i].add(jButton[i]); //mainJPanel.add(jPanel[i], "spany"); jPanel[i].repaint(); jFrame.add(jPanel[i]); jFrame.pack(); jPanel[i].revalidate(); jFrame.revalidate(); //mainJPanel.revalidate(); //jFrame.revalidate(); } //mainJPanel.setSize(600, 400); //jFrame.add(jPanel1); jFrame.setVisible(true); jFrame.setSize(600, 400); jFrame.setAlwaysOnTop(true); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } Output Frame As you can see the output image. The problem here is that when i click on the add subheading button, combobox is added to every jpanel. this is because i can;t pass the value i to the inner class. It would be interesting to know possible solutions for this. FYI I am using Mig Layout. Thanks in advance. A: Only effectively final variables can be accessed from anonymous classes. i is modified by the loop, so it is not effectively final. A workaround would look like this: for (int i = 0; i < n; i++) { ... final int effectivelyFinal = i; jButton[i].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { ... // use effectivelyFinal instead of i }); } But as other suggested, it would be way better to extract the anonymous class into a real class and pass all required parameters using the constructor. This can look like this: class MyListener implements ActionListener { private final int index; // add more fields for other required parameters public MyListener(int index) { this.index = index; } @Override public void actionPerformed(ActionEvent e) { // use index } } Usage: jButton[i].addActionListener(new MyListener(i));
{ "pile_set_name": "StackExchange" }
Q: Trying to send js variables to a php file I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far: map.php <form action="./finalmap.php"> <input class="finish-button" type="submit" value="FINISH" onclick="sendData();" /> </form> map.js function sendData() { $.ajax({ method: "POST", url: "../finalmap.php", data: { selectedLoc: selectionArray, startLoc: start, endLoc: end, dist: distance, locTypes: allLocations }, beforeSend : function(http) { }, success : function(response,status,http) { alert(response); }, error : function(http,status,error) { $('.response').html("<span class='error'>Something went wrong</span>"); $(".response").slideDown(); } }); } finalmap.php <?php $data = $_POST['data']; echo $data; ?> Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null. My goal is to send the data to finalmap.php and redirect to it. A: To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work. <button type="button" id="submit-button">FINISH</button> Note, no <form> is needed; you're submitting through AJAX. Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded): <button type="button" id="submit-button">FINISH</button> <script> // all listener functions need to wait until DOM is loaded $(document).ready(function() { // this is the same idea as your onclick="sendData(); // but this separates the javascript from the html $('#submit-button').on('click', function() { console.log('hello world'); }); }); </script> You use your web console to see the console.log message. Now, try out the ajax command with a simple post: <button type="button" id="submit-button">FINISH</button> <script> // all listener functions need to wait until DOM is loaded $(document).ready(function() { $('#submit-button').on('click', function() { $.ajax({ method: "POST", // "./finalmap.php" or "../finalmap.php"? url: "../finalmap.php", data: {foo: 'bar'}, success: function(response){ console.log('response is: '); console.log(response); } }); }); }); </script> finalmap.php <?php echo 'This is finalmap.php'; If you see This is finalmap.php in the web console after pressing the button, then you can try sending data. finalmap.php <?php echo 'You sent the following data: '; print_r($_POST); See where we're going with this? The way to eat an elephant is one bite at a time.
{ "pile_set_name": "StackExchange" }
Q: android custom theme divider color for listview I have designed a custom theme for the activity.Everything seems to be applying fine to the views except divider color for listview.(android:dividercolor attribute). I applied it along with android:dividerheight attribute as suggested in other threads.divider height also applied correctly. But when i apply divider color through activity xml file for the specific listview,custom color was applied correctly. Can't we apply custom divider color from custom theme? A: Instead of android:dividercolor, use android:listDivider. <style name="MyAppTheme" parent="Some.Base.Theme"> <item name="android:listDivider">@color/my_divider_color</item> <item name="android:dividerHeight">4dp</item> </style>
{ "pile_set_name": "StackExchange" }
Q: Cannot send email with Java in Test Server I'm using Java Email Sender to send emails in Java.. And I'm using VelocityEngine to send HTML emails. In my local computer everything is good! The emails are sent. But when I deploy the code to the test server (which don't have a domain related, just the IP) The connection with gmail fails. I have my email setting in spring-config.xml <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="mail.domain.com" /> <property name="port" value="25" /> <property name="username" value="[email protected]" /> <property name="password" value="*xxxxxx" /> <property name="javaMailProperties"> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">false</prop> <prop key="mail.smtps.ssl.checkserveridentity">true</prop> <prop key="mail.smtps.ssl.trust">*</prop> </props> </property> </bean> When I try to send the email from the server the error I get said: org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not connect to SMTP host: mail.domain.com, port: 25; And then it said, that it is a timeout.. But my question is if is there any security that I need to disabled from the email server or if it's something with tomcat A: Finally I was able to fix this issue using TLS security in the spring-config So I just have to add <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.starttls.enable">true</prop> <prop key="mail.smtps.ssl.checkserveridentity">true</prop> <prop key="mail.smtps.ssl.trust">*</prop> and changed the port to 587. Regards
{ "pile_set_name": "StackExchange" }
Q: Difference between Templates What is the difference between ControlTemplate DataTemplate HierarchalDataTemplate ItemTemplate A: Control Template A ControlTemplate specifies the visual structure and visual behavior of a control. You can customize the appearance of a control by giving it a new ControlTemplate. When you create a ControlTemplate, you replace the appearance of an existing control without changing its functionality. For example, you can make the buttons in your application round rather than the default square shape, but the button will still raise the Click event. An Example of ControlTemplate would be Creating a Button <Button Style="{StaticResource newTemplate}" Background="Navy" Foreground="White" FontSize="14" Content="Button1"/> ControlTemplate for Button <Style TargetType="Button" x:Key="newTemplate"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border x:Name="RootElement"> <!--Create the SolidColorBrush for the Background as an object elemment and give it a name so it can be referred to elsewhere in the control template.--> <Border.Background> <SolidColorBrush x:Name="BorderBrush" Color="Black"/> </Border.Background> <!--Create a border that has a different color by adding smaller grid. The background of this grid is specificied by the button's Background property.--> <Grid Margin="4" Background="{TemplateBinding Background}"> <!--Use a ContentPresenter to display the Content of the Button.--> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4" /> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> More about ControlTemplate Data Templates Data Template are a similar concept as Control Templates. They give you a very flexible and powerful solution to replace the visual appearance of a data item in a control like ListBox, ComboBox or ListView. WPF controls have built-in functionality to support the customization of data presentation. An Example for the DataTemplate would be <!-- Without DataTemplate --> <ListBox ItemsSource="{Binding}" /> <!-- With DataTemplate --> <ListBox ItemsSource="{Binding}" BorderBrush="Transparent" Grid.IsSharedSizeScope="True" HorizontalContentAlignment="Stretch"> <ListBox.ItemTemplate> <DataTemplate> <Grid Margin="4"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" SharedSizeGroup="Key" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Name}" FontWeight="Bold" /> <TextBox Grid.Column="1" Text="{Binding Value }" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> More about DataTemplates and Triggers Item Templates You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection. An Example for Item Template would be <ListBox Margin="10" Name="lvDataBinding"> <ListBox.ItemTemplate> <DataTemplate> <WrapPanel> <TextBlock Text="Name: " /> <TextBlock Text="{Binding Name}" FontWeight="Bold" /> <TextBlock Text=", " /> <TextBlock Text="Age: " /> <TextBlock Text="{Binding Age}" FontWeight="Bold" /> <TextBlock Text=" (" /> <TextBlock Text="{Binding Mail}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" /> <TextBlock Text=")" /> </WrapPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> When you set an ItemTemplate on an ItemsControl, the UI is generated as follows (using the ListBox as an example): During content generation, the ItemsPanel initiates a request for the ItemContainerGenerator to create a container for each data item. For ListBox, the container is a ListBoxItem. The generator calls back into the ItemsControl to prepare the container. Part of the preparation involves the copying of the ItemTemplate of the ListBox to be the ContentTemplate of the ListBoxItem. Similar to all ContentControl types, the ControlTemplate of a ListBoxItem contains a ContentPresenter. When the template is applied, it creates a ContentPresenter whose ContentTemplate is bound to the ContentTemplate of the ListBoxItem. Finally, the ContentPresenter applies that ContentTemplate to itself, and that creates the UI. If you have more than one DataTemplate defined and you want to supply logic to programmatically choose and apply a DataTemplate, use the ItemTemplateSelector property. The ItemsControl provides great flexibility for visual customization and provides many styling and templating properties. Use the ItemContainerStyle property or the ItemContainerStyleSelector property to set a style to affect the appearance of the elements that contain the data items. For example, for ListBox, the generated containers are ListBoxItem controls; for ComboBox, they are ComboBoxItem controls. To affect the layout of the items, use the ItemsPanel property. If you are using grouping on your control, you can use the GroupStyle or GroupStyleSelector property. For more information, see Data Templating Overview.
{ "pile_set_name": "StackExchange" }
Q: Trying to input data into SQL table using PHP / Html from Registration form I've tried so many different things and did many searches with no solution. I am trying to use an html form to submit data to a sql table. Here is the code for my register.php file. $con = mysqli_connect("localhost", "database_name", "password" "database_user"); if($con === false) { die("ERROR Could not Connect." . mysqli_connect_error()); } $lasty= mysqli_real_escape_string($_POST['laz']); $namez=mysqli_real_escape_string($_POST['namer']); $emailAddr=mysqli_real_escape_string($_POST['emaila']); $userName=mysqli_real_escape_string($_POST['usrn']); $passwo=mysqli_real_escape_string($_POST['passw']); $sqql = "INSERT INTO 'database_name' . table' (UserID, FirstName, LastName, Email, UserName, Password) VALUES (NULL, '$namez', '$lasty', '$emailAddr', '$userName', '$passwo')"; if (mysqli_query($con, $sqql)) { echo "Successfull"; } else { echo "Did not work!" . $con->error; } mysqli_close($con); My HTML file is: <form action="register.php" method="POST"> First Name: <input type="text" name="namer" placeholder="First Name"/> <br> Last Name: <input type='text' name='laz' /> <br> Email Address: <input type='text' name='emaila' /> <br> UserName: <input type='text' name='usrn' /> Password: <input type='password' name='passw' /> <input type='submit' id='button' value='Submit' name='login' /> </form> I apologize in advance for the weirdly named variables, I was afraid that the other files would interrupt what I was trying to do here. A: $con = mysqli_connect("localhost", "database_name", "password" "database_user"); //open connection if (mysqli_connect_errno()) { //if connection failed die("Connect failed: ", mysqli_connect_error()); exit(); } $lasty = mysqli_real_escape_string($con, $_POST['laz']); //added $con needs two parameter (connection, input) $namez = mysqli_real_escape_string($con, $_POST['namer']); $emailAddr = mysqli_real_escape_string($con, $_POST['emaila']); $UserName = mysqli_real_escape_string($con, $_POST['usrn']); $password = mysqli_real_escape_string($con, $_POST['passw']); $sqql = "INSERT INTO `table_name`(UserID, FirstName, LastName, Email, UserName, Password) VALUES (NULL, '$namez', '$lasty', '$emailAddr', '$userName', '$passwo')"; if (mysqli_query($con, $sqql)) { echo "Row inserted"; }else{ die("Error: ". mysqli_sqlstate($con)); } mysqli_close($con);
{ "pile_set_name": "StackExchange" }
Q: MuleSoft: Your application will not run due to vCore availability This is super frustrating, I just followed the video in training and created an account, In accessmanagement the sandbox shows 1 vCore, but when I deploy the application it say, "Your application will not run due to vCore availability", still if I go ahead and deploy which it allows, it says "The maximum number(0) of live sandbox applications has been reached." whats going on here, I have read similar blogs and questions here, this is probably going to be considered as duplicate, but none of existing questions help. I am using training account and there is no Dev just sandbox environment, so don't tell me to go to Test environment, as all I find is sandbox environment there. A: Thanks, I fixed it myself, on deployment window in anypoint studio, top right hand corner, if allows you to select group that you have created under organisation. Select group that has vCore assigned and it will get deployed.
{ "pile_set_name": "StackExchange" }
Q: CSS width should depend on parent I guess this is a standard css problem, but I can't figure it out. html <div class="container"> <div class="outer"> <img class="img"> <div> <h4><a href="#">Link</a></h4> <span>Text</span> </div> </div> <div class="outer"> <img class="img"> <div> <h4><a href="#">Link</a></h4> <span>Longer Text which breaks the design</span> </div> </div> <div class="outer"> <img class="img"> <div> <h4><a href="#">Link</a></h4> <span>Text</span> </div> </div> </div> css .container { width: 800px; background-color: yellow; } .outer { width: 31%; margin: 0.5em; background-color: blue; display: inline-block; height: 100px; } .outer div { display: inline-block; float: left; margin: 10px 10px 10px 0; background-color: red; } .img { display: inline-block; float: left; margin: 10px; width: 80px; height: 80px; } http://jsfiddle.net/a6ZjS/ As you can see, if the text inside the <span> element gets to long the design breaks. But I would like the text to break and not the design. There may also be some unnecessary stuff in the css. A: Here's one way of solving it: http://jsfiddle.net/thirtydot/a6ZjS/19/ .outer { display: inline-block; vertical-align: top; } .outer div { overflow: hidden; } .img { float: left; }
{ "pile_set_name": "StackExchange" }
Q: How to divide a string to substring and assign another substring? I want to divide *eString to substrings. Substrings should be like that: y_{1} = y_{1}y_{m+1}y_{2m+1}... y_{2} = y_{2}y_{m+2}y_{2m+2}... y_{m} = y_{m}y_{2m}y_{3m}... where y is the element of *eString, and y is the substring of these elements. For instance, if an user expects the key length which is 5, there should be (string size / 5) substrings. y_{1} has to contain the fist element of each divided substring. So, how can I implement this? #include <stdio.h> #include <stdlib.h> #include <string.h> #define ALPHA 26 char *ReadFile(char *); int main(int argc, char *argv[]) { double frequency[ALPHA] = {0}; int c = 0; int keylen = 0; int counter = 0; double indexofCoincidence = 0,total = 0; const char *eString = ReadFile("cipher.txt"); int len = 0; if (eString) { puts("The encrypted text is:"); puts(eString); puts(""); len = strlen(eString); printf("The length of text is %d\n",len); } puts(""); while(eString[c]!= '\0'){ if(eString[c]>= 'a' && eString[c]<='z') frequency[eString[c]-'a']++; c++; } puts("The letters frequencies are :\n"); for(c=0; c<ALPHA;c++){ if(frequency[c]!= 0) printf("%c : %.3f\t",c+'a',(frequency[c]/len)); total += (frequency[c]*(frequency[c]-1)); } indexofCoincidence = (total/((len)*(len-1))); printf("\n\nIndex of Coincidence : %.3f\n",indexofCoincidence); if(indexofCoincidence < 0.060){ printf("\nIt looks like randomly.\n"); } printf("Enter the your expected key length : "); scanf("%d",keylen); printf("\n"); char *y; while(counter != keylen) { for(int i = 0; i<(len/keylen);i++){ y[counter] = *eString(); } counter++ } return EXIT_SUCCESS; } A: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void){ char *eString = "The quick brown fox jumps over the lazy dog"; int keylen = 5; int len = strlen(eString); int y_len = (len + keylen) / keylen + 1; int i,j; char **y = malloc(keylen * sizeof(*y)); for(i=0; i < keylen; ++i){ y[i] = malloc(y_len * sizeof(**y)); } char *p = eString; i = j = 0; while(*p){ y[i % keylen][j] = *p++; y[i % keylen][j+1] = 0; if(++i % keylen == 0) ++j; } //check print & deallocate for(i = 0; i < keylen; ++i){ printf("y_{%d} : %s\n", i+1, y[i]); free(y[i]); } free(y); return 0; }
{ "pile_set_name": "StackExchange" }
Q: Rationalizing the denominator 3 It is a very difficult question. How can we Rationalizing the denominator? $$\frac{2^{1/2}}{5+3*(4^{1/3})-7*(2^{1/3})}$$ A: Your denominator is a polynomial in $x = 2^{1/3} = \sqrt[3]{2}$, i.e. you can write it as $5 - 7x + 3x^2$. I use $x$ for simplicity (something mathematicians very often do), so everywhere you see one you can swap it for $2^{1/3}$ if you like. We want a polynomial $p(x)$ so that $(5 - 7x + 3x^2)\cdot p(x)$ is just a rational constant term. We will get that by utilizing that $x^3 = 2$ and $x^4 = 2x$. This also means that $p(x)$ doesn't need to be more than a second degree polynomial (were it of any higher degree, we could take any higher degree term and reduce it by three degrees because of $x^3 = 2$). So let's write down a tentative $p(x) = a + bx + cx^2$. We have $$ (5 - 7x + 3x^2)\cdot p(x) = 5a + (5b - 7a)x + (5c - 7b + 3a)x^2 + (-7c + 3b)x^3 + 3cx^4\\ = 5a - 14c + 6b + (5b -7a + 6c)x + (5c - 7b + 3a)x^2 $$ (Note that $(-7c + 3b)$ and $3c$ doubled when I moved them down three degrees. That doubling comes from $x^3 = 2$. If you are going to do this for other cube roots, e.g. $3^{1/3}$, you will have to multiply by something else, e.g. $3$.) This polynomial is supposed to be just a constant term, so we must have $$ 5b - 7a + 6c = 0 \quad \land \quad 5c - 7b + 3a = 0 $$ Since for any valid polynomial $p(x)$ we also have $k\cdot p(x)$ valid for a rational $k$, we can let $k = \frac{1}{c}$, and assume that $c = 1$. We then get $$ 7a - 5b = 6 \quad \land \quad 7b - 3a = 5 $$ with the solutions $$ b = \frac{53}{34}\quad a= \frac{67}{34} $$ so the polynomial $$ p(x) = \frac{67}{34} + \frac{53}{34}x + x^2 $$ works. This is not so pretty, though, so we multiply it by $34$ to get $$ 34\cdot p(x) = 67 + 53x + 34x^2 = 67 + 53\cdot 2^{1/3} + 34\cdot 4^{1/3} $$ So that's what we have to expand the fraction by to get a rational denominator (the denominator happens to become $177$, but that's not the important part of this exercise).
{ "pile_set_name": "StackExchange" }
Q: How is this valid syntax? Fiddling with javascript and arrays, and this passed as valid syntax, how? var x = [asd = {a: 10, b: 20}] this line is to meet question quality standards. A: Let us separate and see: The code you write can change to below: // it not have the `var` like other answer say asd = {a: 10, b: 20} var x = [asd] But be careful about using it, it can cause global define variable. And if it in strict mode,this will not work, because the Implicitly defined global is not allow. A: Here are some ways to achieve the thing you want: Create the object using object literal var asd = {a: 10, b: 20}; Or create the object using object constructor var asd = new Object(); asd.a = 10; asd.b = 20; And Then push this object into your array. The array again can be created in the following ways: Using array literal var x = [asd]; Or using array constructor: var x = new Array; x.push(asd);
{ "pile_set_name": "StackExchange" }
Q: Connection Pooling in Clojure I am unable to understand the use of pool-db and connection function in this connection pooling guide. (defn- get-pool "Creates Database connection pool to be used in queries" [{:keys [host-port db-name username password]}] (let [pool (doto (ComboPooledDataSource.) (.setDriverClass "com.mysql.cj.jdbc.Driver") (.setJdbcUrl (str "jdbc:mysql://" host-port "/" db-name)) (.setUser username) (.setPassword password) ;; expire excess connections after 30 minutes of inactivity: (.setMaxIdleTimeExcessConnections (* 30 60)) ;; expire connections after 3 hours of inactivity: (.setMaxIdleTime (* 3 60 60)))] {:datasource pool})) (def pool-db (delay (get-pool db-spec))) (defn connection [] @pool-db) ; usage in code (jdbc/query (connection) ["Select SUM(1, 2, 3)"]) Why can't we simply do? (def connection (get-pool db-spec)) ; usage in code (jdbc/query connection ["SELECT SUM(1, 2, 3)"]) A: The delay ensures that you create the connection pool the first time you try to use it, rather than when the namespace is loaded. This is a good idea because your connection pool may fail to be created for any one of a number of reasons, and if it fails during namespace load you will get some odd behaviour - any defs after your failing connection pool creation will not be evaluated, for example. In general, top level var definitions should be constructed so they cannot fail at runtime. Bear in mind they may also be evaluated during the AOT compile process, as amalloy notes below.
{ "pile_set_name": "StackExchange" }
Q: iOS: Removing UINavigationBar animation Our app has an UINavigationBar with an image on it. When we segue (push) to another screen then click the back button the image on the Navigation Bar seems to animate from left to right as it reappears. This is a little distracting. How can you remove this back button animation? We tried changing the segue Animates setting but this changes both the push animation and not the back animation. Our Nav Bar code: let logoImage:UIImage = UIImage(named: "ABC")! viewController.navigationItem.titleView = UIImageView(image: logoImage) A: Figured this out in large part due to this answer https://stackoverflow.com/a/8602982/47281 Create a custom Nav Bar and override popItem: class MyNavigationBar: UINavigationBar { override func popItem(animated: Bool) -> UINavigationItem? { return super.popItem(animated: false) } } Entered MyNavigationBar as the Navigation Bar class for our Navigation Controller via the Storyboard: Note I did not override NavigationController popViewControllerAnimated as in the linked answer.
{ "pile_set_name": "StackExchange" }
Q: Fastest way to add to a list elements not in second list I have 2 listBoxes with BindingLists as their data sources. The idea is to make a List builder (as MSDN names it), where first listBox shows currently added columns and second listBox shows the rest of available columns. First list contains ViewColumn objects, while the other list contains strings. I load chosen columns into first listBox from database and then I want to load the rest of available columns into the second listBox (the list itself comes from another place in database). Considering there are no limits on the number of columns, I want to do that in the fastest way possible - what would that be? Here's some code to visualize that: ViewTable _view; BindingList<ViewColumn> _viewColumns = new BindingList<ViewColumn>(); BindingList<string> _detailsColumns = new BindingList<string>(); void CustomInitialize() { _view = //get view and its columns _viewColumns = new BindingList<ViewColumn>(_view.Columns); listBox_CurrentColumns.DataSource = _viewColumns; listBox_CurrentColumns.DisplayMember = "Name"; var detailsTable = //get the list of available columns foreach (var row in detailsTable) { //TODO: if _viewColumns does not contain this value, add it to _detailsColumns _detailsColumns.Add(row.ColumnName); } listBox_AvailableColumns.DataSource = _detailsColumns; } A: I think you want to do something like: _detailsColumns = _allColumns.Except(_viewColumns.Select(c => c.Name)) This should get you all entries in the _allColumns collection excluding the entries in the _viewColumns collection. I assume here that _allColumns contains the overall collection of possible columns.
{ "pile_set_name": "StackExchange" }
Q: Generic Method Type Parameter I've this method that takes 3 parameters of type T that implements interface Comparable public static < T extends Comparable< T > > T maximum( T x, T y, T z ) {} I am asking about declaring this in other way, like the following (assuming that it takes any Comparable object as its parameters) public static <Comparable <T>> T maximum (T x, T y, T z){} another question, in the first declaration, I know that Comparable is an interface so why it's written as <T extends Comparable<T>> instead of <T implements Comparable<T>>?? A: public static <Comparable <T>> T maximum (T x, T y, T z){} is not compiling because the parameter T is undeclared for the method. I know that Comparable is an interface so why it's written as > instead of >?? The syntax for bounded type parameters is with extends not implements even if the parameter is required to implement an interface. A: Both of your questions can be answered with: this is the Java syntax. In the Java language a parameterized method is declared like this: [optional modifiers] <T> [return type] foo() {} It declares a type parameter named T, which can be constrained with an upper bound with the syntax: T extends [type expression] In the rest of the method (return type, formal parameters list, method body) T refers to the type you pass when invoke the method. In a declaration like: Comparable<T> T is not a type parameter, but it's a type argument used to instantiate the parameterized type Comparable<E>, and belongs to a bigger scope like, say: class Foo<T> { public Comparable<T> foo(T arg1, T arg2) {} } Note that the text <Comparable<T>> (a type enclosed in angle brackets) in a source file isn't allowed at all. It doesn't mean anything to a compiler, which will refuse to compile the file. Similarly, regarding your second question, extends is simply a keyword in the Java language and has two different meanings: It can be used in a class declaration to inherit another class It can be used to put an upper bound on a type parameter The Java creators could have decided to use a different keyword to distinguish the two cases, but they simply overloaded an existing one because they felt it was easier to remember for developers. But they are definitely different keywords, that's why you don't use implements when declaring an upper bound for a type parameter.
{ "pile_set_name": "StackExchange" }
Q: Add elements to textarea by clicking a button I want to add text to textarea when user clicks a button. I have used the code bellow : <script> document.addEventListener('DOMContentLoaded', start, false); function start(){ document.getElementById("button0").addEventListener("click", function(){ addText(this); }); function addText(elem) { document.getElementById("transcript").innerHTML += elem.value; } }; </script> When the users click the button the text added to the textarea but the moment they type using their keyboard they won't be able to add the text using the button anymore. A: use .value not .innerHTML. .innerHTML overwrites the markup of the element, not just the text. Since it's a form element you should be manipulating its value only. document.getElementById("button0").addEventListener("click", function() { document.getElementById("transcript").value += "huh"; }); #transcript { height: 100px; } <button id="button0">Click Me</button> <textarea id="transcript"></textarea>
{ "pile_set_name": "StackExchange" }
Q: Javascript how to change cell colour on timing event? I am currently learning JavaScript and I want to get a cell to blink yellow on a time based event, it seems the JavaScript fails every time I get to: document.all.blinkyellow.bgColor = "yellow"; At the moment when my timer reaches 5 it just stops I am guessing it's failing on the above line of code as when I remove it, the timer continues infinitely. The full JavaScript is below with the relevant html. I would like to know how to properly edit the cell bg colour over time without using a JavaScript library if possible. This purely so I can learn JavaScript as a whole rather then using a library and not being able to understand the library when I need to make modification or plugin. Javascript: var count=0; var time; var timer_is_on=0; setTimeout(doIt, 3000); function timedCount() { if(count == 6){ document.all.blinkyellow.bgColor = "yellow"; } document.getElementById('txt').value=count; count=count+1; time=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } HTML: <table> <tbody> <tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 3</td> </tr> <tr> <td class="blinkyellow">Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 3</td> </tr> <tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 3</td> </tr> <tr> <td>Col 1</td> <td>Col 2</td> <td>Col 3</td> <td>Col 3</td> </tr> </tbody> </table> A: How come your looking for and element with the id of "txt"? Also you're calling doIt in your setTimeout(doIt, 3000) you may want to change that to setTimeout("timedCount();", 3000); Also document.all is IE only (Very Important)! var count=0; var time; var timer_is_on=0; setTimeout("timedCount();", 3000); function timedCount() { if(count == 6){ document.getElementById('blinkyellow').style.backgroundColor = "yellow"; } count=count+1; time=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } remember to change the class on the td to an id like this <td id="blinkyellow">Col 1</td>
{ "pile_set_name": "StackExchange" }
Q: Convex optimization: Piece-wise, quadratic objective This question is about convex optimization with a convex objective function, which is defined piecewise. We have two functions, a concave function A(x) and a strictly convex, increasing function B(x), both defined on [0, infinity) and not negative, $a, b, c, \alpha, \beta$ are constants. The objective function of the problem is A(x) - B(x), so the optimization problem is convex and formulated like this: $$A(x) = \begin{cases} \beta x - \frac{\alpha}{2} x^2, & 0 \leq x < \frac{\beta}{\alpha} \\ \frac{\beta^2}{2 \alpha}, & x \geq \frac{\beta}{\alpha} \end{cases}$$ $$B(x) = a x^2 + b x + c$$ $$\max_{\substack{\mathbf{x} \in \mathbb{R}}} A(x) - B(x)$$ Here, we have the plot of A (red), B (blue) and the objective function A - B (green) as an example. Optimization problem plot Note, that this is a simplified version of the actual problem, where we have a sum of A minus a sum of B with multiple variables, summed up as x in the above problem, but for the core issue I have, this simplified approach is essential. My question is, how to formulate this problem for an optimizer, like JOptimizer, how to cover both cases of A? What class of problem is this, if not QP or QCQP? What I have tried so far: The problem is convex and from my limited knowledge about optimization theory, I can only classify it as QP or QCQP among LP, QP, QCQP, SOCP, SDP, GP. I can successfully transform the problem to QP without the second case (constant case) of A, because then, the problem is quadratic but not solvable in general (only for the defined range of the first case of course). I have researched a lot about this, but I have not found a single source on how to classify the problem or transform it in case there is a function with two cases as A. The only thing I found was for linear programs with multiple linear functions, by introducing an auxiliary variable to maximize, but that does not work in this case, because the second case of A is always the maximum and the first is always the minimum. A: I'm not sure if this is going to generalize to your more complex model, but the scalar case isn't that difficult here. Let's define $\bar{A}(z) = \beta z - \alpha z^2 / 2$, the first "mode" if $A$. Then $$A(x) = \max\{\bar{A}(z) \,|\, z\leq x, ~z \leq \beta/\alpha\}$$ So your original problem transforms from this: $$\begin{array} \text{maximize}_x & A(x) - B(x) \\ \text{subject to} & x \geq 0 \end{array}$$ to this: $$\begin{array} \text{maximize}_{x,z} & \bar{A}(z) - B(x) \\ \text{subject to} & x \geq 0 \\ & x \geq z \\ & z \leq \beta/\alpha \end{array}$$ Now you have a garden variety QP.
{ "pile_set_name": "StackExchange" }