text
stringlengths
64
81.1k
meta
dict
Q: reading into an enum from xml in c# I currently have a project I am working on in c# that uses an enum. At the moment it looks like this . . . public enum Temp { CAREA = 10, CAREB = 20, CAREC = 22, CARED = 35 } However instead of that I would like to call the same data (as an enum) from either a .txt file or an .xml file. Either will do. This is to save a re-build every time I have to add another entry into the enum (this happens frequently) - it would be much easier to edit the .txt or .xml file. A: Instead of using an enum which changes dynamically at runtime I suggest you use a Dictionary. class MyClass { private Dictionary<string, int> tempValues = new Dictionary<string, int>() { { "CAREA", 10 }, { "CAREB", 20 }, { "CAREC", 22 }, { "CARED", 35 } } public Dictionary<string, int> TempValues { get { return this.tempValues } } } You still need to load the values from a file and fill them: private void ReadValues(string path) { foreach(string line in File.ReadAllLines(path)) { string[] tokens = string.Split(','); string key = tokens[0]; int value = int.Parse(tokens[1]); // TODO: check if key does not already exist this.tempValues.Add(key, value); } } Your input file would need to look like this: CAREA,10 CAREB,20 CAREC,22 CARED,35
{ "pile_set_name": "StackExchange" }
Q: Add class to button inside a js function I want to create buttons and add classes to those button after creation I am working on below code !1 Please Help me out :) Will this work? $("#"+element.id).addClass(".btn"); Thank you in advance !! for (var i = 0; i < 9; i++) { add(i); } function add(i) { var element = document.createElement("input"); element.type = "button"; element.value = i; element.name = i + 1; element.id = "btn" + i; element.onclick = function() { window.move(i); }; var append = document.getElementById("append"); append.appendChild(element); alert(element.id); $("#" + element.id).addClass(".btn"); } A: You can add classes in javascript like that: element.className += 'className'; If you are using jQuery then what you did is correct, except the dot you put into addClass function. So instead of: $(element).addClass('.className'); You do: $(element).addClass('className');
{ "pile_set_name": "StackExchange" }
Q: Javascript Do while loop stops after one iteration only I have a do while loop that stops after one iteration only, although the condition has a false result more than once. Another thing - everything that comes after the while statement isn't executed. The code is very long so here is an example of the test condition: do { let x = 0; let y = 3; for (let j = 0; j < 9; j++) { if(j%2==0){ x++; } } } while (x < y); Anyone knows why? A: The reason is x is not defined. let has got a block scope. and you have declared x and y in do block which doesn't have scope after the block. If you want to use them in the while condition place them either outside or change the let to var. You are ending up with an error and hence, the code doesn't execute after the while. To sense the error surround it with a try catch. do { let x = 0; let y = 3; for (let j = 0; j < 9; j++) { if (j % 2 == 0) { x++; } } } while (x < y); do { var x = 0; var y = 3; for (let j = 0; j < 9; j++) { if (j % 2 == 0) { x++; } } } while (x < y); console.log(x) Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Question when you make a phone call I was watching tv, one scene is that when someone make a phone call and look for Mr. Lee, he says”this is dr. Anderson, Mr. Lee in, please.” So my question is that “Mr.lee in, please.” is a common way to express when you want to speak to someone on the phone or it has to be in certain situation you will say so?? Thanks for answering. A: For spoken English the dropping of "Is ..." as "Is Mr. Lee in?" is okay. This normally happens with casual speech. Written English, the verb would always be included. Another example, also on the phone: Hi, this is Dr. Anderson. Jonathan there? or: Hi, this is Dr. Anderson. Is Jonathan there? Entering a house that looks empty: Anybody home? or: Is anybody home? At a dinner table, pointing to some food: Anyone eating this? or: Is anyone eating this? For more information, you can look at: Questions omitting initial auxiliary verb (View of MLA, APA, Chicago?) A: This does not sound like the sort of thing that a native speaker would say. Either you misheard "Is Dr Lee in, please" (The word "is" might be unstressed and could sound almost like "zdoctorleen") Or you misheard "Dr Lee, please". It is possible that the actor made a mistake or misspoke.
{ "pile_set_name": "StackExchange" }
Q: Bind search input to ng-repeat in different controller I am building a web application using Angular. We have a Twitter-like navigation bar up top with a search box in it. Then we have a bunch of entries below, using the ng-repeat directive. I want to be able to bind the search box with the entries below. The challenge is due to the fact that our header and our entries are in two different controllers. If they were in the same controller, then we could do this: <input type="search" ng-model="search"> <div ng-repeat="entry in entries | filter:search"> {{ entry.text }} </div> But since in my application the search box is in a different controller, search isn't in scope so it's not working. Any suggestions? A: If you put the search string inside a service you can share the data between both controllers. Here is an example. <!doctype html> <html ng-app="app"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script> <script> angular.module('app', []); angular.module('app') .controller('Ctrl1', function($scope, ShareData) { $scope.myData1 = ShareData; }); angular.module('app') .controller('Ctrl2', function($scope, ShareData) { $scope.myData2 = ShareData; $scope.entries = [ '1', '2', '3', '11' ] }); angular.module('app') .service('ShareData', function(){ return { search: "1" } }) </script> </head> <body > <div ng-controller="Ctrl1"> <h2>Inside Ctrl 1</h2> <input type="text" ng-model="myData1.search"> </div> <hr> <div ng-controller="Ctrl2"> <h2>Inside Ctrl 2</h2> <div ng-repeat="entry in entries | filter:myData2.search"> {{entry}} </div> </div> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Elasticsearch Aggregation by Day of Week and Hour of Day I have documents of type: [{"msg":"hello", date: "some-date"},{"msg":"hi!", date: "some-date"}, ... I want to have the count of documents by day of week. For example x messages were sent on Monday and y were sent on Tuesday and so on. I have used date_histogram with aggregation but it returns me the documents day wise. It does return me the day, but say "Wed, 22" and "Wed, 29" are returned as separate aggregation documents. This is somewhat related to Elasticsearch - group by day of week and hour but there is no answer to that question so I am reposting it. According to the suggestion there it asks me to do term aggregation on key_as_string, but I need to add doc_count for every object instead of just count the terms. I also don't know how to use key_as_string in the nested aggregation. This is what I have tried: "aggs" : { "posts_over_days" : { "date_histogram" : { "field" : "created_time", "interval": "day", "format": "E" } } A: Re-post from my answer here: https://stackoverflow.com/a/31851896/6247 Does this help: "aggregations": { "timeslice": { "histogram": { "script": "doc['timestamp'].value.getHourOfDay()", "interval": 1, "min_doc_count": 0, "extended_bounds": { "min": 0, "max": 23 }, "order": { "_key": "desc" } } } This is nice, as it'll also include any hours with zero results, and, it'll extend the results to cover the entire 24 hour period (due to the extended_bounds). You can use 'getDayOfWeek', 'getHourOfDay', ... (see 'Joda time' for more). This is great for hours, but for days/months it'll give you a number rather than the month name. To work around, you can get the timeslot as a string - but, this won't work with the extended bounds approach, so you may have empty results (i.e. [Mon, Tues, Fri, Sun]). In-case you want that, it is here: "aggregations": { "dayOfWeek": { "terms": { "script": "doc['timestamp'].value.getDayOfWeek().getAsText()", "order": { "_term": "asc" } } } Even if this doesn't help you, hopefully someone else will find it and benefit from it. A: The same kind of problem has been solved in this thread. Adapting the solution to your problem, we need to make a script to convert the date into the hour of day and day of week: Date date = new Date(doc['created_time'].value) ; java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH'); format.format(date) And use it in a query: { "aggs": { "perWeekDay": { "terms": { "script": "Date date = new Date(doc['created_time'].value) ;java.text.SimpleDateFormat format = new java.text.SimpleDateFormat('EEE, HH');format.format(date)" } } } }
{ "pile_set_name": "StackExchange" }
Q: Difference between h:button and h:commandButton In JSF 2, what is the difference between h:button and h:commandButton ? A: <h:button> The <h:button> generates a HTML <input type="button">. The generated element uses JavaScript to navigate to the page given by the attribute outcome, using a HTTP GET request. E.g. <h:button value="GET button" outcome="otherpage" /> will generate <input type="button" onclick="window.location.href='/contextpath/otherpage.xhtml'; return false;" value="GET button" /> Even though this ends up in a (bookmarkable) URL change in the browser address bar, this is not SEO-friendly. Searchbots won't follow the URL in the onclick. You'd better use a <h:outputLink> or <h:link> if SEO is important on the given URL. You could if necessary throw in some CSS on the generated HTML <a> element to make it to look like a button. Do note that while you can put an EL expression referring a method in outcome attribute as below, <h:button value="GET button" outcome="#{bean.getOutcome()}" /> it will not be invoked when you click the button. Instead, it is already invoked when the page containing the button is rendered for the sole purpose to obtain the navigation outcome to be embedded in the generated onclick code. If you ever attempted to use the action method syntax as in outcome="#{bean.action}", you would already be hinted by this mistake/misconception by facing a javax.el.ELException: Could not find property actionMethod in class com.example.Bean. If you intend to invoke a method as result of a POST request, use <h:commandButton> instead, see below. Or if you intend to invoke a method as result of a GET request, head to Invoke JSF managed bean action on page load or if you also have GET request parameters via <f:param>, How do I process GET query string URL parameters in backing bean on page load? <h:commandButton> The <h:commandButton> generates a HTML <input type="submit"> button which submits by default the parent <h:form> using HTTP POST method and invokes the actions attached to action, actionListener and/or <f:ajax listener>, if any. The <h:form> is required. E.g. <h:form id="form"> <h:commandButton id="button" value="POST button" action="otherpage" /> </h:form> will generate <form id="form" name="form" method="post" action="/contextpath/currentpage.xhtml" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="form" value="form" /> <input type="submit" name="form:button" value="POST button" /> <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="...." autocomplete="off" /> </form> Note that it thus submits to the current page (the form action URL will show up in the browser address bar). It will afterwards forward to the target page, without any change in the URL in the browser address bar. You could add ?faces-redirect=true parameter to the outcome value to trigger a redirect after POST (as per the Post-Redirect-Get pattern) so that the target URL becomes bookmarkable. The <h:commandButton> is usually exclusively used to submit a POST form, not to perform page-to-page navigation. Normally, the action points to some business action, such as saving the form data in DB, which returns a String outcome. <h:commandButton ... action="#{bean.save}" /> with public String save() { // ... return "otherpage"; } Returning null or void will bring you back to the same view. Returning an empty string also, but it would recreate any view scoped bean. These days, with modern JSF2 and <f:ajax>, more than often actions just return to the same view (thus, null or void) wherein the results are conditionally rendered by ajax. public void save() { // ... } See also: How to navigate in JSF? How to make URL reflect current page (and not previous one) When should I use h:outputLink instead of h:commandLink? Differences between action and actionListener A: h:button - clicking on a h:button issues a bookmarkable GET request. h:commandbutton - Instead of a get request, h:commandbutton issues a POST request which sends the form data back to the server. A: h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows: <h:form> <h:commandButton action="page.xhtml" value="cmdButton"/> </h:form> this code generates the follwing html: <form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded"> whereas the h:button is simpler and just used for static or rule based navigation as follows <h:button outcome="page.xhtml" value="button"/> the generated html is <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />
{ "pile_set_name": "StackExchange" }
Q: Convert single-element array into string I have a strange array format after converting from a SimpleXMLElement. I have an array like this: Array ( [test] => Array ( [0] => Array ( [a] => Array ( [0] => 1 ) [b] => Array ( [0] => 2 ) [c] => Array ( [0] => 3 ) And i want to transform it into this: Array ( [test] => Array ( [0] => Array ( [a] => 1 [b] => 2 [c] => 3 Any ideas? A: I use this, to optimize single element arrays from SimpleXmlElement: function optimize( $config ) { foreach ( $config as $key => $value ) if( is_array( $value ) && count( $value ) == 1 && isset( $value[0] )) $config[$key] = $value[0]; return $config } As single array elements can be nested some levels deep, you can use this function as a recursive function.
{ "pile_set_name": "StackExchange" }
Q: "Dive" = "fly into"? The words 飛ぶ and 跳ぶ are both read as とぶ, the former meaning "to fly" and the latter meaning "to jump" (generally; don't know if they are interchangeable at all). The compound-verb suffix 〜込【こ】む means that the action "goes in (to)", "enters", etc. So the word とびこむ means "to jump/dive into", both literally and figuratively ("jump into (doing) a mountain of homework", "butt in to someone's business", etc.). However, とびこむ is written with the "to fly" version of the kanji: 飛び込む. Why is this? When 跳ぶ means jump and 〜込む means "into", why wasn't 跳 chosen for とびこむ? This doesn't make sense to me at all. A: 飛ぶ is the general term that covers all the uses of homophonous kanjis such as 跳ぶ and 翔ぶ. 跳ぶ is a specific one, entailing some mid-air movement (such as pedaling your legs, etc.). As usual with homophonous kanjis, the specific one can be replaced by the general one, but not the other way around. In the literal sense "to dive in to e.g. a swimming pool", you can use 飛び込む as well as 跳び込む. For the metaphoric sense "jump into homework/business", 跳ぶ is probably too specific because those senses do not accompany movement in the air, and you have to use the general 飛ぶ.
{ "pile_set_name": "StackExchange" }
Q: How to implement an instrument/score pattern in supercollider? I've been through a few of the tutorials, but none of them seem to get at what, in my opinion, is a sensible architecture: There are one or more Instrument instances, There is a Score which defines a set of Note objects, A Player class (maybe function) that routes the Note instances from the score to the instruments so that music is produced. What I see in this pattern, but haven't seen in the examples I've read so far, is (a) the total separation between the score and the instruments and (b) explicit definition (in the form of a class and/or API) of the Note objects that tell the instruments what to do. Are their built in utilities that support this type of operating pattern? Is this an un-smallalkey way of thinking about the problem? A: I'm not sure exactly what you want, given that you've looked at the examples. The odd bit is the "total separation" requirement; usually a score needs to make some assumptions about what parameters are relevant to what instruments - although there are enough introspective methods in SynthDef that a program could make educated guesses. But the basic schematic is pretty standard: SynthDef defines instruments, Collection and its subclasses store data, Routine and other classes can interpret data structures in scheduled time to make music. At the bottom I'm pasting some boilerplate code for a very simple c-like approach to such a structure, using SynthDef, Routine, and Array. Which instrument to use is arbitrarily chosen at note generation time, and the "score" is instrument-agnostic. However, the idiomatic approach in SC is to use Patterns and Events, and the Pbind class in particular. Personally I find these a little restrictive and verbose, but they'll certainly do what you ask. Check out the "Streams-Patterns-Events" series of helpfiles. And various people have written third-party extensions like Instr and Voicer to accommodate their own flavors of the score-instrument model. Check out the Quarks listing or consider rolling your own? s = Server.local.boot; s.waitForBoot{ Routine { /// in a "real" patch, i'd make these local variables, /// but in testing its convenient to use environment variables. // var inst, tclock, score, playr, switchr; // the current instrument ~inst = \ding; // a fast TempoClock ~tclock = TempoClock.new(8); // two instruments that take the same arguments SynthDef.new(\ding, { arg dur=0.2, hz=880, out=0, level=0.25, pan=0.0; var snd; var amp = EnvGen.ar(Env.perc, doneAction:2, timeScale:dur); snd = SinOsc.ar(hz) * amp * level; Out.ar(out, Pan2.ar(snd, pan)); }).send(s); SynthDef.new(\tick, { arg dur=0.1, hz=880, out=0, level=0.25, pan=0.0; var snd; var amp = EnvGen.ar(Env.perc, doneAction:2, timeScale:dur); snd = LPF.ar(WhiteNoise.ar, hz) * amp * level; Out.ar(out, Pan2.ar(snd, pan)); }).send(s); s.sync; // the "score" is just a nested array of argument values // there are also many kinds of associative collections in SC if you prefer ~score = [ // each entry: // midi note offset, note duration in seconds, wait time in beats [0, 0.4, 2], [0, 0.4, 1], [7, 0.2, 1], [0, 0.2, 1], [7, 0.15, 1], [10, 0.5, 2], [7, 0.1, 1], [2, 0.3, 1] ]; // a routine that plays the score, not knowing which instrument is the target ~playr = Routine { var note, hz; inf.do({ arg i; // get the next note note = ~score.wrapAt(i); // interpret scale degree as MIDI note plus offset hz = (note[0] + 60).midicps; // play the note Synth.new(~inst, [\hz, hz, \dur, note[1] ], s); // wait note[2].wait; }); }.play(~tclock); // a routine that randomly switches instruments ~switchr = Routine { var note, hz; inf.do({ arg i; if(0.2.coin, { if(~inst == \ding, { ~inst = \tick; }, { ~inst = \ding; }); ~inst.postln; }); // wait 1.wait; }); }.play(~tclock); }.play; };
{ "pile_set_name": "StackExchange" }
Q: Selecting each input fields in the table column with jQuery I want to select the input fields' values in each column. <table id="tablo"> <tr> <td><input class="Name" type="text" /></td> <td><input class="Age" type="text" /></td> <td><input class="No" type="text" /></td> </tr> <tr> <td><input class="Name" type="text" /></td> <td><input class="Age" type="text" /></td> <td><input class="No" type="text" /></td> </tr> <tr> <td><input class="Name" type="text" /></td> <td><input class="Age" type="text" /></td> <td><input class="No" type="text" /></td> </tr> ... </table> Then selecting each input value, I will create an object with these values and push the object in an array by looping through the selected inputs: var arr= [] var obj = { Name: jquery selector will come here, Age: jquery selector will come here, No: jquery selector will come here } arr.push(obj); I've tried with jQuery's $.each() function, but I just only reach the columns. A: Id must be unique, so try it with using class like, var objs=[]; $('#tablo tr').each(function(){ var inputs = $(this).find('input'),o={}; inputs.each(function(){ o[$(this).attr('class')]=this.value; }); objs.push(o); }); Snippet, var objs = []; $('#tablo tr').each(function() { var inputs = $(this).find('input'), o = {}; inputs.each(function() { o[$(this).attr('class')] = this.value; }); objs.push(o); }); console.log(objs); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tablo"> <tr> <td><input class="Name" type="text" value="test1"/></td> <td><input class="Age" type="text" value="123"/></td> <td><input class="No" type="text" value="no1" /></td> </tr> <tr> <td><input class="Name" type="text" /></td> <td><input class="Age" type="text" /></td> <td><input class="No" type="text" /></td> </tr> <tr> <td><input class="Name" type="text" /></td> <td><input class="Age" type="text" /></td> <td><input class="No" type="text" /></td> </tr> </table>
{ "pile_set_name": "StackExchange" }
Q: python pandas indexing matplot omit one of the indexes in the plot I have a list of names, states, year, sex and the number of times that name appears. I am trying to plot a given name over the years in all states combined. allyears.head() and here is the results: name sex number year state 0 Mary F 7065 1880 FL 1 Anna F 2604 1880 NY 2 Emma F 2003 1880 AZ 3 Eli F 1939 1880 AS 4 Minnie F 1746 1880 AK then I do indexing: allyears_indexed = allyears.set_index(['sex','name', 'state', 'year']).sort_index() and through my function: def plotname(sex,name): data = allyears_indexed.loc[sex,name] pp.plot(data.index,data.values) then I would like to get all the "Emma"s over the years in all of states combined: plotname('F', 'Emma') but i get an error instead and an empty plot! But when I pass in the 'state' parameter to the function, and provide the state name in the call, I get the 'Emma's overs the years in that particular state. How can I get it over the years all states combined and keeping the same indexing pattern? A: I believe you first need to group on the year and name, and then use loc to access the resulting data. The groupby will sum across all states. df = allyears.groupby(['year', 'name'], as_index=False).number.sum() >>> df year name number 0 1880 Anna 2604 1 1880 Eli 1939 2 1880 Emma 2003 3 1880 Mary 7065 4 1880 Minnie 1746 >>> df.loc[df.name == 'Emma'] year name number 2 1880 Emma 2003 And to plot it: df.loc[df.name == 'Emma', ['year', 'number']].set_index('year').plot(title='Emma')
{ "pile_set_name": "StackExchange" }
Q: check if two ZFS filesystems are identical I would like to verify that two ZFS filesystems (in this case on different pools) are identical. Is there a best practice way to do this? A: If checking the contents of the filesystem and not the filesystem itself, see: https://stackoverflow.com/questions/4997693/given-two-directory-trees-how-can-i-find-out-which-files-differ#4997724
{ "pile_set_name": "StackExchange" }
Q: Collapsible Accordion in Angular WITHOUT using a JS code, But only HTML. Whenever I click the button, it does nothing. Please solve this I am trying to implement an Accordion button on my webpage using the HTML code given below. I am currently implementing this on a very basic scale without using any javascript code with this accordion snippet. The button just clicks and does nothing and the basic collapsing doesn't take place nor does the accordion functionality is implemented. Kindly help me in implementing this! <div class="panel panel-default"> <div class="panel-heading"> <button class="btn btn-primary" type="button" data toggle="collapse" data-target="#collapseButtonExample" aria- expanded="true" aria-controls="collapseExample">Question </button> </div> <div class="collapse" id="collapseButtonExample" > <div class="card card-body"> <p></p> </div> </div> </div> A: Something like this will work if there is single element <div class="panel panel-default"> <div class="panel-heading"> <button class="btn btn-primary" type="button" #btn (click)="btn.toggle = !btn.toggle" >Question </button> </div> <div [ngClass]="{collapse:!btn.toggle}" > <div class="card card-body"> <p>1# something</p> </div> </div> </div> if you have many element this trick will work <div class="panel panel-default" *ngFor="let i of [1,2,3,4]"> <div class="panel-heading"> <button class="btn btn-primary" type="button" #btn (click)="btn.toggle = !btn.toggle" >Question </button> </div> <div [ngClass]="{collapse:!btn.toggle}" > <div class="card card-body"> <p>{{i}}# something</p> </div> </div> </div> stackblitz demo
{ "pile_set_name": "StackExchange" }
Q: How do I use trigonometric functions? I want to know how to use trigonometric functions (an example would be helpful), and what I have to import to use them. Are they in math.h with things like pow() and sqrt()? A: You just want to use things like sin() cos() and such? If so, you don't even need to import math.h as long has you have: #import <Foundation/Foundation.h> in your header file. You can just do something like double result = cos(12);
{ "pile_set_name": "StackExchange" }
Q: How to limit Gradle downloads to only one file per instance While I have an unstable connection I would like gradle to download files only one after another, instead of the default parallel download mode, a preview of parallel-mode is below: Because as it is currently none of the files gets ever downloaded to its end, it's wasting time, and time is money. A: You can refer the solution shared by sterling here And we can set the org.gradle.parallel property in a gradle.properties file (which should be placed in the projects root directory, besides of build.gradle file), just append a line like org.gradle.parallel=false to gradle.properties file. see also: Disabling parralel threads
{ "pile_set_name": "StackExchange" }
Q: How to use function pointers in a struct in C? It's pretty simple what I'm trying to do, and I'm merely having trouble figuring out the right syntax. I want my struct to look like this: struct myStruct { functionPointer myPointer; } Then I have another function somewhere else that passes a function to a function and returns an instance of my struct. Here's what it does: struct myStruct myFunction(int (*foo) (void *)) { myStruct c; c.myPointer = foo; return c; } How can I make this actually work? What's the correct syntax for: Declaring a function pointer in my struct (obviously functionPointer myPointer; is incorrect) Assigning a function's address to that function pointer (pretty sure c.myPointer = foo is incorrect)? A: It's really no different to any other instance of a function pointer: struct myStruct { int (*myPointer)(void *); }; Although often one would use a typedef to tidy this up a little.
{ "pile_set_name": "StackExchange" }
Q: Spring Error: No property prod found for type Product I am new to Spring and facing some problem. My entity has a field: package com.ecommercesystem.ecommerce.entities; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.sql.Blob; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer ID_product; @NotNull private String prod_name; @NotNull private String prod_desc; @NotNull private float price; @NotNull private String prod_brand; @NotNull private Blob prod_image; private int prod_rating; @ManyToOne private Category category; protected Product(){} public Product(Integer ID_product, @NotNull String prod_name, @NotNull String prod_desc, @NotNull float price, @NotNull String prod_brand, @NotNull Blob prod_image, int prod_rating, Category category) { this.ID_product = ID_product; this.prod_name = prod_name; this.prod_desc = prod_desc; this.price = price; this.prod_brand = prod_brand; this.prod_image = prod_image; this.prod_rating = prod_rating; this.category = category; } public Integer getID_product() { return ID_product; } public void setID_product(Integer ID_product) { this.ID_product = ID_product; } public String getProd_name() { return prod_name; } public void setProd_name(String prod_name) { this.prod_name = prod_name; } public String getProd_desc() { return prod_desc; } public void setProd_desc(String prod_desc) { this.prod_desc = prod_desc; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getProd_brand() { return prod_brand; } public void setProd_brand(String prod_brand) { this.prod_brand = prod_brand; } public Blob getProd_image() { return prod_image; } public void setProd_image(Blob prod_image) { this.prod_image = prod_image; } public int getProd_rating() { return prod_rating; } public void setProd_rating(int prod_rating) { this.prod_rating = prod_rating; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } My Product Repository is something like this: package com.ecommercesystem.ecommerce.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.ecommercesystem.ecommerce.entities.Product; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Optional; // This will be AUTO IMPLEMENTED by Spring into a Bean called productRepository // CRUD refers Create, Read, Update, Delete @Repository public interface ProductRepository extends JpaRepository<Product, Integer> { Optional<Product> findByProd_name(String prod_name); // Optional<Product> findByProd_brand (String prod_brand); } and my Product Controller is something like this: package com.ecommercesystem.ecommerce.controllers; import com.ecommercesystem.ecommerce.entities.Category; import com.ecommercesystem.ecommerce.entities.Product; import com.ecommercesystem.ecommerce.repositories.ProductRepository; //import com.ecommercesystem.ecommerce.services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.Optional; @Controller public class ProductController { @Autowired ProductRepository productRepository; @GetMapping(path = "/") public String front() { return "index"; } @GetMapping(path = "/search_results") public String search(@RequestParam(value = "search", required = false) String search, Model model){ Optional<Product> productName = productRepository.findByProd_name(search); if (productName.isPresent()){ if (search.equals(productName.get().getProd_name())){ model.addAttribute("ID_product", productName.get().getID_product()); model.addAttribute("price", productName.get().getPrice()); model.addAttribute("prodName", productName.get().getProd_name()); model.addAttribute("category_name", productName.get().getCategory().getCategory_name()); // model.addAttribute("prodDesc", productName.get().getProd_desc()); // model.addAttribute("prodImage", productName.get().getProd_image()); // model.addAttribute("prodBrand", productName.get().getProd_brand()); } } return "search_results"; } } But when i run the program i got this Error Message: Error Log: [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 10.277 s <<< FAILURE! - in com.ecommercesystem.ecommerce.EcommerceApplicationTests [ERROR] contextLoads(com.ecommercesystem.ecommerce.EcommerceApplicationTests) Time elapsed: 0.017 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productController': Unsatisfied dependency expressed through field 'productRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product! Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product! Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.ecommercesystem.ecommerce.repositories.ProductRepository.findByProd_name(java.lang.String)! No property prod found for type Product! Caused by: org.springframework.data.mapping.PropertyReferenceException: No property prod found for type Product! Any help is highly appreciated. Thank You! A: Spring Data uses camelCase convention when searching for method names public void setProdName(String prodName) { this.prodName = prodName; } public String getProdName() { return prodName; }
{ "pile_set_name": "StackExchange" }
Q: Using split method on a string returns an empty string I'm just wondering why 'hello world'.split('world') also returns an empty string '' in the list ['hello ',''] while it splits perfectly for 'hello world people'.split('world') into the list ['hello ',' people'] A: The .split function separates the string by what is in the brackets and what os on the brackets is omitted from the string. Therefore, your results are completely correct. If you want to split by words, do: 'hello world people'.split() This splits by a space and therefore returns: ['hello','world','people']
{ "pile_set_name": "StackExchange" }
Q: Mysql priviléges for user boss12 i associate the right to modify only the name, But I want to know how to associate that renaming only the student with idStu = 12, i.e he can change the name of the student (idStu = 12) but he can not for the student (idStu = 13). create database gcr; use gcr; create table Student( idStu int primary key, nom varchar(30), moyen real)engine=innodb; insert into Student values(12,'hassen',15.0); insert into Student values(13,'ouss',12.0); create user boss12@localhost identified by 'enig'; create user prof@localhost identified by 'gcrgcr'; use mysql; grant select, update,insert on gcr.Student to prof@localhost with grant option; grant update (nom) on gcr.Student to boss12@localhost with grant option; A: Impossible in any straightforward way. There's no row-level security in the very vast majority of RDBMS. However, theoretically, you can build the additional level that encapsulates the main dataset + additional row level security data (e.g. table(s) that describes the access grants/policies/restrictions for particular rows + reference to these rules from the main data tables) - and then But that's quite tricky part, let me tell you - even for reads. And I'm really not sure is it possible for updates in such a case. The other way is to set a before-update trigger on the given table, then check whatever conditions you want against the requestor's user - and fail the transaction if needed. But that, honestly, is a dirty hack in your case - heavily data-depending (thus error prone) and hardly maintainable.
{ "pile_set_name": "StackExchange" }
Q: error Uncaught SyntaxError: Unexpected token < i want to create a form which has 2 dropdown, the second dropdown will be trigger by the first dropdown without reload the page, after the first dropdown selected/change, so i decide to use ajax instead trigger the second dropdown it is returning this error Uncaught SyntaxError: Unexpected token < add_product.php:1 error on above happen if i use google chrome and this the error when i use firefox with firebug Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/portofolio1/dd-multiple.php on line 15 Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in /opt/lampp/htdocs/portofolio1/dd-multiple.php on line 16 {"data":null} SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js (line 34, col 26) this is script.js file function AjaxFunction(id1,id2) { alert(id1); var httpxml; try { // Firefox, Opera 8.0+, Safari httpxml=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { httpxml=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpxml=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } function stateck(){ if(httpxml.readyState===4) { var myarray = JSON.parse(httpxml.responseText); // Before adding new we must remove previously loaded elements for(j=document.getElementById(id2).length-1;j>=0;j--) { document.getElementById(id2).remove(j); } for (i=0;i<myarray.data.length;i++) { var optn = document.createElement("OPTION"); optn.text = myarray.data[i].subcategory; //optn.value = myarray.data[i].subcat_id; // You can change this to subcategory optn.value = myarray.data[i].subcategory; document.getElementById(id2).options.add(optn); } } } var str=''; var s1ar=document.getElementById(id1); for (i=0;i< s1ar.length;i++) { if(s1ar[i].selected){ str += s1ar[i].value + ','; } } //alert (s1ar); var str=str.slice(0,str.length -1); // remove the last coma from string //alert(str); ///// //alert(str); var url="dd-multiple.php"; url=url+"?cat_id="+str; url=url+"&sid="+Math.random(); //alert(url); httpxml.onreadystatechange=stateck; httpxml.open("GET",url,true); httpxml.send(null); } this my add_product.php file <?php require_once './model/functions.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <link href="css/bootstrap.min.css" rel="stylesheet"/> </head> <body> <div class="container"> <div class="row"> <div class="center-block" style="width: 130px;"> <h3><strong>Add Book</strong></h3> </div> </div> <form method="post" action="" class="form-horizontal"> <div class="form-group"> <label for="kategori" class="col-lg-4 control-label">Kategori : </label> <div class="col-lg-6"> <input type="text" class="form-control" id="kategori" name="kategori" placeholder="pilih kategori"> </div> </div> <div class="form-group"> <label for="tipeIklan" class="col-lg-4 control-label">Tipe Iklan : </label> <div class="col-lg-6"> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="tipeIklan" value=1>Dicari </label> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="tipeIklan" value=0>Dijual </label> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="tipeIklan" value=2>Disewakan </label> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="tipeIklan" value=3>Jasa </label> </div> </div> <div class="form-group"> <label for="judul" class="col-lg-4 control-label">Judul : </label> <div class="col-lg-6"> <input type="text" class="form-control" id="judul" name="judul" placeholder="Judul iklan anda"> </div> </div> <div class="form-group"> <label for="deskripsi" class="col-lg-4 control-label">Deskripsi : </label> <div class="col-lg-6"> <textarea id="deskripsi" class="form-control" rows="5"></textarea> </div> </div> <div class="form-group"> <label for="harga" class="col-lg-4 control-label">Harga(Rp.) : </label> <div class="col-lg-3"> <input type="text" class="form-control" id="harga" name="harga" aria-describedby="helpBlock" placeholder="cukup tuliskan angka"> <span id="helpBlock" class="help-block">Contoh: 2000</span> </div> </div> <div class="form-group"> <label for="kondisi" class="col-lg-4 control-label">Kondisi : </label> <div class="col-lg-6"> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="kondisi" value=0>Bekas </label> <label class="radio-inline"> <input type="radio" name="genderRadioOptions" id="kondisi" value=1>Baru </label> </div> </div> <div class="form-group"> <label for="provinsi" class="col-lg-4 control-label">Provinsi : </label> <div class="col-lg-3"> <select id="provinsi" name="s1[]" class="form-control" onchange="AjaxFunction('provinsi', 'kota')"> <option>select one</option> <?php $provinsi_set = find_all_province(); while($provinsi = mysqli_fetch_assoc($provinsi_set)){ ?> <option value="<?php echo $provinsi["id"];?>"><?php echo $provinsi["nama"]; ?></option> <?php } ?> </select> </div> </div> <div class="form-group"> <label for="kota" class="col-lg-4 control-label">Kota : </label> <div class="col-lg-3"> <select id="kota" name="s2[]" class="form-control"> </select> </div> </div> <div class="form-group"> <label for="foto" class="col-lg-4 control-label">Upload Foto : </label> <div class="col-lg-6"> <img src="uploads/raditya.jpg" alt="" width="140" height="140" class="img-thumbnail"> <img src="uploads/Kambing_Jantan_buku_2.jpg" alt="" width="140" height="140" class="img-thumbnail"> <img src="uploads/raditya.jpg" alt="" width="140" height="140" class="img-thumbnail"> </div> </div> <div class="col-lg-offset-4"> <button type="button" id="registrationbutton" class="btn btn-default">Tayangkan!</button> </div> </form> </div> <script src="jquery.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/script.js"></script> <?php close_connection(); ?> </body> </html> the problem dissapear when i remove this code onchange="AjaxFunction('provinsi', 'kota')" and this is my dd-multiple.php in case someone asking for it <?php @$cat_id=$_GET['cat_id']; $mn=split(",",$cat_id); // creating array while (list ($key, $val) = each ($mn)) { if(!is_numeric($val)){ // checking each element echo "Data Error "; exit; } } global $id_mysql; $query = "SELECT nama,id FROM KOTA WHERE id_prov IN ($cat_id)"; $row = mysqli_query($id_mysql, $query); $result = mysqli_fetch_assoc($row); $main = array('data'=>$result); echo json_encode($main); ?> A: The reason you get that error is because your mysqli_query is incorrect. You have your link which is null. Your link should be the connection to your database, ie: $link = mysqli_connect("localhost", "my_user", "my_password", "database"); $query = "SELECT nama,id FROM KOTA WHERE id_prov IN ($cat_id)"; $row = mysqli_query($link, $query); $result = mysqli_fetch_assoc($row); $main = array('data'=>$result); echo json_encode($main);
{ "pile_set_name": "StackExchange" }
Q: Unable to play mp4 Videos in Angular after passing it as JSON files from assets/videos This is my html template where I am displaying the data to the view: <mat-grid-list cols="2" rowHeight="550px"> <mat-grid-tile *ngFor='let video of videos'> <video controls (click)="toggleVideo()" #videoPlayer width="640" height="400" allow="autoplay"> <source src="{{video.videoUrl}}" type="video/mp4" /> Browser not supported </video> <mat-grid-tile-header> {{ video.pageTitle }} </mat-grid-tile-header> <mat-grid-tile-footer style="background-color: black"> <span>Posted on - {{ video.postDate }}</span> </mat-grid-tile-footer> </mat-grid-tile> </mat-grid-list> This is my TS component where I decide to play the video or pause the video: @ViewChild('videoplayer') private videoplayer: any; toggleVideo(event: any) { this.videoplayer.nativeElement.play(); // this.videoplayer.nativeElement.pause();} This is the JSON file I am passing to the template for the view: const posts = [ { videoId: "kode5476", pageTitle: "The man of my dream", postDate: "Mar 18, 2019", videoUrl: "../src/assets/videos/theweekend.mp4" }, { videoId: "jkde5498", pageTitle: "The woman who makes the money", postDate: "June 23, 2018", videoUrl: "../src/assets/videos/daniel.mp4" }, { videoId: "jkde`enter code here`5498", pageTitle: "The woman who makes the money", postDate: "November 17, 2000", videoUrl: "../src/assets/videos/theweekend.mp4" }]; A: I finally solved it after 5 days of trying different methods. The problem was locating my videos in assets through the src folder instead of referencing the asset folder direct. So I finally did it like this and it work fine.So I had to edit my JSON file to look like this: const posts = [ { videoId: "fade3536", pageTitle: "A woman who build her home", postDate: "June 18, 2017", videoUrl: "assets/videos/daniel.mp4", Type: "video/mp4" }, { videoId: "kode5476", pageTitle: "The man of my dream", postDate: "Mar 18, 2019", videoUrl: "assets/videos/theweekend.mp4", Type: "video/mp4" }, { videoId: "jkde5498", pageTitle: "The woman who makes the money", postDate: "June 23, 2018", videoUrl: "assets/videos/twws.mp4", Type: "video/mp4" }, { videoId: "jkde5498", pageTitle: "The woman who makes the money", postDate: "November 17, 2000", videoUrl: "assets/videos/daniel.mp4", Type: "video/mp4" } ]; There was no need for me to add nativeElement in order to play or pause the video because the video tag already come with those features.
{ "pile_set_name": "StackExchange" }
Q: Position sprite inside camera view I'm trying to position a sprite, the problem is that I have a camera view and I can't figure a way out to center my sprite inside the view. I tried to to something like this: sprite.position = CGPoint(x: cameraNode.frame.midX, y: cameraNode.frame.midY) to center the sprite in the screen. but it is not working. the sprite is not being centered. This is the camera: camera = cameraNode camera?.position = CGPoint(x: size.width/2, y: size.height/2) the variable cameraNode is a simple SKCameraNode() A: Actually the frame property isn't directly from SKCameraNode, its from its SKNode parent class and here is what it does (from Apple Developper documentation): The frame property provides the bounding rectangle for a node’s visual content, modified by the scale and rotation properties. A camera node doesn't draw any content, it is just a representation of a camera you can use as a point of view; therefore the frame property isn't useful here. From the documentation: The scene is rendered so that the camera node’s origin is placed in the middle of the scene. Therefore you should rather use the position property of your camera node to place your object as you want.
{ "pile_set_name": "StackExchange" }
Q: What Is the Procedure and Guidelines for Moving Comments on a Question to Meta? Is It Necessary? On some of the beta sites, such as Project Management Stack Exchange, some of the questions accumulate a series of comments related to the on/off-topic nature of the question. One question has 10 comments discussing why the question was closed by a moderator, what was done to fix those problems, and requests to reopen the question. After the edits, the question was reopened. Should the comments be moved to the site meta or should the comments be left as a signpost for other users to help convey the metamorphosis from a bad, subjective rant to a good, subjective question? If the comments should be moved, how does one accomplish that? Can regular users move comments? Can a moderator? A: There is no widely common procedure or guideline for moving the actual comments from the main site into a Meta discussion. It varie a lot between sites, some sites preserve a lot of comment streams while others only preserve some of the particularly noteworthy ones. Some put it in chat and link the transcript, others post into a post body. There is no actual "move" functionality. In terms of simplicity, the best option is traditionally a whole-sale copy/paste of the comment thread into an appropriate medium, then the moderator "Delete Comments" ability to clear the thread. You'll need a moderator to accomplish the latter, but a normal user could always do the first part and then flag for the second. As far as when to do it, it depends a lot on the nature of the comment exchange. Generally, Meta discussion (or a move to chat) is sprung when things are no longer suited to sticking in comments. This often comes up because: The comments are getting too heated The comments are straying away from the content of the post they are attached to The comments are numerous in quantity It is a reasonable expectation that one of the above is going to happen if nothing is done In general, preserving the comments in the Meta discussion is only necessary if you're getting rid of the comments on the Main site, and only if the comments are worth preserving. For example, if it's a heated discussion, then keeping all the flames alight is probably not wise. Or, if you're just pre-empting a thick discussion, then adding a comment "This has now had a Meta discussion opened, please direct further commentary there" can let you simply leave the 10 or so comments on the post, if they're fine on their own right.
{ "pile_set_name": "StackExchange" }
Q: Integrate over the region bounded by two regions. Using Polar coordinates. Using Polar Coordinates integrate over the region bounded by the two circles: $$x^2+y^2=4$$ $$x^2+y^2=1$$ Evaluate the integral of $\int\int3x+8y^2 dx$ So what I did was said that as $x^2+y^2=4$ and $x^2+y^2=1$ That $1 \le r \le 2$. And as there is a symmetry in the four quadrants $0 \le \theta \le \frac{\pi}{2}$ which gave me $\int_0^\frac{\pi}{2}\int_1^2 3r^2\cos(\theta) +8r^3\sin^2(\theta) ~dr d\theta$ The answer it gives in the book is $30\pi$. I'm getting $28 +30\pi$ A: There is less symmetry than you think because of the $x$. Well, there is symmetry there too, but it is cancellation symmetry: the contribution of $x$ to the integral is $0$. You can either note that, or integrate from $0$ to $2\pi$, or integrate from $0$ to $\pi$ and double. Note that we need to replace $dx\,dy$ by $r\,dr\,d\theta$.
{ "pile_set_name": "StackExchange" }
Q: Is there an IDE for PHP CLI? I downloaded Eclipse PDT, Zend, and Netbeans (trial) and they only seem to have support for PHP on a web server. I want to use PHP CLI as a programming language, is there an IDE for it? Edit: I don't want to use the command line. I want a program that can run PHP CLI in a GUI. A: Komodo allows you to run your scripts in CGI environment. NuSphere has command line tab. Zend Studio has PHP CLIs both version 4 and version 5 installed within the IDE, PHP CLI PHP IDE allows you to quickly test PHP CLI script,
{ "pile_set_name": "StackExchange" }
Q: Why is this black line appearing on my mesh when I render? I am new in Blender and I can't understand why rendering goes wrong? A: I just had to check normals with Ctrl+N in Edit mode
{ "pile_set_name": "StackExchange" }
Q: Strange characters when booting ubuntu 14.04.2 with TEXT mode i've installed xubuntu 14.04.2 desktop x86 on my laptop. i changed /boot/grub/grub.cfg to have it booting with TEXT mode. everything works find but one: strange characters are shown before showing login prompt. what can i do to avoid this? I use ubuntu for my commercial customers who complaint with this... many thx! A: Unfortunately, I don't think that this is related to software problem or OS problem at all, I think that your graphic card is at the end of life. Three days ago card on my laptop died and it was showing same characters on display, they appeared in BIOS and when starting system, and GUI can't even start any more. I hope that I'm wrong but...
{ "pile_set_name": "StackExchange" }
Q: How do I show that the Dirac measure is countably additive? I want to show that the Dirac measure is countably additive. A: If $A_n$ are disjoint.Then at most only one can contain the point of mass ($0$). Therefore $$\delta(A_n)=0$$ for all $n$, except perhaps one of them for which it is equal to $1$. If there is one for which it is equal to $1$ then $\bigcup_n A_n$ contains the point of mass. Therefore $$\delta(\bigcup_n A_n)=1=\sum_n \delta(A_n).$$ If none of them contain the point of mass so doesn't $\bigcup_n A_n$ and therefore $$\delta(\bigcup_n A_n)=0=\sum_n\delta(A_n).$$ Notice we didn't really used the cardinality of the set of indexes. So, the Dirac delta measure is actually additive for any number of disjoints measurable sets.
{ "pile_set_name": "StackExchange" }
Q: Users stating that they do not want their posts to be edited I was browsing through Stack Overflow looking for Q&A related to a regex-related issue I'm having and noticed this particular question with a warning-like statement written at the end of the question: Do not edit my posts, if you have a question comment instead and I'll be happy to clarify. Considering the fact that there will be members in the community who might be discouraged from contributing improvements and/or relevant edits to these posts, is it allowed for members to make statements like this in their posts? A: While the OP technically owns the post and has given Stack Overflow a license to publish it, this license does not give them the power to prevent us from making copy edits to it as we deem fit. Messages like this are misleading and unnecessary, and should (ironically!) be edited out. In this specific situation, it might be best to get a mod involved since that has "rollback war" written all over its history. A: If you want your question, or answer, to exist unmodified, the answer is very simple. You have to make it perfect, and the perfection has to survive changes over time. Allowing contributors to mark their stuff read/only will lead to incorrect, outdated, poor practice answers existing while new q/a are posted to show the correct/updated/best practice answer. Now you have correct and incorrect versions and who's to say which one is right. Better solution would be to bring in a moderator to moderate when there is disagreement over a correct answer.
{ "pile_set_name": "StackExchange" }
Q: How do I check if a value type has a value of IntPtr.Zero So I am writing a Xamarin application and I have built a CustomRenderer now my method: horizontalScrollView.ScrollTo(this.Width, 0); keeps throwing an exception: System.ArgumentException: 'jobject' must not be IntPtr.Zero. 10-21 12:10:41.898 E/AndroidRuntime(15053): Parameter name: jobject 10-21 12:10:41.898 E/AndroidRuntime(15053): at Android.Runtime.JNIEnv.CallIntMethod (intptr,intptr) [0x00010] in /Users/builder/data/lanes/2185/53fce373/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:378 10-21 12:10:41.898 E/AndroidRuntime(15053): at Android.Views.View.get_Width () So looking at the exception and from my breakpoints I find that the problem is that when I hover over this.Width I get 'jobject' must not be IntPtr.Zero instead of an integer so I try to defensively code against this and do: if (this.Width != IntPtr.Zero) { horizontalScrollView.ScrollTo(this.Width, 0); } but this doesnt compile and gives me the error: Operator '!=' cannot be applied to operands of type 'int' and 'IntPtr' So my questions is. Is there a way to check whether a value type is equal to IntPtr.Zero? A: Since you are working on a custom renderer I assume you are using Xamarin.Forms. You can't check for IntPtr.Zero here. The IntPtr is set internally by Xamarin.Forms. You have usually no access to the wrong pointer. So you can't see it's there but you receive an error when you access the Width property because it works internally with that pointer. There are two possible causes for this error: You didn't initialize the control properly. So it contains null pointers. There is a bug in Xamarin.Forms. Test your code against other versions of Xamarin.Forms. If the error doesn't occur in a different version or you believe it's a bug then file it here.
{ "pile_set_name": "StackExchange" }
Q: Why Does My Tax Free Savings Account Say I Have 0 Contribution Room as of 2015? I am living in Canada, and I recently went to http://www.cra-arc.gc.ca/esrvc-srvce/tx/ndvdls/myccnt/menu-eng.html and tried to check my TFSA contribution room for this year. I turned 18 on February 9th of 2014. And I am now 19 this year. I know I was close to maxing out my TFSA last year (I think I put in around $5000.00). When I went to the site to check my contribution room, it said: Your 2015 TFSA contribution room on January 1, 2015 is $0. The calculation of your TFSA contribution room for a year is based on information provided to us by your financial institution(s) about transactions you made before that year. If we receive or process additional information, your TFSA contribution room could change. As the CRA is currently receiving information from financial institutions, we are unable to calculate your TFSA contribution room for 2015 at this time. If you want to calculate your TFSA contribution room using your own records, use Form RC343, Worksheet - TFSA contribution room. I have not contributed any money to my TFSA in 2015. Therefore, I am wondering if my TFSA contribution room increased by an additional $5500.00? Additionally, I don't see why I would have 0 contribution room this year as I thought that the contribution room increases on January 1st of each year. I want to know this as I am interested in investing via my TFSA this year, but I don't want to over contribute. Thank you for any help. All help is greatly appreciated. A: You might consider calling the broker you invest with. At mine, you can see the room left to contribute each year in the TFSA. The CRA might just have old/bad data.
{ "pile_set_name": "StackExchange" }
Q: Package inputenc Error: Unicode char ẁ (U+1E81) I'm trying to use the 'ẁ' character in my text, however it doesn't show on the right hand side of latex and throws the following error: Package inputenc Error: Unicode char ẁ (U+1E81) I tried adding \usepackage[latin1]{inputenc} to the top of my document, which then gave another error telling me to add 'utf8, latin1' to my \documentclass which I tried but this is also not working. Is there any way I can solve this? A: The ẁ character is not supported in Latin-1; save your file as UTF-8 and add \usepackage[utf8]{inputenc} and also \DeclareUnicodeCharacter{1E81}{\`w} Full example: \documentclass{article} \usepackage[utf8]{inputenc} \DeclareUnicodeCharacter{1E81}{\`w} \begin{document} Is the character ẁ used in some language? \end{document}
{ "pile_set_name": "StackExchange" }
Q: Acceptor pooling and load balancing in Erlang? From http://www.erlang.org/doc/man/gen_tcp.html#accept-1: It is worth noting that the accept call does not have to be issued from the socket owner process. Using version 5.5.3 and higher of the emulator, multiple simultaneous accept calls can be issued from different processes, which allows for a pool of acceptor processes handling incoming connections. (Q1) Does it mean that we can have Unicorn-style load balancing in Erlang? (Q2) If so, are there any existing servers or libraries making use of this feature? (Q3) Unicorn works under the assumption that request processing is fast. Under the same assumption, is it possible to gain better performance by combining acceptors and workers in Erlang? For those who are not familiar with Unicorn, it is a traditional UNIX prefork web server. Load balancing between worker processes is done by the OS kernel. All workers share a common set of listener sockets and does non-blocking accept() on them. The kernel will decide which worker process to give a socket to and workers will sleep if there is nothing to accept(). For a single listener socket, I believe it's the same when the worker processes do blocking accept() and the OS kernel decides the result of the "race". A: I also posted this question in the Erlang Questions mailing list. As pointed out by Daniel Goertzen, there are acceptor pool libraries in Erlang, such as ranch and swarm. ranch works differently from Unicorn in such a way that it only does "accept" in many processes, and then passes the socket to some worker process. The way swarm works is the same as Unicorn in the sense that the acceptor and worker is combined. (Thanks to Loïc Hoguin for pointing out) But they are a bit different because swarm can accept a new socket in parallel with the processing of the accepted socket, while Unicorn only accepts after the accepted socket is processed I prefer the swarm style since it's ideal for both fast and slow requests, while Unicorn requires fast requests. Instead of attempting to be efficient at serving slow clients, unicorn relies on a buffering reverse proxy to efficiently deal with slow clients. unicorn is not suited for all applications. unicorn is optimized for applications that are CPU/memory/disk intensive and spend little time waiting on external resources (e.g. a database server or external API). unicorn is highly inefficient for Comet/reverse-HTTP/push applications where the HTTP connection spends a large amount of time idle.
{ "pile_set_name": "StackExchange" }
Q: If statement problem in Field Calculator - Arcgis I have a field entitled "Lung_lunc". It contains some "0" values and the rest are values > 0. I want to turn those "0" values, into "0.0001". I have added a new field: "Lung_lunca", and I want to use a IF statement in Field calculator, to do so. I have tried the version in the image, but when I run the script, nothing changes (the values remain the same, as in the previous field). I have looked over similar questions here, but did not manage to find a solution. How should I modify the script, in order to work? P.S. I have made sure that both "Lung_lunc" and "Lung_lunca" are double fields, so they accept decimals. A: I'm not really familiar with VB, but you could use this Python code: def check(value): if value == 0: results = 0.0001 else: results = value return results And for the Expression put: check(!Lung_lunc!) Make sure to change the Expression Type to Python.
{ "pile_set_name": "StackExchange" }
Q: How to download images from one server to another I have a VPS running Centos. I also have a site (say, example.com) hosted on separate, shared hosting. I would like to backup all images in the "images" folder, which consist of the following structure: example.com/images/mammals example.com/images/reptiles example.com/images/birds The files can be .JPG, .PNG and .GIF How do I backup the entire folder from the shared hosting to my VPS? Would I use wget? If yes, what would be the command(s)? Thanks very much! A: Best way to synchronize remote folders is rsync. To have security use rsync over ssh. So first make sure that you can use ssh and rsync on VPS server. If you do not have rsync, then you can use wget --mirror. With wget you can filter which file pattern to download.
{ "pile_set_name": "StackExchange" }
Q: I want one array to display the value of the other array when looped through I created a table in HTML, with one row and three columns. These are sumName, sumEmail & sumCard. I would like to get the text value from another table, with the ID's of commentNameA, commentEmailA & commentCardA and have them transfer accordingly to the sum ID's. I have tried using different functions however i can't find the right solution. Java Script: function summary() { var sumShow = [name, email, card]; var position = [posName, posEmail, posCard]; var name = document.getElementById("commentNameA").value; var email = document.getElementById("commentEmailA").value; var card = document.getElementById("commentCardA").value; var posName = document.getElementById("sumName").innerHTML; var posEmail = document.getElementById("sumEmail").innerHTML; var posCard = document.getElementById("sumCard").innerHTML; for(var i = 0; i < 3; i++ ){ var k = 0; position[i] = sumShow[k]; k += 1; } } HTML: <form action=" " method=" " > <table id = "order"> <tr> <td id = "commentName">Name:<input type="text" name="Name" id="commentNameA" class="name" placeholder="Enter Your Full Name" onkeyup="validateName()" ></td> </tr> <tr> <td id="commentEmail">Email:<input type="email" name="Email" id="commentEmailA" onkeyup="validateEmail()" class="email" placeholder="Enter Your Email"></td> </tr> <tr> <td id ="commentCard">Card:<input type="text" name="Card_Number" id="commentCardA" class="card" onkeyup="update(this.value)" placeholder="Enter a Proxy Credit Card Number" ></td> </tr> <tr> <td id="commentButton"><button id="commentForm" type="submit" name="submit" class="btn" >Submit Form</button></td> </tr> </table> </form> <div id="sumTable" class="summary"> <table id="sumTableA" class="summaryTable" style="width:100%" > <tr> <th>Name</th> <th>Email</th> <th>Card Number</th> </tr> <tr> <td id="sumName"> </td> <td id="sumEmail"> </td> <td id="sumCard"> </td> </tr> <input id="sumBtn" onclick="summary()" type="submit" name="summary" class="sumBtn" value="summary" /> </table> </div> There are no errors. A: E.g. posName ist storing the innerHTML as a string and not a reference to this attribute in the DOM. so when you cange position[i] = sumShow[k];, you are not modifying the DOM but just changing the string inside the variables. To fix this, store the actual DOM node in e.g. posName and apply the value to the innerHTML inside the loop: position[i].innerHTML = sumShow[k]; I can also see no reason to use the different variables i and k. You could use i for both array. And if the inputs do not contain HTML code but only strings, you could insert them with the textContent attribute instead of the innerHTML. function summary() { var name = document.getElementById("commentNameA").value; var email = document.getElementById("commentEmailA").value; var card = document.getElementById("commentCardA").value; var posName = document.getElementById("sumName"); var posEmail = document.getElementById("sumEmail"); var posCard = document.getElementById("sumCard"); var sumShow = [name, email, card]; var position = [posName, posEmail, posCard]; for(var i = 0; i < position.length; i++ ){ position[i].textContent = sumShow[i]; } } <form action=" " method=" "> <table id="order"> <tr> <td id="commentName">Name:<input type="text" name="Name" id="commentNameA" class="name" placeholder="Enter Your Full Name"></td> </tr> <tr> <td id="commentEmail">Email:<input type="email" name="Email" id="commentEmailA" class="email" placeholder="Enter Your Email"></td> </tr> <tr> <td id="commentCard">Card:<input type="text" name="Card_Number" id="commentCardA" class="card" placeholder="Enter a Proxy Credit Card Number"></td> </tr> </table> </form> <div id="sumTable" class="summary"> <table id="sumTableA" class="summaryTable" style="width:100%"> <tr> <th>Name</th> <th>Email</th> <th>Card Number</th> </tr> <tr> <td id="sumName"> </td> <td id="sumEmail"> </td> <td id="sumCard"> </td> </tr> </table> <input id="sumBtn" onclick="summary()" type="submit" name="summary" class="sumBtn" value="summary" /> </div>
{ "pile_set_name": "StackExchange" }
Q: Java REST is there a way to default to a particular method if none of the paths match? (Instead of getting a 405) I apologize if some of my terminology is off, I'm still trying to learn: I'm using the Dropwizard framework and I have a resource class with all my various POST/GET/etc methods. They all work fine when hit from Postman, browsers, etc. If I try something that has no matching path in the resource class I get an exception with HTTP status 405 - method not allowed. Is there a way to default to some other method where I can display troubleshooting help -- like a list of what the available APIs are or a link to some documentation? Sort of like a try catch type of logic. Not sure what the options are or if there is a best way to do this. Any help is appreciated. Thanks! A: I don't think you might want to do that. REST over HTTP is driven "mostly" by the HTTP method and the end-point the same will act upon it. In any stack, try to avoid that since you have specific actions for specific resources...anything else should be treated as something the server didn't understand, in the same way the HTTP protocol would behave. Being said that, just apply a wildcard, usually * to one of the methods as a fallback action. That should work on Jersey and Spring Boot (MVC) as well.
{ "pile_set_name": "StackExchange" }
Q: Pyramid shaped observatories There are some pyramid shaped observatories around the world, like the Solar Lab Pyramid in the Canary Islands or The Pyramid International Laboratory in Nepal. I was wondering, why a pyramid? Because of its relative stability, or is there something else? below: Solar Lab Pyramid in the Canary Islands. below: The Pyramid International Laboratory in Nepal. A: Both are solar observatories, and so have different requirements from conventional telescopes. The sloping sides may allow for smoother air flow around the building, as heating during the day causes air to rise, which affects the resolution of the image. Also the pyramid is structurally strong (useful when you have a building on top of a mountain) and attractive, echoing she shape of the mountains. The Nepali observatory uses the flat walls to mount photovoltaic cells.
{ "pile_set_name": "StackExchange" }
Q: How do I upsert a row that is new or precisely the same as the existing row, and raise an error in every other case? Suppose we have the following: CREATE TABLE TBL (key INTEGER PRIMARY KEY, value TEXT); I would like to have an upsert statement that does one of three things: Inserts the row if there is no conflict. Does nothing if the row to be inserted exactly matches the row with which it is in conflict. Raises an error if the row to be inserted does not match the row with which it is in conflict. For example, I would like something along these lines, where the first statement succeeds and inserts, the second does nothing, and the third fails: INSERT INTO TBL(key, value) VALUES (1, 'foo') ON CONFLICT(key) ...; INSERT INTO TBL(key, value) VALUES (1, 'foo') ON CONFLICT(key) ...; INSERT INTO TBL(key, value) VALUES (1, 'bar') ON CONFLICT(key) ...; I don't know what to put in the ellipses, or if this is even the right approach. Just adding DO NOTHING doesn't do what I want, since it won't fail if there is a row mismatch: # Not what I want. INSERT INTO TBL(key, value) VALUES (1, 'bar') ON CONFLICT(key) DO NOTHING; I can always query after the upsert to see if the row in the table is the same as the one I tried to upsert, but I wonder if there is a more elegant way of doing this. A: One way to do to this uses a BEFORE trigger to do the validation: sqlite> CREATE TABLE tbl(key INTEGER PRIMARY KEY, value TEXT); sqlite> CREATE TRIGGER tbl_validate BEFORE INSERT ON tbl BEGIN ...> SELECT CASE WHEN new.value = tbl.value THEN raise(IGNORE) ...> ELSE raise(ABORT, 'value differs from existing') -- For a better error message ...> END ...> FROM tbl WHERE tbl.key = new.key; ...> END; sqlite> INSERT INTO tbl(key, value) VALUES (1, 'foo'); sqlite> INSERT INTO tbl(key, value) VALUES (1, 'foo'); sqlite> INSERT INTO tbl(key, value) VALUES (1, 'bar'); Error: value differs from existing sqlite> SELECT * FROM tbl; key value ---------- ---------- 1 foo
{ "pile_set_name": "StackExchange" }
Q: Validating country codes Our enterprise data systems maintain a list of 2-character country codes that I want to enforce inside Salesforce. I'm having trouble writing a validation rule that successfully does this. The rule on Lead.Country is: AND( !ISBLANK(Country), LEN(Country) <> 2, NOT(CONTAINS("00:AD:AE:AF:AG:AI:AL:AM:AN:AO:AQ:AR:AS:AT:AU:AW:AX:AZ:BA:"& "BB:BD:BE:BF:BG:BH:BI:BJ:BL:BM:BN:BO:BR:BS:BT:BV:BW:BY:BZ:"& "CA:CC:CD:CF:CG:CH:CI:CK:CL:CM:CN:CO:CR:CU:CV:CX:CY:CZ:"& "DE:DJ:DK:DM:DO:DZ:EC:EE:EG:EH:ER:ES:ET:FI:FJ:FK:FM:FO:FR:"& "GA:GB:GD:GE:GF:GH:GI:GL:GM:GN:GP:GQ:GR:GS:GT:GU:GW:GY:HK:HM:HN:"& "HR:HT:HU:ID:IE:IL:IM:IN:IO:IQ:IR:IS:IT:JE:JM:JO:JP:KE:KG:KH:KI:KM:KN:KP:"& "KR:KW:KY:KZ:LA:LB:LC:LI:LK:LR:LS:LT:LU:LV:LY:MA:MC:MD:ME:MF:MG:MH:MK:ML:"& "MM:MN:MO:MP:MQ:MR:MS:MT:MU:MV:MW:MX:MY:MZ:NA:NC:NE:NF:NG:NI:NL:NO:NP:NR:"& "NU:NZ:OM:PA:PE:PF:PG:PH:PK:PL:PM:PN:PR:PS:PT:PW:PY:QA:RE:RO:RS:RU:RW:SA:"& "SB:SC:SD:SE:SG:SH:SI:SJ:SK:SL:SM:SN:SO:SR:ST:SV:SY:SZ:TC:TD:TF:TG:TH:TJ:"& "TK:TL:TM:TN:TO:TR:TT:TV:TW:TZ:UA:UG:UM:US:UY:UZ:VA:VC:VE:VG:VI:VN:VU:WF:"& "WS:XK:YE:YT:YU:ZA:ZM:ZW", Country)) ) Here are some sample results: Fails validation "1" "ABC" Passes validation "A" "AB" It seems that since every letter of the alphabet is in the Contains block and single or two-character combination passes. A: Why not trying using a VLookup. you can store all of your values in an object and then use the VLOOKUP() formula to see if it exists in the list. That way you avoid running into the size limit on formula fields and you can more easily maintain the list of valid country codes. https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_functions.htm&language=en#VLOOKUP A: The problem turned out to be in the AND clause. I re-examined the Salesforce example for US states and realized I need to OR together the LEN and CONTAINS functions. AND( !ISBLANK(Country), OR( LEN(Country) <> 2, NOT(CONTAINS("00:AD:AE:AF:AG:AI:AL:AM:AN:AO:AQ:AR:AS:AT:AU:AW:AX:AZ:BA:"& "BB:BD:BE:BF:B <snip>) ) )
{ "pile_set_name": "StackExchange" }
Q: Create TBase objects from Thrift-generated classes in Scala I have some Scala classes I generated with Thrift (Scrooge). Now I need to somehow instantiate those as TBase class, b/c the TSerializer class needs this as an input This is my approach: def createTestBinary(): String = { val proto = new TBinaryProtocol.Factory val err = new ClientError{} val binary = new TSerializer().serialize(err) "" } ClientError is the generated class. How can I instantiate it or wrap it as a TBase member? Any ideas how to do this? Thanks in advance! A: You don't need TSerializer, that's for "vanilla" thrift, not for scrooge-generated classes. You need to do something like this instead: val transport = TMemoryBuffer(1024) // or whatever err.write(new TBinaryProtocol(transport)) val binary = transport.getArray
{ "pile_set_name": "StackExchange" }
Q: Python Dictionary Multiple Keys, Search Function I have the following sample CSV named results1111.csv: Master #,Scrape,Date of Transaction 2C7E4B,6854585658,5/2/2007 2C7E4B,8283876134,5/8/2007 2C7E4B,4258586585,5/18/2007 C585ED,5554541212,5/18/2004 585868,5555551214,8/16/2012 I have the following code which opens the CSV and then puts the data into multiple dictionaries: with open('c:\\results1111.csv', "r") as f: f.next() reader = csv.reader(f) result = {} for row in reader: key = row[0] result[key] = row[1:] values = row[1:] telnumber = row[1] transdate = row[2] #print key #print values #print telnumber #print transdate #print result d = {} d.setdefault(key, []).append(values) print d The output of the above code is: {'2C7E4B': [['6854585658', '5/2/2007']]} {'2C7E4B': [['8283876134', '5/8/2007']]} {'2C7E4B': [['4258586585', '5/18/2007']]} {'C585ED': [['5554541212', '5/18/2004']]} {'585868': [['5555551214', '8/16/2012']]} I would like to search the dictionaries for any instance where the same key has multiple phone numbers tied to it, such as the first three entries in the output above. When that happens, I would then like to remove the dictionary with the earliest date. I would then like to output all of the remaining dictionaries back into a CSV. The output should look like this: 2C7E4B,8283876134,5/8/2007 2C7E4B,4258586585,5/18/2007 C585ED,5554541212,5/18/2004 585868,5555551214,8/16/2012 Since there are thousands of keys (in the real input csv), I am not sure how to write a statement to do this. Any help is appreciated. A: You'll need to sort all of the reocrds for a single master by date, which is more easily done with a list than a dict. Since month/day/year date doesn't sort correctly without some sort of conversion, I create a datetime object as the first item of the record. Now the list will sort by date (and if two records have the same date, by telephone number) so it's just a question of finding, sorting and deleting items from the list. import csv import collections import datetime as dt open('temp.csv', 'w').write("""Master #,Scrape,Date of Transaction 2C7E4B,6854585658,5/2/2007 2C7E4B,8283876134,5/8/2007 2C7E4B,4258586585,5/18/2007 C585ED,5554541212,5/18/2004 585868,5555551214,8/16/2012 """) with open('temp.csv') as f: f.next() reader = csv.reader(f) # map master to list of transactions result = collections.defaultdict(list) for row in reader: key = row[0] # make date sortable sortable_date = dt.datetime.strptime(row[2], '%m/%d/%Y') result[key].append([sortable_date, row[1], row[2]]) for value in result.values(): # discard old records if len(value) > 1: value.sort() del value[0] # or to delete all but the last one # del value[:-1] keys = result.keys() keys.sort() for key in keys: transactions = result[key] for transaction in transactions: print key, transaction[1], transaction[2]
{ "pile_set_name": "StackExchange" }
Q: Cancelling boost::asio::async_read gracefully I have a class that looks like this: class MyConnector : public boost::noncopyable, public boost::enable_shared_from_this<MyConnector> { public: typedef MyConnector this_type; boost::asio::ip::tcp::socket _plainSocket; boost::shared_ptr<std::vector<uint8_t>> _readBuffer; // lot of obvious stuff removed.... void readProtocol() { _readBuffer = boost::make_shared<std::vector<uint8_t>>(12, 0); boost::asio::async_read(_plainSocket, boost::asio::buffer(&_readBuffer->at(0), 12), boost::bind(&this_type::handleReadProtocol, shared_from_this(), boost::asio::placeholders::bytes_transferred, boost::asio::placeholders::error)); } void handleReadProtocol(size_t bytesRead,const boost::system::error_code& error) { // handling code removed } }; This class instance is generally waiting to receive 12 bytes protocol, before trying to read the full message. However, when I try to cancel this read operation and destroy the object, it doesn't happen. When I call _plainSocket.cancel(ec), it doesn't call handleReadProtocol with that ec. Socket disconnects, but the handler is not called. boost::system::error_code ec; _plainSocket.cancel(ec); And the shared_ptr of MyConnector object that was passed using shared_from_this() is not released. The object remains like a zombie in the heap memory. How do I cancel the async_read() in such a way that the MyConnector object reference count is decremented, allowing the object to destroy itself? A: Two things: one, in handleReadProtocol, make sure that, if there is an error, that readProtocol is not called. Canceled operations still call the handler, but with an error code set. Second, asio recommends shutting down and closing the socket if you're finished with the connection. For example: asio::post([this] { if (_plainSocket.is_open()) { asio::error_code ec; /* For portable behaviour with respect to graceful closure of a connected socket, call * shutdown() before closing the socket. */ _plainSocket.shutdown(asio::ip::tcp::socket::shutdown_both, ec); if (ec) { Log(fmt::format("Socket shutdown error {}.", ec.message())); ec.clear(); } _plainSocket.close(ec); if (ec) Log(fmt::format("Socket close error {}.", ec.message())); } });
{ "pile_set_name": "StackExchange" }
Q: How to deploy complex tcl applications How to deploy complex tcl applications and where to find a good getting started with a minimal example? I want to deploy the application in form of a tcl interpeter with the application tcl packages included. Preferable as one binary. A: The canonical way to do that with Tcl is a so called starpack or starkit. A starpack is a single binary that contains a Tcl runtime and all needed scripts and extensions in a single file. A starkit does it with two files (one runtime originally called tclkit and a bundled data/script archive inside a database). Sadly the documentation for that is a bit fragmented and unorderly these days, and there are a variety of runtimes now, that have various up and downsides. So I'll have to provide a few more links and steps to get you into the right direction. If you are on windows, maybe start right here on Stackoverflow with this excellent answer (just use my download links for the basekits and sdx below, as the old equi4.com links are gone): Steps to Create A Tcl Starkit on a Windows Platform The most polished version is surely the commercial ActiveState TDK with its TclApp wrapping tool (see the docs at http://docs.activestate.com/tdk/5.4/TclApp.html), it basically shows what can be done in general with those starkits. Outside of that, you can find a lot of information spread over the Tcl'ers wiki, start from: http://wiki.tcl.tk/52 You need one basekit of some kind, the current ones would probably the ones provided by Roy Keene (http://tclkits.rkeene.org/fossil/wiki/Downloads). You will also want SDX (see http://wiki.tcl.tk/3411 for sources to get it). Once you have those parts together, you can follow the step-by-step guides from (http://wiki.tcl.tk/10558). The Building a Starkit section at http://wiki.tcl.tk/3661 has a few more recipes.
{ "pile_set_name": "StackExchange" }
Q: $k | x^{k} - x,$ for $k, x \in \mathbb{Z}$? I seem to have found that: $$k | x^{k} - x, \ \text{for} \ k, x \in \mathbb{Z}.$$ I have tried it with a few values, and it seems to be true. I am sure that this has been discovered before. A: In fact, it does not work for all $k, x \in \mathbb{Z}$. Consider $k = 4, x = 2$: $4$ does not divide $2^4 - 2 = 16 - 2 = 14$. However, this works if $k$ is prime, and is well-known Fermat's little theorem.
{ "pile_set_name": "StackExchange" }
Q: What is the best way to handle the restriction of an API? Our core domain so far has an abstraction called PersonName with methods for firstName, lastName, middleInitial etc. As we are expanding the domain to Spain, we figured that they only talk in terms of name, firstSurname and secondSurname i.e. middleInitial etc have no significance to them. The PersonName interface is currently being used at many places in the current API and the SpainPersonName should also be used at the same places. So, my option is to extend SpainPersonName from PersonName. But, if i do this then I will end up exposing the API for firstName, middleInitial etc which are not applicable for Spain domain. My question is how best we can refactor the current abstractions still keeping the backward compatibility? Any refactoring or design suggestions are greatly appreciated. A: I am not too sure what your question is. By "to extend SpainPersonName from PersonName", do you mean make SpainPersonName implement or inherit from PersonName? In any case, let me speculate that the PersonName abstraction might be a flawed one. An abstraction must be widely applicable, at least to the situations where it is applied, right? We Spaniards do not think in terms of first name vs. last name, as you well point out. Maybe the abstraction needs to be rethought. In my experience, an abstraction based on GivenName plus FamilyName is the most widely applicable one, even to Asian cultures where the order of names is not the "usual" one. Being constructive, I think that you need to map the Spanish first and second surnames to the abstract last name, because that (first and second surnames) is what we Spaniards conceive as our "last name". If you can do that, then you are doing acceptably well.
{ "pile_set_name": "StackExchange" }
Q: JS custom scrollbar thumb sizing problems relative to element scrollwidth I made a custom scrollbar for a component. I calculate length of its thumb by viewportWidth / element.scrollWidth; It gives me the value in % that I then apply to the thumb element. But for some reason, after viewportWidth becomes a certain amount(622px wide in my case, and I don't know what this number means or does such that scrollbar breaks, content is a bunch of boxes, each box is 350px wide and has 1rem(16px) wide margins on both sides, thus each box takes around 382 pixels if that matters) scrollbar becomes longer than it should be, and in order to scroll content all the way left, you need to move thumb out of scrollbar length. Here is my code: const clamp = (val, min, max) => { return Math.min(Math.max(val, min), max); } class ScrollableComponent extends React.Component { state = { holding: false, xLocation: 0, width: 0 }; lastPos = 0; constructor(props) { super(props); this.scrollbarRef = React.createRef(); this.scrollContentRef = React.createRef(); } correction = 0; scroll = amount => { this.setState({ xLocation: clamp( this.state.xLocation + amount, 0, this.getFullWidth() - this.getAbsoluteThumbWidth() - this.correction ) }); }; componentDidMount = () => { document.body.addEventListener("mousemove", e => { if (this.state.holding) { let delta = e.pageX - this.lastPos; this.scroll(delta); this.lastPos = e.pageX; } }); document.body.addEventListener("mouseup", e => { this.setState({ holding: false }); }); }; getFullWidth = () => { return this.scrollbarRef.current ? this.scrollbarRef.current.clientWidth : this.default; }; contentScrollWidth = () => { if (this.scrollContentRef.current) { return this.scrollContentRef.current.scrollWidth; } }; contentViewportWidth = () => { if (this.scrollContentRef.current) { return this.scrollContentRef.current.clientWidth; } }; getRelativeThumbWidth = () => { // console.log(this.getFullWidth(), this.contentScrollWidth()); return this.getFullWidth() / this.contentScrollWidth(); }; getAbsoluteThumbWidth = () => { return this.getRelativeThumbWidth() * this.getFullWidth(); }; default = 100; render() { let calcedWidth = this.getRelativeThumbWidth(); let thumbPosition = this.state.xLocation / (this.getFullWidth() - this.getAbsoluteThumbWidth() - this.correction); console.log(thumbPosition); let scrollAmount = thumbPosition * (this.contentScrollWidth() - this.contentViewportWidth()); // console.log(thumbPosition, scrollAmount); if (this.scrollContentRef.current) { this.scrollContentRef.current.scrollLeft = scrollAmount; } return ( <div {...this.props} onWheel={e => { this.scroll(e.deltaY); }} onTouchMove={e => { let newX = e.touches[0].clientX; this.scroll(newX - this.lastPos); this.lastPos = newX; }} > <div ref={this.scrollContentRef} className="overflow-hidden"> {this.props.children} </div> <div className={"scrollbar" + " mt-auto"} ref={this.scrollbarRef}> <span style={{ transform: `translateX(${this.state.xLocation}px)`, width: calcedWidth * 100 + "%" }} onMouseDown={e => { this.lastPos = e.clientX; this.setState({ holding: true }); }} ></span> </div> </div> ); } } class PreviewBox extends React.Component { render() { return ( <div className={ "bg-black mx-4 w-350px h-48 flex-shrink-0 inline-block align-top " + "previewBox" } ></div> ); } } ReactDOM.render( <ScrollableComponent className={ "transition-all duration-500 ease-in-out my-auto flex flex-col w-full px-8 " } > <div className="inline-block whitespace-no-wrap mb-4 py-8 "> <PreviewBox /> <PreviewBox /> <PreviewBox /> <PreviewBox /> <PreviewBox /> </div> </ScrollableComponent>, document.getElementById("root") ); .scrollbar { user-select: none; touch-action: none; margin-top: 0; height: 25px; background: black; display: flex; // padding: 5px; overflow: hidden; } span { min-width: 200px; cursor: pointer; background: #b94747; } span:hover { background: #ff6060; } .previewBox { width:350px; background:black; transition: all 0.15s ease-in; cursor: pointer; } .previewBox:hover { transition: all 0.15s ease-out; transform: scale(1.025); } <div id = "root"></div> <p class="px-8 mt-3">If you make your screen wider, you'll see that scrollbar works OK, if its not wide enough, its thumb will have to go out of viewport to work</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> it's confusing, since scrollWidth stays the same no matter the screen size, thus we know that scrollWidth is definitely correct. Variable here is viewportWidth, it changes, but so far, as I think, it changes correctly too. state.xLocation just can not be wrong even theoretically, its just a number that you can increase as much as you want. this.getFullWidth() gives correct value. Hence, thumb size is correct. Problem lays in thumbPosition, but here is a catch, How does this happen if formula for thumbPosition uses all correct values?! (this.getAbsoluteThumbWidth() is just relative width in fractions, multiplied by viewportWidth) I am sincerely confused by my creation. A: const clamp = (val, min, max) => { return Math.min(Math.max(val, min), max); } class ScrollableComponent extends React.Component { state = { holding: false, xLocation: 0, width: 0 }; lastPos = 0; constructor(props) { super(props); this.scrollbarRef = React.createRef(); this.scrollContentRef = React.createRef(); } correction = 0; scroll = amount => { this.setState({ xLocation: clamp( this.state.xLocation + amount, 0, this.getFullWidth() - this.getAbsoluteThumbWidth() - this.correction ) }); }; componentDidMount = () => { document.body.addEventListener("mousemove", e => { if (this.state.holding) { let delta = e.pageX - this.lastPos; this.scroll(delta); this.lastPos = e.pageX; } }); document.body.addEventListener("mouseup", e => { this.setState({ holding: false }); }); }; getFullWidth = () => { return this.scrollbarRef.current ? this.scrollbarRef.current.clientWidth : this.default; }; contentScrollWidth = () => { if (this.scrollContentRef.current) { return this.scrollContentRef.current.scrollWidth; } }; contentViewportWidth = () => { if (this.scrollContentRef.current) { return this.scrollContentRef.current.clientWidth; } }; getRelativeThumbWidth = () => { // console.log(this.getFullWidth(), this.contentScrollWidth()); return this.getFullWidth() / this.contentScrollWidth(); }; getAbsoluteThumbWidth = () => { return this.getRelativeThumbWidth() * this.getFullWidth(); }; default = 100; render() { let calcedWidth = this.getRelativeThumbWidth(); let thumbPosition = this.state.xLocation / (this.getFullWidth() - this.getAbsoluteThumbWidth() - this.correction); console.log(thumbPosition); let scrollAmount = thumbPosition * (this.contentScrollWidth() - this.contentViewportWidth()); // console.log(thumbPosition, scrollAmount); if (this.scrollContentRef.current) { this.scrollContentRef.current.scrollLeft = scrollAmount; } return ( <div {...this.props} onWheel={e => { this.scroll(e.deltaY); }} onTouchMove={e => { let newX = e.touches[0].clientX; this.scroll(newX - this.lastPos); this.lastPos = newX; }} > <div ref={this.scrollContentRef} className="overflow-hidden"> {this.props.children} </div> <div className={"scrollbar" + " mt-auto"} ref={this.scrollbarRef}> <span style={{ transform: `translateX(${this.state.xLocation}px)`, width: calcedWidth * 100 + "%" }} onMouseDown={e => { this.lastPos = e.clientX; this.setState({ holding: true }); }} ></span> </div> </div> ); } } class PreviewBox extends React.Component { render() { return ( <div className={ "bg-black mx-4 w-350px h-48 flex-shrink-0 inline-block align-top " + "previewBox" } ></div> ); } } ReactDOM.render( <ScrollableComponent className={ "transition-all duration-500 ease-in-out my-auto flex flex-col w-full px-8 " } > <div className="inline-block whitespace-no-wrap mb-4 py-8 "> <PreviewBox /> <PreviewBox /> <PreviewBox /> <PreviewBox /> <PreviewBox /> </div> </ScrollableComponent>, document.getElementById("root") ); .scrollbar { user-select: none; touch-action: none; margin-top: 0; height: 25px; background: black; display: flex; // padding: 5px; overflow: hidden; } span { width: 200px; cursor: pointer; background: #b94747; } span:hover { background: #ff6060; } .previewBox { width:350px; background:black; transition: all 0.15s ease-in; cursor: pointer; } .previewBox:hover { transition: all 0.15s ease-out; transform: scale(1.025); } <div id = "root"></div> <p class="px-8 mt-3">If you make your screen wider, you'll see that scrollbar works OK, if its not wide enough, its thumb will have to go out of viewport to work</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> So here is the problem span { min-width: 200px; // this cursor: pointer; background: #b94747; } you should change it to width so that it can be overwritten you may also want to update the width in componentDidMount for the first render
{ "pile_set_name": "StackExchange" }
Q: O que é e para que serve um Seeder? Vi no Laravel que existe uma pasta chamada database. Nela temos os migrations e o seeds. Eu entendo que as migrations são migrações, são códigos que fornecem especificações para criação das tabelas no banco de dados, sem a necessidade de conhecer o SGDB que se pretende utilizar. Porém o que seria esse seeder ou seed? Esse nome Seeder é algum conceito da programação, ou algo relacionado com banco de dados? Está relacionado diretamente com as migrações (migrations)? Nota: Lembrando que a pergunta não é sobre Laravel, mas sim sobre a explanação sobre o nome Seeder ou Seed que aparece lá. A: Porém o que seria esse seeder ou seed? Nada mais é do que dados pré determinados que serão inseridos no banco de dados na inicialização do mesmo. Está relacionado diretamente com as migrações (migrations)? Não com migrations em si, mas sim no conceito de "Code First", ou seja, onde você cria seu banco de dados de acordo com o modelo que você de dados que sua aplicação possui. E quando devo utilizar? Esse conceito é muito utilizado em testes, mas não se limitam somente à testes. Um bom exemplo é quando você necessita criar um usuário sempre que for "instalar" seu sistema em um novo ambiente. Ao invés de criar um usuário na mão, pode configurar um seed do usuário e senha que será inserido automaticamente no sistema, simples não? Outro exemplo seria os dados em tabelas que irão preencher combobox, cidades/estados, dentre muitos outros exemplos. Fungindo um pouco do foco... Você comentou sobre larável, mas irei colocar um exemplo com o Entity Framework aqui. public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolDBContext> { protected override void Seed(SchoolDBContext context) { var user = new User{Name = "Admin", Password = "Admin"}; context.Users.Add(user ); base.Seed(context); } } Neste exemplo, toda vez que o banco for inicializado pelo código, será inserido o usuário Admin na base de dados.
{ "pile_set_name": "StackExchange" }
Q: Image and kernel of a matrix transformation I had a couple of questions about a matrix problem. What I'm given is: Consider a linear transformation $T: \mathbb R^5 \to \mathbb R^4$ defined by $T( \vec{x} )=A\vec{x}$, where $$A = \left(\begin{array}{crc} 1 & 2 & 2 & -5 & 6\\ -1 & -2 & -1 & 1 & -1\\ 4 & 8 & 5 & -8 & 9\\ 3 & 6 & 1 & 5 & -7 \end{array}\right)$$ Find $\mathrm{im}(T)$ Find $\ker(T)$ My questions are: What do they mean by the transformation? What do I use to actually find the image and kernel, and how do I do that? A: After a long night of studying I finally figured out the answer to these. The previous answers on transformation were all good, but I have the outlined steps on how to find $\mathrm{im}(T)$ and $\ker(T)$. $$A = \left(\begin{array}{crc} 1 & 2 & 2 & -5 & 6\\ -1 & -2 & -1 & 1 & -1\\ 4 & 8 & 5 & -8 & 9\\ 3 & 6 & 1 & 5 & -7 \end{array}\right)$$ (1) Find $\mathrm{im}(T)$ $\mathrm{im}(T)$ is the same thing as column space or $C(A)$. The first step to getting that is to take the Transpose of $A$. $$ A^T = \left(\begin{array}{crc} 1 & -1 & 4 & 3 \\ 2 & -2 & 8 & 6 \\ 2 & -1 & 5 & 1 \\ -5 & 1 & -8 & 5 \\ 6 & -1 & 9 & -7 \end{array}\right)$$ once that's done the next step is to reduce $A^T$ to Reduced Row Echelon Form $$ \mathrm{rref}(A^T) = \left(\begin{array}{crc} 1 & 0 & 1 & -2 \\ 0 & 1 & -3 & -5 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \end{array}\right)$$ now on this step I honestly don't know the reasons behind it, but the thext thing you do is take the rows and that's your answer. so that: $$\mathrm{im}(T)\ = \begin{align*} \operatorname{span}\left\{\left(\begin{array}{crc} 1 \\ 0 \\ 1 \\ -2 \end{array}\right), \left(\begin{array}{crc} 0 \\ 1 \\ -3 \\ -5 \end{array}\right)\right\} \end{align*}$$ (2) Find $\ker(T)$ $\ker(T)$ ends up being the same as the null space of matrix, and we find it by first taking the Reduced Row Echelon Form of A $$ \mathrm{rref}(A) = \left(\begin{array}{crc} 1 & 2 & 0 & 3 & -4\\ 0 & 0 & 1 & -4 & 5\\ 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0 \end{array}\right)$$ we then use that to solve for the values of $\mathbb R^5$ so that we get $$\begin{align*} \left(\begin{array}{crc} x_1 \\ x_2 \\ x_3 \\ x_4 \\ x_5 \end{array}\right) = r\left(\begin{array}{crc} -2 \\ 1 \\ 0 \\ 0 \\ 0 \end{array}\right) + s\left(\begin{array}{crc} -3 \\ 0 \\ 4 \\ 1 \\ 0 \end{array}\right) + t\left(\begin{array}{crc} 4 \\ 0 \\ -5 \\ 0 \\ 1 \end{array}\right) \end{align*}$$ from that we arrange the vectors and get our answer the vectors and that gives us our answer $$\begin{align*} \ker(T) = \operatorname{span}\left\{\left(\begin{array}{crc} -2 \\ 1 \\ 0 \\ 0 \\ 0 \end{array}\right), \left(\begin{array}{crc} -3 \\ 0 \\ 4 \\ 1 \\ 0 \end{array}\right), \left(\begin{array}{crc} 4 \\ 0 \\ -5 \\ 0 \\ 1 \end{array}\right)\right\} \end{align*}$$ and that's that. A: What they mean by the transformation $T$ is the transformation which is induced by multiplication by $A$. You can verify that matrix multiplication is in fact a linear mapping, and in our particular case we have the linear mapping $T:\ \mathbf{x}\mapsto A\mathbf{x}$. The image is then defined as the set of all outputs of the linear mapping. That is $$\operatorname{Im}(T) = \left\{\mathbf{y}\in \mathbb{R}^4\ \big|\ \mathbf{y} = A\mathbf{x}\ \text{such that}\ \mathbf{x}\in\mathbb{R}^5 \right\}$$ If you play around with the mapping a little bit then you should find that the image is in fact a very familiar subspace associated with the matrix $A$ (take a look at how the mapping $T$ acts on the standard basis). The kernel is correspondingly defined as the set of all inputs which are taken to zero. $$\ker(T) = \left\{\mathbf{x}\in \mathbb{R}^5\ \big|\ A\mathbf{x} = \mathbf{0} \right\}$$ Again, there is a familiar subspace of the matrix $A$ associated with the kernel, look carefully at the definition and you should be able to figure out what it is. A: By a linear transformation, they mean a function between vector spaces which satisfies $T(cx + y) = cT(x) + T(y)$. In our case, this transformation is multiplication by the matrix $A$. The image is the set of all points in $\mathbb{R}^4$ that you get by multiplying this matrix to points in $\mathbb{R}^5$, you can find these by checking the matrix on the standard basis. The kernel is the set of all points in $\mathbb{R}^5$ such that, multiplying this matrix with them gives the zero vector. Again you can find this in a similar way.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to restrict event registration to members? I've been trying to figure out how to set up events where only members can register. Is this possible? What I'm looking for is the ability to: specify one or more memberships that can register for an event, and limit registration to those members. require authentication as part of registration for events where membership is required OR allow membership signup during registration not require authentication if the event registration is not limited to members only. I'm running CiviCRM on Drupal, and I know I could set the Drupal permission for CiviEvent: register for events so that only logged-in users with a given role could register. I would then sync CiviCRM memberships with Drupal roles. But I only want to limit some events, not all, so this approach won't work. Also, if I had multiple roles (one per membership), those roles would all need the same Register permission, meaning any member could register for any event, even those events should be limited to people holding a specific membership. I also know that I could publish details of member-only events to just those members. But those members could share the registration URL with non-members, who could then register. Any suggestions? A: This extension allows you to restrict online registration to certain events to logged in members only but still have other events open to the public. The extension allows you to set a flag to any event so registration is restricted to those that have a current membership. https://civicrm.org/extensions/member-only-event A: The way I do this is by using the "Require participant approval?" feature in the event set up. This means that anyone can apply for the event, but then their application is manually reviewed by one of the admins to see if they are a member. Clearly, this introduces a manual process, but it does mean it's quite secure and it means any anonymous user can apply without having to log in.
{ "pile_set_name": "StackExchange" }
Q: Why not one pixel per color clock? Early home computers and game consoles output video to TV sets. The NTSC color clock frequency is 3.58 MHz. This informed the design of some video systems: http://pineight.com/mw/index.php?title=Dot_clock_rates In particular, the Atari 2600 and Intellivision have one pixel per color clock, which is an obviously reasonable way to do it. In the Apple II, the pixel clock is exactly twice the color clock. That makes sense because it has an option to turn off the color clock to generate reasonably crisp black-and-white text, then turn it on for the ability to generate artifact colors. This arrangement is very economical on parts count, which was important at the time. The Atari 800 also has a pixel clock exactly twice the color clock, but as far as I know, it does not have the option to turn off the color clock. I'm trying to figure out what advantage it gains from this. Specifically, I know if you run at an exact multiple of the color clock you can generate artifact colors, but surely you would get strictly better results by running exactly at the color clock and spending the memory and bandwidth on coloring fewer pixels? For example, say the Atari is operating in a mode with 1 bit per pixel, and generating artifact colors. Would it not be better off halving the pixel resolution and using 2 bits per pixel to just generate the wider range of colors directly? There is a theory that says it makes sense to subsample the chroma information, in other words run the luma information at twice the frequency, because the luma information is more important, but as far as I can see based on e.g. https://en.wikipedia.org/wiki/Apple_II_graphics#Color_on_the_Apple_II the result of this is that the luma information simply gets converted into artifact colors, and you might as well have done this directly. The situation with other machines like the NES looks even worse; it outputs somewhat more than one pixel per color clock, but less than two, so that the extra resolution will just convert into uncontrollable color fringing. On the face of it, the NES looks like a reduction of the resolution to 3.58 MHz pixel clock would produce better results for lower cost. What advantage was there in going higher than one pixel per color clock (in machines that weren't going to turn off the color clock to generate black-and-white text like the Apple II), that I am missing? A: I think you're conflating a few issues: being in-phase with the colour subcarrier; being sampled at a rate less than or equal to the colour subcarrier; and being sampled at an integer division of the colour subcarrier. Being in-phase has exactly one effect: the artefacts on horizontal edges are consistent from one line to the next. The edges do not demonstrate chroma crawl. Being at a rate less than or equal to the colour subcarrier also has exactly one effect: the true colour is going to be displayed somewhere, at least instantaneously, for each pixel. Being at any integer divisor of the colour clock rate buys a third separate advantage: the pixel looks identical no matter where you put it on the display. Nothing you can do is going to get you sharp pixels. All you're doing is picking which sort of artefacts you want. However, you buy yourself a substantial disadvantage for being in-phase: NTSC signals are not normally in-phase by careful design. Being 50% out of phase makes the colour subcarrier's interference with the luminance signal much less visible. This stems from the original design requirement that a colour signal be viewable on an unfiltered black and white set from before the specification of colour without undue ugliness. You buy yourself a substantial disadvantage for being less than or equal to the colour subcarrier frequency: low-resolution graphics. You also buy yourself at least two substantial disadvantage if you optimise for being exactly on the colour subcarrier: your allegation that adding luminance information above and beyond the colour subcarrier frequency doesn't have a visible effect becomes true because the information you can add gets trapped in the vestigial parts of the subcarrier filtering. The actual rule is that with real-life filters, luminance information is liable to be lost only exactly when it is a multiple or divisor of the colour subcarrier — a comb filter is often considered the gold standard for chroma/luma separation and it has that name exactly because its frequency domain response graph spikes at integer intervals; and you've optimised for something that isn't actually a constant supposing you ever want to ship in a PAL country. A chip you didn't mention is the Texas Instruments TMS 9918, which is in-phase but uses a non-integer divisor of the colour subcarrier (specifically, each pixel is 2/3rds of an NTSC cycle long). TI considered the constancy of horizontal colour artefacts to be a bug not a feature, dubbing it the rainbow effect. The linked memo shows a suggested modification that switches to ordinary chroma crawl. The non-engineers were apparently filing it as a bug report. So, to summarise, if you are at exactly the colour subcarrier rate: you look much worse on old and/or cheap black and white sets that don't filter the chroma, which the NTSC spec says they shouldn't have to; you lose the fine luminance information as a simple practical consequence of the frequency response of ordinary separation filters; except in PAL countries of course, where all the software you optimised for the results of your decision suddenly has the opposite design decision. And to throw in a bonus argument of lesser weight: the SCART connector dates from the '70s. Even by 1982 all but the very cheapest European micros offered full RGB output — cf. the Oric or the Electron. Fixating on the subset of users that have a magically clean RF connection or a TV with composite connectors but not a SCART or S-Video socket isn't a very long-sighted strategy. A: The pixel clock has to be fast enough to generate the number of pixels you want to display horizontally within the 56 microsecond scan line interval. At 3.58MHz, you only get about 200 pixels. This was fine for the Atari 2600 et al, which had 160 horizontal pixels, but the other systems you mentioned had higher horizontal resolution, so had to use a faster pixel clock. Edited to clarify in response to comment: This is actually useful. A standard definition TV is actually able to display more detail horizontally in terms of luminance (i.e. brightness) than it can in chrominance (i.e. "colour"). An NTSC TV is limited to approximately 200 transitions of colour in each horizontal line, due to the 3.58MHz colour signal bandwidth, but it can manage somewhere between 400 and 700 brightness transitions per line, depending on the quality of the electronics and how good the signal it's receiving is. PAL and SECAM have slightly higher figures, but in the grand scheme of things the difference is small. This is why the last generation of systems that were designed primarily for TV output tended to have between 256 and 320 horizontal pixels (e.g. the Commodore 64 or Sinclair Spectrum) -- these were the most convenient figures that could reliably be displayed. 480 or 512 pixels might have been interesting, but a lot of users would never have been able to see the detail added by such high resolutions, so it wasn't commercially useful to provide it. On the other end of the spectrum (no pun intended), DVD was designed with a horizontal resolution of 720 pixels because that was the lowest convenient resolution that was universally acknowledged to be beyond the capabilities of NTSC and PAL TVs. But it still encoded the picture in a format that had a lower chrominance resolution than luminance - it uses 4:2:0 subsampling, which actually has less resolution in the vertical direction than a TV signal has (although it probably has more in the horizontal direction). A: Short Answer: There is no relation. What seems like a relaiton is non related coincidence. Long Answer: First of all, there is no colour clock. The mentioned frequency of 3.58 MHz is not a colour clock, but the carrier frequency used to modulate the encoded colour signal atop the basic B&W signal. There is no relation to RAM speed, pixel generation or alike. Especially nothing that needs to be adjusted to this clock, either direct or in any multiple thereof. Computers are digital and use digital clocking. TV isn't. The reason why this frequency is used that often in home computers is simple: cost. A 3.58 MHz crystal is dirt cheap compared to more 'logical' values. And that's not just by some pennies. They where the single most produced value. For example, in 1980 (just checked some magazines) a 4 MHz crystal (and next to any other) was around 4-5 USD, while a 3.58 MHz could be acquired at 0.87 USD. That's quite a lot to be saved for a mere 10% less speed. Further, depending on the kind of video generation, the 3.58 MHz were needed to encode the colour signal. So instead of having two crystals, one for CPU and Memory, the other for signal generation, one was sufficient - saving even more. Technical background: lines and pixel, and resolution vs. colour. The colour signal in itself doesn't define any pixels, as it again is analogue. The colour carrier frequency is about 227.5 times the line frequency. Together with a usable line length of 52/64 this gives ~185 complete colour changes. In a digital system this would be the same as a maximum of 370 'colour' pixels. Now colour is just some frosting atop a b&w base signal. This signal gives us the intensity of a spot and is again analogue. There is no pixelation. Sure, on Y a 'pixel' is formed by the lines used to draw the picture. So while this makes discrete steps along the vertical, horizontally any stepping between 1 (one pixel per line) and infinite is possible (*1). Due to analogue available bandwidth in a real world transmission system it's for all existing (classic) TV systems on this planet less than 320 vertical lines (*2). In today's terms that may be described as 640 pixels. In reality there are usually less than 550 usable. So if we really want to talk about what amount of pixels is possible, we need to take both numbers into account. Up to ~370 distinct, non interacting colour positions and up to ~550 distinct B&W positions are possible. As a result any system producing with up to 370 pixel can be displayed on a TV based CRT system. Each of these pixels will be able to have any (displayable) colour at any (possible) intensity (*3). With more than ~370 pixels per line, a classic colour TV will no longer be able to guarantee a distinct colour to each pixel. For example an orange pixel next to a yellow pixel might, even at 500 pixels per line, still come out well defined, while a blue instead will tend to look more like green. Now it depends on one pixel ahead if it will become blue over time or not. A sequence of blue and yellow dots will look like bluish green and yellowish green instead. (No, this is not the (in)famous NTSC colour bleeding, though looking similar.) (It also isn't the restriction of adjacent colours on an Apple II, as this is given through the encoding used by Woz.) So, long story short: there is no direct relation between pixel clock, memory clock and colour carrier. If at all, it's within design decisions taken by whoever made a computer following certain design goals - usually price, thus reduction of components. *1 - Okay, the X resolution is limited by the upper frequency the electron beam can be modulated, and even before that by the upper frequency the television signal allows. As a third limiter, usually somewhere in between, the colour mask further limits arbitrary changes. *2 - Horizontal resolution is described in classic analogue TV as the number of vertical black lines on a white background that still can be displayed. Or in other words, that (sine) signal which still can be encoded as full transition between minimum and maximum intensity - which happens to be exactly the frequency assigned to a channel. For most TV systems something between 4 and 6 MHz *3 - Well, since an analogue signal can not flip from on state to the exact opposite in zero time, there will be, in both cases (colour and intensity) border effects, which will become more and more visible as frequency (changes) close in to maximum distance and maximum frequency.
{ "pile_set_name": "StackExchange" }
Q: how to calculate expiry date using mysql query? Calculate expiry date using mysql query. calculate make_date and expiry_date difference against tblt_name in mysql query. A: You can use this below query.. select tblt_name, (CASE WHEN datediff(expiry_date,CURDATE()) > 0 then datediff(expiry_date,CURDATE()) ELSE 'Expired' END) as Remaining_days_expired from tablets; SQL fiddle
{ "pile_set_name": "StackExchange" }
Q: C++Builder 10 TGrid Помогите пожалуйста с функцией Grid1SetValue: void __fastcall TForm4::Grid1SetValue(TObject *Sender, const int Col, const int Row, const TValue &Value) { if (Grid1->Columns[Col] == Surname) { colData[Row] = ; } } colData это массив UnicodeString, не могу записать значение Value в строку. Value->ToString() не работает, выдает ошибку member reference type 'const System::Rtti::TValue' is not a pointer , как нормально преобразовать TValue в UnicodeStrig. Value->AsType тоже не работает. Буду благодарен. A: все оказалось очень просто, именно в версии 10 функции OnSetValue значение Value стало константным, и поэтому теперь функция тоже немного изменилась. const_cast<TValue*>(&Value)->ToString(); А добраться до ячейки можно Form1->Grid1->Columns[Col]->Controls->Items[Row] значение будет опять таки TValue
{ "pile_set_name": "StackExchange" }
Q: Manipulating array outside of function using pointer? KEEP IN MIND I WROTE THIS CODE IN HERE TO SIMPLIFY MY QUESTION, PLEASE IGNORE MINOR MISTAKES IF THERE ARE ANY, MY PROBLEM FOCUSES ON MANIPULATING AN ARRAY OUTSIDE OF A FUNCTION BY USING IT'S POINTER. I create a static array like this char *array[size1][size2]; For the purposes of my example size1 = 3 and size2 = 6. Then I use a function to pass the pointer of the array, and allocate strings to it. int counter = 0; void somefunction(char *a, char *b, int size1){ while(counter<size1){ //do some stuff to a strcpy(b+counter, a); counter++; printf("Adding %s to pos %i RESULT: %s\n",a,counter,b+counter); } } This works nicely and the output is correct (when outputting array b in the function), but it does not actually effect the array[] outside of the function. If I use somefunction(a,array,size1); The output will be correct, but the actual array outside of the function (array[]) will output gibberish random memory. I output it like this: for(int i=0;i<size1;i++){ printf("%s\n",array[i]); } So what am i doing wrong here? I thought the array when passed to a function decays into a pointer to the first element (and therefore that array), but that doesn't seem to be the case. What am I doing wrong? How do I manipulate the array outside of the function by passing it's pointer? Thanks! A: From the comments: What Im trying to do is I calculate the length of the string (size2). So all of the strings contained will be of length 3 in this case, "ABC" for example. Size 1 is simply the amount of strings of size 3 that I need to store and iterate through. So size1=6 size2=3 means I want to have 6 strings accesable by ordered array, all of which are 3 chars in length. Once I compute size1 and size2 (I do this before creating the array) they do indeed stay constant. In that case, you want to declare array as a 2D array of char: char array[size1][size2]; // no * Note that to store a string of length N, you need an N+1-element array to account for the 0 terminator. So if you're storing strings like "ABC" ({'A','B','C',0}), then size2 needs to be 4, not 3. When you pass it to somefunction, the type of the expression array "decays" to "pointer to size2-element array of char" (char (*)[size2])1. Based on your description, it sounds like you declare array as a variable-length array (i.e., size1 and size2 are not known until runtime). If that's the case, then your function definition needs to look like /** * size2 must be declared in the argument list before char (*b)[size2] * b may also be declared as char b[][size2]; it means the same thing */ void somefunction( char *a, size_t size2, char (*b)[size2], size_t size ) { ... strcpy( b[counter], a ); ... } and should be called as somefunction( a, size2, array, size1 ); Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array. In your case, N is size1 and T is "size2-element array of char".
{ "pile_set_name": "StackExchange" }
Q: Proof of Quadratic Approximation to $f(\mathbf{\vec{x}})$ Let $\mathbf{\vec{x}} = \left[\begin{array}{c} x_1 \\ x_2 \\ x_3 \\ . \\ . \\ . \\ x_n \end{array}\right]$ and $f(\mathbf{\vec{x}}): \mathbb{R}^n \to \mathbb{R}$, $n \in \mathbb{N}$ be a scalar-valued function, then its Quadratic approximation $Q(\mathbf{\vec{x}})$ about a point $\mathbf{\vec{x}}_0$ is given by: $$Q(\mathbf{\vec{x}}) = f(\mathbf{\vec{x}}_0) + \mathbf{\nabla}f(\mathbf{\vec{x}}_0)^T (\mathbf{\vec{x} - \vec{x}}_0) + \dfrac{1}{2} (\mathbf{\vec{x} - \vec{x}}_0)^T \mathbf{H}_f (\mathbf{\vec{x}}_0) (\mathbf{\vec{x} - \vec{x}}_0)$$ where $\mathbf{\nabla}f$ is the gradient and $\mathbf{H}_f$ the Hessian matrix of $f$. We know that the function $Q(\mathbf{\vec{x}})$ is suppose to have the same output, first and second partial derivatives as $f(\mathbf{\vec{x}})$ at the point $\mathbf{\vec{x}}_0$. Clearly, $Q(\mathbf{\vec{x}}_0) = f(\mathbf{\vec{x}}_0)$. Now, how do I prove the following?: $$\mathbf{\nabla}Q(\mathbf{\vec{x}}_0) = \mathbf{\nabla}f(\mathbf{\vec{x}}_0)$$ $$\mathbf{H}_Q(\mathbf{\vec{x}}_0) = \mathbf{H}_f(\mathbf{\vec{x}}_0)$$ A: You can verify that the gradients and Hessian agree by direct calculation. Observe that both $\nabla f[\vec{\mathbf x}_0]$ and ${\mathbf H}_f[\vec{\mathbf x}_0]$ are constants, so the second term of $Q$ is a linear function of $\vec{\mathbf x}-\vec{\mathbf x}_0$ and the third term a quadratic form in $\vec{\mathbf x}-\vec{\mathbf x}_0$. (I use square brackets to indicate evaluation at a point in an attempt at disambiguation in the following.) Analogous to the single-variable differentiation rule $(cx)'=c$ we have $$\nabla(\vec{\mathbf v}^T\vec{\mathbf x}) = \nabla\left(\sum_i v_ix_i\right) = \vec{\mathbf v},$$ therefore $$\nabla(\nabla f[\vec{\mathbf x}_0]^T(\vec{\mathbf x}-\vec{\mathbf x}_0)) = \nabla(\nabla f[\vec{\mathbf x}_0]^T\vec{\mathbf x})-\nabla(\nabla f[\vec{\mathbf x}_0]^T\vec{\mathbf x}_0) = \nabla f[\vec{\mathbf x}_0].$$ More generally, the differential of a linear function $A\mathbf x$ of $\mathbf x$ is $A$—the best linear approximation to a linear map is the map itself. For the quadratic term, we can use the product rule $\nabla(u^Tv)=u^T\nabla v+(\nabla u)^Tv$: $$\begin{align} \nabla\left(\frac12(\vec{\mathbf x}-\vec{\mathbf x}_0)^T{\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0)\right) &= \frac12 (\vec{\mathbf x}-\vec{\mathbf x}_0)^T \nabla({\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0)) + \frac12(\nabla(\vec{\mathbf x}-\vec{\mathbf x}_0))^T{\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0) \\ &= \frac12 (\vec{\mathbf x}-\vec{\mathbf x}_0)^T {\mathbf H}_f[\vec{\mathbf x}_0] + \frac12 {\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0) \\ &= {\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0) \end{align}$$ since ${\mathbf H}_f$ is symmetric. This vanishes at $\vec{\mathbf x}_0$, therefore $\nabla Q[\vec{\mathbf x}_0] = \nabla f[\vec{\mathbf x}_0]$. (We could’ve gotten to this without actually differentiating by noting that the result must be a linear combination of $x_i-x_{0i}$ terms, all of which vanish.) For ${\mathbf H}_Q[\vec{\mathbf x}_0]$ we can proceed in a similar fashion by differentiating $\nabla Q = \nabla f[\vec{\mathbf x}_0]+{\mathbf H}_f[\vec{\mathbf x}_0](\vec{\mathbf x}-\vec{\mathbf x}_0)$ directly, producing ${\mathbf H}_f[\vec{\mathbf x}_0]$ per the earlier observation regarding the differential of a linear function, or note that the Hessian of a constant or linear function vanishes, while the Hessian of a quadratic form is 2 times the (constant) matrix of the form (analogously to the single-variable $(ax^2)''=2a$), so that the only term that survives when computing the Hessian directly from $Q$ is ${\mathbf H}_f[\vec{\mathbf x}_0]$.
{ "pile_set_name": "StackExchange" }
Q: generate chirp signals in android i have been trying to generate a linear Chirp signal using smartphone speakers. i wrote a code following this equation that i found here. the equation looks logical to me but when i tried to test on high frequencies like 24KHz or 26KHz the sound is still audible and gets out of the speakers though my smartphone doesnt support frequencies over 22KHz. Please if you notice anything wrong with my code, you will be giving me a great help. public class MainActivity extends Activity { int duration=1; int sampleRate=44100; int numSample=duration*sampleRate; double sample[]=new double[numSample]; double freq1=23000; double freq2=24000; byte[] generatedSnd= new byte[2*numSample]; Handler handler=new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Thread thread=new Thread(new Runnable(){ public void run(){ try { genTone(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.post(new Runnable(){ public void run(){ playSound(); } }); } }); thread.start(); } protected void onResume() { super.onResume(); } void genTone() throws IOException{ double instfreq=0, numerator; for (int i=0;i<numSample; i++ ) { numerator=(double)(i)/(double)numSample; instfreq =freq1+(numerator*(freq2-freq1)); if ((i % 1000) == 0) { Log.e("Current Freq:", String.format("Freq is: %f at loop %d of %d", instfreq, i, numSample)); } sample[i]=Math.sin(2*Math.PI*i/(sampleRate/instfreq)); } int idx = 0; for (final double dVal : sample) { // scale to maximum amplitude final short val = (short) ((dVal * 32767)); // max positive sample for signed 16 bit integers is 32767 // in 16 bit wave PCM, first byte is the low order byte (pcm: pulse control modulation) generatedSnd[idx++] = (byte) (val & 0x00ff); generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8); } void playSound(){ AudioTrack audioTrack= null; try{ audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, generatedSnd.length, AudioTrack.MODE_STATIC); audioTrack.write(generatedSnd, 0, generatedSnd.length); audioTrack.play(); A: What you are experiencing is a phenomenon known as aliasing. For more information, read about the Nyquist Theorem. Essentially what this means is that you can reproduce any frequency up to 1/2 of the sample rate. But once you cross that threshold, the frequency begins folding back such that a sine at sample rate plus 1kHz is indistinguishable from a sine at sample rate minus 1kHz, and so on. It's very similar to something you might have seen on film where a car wheel appears to stop or even move backward (the wagon wheel effect). The best solution to your problem is to prevent the user from entering a frequency greater than half the sample rate.
{ "pile_set_name": "StackExchange" }
Q: How can I calculate a limit with a free variable? For example, when I evaluate Limit[(1 + x^n + (x^2/2)^n)^(1/n), n -> Infinity] Mathematica does not output any result. When I evaluate Plot[Limit[(1 + x^n + (x^2/2)^n)^(1/n), n -> Infinity], {x, -10, 10}] a piecewise graph is output. But I want to get the function, not only the graph. How can I do it? A: The short answer is you cannot (quite) do this. Limit has trouble with exp-log-polynomial growth at infinity in the situation where parameters are present. You can give Limit assumptions about the parameter and that sometimes helps. Limit[(1 + x^n + (x^2/2)^n)^(1/n), n -> Infinity, Assumptions -> -1 < x < 1] (* Out[1]= 1 *) You can substitute a known but symbolic value, such as pi, for x. This is useful in cases where you believe (i) the limit will not involve that particular value and (ii) you believe the limit is some function of the parameter. For example, to get the quadratic growth part of that parametrized limit, you could do this. Limit[(1 + x^n + (x^2/2)^n)^(1/n) /. x -> -Pi, n -> Infinity] (* Out[6]= \[Pi]^2/2 *) This does not prove anything but it gives a result that might all the same be useful: where the behavior is quadratic in x, it is x^2/2. A graph suggests it is linear in x for 1<x<1. The value is simple x in this range. Here I use a symbolic-numeric value to indicate this. Limit[(1 + x^n + (x^2/2)^n)^(1/n) /. x -> Pi/E, n -> Infinity] (* Out[16]= \[Pi]/E *) How to get Limit to do this better? I do not know.
{ "pile_set_name": "StackExchange" }
Q: Responsive web design and resizing images Repsonsive web design works great on most html elements excepts images.I find it a mess. When resizing viewports, you cannot use resizing percentages on an image since it will take on the parent element width and height right. You need to set fixed widths and heights for images...Or am I missing something? So how exactly do you do a responsive design involving images whose container element/parent will stretch above its native width and shrink below its native width? Thank you A: The done thing in responsive design is to set this in your css for images and some other elements: img, embed, object, video { max-width:100%; height:auto; } Then in your html the image simply takes up the size of it's container. You do not set the image size itself you just let it grow/shrink itself.
{ "pile_set_name": "StackExchange" }
Q: Problems with std::piecewise_constant_distribution and std::vector Given a bunch of strings I'm trying to create a program that can mimic a pseudo-random behaviour with weighted distribution based on my input. So far I came up with this #include <iostream> #include <random> #include <type_traits> #include <map> #include <vector> #include <string> #include <initializer_list> #define N 100 int main() { std::vector<std::string> interval{"Bread", "Castle", "Sun"}; std::vector<float> weights { 0.40f, 0.50f, 0.10f }; std::piecewise_constant_distribution<> dist(interval.begin(), interval.end(), weights.begin()); std::random_device rd; std::mt19937 gen(rd()) ; for(int i = 0; i<N;i++) { std::cout << dist(gen) << "\n"; } return(0); } But this thing doesn't works and I have no clue why, the usual usage of std::piecewise_constant_distribution , according to online examples, it's with std::arrays, but I'm trying to implement it using std::vector, this is the main difference that I found. With Clang++ the output of the error is /usr/bin/../lib/gcc/x86_64-linux-gnu/4.7/../../../../include/c++/4.7/bits/random.tcc:2409:10: error: no matching member function for call to 'push_back' _M_int.push_back(*__bbegin); ~~~~~~~^~~~~~~~~ but I can't understand it because there is no explicit .push_back in my code, I also don't get from what is coming from because debugging a templated class it's a nightmare and I'm just starting with this one. Anyone having any idea why code doesn't work ? A: The default result type of std::piecewise_constant_distribution is RealType (double here). It seems like you're trying to choose from 3 string options with various weights, but this isn't what std::piecewise_constant_distribution is for. It's designed to generate uniform random values from numeric intervals with the given weighting. If you modify your example and change interval to: std::vector<double> interval {1, 3, 5, 10, 15, 20}; Everything will compile happily. By the looks of it, you want std::discrete_distribution: ... std::vector<std::string> interval{"Bread", "Castle", "Sun"}; std::vector<float> weights { 0.40f, 0.50f, 0.10f }; std::discrete_distribution<> dist(weights.begin(), weights.end()); std::mt19937 gen(rd()); for(int i = 0; i<N;i++) { std::cout << interval[dist(gen)] << "\n"; } ...
{ "pile_set_name": "StackExchange" }
Q: Eagle: Alternative to Pinswap for GPIO expander I'm working on a PCB which is basically multiple MCP23017 GPIO expanders driven from I2C. As I layout the board (in EAGLE), I frequently find places where using different IO pins would avoid vias and other routing complications. But of course, the standard library part for this device doesn't allow pin-swapping, because that would be a functional change in the design. In my case, I'm also writing the software to drive the I2C, and in most cases, it's a simple re-ordering in code, to use a different pin - so it would be no problem for me. (Especially since the MCP23017 allows pin-level selection of in/out mode) Given this, is there a way to achieve pin-swap like functionality when laying out? Going back into to the schematic to adjust things manually is awkward but what I have been doing so far. I'm aware I could clone the part into a local library and edit the pins to enable pin-swap, are there any drawbacks or downsides to this? A: The bottom line here is that you always want your schematic to exactly represent your design. A pin swap function in the layout package still needs to be able to back annotate into the schematic so that the schematic accurately represents the layout design. That can work out nice in that this back annotate function can automate some of the schematic update work. I suggest that trying to enable pin swap in the I/O Expander may not be ideal. Pin swapping really is aimed at pins which are exactly functionally equivalent. Your I/O Expander pins are not really following this as there is an internal register interface difference between a GPB4 and a GPA6 pin. One usually tends to draw the symbol for a part like the I/O Expander so that the "port sets" of pins (i.e. all the GPA or GPB groups) are grouped together in bit order so that it is easy to visualize the connections from the schematic to the software. Some of this visualization seems like it will be lost when pin swaps would occur. The worst case of this is when a subgroup of the I/O pins are used together in a weighted binary group. For example GPB[2::0] used to connect to the A{2::0} selector pins of a 8 to 1 selector chip. For your general usage of multiple I/O Expanders it is highly likely that there can be layout optimizations to swapping GPIO connections between different components. A layout package's pin swapping function is not going to support this type of swap and you would be back to doing the back annotation into the schematic manually for this case. I suggest to just go ahead and swap your net list connections manually in the layout package and mark up accordingly on your paper working copy of the schematic. Once you have completed the layout you can go to manually back annotate into the schematic all at once. One good suggestion is that you have all of the nets be named in the design with names that you have edited rather than leaving some to be autonamed by the design tools. The reason for this is that with auto named nets you will likely have name collisions or missing name problems next time you revise your schematic and want to re-import the net list back into the schematic.
{ "pile_set_name": "StackExchange" }
Q: Creating a loop to check for cycles in a permutation My homework assignment has me check for all possible cycle notations from user inputted numbers. I have the input sent into an array but i'm not sure how to start the loop. How could I edit this loop to not display the same numbers more than once? Sorry if this isn't proper format, first time posting. // example of user input var permutation = [ 9,2,3,7,4,1,8,6,5 ] ; // add zero to match index with numbers permutation.unshift(0) ; // loop to check for all possible permutations for (var i = 1; i < permutation.length -1; i++) { var cycle = []; var currentIndex = i ; if ( permutation [ currentIndex ] == i ) cycle.push(permutation [currentIndex]); while ( permutation [ currentIndex ] !== i ) { cycle.push( permutation [currentIndex]); currentIndex = permutation [ currentIndex ] ; } // display in console console.log(cycle); } A: I answered a similar question here. The idea is to use recursive functions.Here's a sample: var array = ['a', 'b', 'c']; var counter = 0; //This is to count the number of arrangement possibilities permutation(); console.log('Possible arrangements: ' + counter); //Prints the number of possibilities function permutation(startWith){ startWith = startWith || ''; for (let i = 0; i < array.length; i++){ //If the current character is not used in 'startWith' if (startWith.search(array[i]) == -1){ //If this is one of the arrangement posibilities if ((startWith + array[i]).length == array.length){ counter++; console.log(startWith + array[i]); //Prints the string in console } //If the console gives you "Maximum call stack size exceeded" error //use 'asyncPermutation' instead //but it might not give you the desire output //asyncPermutation(startWith + array[i]); permutation(startWith + array[i]); //Runs the same function again } else { continue; //Skip every line of codes below and continue with the next iteration } } function asyncPermutation(input){ setTimeout(function(){permutation(input);},0); } }
{ "pile_set_name": "StackExchange" }
Q: PHP - Delete XML Element I need to delete elements of an XML file using PHP. It will be done via ajax and I need to find the XML element via an attribute. This is my XML file <?xml version="1.0" encoding="utf-8"?> <messages> <message time="1248083538"> <name>Ben</name> <email>Ben's Email</email> <msg>Bens message</msg> </message> <message time="1248083838"> <name>John Smith</name> <email>[email protected]</email> <msg>Can you do this for me?</msg> </message> </messages> So what I would say is something like delete the element where the time equals 1248083838. Ive been using Simple XML up until now and I've just realised it can do everything except delete elements. So how would I do this? A: Dave Morgan is correct in that DOM classes are more powerful, but in case you want to stick with SimpleXML, try using the unset() function on any node, and that node will be removed from the XML. unset($simpleXMLDoc->node1->child1) A: You can use the DOM classes in PHP. ( http://us3.php.net/manual/en/intro.dom.php ). You will need to read the XML document into memory, use the DOM classes to do manipulation, and then you can save out the XML as needed (to http or to file). DOMNode is an object in there that has remove features (to address your question). It's a little more complicated than SimpleXML but once you get used to it, it's much more powerful (semi-taken from a code example at php.net) <?php $doc = new DOMDocument; $doc->load('theFile.xml'); $thedocument = $doc->documentElement; //this gives you a list of the messages $list = $thedocument->getElementsByTagName('message'); //figure out which ones you want -- assign it to a variable (ie: $nodeToRemove ) $nodeToRemove = null; foreach ($list as $domElement){ $attrValue = $domElement->getAttribute('time'); if ($attrValue == 'VALUEYOUCAREABOUT') { $nodeToRemove = $domElement; //will only remember last one- but this is just an example :) } } //Now remove it. if ($nodeToRemove != null) $thedocument->removeChild($nodeToRemove); echo $doc->saveXML(); ?> This should give you a little bit of an idea on how to remove the element. It will print out the XML without that node. If you wanted to send it to file, just write the string to file.
{ "pile_set_name": "StackExchange" }
Q: Why does Google Cloud logging show response of 200 while also tagging log entry as error? Below is a screenshot from Google Cloud console logging. It shows an error while calling /get_user from my server. However the response status is 200 which should mean SUCCESS. How is this possible? Also what is the actual error? None of the lines below give anything remotely resembling an error message. { httpRequest: { status: 200 } insertId: "59f27485000f32ab85505e70" labels: { clone_id: "00c61b117c384e485a095752c23b4277d1844399c104ae542bd367f2b52df046b21a56584c7d" } logName: "projects/villagethegame111/logs/appengine.googleapis.com%2Frequest_log" operation: { first: true id: "59f2748500ff00ff5dbae8f3b5ad0001737e76696c6c61676574686567616d65313131000170726f643230313730393233000100" last: true producer: "appengine.googleapis.com/request_id" } protoPayload: { @type: "type.googleapis.com/google.appengine.logging.v1.RequestLog" appEngineRelease: "1.9.54" appId: "s~villagethegame111" cost: 8.0801e-8 endTime: "2017-10-26T23:49:25.076502Z" finished: true first: true host: "villagethegame111.appspot.com" httpVersion: "HTTP/1.1" instanceId: "00c61b117c384e485a095752c23b4277d1844399c104ae542bd367f2b52df046b21a56584c7d" instanceIndex: -1 ip: "38.102.224.170" latency: "0.052508s" line: [ 0: { logMessage: "200 OK" severity: "ERROR" time: "2017-10-26T23:49:25.068980Z" } ] megaCycles: "29" method: "GET" requestId: "59f2748500ff00ff5dbae8f3b5ad0001737e76696c6c61676574686567616d65313131000170726f643230313730393233000100" resource: "/api/get_user" responseSize: "272" startTime: "2017-10-26T23:49:25.023994Z" status: 200 urlMapEntry: "village.api.root" userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36" versionId: "prod20170923" } receiveTimestamp: "2017-10-26T23:49:26.000113484Z" resource: { labels: { module_id: "default" project_id: "villagethegame111" version_id: "prod20170923" zone: "us14" } type: "gae_app" } severity: "ERROR" timestamp: "2017-10-26T23:49:25.023994Z" } A: This can be perfectly normal if the respective request log also has an app log at the ERROR level attached to it, created by your application code during handling of the request. And as long as the app is able to formulate a response to the request, of course. The request log will be tagged with the "worst" logging level across all app logs attached to it. Just scroll down a bit more on the page pictured in your snapshot to see if there are app logs attached to that request log. You can see an illustration of this (with logging level INFO, not ERROR) in Reading Application Logs on Google App Engine from Developer Console. See also: Request logs vs application logs
{ "pile_set_name": "StackExchange" }
Q: linq select with group by I made a simple messaging system and my SQL table is like id | from_id | to_id | text --------------------------- 1 | 10 | 11 | abc 2 | 11 | 10 | cde 3 | 10 | 11 | fgh for example I'm "user 10" and when I send message to "user 11" I have to see my message box like ---> 11 fgh and when user 11 sends me a reply ex. "hij" I have to see result like 11 hij its like twitter dm system. If I'm the last one who sends the message, I have to see who I send the message to and my message content. return (from data in db.user_messages.AsEnumerable() where data.id == ((from messages in db.user_messages where messages.from_id == data.from_id orderby messages.message_created_at descending select new { messages.id }).Take(1).FirstOrDefault().id) && data.to_id == user.UserId orderby data.message_created_at descending select data).ToList(); With this code I can only see when user sends me a message, I can't get any result if I'm the one who sends the last message. How can I improve this select? Thank you. A: If you want to select last message from each conversation of user: from um in db.user_messages where um.from_id == user.UserId || um.to_id == user.UserId let otherId = (um.from_id == user.UserId) ? um.to_id : um.from_id group um by otherId into g select g.OrderByDescending(um => um.message_created_at).FirstOrDefault() NOTE: This query will be translated into SQL and executed on database side. Displaying conversation can look like: foreach(var message in query.OrderBy(um => um.message_created_at)) Console.WriteLine("{0}{1}{2}", message.from_id == user.UserId ? "--->" : "", message.from_id == user.UserId ? message.to_id : message.from_id, message.text); BTW you can select otherId from query to avoid additional id checks.
{ "pile_set_name": "StackExchange" }
Q: Renumber reference variables in text columns Background For a data entry project, a user can enter variables using a short-hand notation: "Pour i1 into a flask." "Warm the flask to 25 degrees C." "Add 1 drop of i2 to the flask." "Immediately seek cover." In this case i1 and i2 are reference variables, where the number refers to an ingredient. The text strings are in the INSTRUCTION table, the ingredients the INGREDIENT table. Each ingredient has a sequence number for sorting purposes. Problem Users may rearrange the ingredient order, which adversely changes the instructions. For example, the ingredient order might look as follows, initially: seq | label 1 | water 2 | sodium The user adds another ingredient: seq | label 1 | water 2 | sodium 3 | francium The user reorders the list: seq | label 1 | water 2 | francium 3 | sodium At this point, the following line is now incorrect: "Add 1 drop of i2 to the flask." The i2 must be renumbered (because ingredient #2 was moved to position #3) to point to the original reference variable: "Add 1 drop of i3 to the flask." Updated Details This is a simplified version of the problem. The full problem can have lines such as: "Add 1 drop of i2 to the o3 of i1." Where o3 is an object (flask), and i1 and i2 are water and sodium, respectively. Table Structure The ingredient table is structured as follows: id | seq | label The instruction table is structured as follows: step Algorithm The algorithm I have in mind: Repeat for all steps that match the expression '\mi([0-9]+)': Break the step into word tokens. For each token: If the numeric portion of the token matches the old sequence number, replace it with the new sequence number. Recombine the tokens and update the instruction. Update the ingredient number. Update The algorithm may be incorrect as written. There could be two reference variables that must change. Consider before: seq | label 1 | water 2 | sodium 3 | caesium 4 | francium And after (swapping sodium and caesium): seq | label 1 | water 2 | caesium 3 | sodium 4 | francium Every i2 in every step must become i3; similarly i3 must become i2. So "Add 1 drop of i2 to the flask, but absolutely do not add i3." Becomes: "Add 1 drop of i3 to the flask, but absolutely do not add i2." Code The code to perform the first two parts of the algorithm resembles: CREATE OR REPLACE FUNCTION renumber_steps( p_ingredient_id integer, p_old_sequence integer, p_new_sequence integer ) RETURNS void AS $BODY$ DECLARE v_tokens text[]; BEGIN FOR v_tokens IN SELECT t.tokens FROM ( SELECT regexp_split_to_array( step, '\W' ) tokens, regexp_matches( step, '\mi([0-9]+)' ) matches FROM instruction ) t LOOP RAISE NOTICE '%', v_tokens; END LOOP; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; Question What is a more efficient way to solve this problem (i.e., how would you eliminate the looping constructs), possibly leveraging PostgreSQL-specific features, without a major revision to the data model? Thank you! System Details PostgreSQL 9.1.2. A: You have to take care that you don't change ingredients and seq numbers back and forth. I introduce a temporary prefix for ingredients and negative numbers for seq for that purpose and exchange them for permanent values when all is done. Could work like this: CREATE OR REPLACE FUNCTION renumber_steps(_old int[], _new int[]) RETURNS void AS $BODY$ DECLARE _prefix CONSTANT text := ' i'; -- prefix, incl. leading space _new_prefix CONSTANT text := ' ###'; -- temp prefix, incl. leading space i int; o text; n text; BEGIN IF array_upper(_old,1) <> array_upper(_new,1) THEN RAISE EXCEPTION 'Array length mismatch!'; END IF; FOR i IN 1 .. array_upper(_old,1) LOOP IF _old[i] <> _new[i] THEN o := _prefix || _old[i] || ' '; -- leading and trailing blank! -- new instruction are temporarily prefixed with new_marker n := _new_prefix || _new[i] || ' '; UPDATE instruction SET step = replace(step, o, n) -- replace all instances WHERE step ~~ ('%' || o || '%'); UPDATE ingredient SET seq = _new[i] * -1 -- temporarily negative WHERE seq = _old[i]; END IF; END LOOP; -- finally replace temp. prefix UPDATE instruction SET step = replace(step, _new_prefix, _prefix) WHERE step ~~ ('%' || _new_prefix || '%'); -- .. and temp. negative seq numbers UPDATE ingredient SET seq = seq * -1 WHERE seq < 0; END; $BODY$ LANGUAGE plpgsql VOLATILE STRICT; Call: SELECT renumber_steps('{2,3,4}'::int[], '{4,3,2}'::int[]); The algorithm requires ... ... that ingredients in the steps are delimited by spaces. ... that there are no permanent negative seq numbers. _old and _new are ARRAYs of the old and new instruction.seq of ingredients that change position. The length of both arrays has to match, or an exception will be raised. It can contain seq that don't change. Nothing will happen to those. Requires PostgreSQL 9.1 or later.
{ "pile_set_name": "StackExchange" }
Q: Secure database password using a SQL connection I want to program a Java Applet that connects to my personal MySQL database. Now my question is: Can somebody e.g. open the class-file(s) from the JAR and look for the password/string? (Of course I would exclude the source files when I generate the JAR.) So is it insecure to put the password (as a plain string) in the code? If it is insecure, what would you suggest. Obfuscator? No direct connection (e.g. using PHP-scripts)? Other options? A: It's in general a bad idea as anyone could as well just sniff the packets sent. You should write a small web service (simple php/asp page) that handles authentication through http get/post and only submits requests you permit (e.g. avoid someone sniffing the username/password and then drop the database or modify it). Also let the user create his/her own account to submit. If you're talking about some proposed high score functionality, just submit the name, highscore and some kind of checksum (and maybe some token) but there's no 100% secure way to do it.
{ "pile_set_name": "StackExchange" }
Q: which number stands out the most in the given series? 5, 11, 17, 23, 29, 41 Please note that I don't have an answer to this problem. I thought of 2 possible answers, a) 5 - it is the only single digit number in the sequence. b) 41 - all other adjacent numbers have a difference of 6 A: 5, 11, 17, 23, 29, 41 5 is the answer because it's the only single digit number. 11 is the answer because it contains repeating digits, which stands out amongst those numbers. 17 is the answer because the difference between its digits is the same difference between it and the other numbers around it. 23 is the answer because its digits are neighbors on the number line. 29 is the answer because it has the greatest difference between its digits. 41 is the answer because it is 12 units away from its previous neighbor in the list, rather than 6 like the others (or 5 like the first). As you can see, each and every answer is the only true answer. A: 29 is the odd number out because they're listing every other prime number starting from 5 (prime numbers from 5 to 41 are 5,7,11,13,17,19,23,29,31,37,41) so the sequence should have been 5,11,17,23,31,41 . 29 breaks that sequence.
{ "pile_set_name": "StackExchange" }
Q: Scatter/gather socket write in Python In POSIX C we can use writev to write multiple arrays at once to a file descriptor. This is useful when you have to concatenate multiple buffers in order to form a single message to send through a socket (think of a HTTP header and body, for instance). This way I don't need to call send twice, once for the header and once for the body (what prevent the messages to be split in different frames on the wire), nor I need to concatenate the buffers before sending. My question is, is there a Python equivalent? A: There is in the upcoming Python 3.3, now in alpha testing. See socket.sendmsg.
{ "pile_set_name": "StackExchange" }
Q: How to localize iOS 8 Today Widget? I am trying to localize my iOS 8 Today center widget. I have a storyboard specifically for the widget and hit the localize button and selected Spanish. The same way I localized the normal part of the app. As you can see here: The files have the following settings with Target Membership set to my extension: No matter what I try (using .strings or individual .storyboards for each language or even setting the NSLocalizedStrings through code), I cannot get the language to show up correctly localized in the notification center widget. Everything works as expected in the regular app. Anyone have any experience or thoughts? Thanks! A: For those experiencing the same problem, I had to delete the storyboard and rebuild a new one. Localizing this seemed to work.
{ "pile_set_name": "StackExchange" }
Q: How do I remove the water/temperature control faucet if there are no visible screws? My Delta branded shower faucet doesn't have any screws besides for two that hold the panel independently to the wall. The handles have no apparent way to be removed. Can anyone suggest a method that may be used to remove the handle? I repeat, there is definitely no hole, screw or anything of that sort anywhere on the controls. A: Pull the outer temp control knob off, or pry it gently with a pair of non-marring tools from each side.
{ "pile_set_name": "StackExchange" }
Q: Django multi-database routing I have been using manual db selection to cope with a project which has two seperate dbs. I have defined my databases in the settings. After some further reading it seems that database routing is actually the way to go with this. However, after reading the docs and some relevant posts here I am more confused than ever. In my settings I have: DATABASES = { 'default': { .... }, 'my_db2': { .... } } DATABASE_ROUTERS = ['myapp2.models.MyDB2Router',] I know I have to define my router class (I think in myapp2.models.py file) like so: class MyDB2Router(object): """A router to control all database operations on models in the myapp2 application""" def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp2': return 'my_db2' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp2': return 'my_db2' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'myapp2' or obj2._meta.app_label == 'myapp2': return True return None def allow_syncdb(self, db, model): if db == 'my_db2': return model._meta.app_label == 'myapp2' elif model._meta.app_label == 'myapp2': return False return None Then what? Does each model require a meta.app_label or is that automatic? Aside from that, I still get an error: django.core.exceptions.ImproperlyConfigured: Error importing database router JournalRouter: "cannot import name connection Can anyone help me understand what is happening and what is going wrong? Any help much appreciated. A: OK, so I just solved my own problem. The router class goes into a separate file called routers.py under /myapp2. No meta.app_label is required as I guess it is automatically assigned. Hope this helps someone. I have also documented the process here. A: Did not help me, so I did some debugging. Maybe the results can save someone some pain. :) The problem in django 1.4 is a circular reference that occurs when django tries to import the custom router class. This happens in django.db.utils.ConnectionRouter. In my case the app's __init__.py imported a module (tastypie.api to be precise) that in turn (and through a long chain) imported django.db.models. That is not bad in itself, but models tries to import connection from django.db and that happens to have a dependency on ConnectionRouter. Which is exactly where our journey started. Hence the error. This is described as a bug in django < 1.6 here: https://code.djangoproject.com/ticket/20704 and there is a nice small changeset thats supposed to fixed it in django 1.6:https://github.com/django/django/commit/6a6bb168be90594a18ab6d62c994889b7e745055 My solution however was to simply move routers.py from the app directory to the project directory. No nasty dependencies there. A: One more mistake to ommit, is to import the models in the router, this will lead to the same error, even if the router is defined in a different file.
{ "pile_set_name": "StackExchange" }
Q: Fallback for CSS3 transitions I have a CSS3 transition that resizes/positions an image inside a div on hover. FIDDLE This works as desired but my concern is about browsers that don't support CSS3 transitions like IE9-. Would it be possible to write this CSS code so that these browsers have a fallback? Idealy, the fallback should display the image so it fits the div and isn't zommed (fiddle example) and with no animation on hover. I would prefer a CSS only solution and to not to alter the markup. Full code example : HTML : <div><img src="http://lorempixel.com/output/people-q-c-1000-500-7.jpg" /> CSS : div{ overflow:hidden; width:500px; height:250px; position:relative; } img{ display:block; position:absolute; height:auto; width:200%; left:-30%; top:-60%; -webkit-transition-property: width, left, top; -webkit-transition-duration: .8s; -webkit-transition-timing-function: ease-out; transition-property: width, left, top; transition-duration: .8s; transition-timing-function: ease-out; } div:hover img{ width:100%; top:0; left:0; } A: You could use Modernizr or go through the javascript feature detection route. Both ways are detailed here: Detect support for transition with JavaScript A: Generally speaking, CSS transitions (and most of CSS, really) were designed with progressive enhancement in mind. The intended fallback in browsers that don't understand transitions is quite simply to ignore the transition properties themselves. This allows the style changes to still take place, only immediately and not in a smooth transition (as implied by the name), and obviates the need for complex workarounds. What you're looking to do however is to not have any change in state occur at all; you want your image to be fixed in the unzoomed state. That will take a bit more work. If @supports had been implemented in the beginning, you could easily get away with img{ display:block; position:absolute; height:auto; width:100%; top:0; left:0; -webkit-transition-property: width, left, top; -webkit-transition-duration: .8s; -webkit-transition-timing-function: ease-out; transition-property: width, left, top; transition-duration: .8s; transition-timing-function: ease-out; } @supports (-webkit-transition-property: all) or (transition-property: all) { div:not(:hover) img{ width:200%; left:-30%; top:-60%; } } But of course, not everything works that way. It's a real shame that @supports was proposed so late and implementations still haven't caught on. But I digress. Looking at the support tables at caniuse.com, it looks like Gecko- and WebKit/Blink-based browsers are extremely well covered (except maybe Firefox 3.6 and older), which is a relief because I can't think of any pure CSS-based solution to cater to those engines (other than ugly hacks). For other browsers, I can see some other workarounds: It may be worth including the -o- prefix if you care about Presto Opera. Likewise with -moz- if you care about Firefox < 16. For IE, simply hiding the div:not(:hover) img rules in conditional comments is enough, since the first version of IE to support transitions and ignore conditional statements happens to be the same — version 10: <!--[if !IE]><!--> <style> div:not(:hover) img{ width:200%; left:-30%; top:-60%; } </style> <!--<![endif]--> Note the use of div:not(:hover) here, analogous to the hypothetical @supports example above. You will need to swap the declarations with your img rule accordingly.
{ "pile_set_name": "StackExchange" }
Q: How does vi restore terminal content after quitting it? How does a program like vi or man or any other program replace the terminal content with the program's own contents then after quitting those programs they bring back the old terminal content? A: By sending control sequences to the terminal (xterm, vt-220) or using ncurses (like mc). A ANSI Escape Sequence starts with ESC (\033 octal) [. ; separates Numbers. C Example that clears the Screen and moves the cursor to 1,1. #include <stdio.h> int main() { // clear the terminal printf("\033[2J\033[1;1H"); printf("hello"); } Example of switchting to alternate Buffer and back (xterm). #include <stdio.h> #include <unistd.h> int main() { printf("\033[?1049h\033[H"); printf("hello\n"); sleep(1); printf("bye"); sleep(1); printf("\033[?1049l"); } A: Vi flips to the alternate screen buffer, supported by terminals. This is achieved using escape sequences. See this link for full details. The termcap entry for these are 'ti' to enter, and 'te' to exit full-screen mode. As @Celada points out below, hardcoding xterm escape sequences is not a Good Idea™, because the sequences vary according to $TERM, for example: xterm-color ti: <Esc> 7 <Esc> [ ? 47 h te: <Esc> [ 2 J <Esc> [ ? 4 7 l <Esc> 8 xterm-256color ti: <Esc> [ ? 1 0 4 9 h te: <Esc> [ ? 1 0 4 9 l On the other hand, xterm support is very broad these days among non-xterm terminals. Supporting only xterm is unlikely to cause problems, except for users with exotic or obsolete $TERM settings. Source: I support products that do this.
{ "pile_set_name": "StackExchange" }
Q: can you pass a mysql column alias to a user defined function I have a select statement which displays a number of counts based on different criteria I want to pass the counts to a user defined function (UDF) to do some calculations e.g. SELECT player, COUNT(IF(action=1,1,NULL)) AS tot_bullseye, COUNT(IF(action=2,1,NULL)) AS tot_twentys UDF(tot_bullseye, tot_twentys) A: No, column aliases can never be accessed in the SELECT or WHERE clause for the same query. You have to either repeat the expression, or use a subquery: SELECT player, tot_bullseye, tot_twentys, UDF(tot_bullseye, tot_twentys) FROM (SELECT player, COUNT(IF(action=1,1,NULL)) AS tot_bullseye, COUNT(IF(action=2,1,NULL)) AS tot_twentys ...) AS subq
{ "pile_set_name": "StackExchange" }
Q: Pylint Error Message: "E1101: Module 'lxml.etree' has no 'strip_tags' member'" I am experimenting with lxml and python for the first time for a personal project, and I am attempting to strip tags from a bit of source code using etree.strip_tags(). For some reason, I keep getting the error message: "E1101: Module 'lxml.etree' has no 'strip_tags' member'". I'm not sure why this is happening. Here's the relevant portion of my code: from lxml import etree ... DOC = etree.strip_tags(DOC_URL, 'html') print DOC Any ideas? Thanks. A: The reason for this is that pylint by default only trusts C extensions from the standard library and will ignore those that aren't. As lxml isn't part of stdlib, you have to whitelist it manually. To do this, navigate to the directory of your project in a terminal, and generate an rcfile for pylint: $ pylint --generate-rcfile > .pylintrc Then, open that file and add lxml to the whitelist like so: extension-pkg-whitelist=lxml After that, all E1101 errors regarding lxml should vanish. More details in this answer.
{ "pile_set_name": "StackExchange" }
Q: centering (horizontally and vertically) in navbr div I know this has been addressed previously, but for the life of me I can't get it to work with my code (yes, I'm new to this so please be gentle, and do let me know if I am going against SO etiquette!). Basically, trying to setup a navbar with links centered vertically that become highlighted when hovered over. I got it setup by eyeballing it and adjusting the margins / padding, but surely there is a better way to to go about this. Also, how do I go about centering the links horizontally as well? Here's the relevant code. http://jsbin.com/wekuqidu/1/ Thanks all!!!! A: Here is an example using line-height, you can also try using table-cell to vertically align in the middle http://jsbin.com/nagoposu/2/
{ "pile_set_name": "StackExchange" }
Q: FALSE and TRUE vs NULL and TRUE I have column with type BOOLEAN At first (on INSERT), value would be always FALSE, only after may be updated column as TRUE So question is: make this column NOT NULL DEFAULT FALSE, or make this column DEFAULT NULL and then update as TRUE (and if then also would be reversing update, set column NULL and not FALSE value, so in this case, never would be used FALSE value ) Which choice will be better point of view performance and storage saving ? A: It makes no meaningful difference to storage. Depending on other nullable columns, we're talking at most a single byte if this column happens to overflow the nullable bitmap to the next byte, but in all likelihood it won't add any storage at all. For performance (as well as programmer productivity/maintenance), it depends a lot on how you plan to use this. There's nowhere near enough information here, nor would it be possible to get enough info without inviting anyone who actually reads this question to all of your project meetings. Personally, when I have a boolean column that is false by default (however you choose to represent it) and then will at some point become true and stay true, I like use a nullable DateTime column for this value, where any date at all means the value is true, and NULL means false. My experience is that you'll almost always eventually want to know the date and time on which the value became true. As an example of this, I work in Higher Ed. One thing that happens in this business is sending financial aid award letters to students. Students then sign and return the letters. Accepted awards may later be declined or superceeded, but that won't change the fact that the student had signed this letter and accepted this award. Regulations require us to keep these letters on file, but from a database standpoint it was good enough just to know the boolean question of whether awards in the letter are accepted. It quickly became apparent that we also need to know when the awards are accepted. Thus, a datetime column is used for that field. A: If you want to assume FALSE unless specifically set to TRUE, then use NOT NULL DEFAULT FALSE. It also depends on how you are using this column. If you only test where column = TRUE, then don't think it will matter. The point being that NULL is not equal to FALSE. A: The trouble with pretending that NULL is FALSE is that NULL is neither FALSE nor TRUE. If you have a column null_or_true in a table some_table, you might write a trio of SELECT statements: SELECT COUNT(*) FROM some_table; SELECT COUNT(*) FROM some_table WHERE null_or_true; SELECT COUNT(*) FROM some_table WHERE NOT null_or_true; The first gets the total number of rows, say 30. The second gets the number of rows where the value in null_or_true is TRUE; this might return 15. The third query returns the number of rows where null_or_true is FALSE, but if you only store NULL and not FALSE in those columns, it will return 0. To count the other 15 rows, you'd have to write a variant on: SELECT COUNT(*) FROM some_table WHERE null_or_true IS NULL; This counter-intuitive behaviour means you will get wrong answers from people who can be forgiven for being confused by the data stored in your table. Therefore, you should go with: NOT NULL DEFAULT FALSE The other path leads to madness, sooner or later.
{ "pile_set_name": "StackExchange" }
Q: \ escape character passed as json in PutAsJsonAsync I am trying to send a PUT request to update some data. In Fiddler in the Inspectors > Text View the data is shown as following : "{\"site\":[{\"technologyId\":1,\"isActive\":1},{\"technologyId\":2,\"isActive\":1},{\"technologyId\":3,\"isActive\":1},{\"technologyId\":4,\"isActive\":1}]}" If I open the jsonData in TextViewer while debugging it shows the following: {"site":[{"technologyId":1,"isActive":1},{"technologyId":2,"isActive":1},{"technologyId":3,"isActive":1},{"technologyId":4,"isActive":1}]} I thought this is what is passed to the server when I passed jsonData in PutAsJsonAsync. In fiddler the response comes back as 500 Internal Server Error and if I click on TextView it shows {"error":"Error: invalid json"}. To my understanding the \ is escape character for " in C# and should not be passed. I am not sure how to resolve this static void Main() { RunAsync().Wait(); } static async Task RunAsync() { using (var client = new HttpClient()) { Uri siteTechUpdateUrl = new Uri("http://xyz/api/1234"); // HTTP PUT // Update site# 16839 Technologies var collection = new List<SiteTechnology>(); collection.Add(new SiteTechnology() { technologyId = 1, isActive = 1 }); collection.Add(new SiteTechnology() { technologyId = 2, isActive = 1 }); collection.Add(new SiteTechnology() { technologyId = 3, isActive = 1 }); collection.Add(new SiteTechnology() { technologyId = 4, isActive = 1 }); dynamic siteTechs= new { site = collection }; string jsonData = JsonConvert.SerializeObject(siteTechs); // jsonData value "{\"site\":[{\"technologyId\":1,\"isActive\":1},{\"technologyId\":2,\"isActive\":1},{\"technologyId\":3,\"isActive\":1},{\"technologyId\":4,\"isActive\":1}]}" HttpResponseMessage response2 = await client.PutAsJsonAsync(siteTechUpdateUrl, jsonData); if (response2.IsSuccessStatusCode) { Console.ReadLine(); } } } class SiteTechnology { public int technologyId; public int isActive; } A: You're serializing it to a string, and then sending the string as JSON. Instead of: client.PutAsJsonAsync(siteTechUpdateUrl, jsonData); try: client.PutAsJsonAsync(siteTechUpdateUrl, siteTechs);
{ "pile_set_name": "StackExchange" }
Q: Minimize a program on start up I have a program which I'm struggling to get opened and minimized through a script (Platform: Windows 7 Pro). I have tried startup /minimize, I've tried sendkeys. I think the problem is that when the program is open and you press Alt+Spacabar+n, the Minimize option is greyed out. Some background: the application needs to stay open at all times for us to send data down from our servers. The users tend to close the application if it just opens on their screens (without minimizing). It can't be run as a service because the users also need to use application in the foreground at certain times. I can't have 2 instances of it running in Task Manager because it causes issues in the software. Any help or suggestions would be greatly appreciated. Thank you. A: That sounds like it is by developer design, as if they removed the minimize ability on purpose. If it is an in-house app a simple edit/recompile of the source could alleviate the issue. If it is third party, discuss with vendor, ideally they could add a notification icon in the clock area keeping the app open while minimized.
{ "pile_set_name": "StackExchange" }
Q: "No plugin found for prefix ''spring-root' in the current project error after I install two updates in STS I am using Spring Tool Suite. I check out demo projects in STS. It works fine without any problem before I installed updates in STS today. I have checked this post, but its solution (Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups) is not working for me. The steps to reproduce my bug: In STS, in "File" -> "New" -> "Import Spring Getting Started Content", then check out "Building a RESTful Web Service" this project. https://spring.io/guides/gs/rest-service/ I go to my project folder, type 'mvnw spring-root:run' (I am using Windows). Then got following error. I do not if this bug related to I installed two updated in STS today, because today STS told me that I have two updates to install, then I just installed. Update: Sorry, I have a typo. I type 'mvnw spring-boot:run', now it gives this error: [ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.5.6.RELEASE:run (default-cli) on project gs-rest-service: An exception occurred while running. null: InvocationTargetException: Connector configured to listen on port 8080 failed to start -> [Help 1] A: You have a typo in your maven command. Use spring-boot with a b not spring-root.
{ "pile_set_name": "StackExchange" }
Q: Keras misinterprets training data shape My training data has the form (?,15) where ? is a variable length. When creating my model I specify this: inp = Input(shape=(None,15)) conv = Conv1D(32,3,padding='same',activation='relu')(inp) ... My training data has the shape (35730,?,15). Checking this in python I get: X.shape Outputs: (35730,) X[0].shape Outputs: (513, 15) When I try to fit my model on my training data I get the ValueError: Error when checking input: expected input_1 to have 3 dimensions, but got array with shape (35730, 1) I can only train my model by using model.train_on_batch() on a single sample. How can I solve this? It seems like keras thinks the shape of my input data is (35730, 1) when it actually is (35730, ?, 15) Is this a bug in keras or did I do something wrong? I am using the tensorflow backend if that matters. This is keras 2 A: (Edited, according to OP's comment on this question, where they posted this link: https://github.com/fchollet/keras/issues/1920) Your X is not a single numpy array, it's an array of arrays. (Otherwise its shape would be X.shape=(35730,513,15). It must be a single numpy array for the fit method. Since you have a variable length, you cannot have a single numpy array containing all your data, you will have to divide it in smaller arrays, each array containing data with the same length. For that, you should maybe create a dictionary by shape, and loop the dictionary manually (there may be other better ways to do this...): #code in python 3.5 xByShapes = {} yByShapes = {} for itemX,itemY in zip(X,Y): if itemX.shape in xByShapes: xByShapes[itemX.shape].append(itemX) yByShapes[itemX.shape].append(itemY) else: xByShapes[itemX.shape] = [itemX] #initially a list, because we're going to append items yByShapes[itemX.shape] = [itemY] At the end, you loop this dictionary for training: for shape in xByShapes: model.fit( np.asarray(xByShapes[shape]), np.asarray(yByShapes[shape]),... ) Masking Alternatively, you can pad your data so all samples have the same length, using zeros or some dummy value. Then before anything in your model you can add a Masking layer that will ignore these padded segments. (Warning: some types of layer don't support masking)
{ "pile_set_name": "StackExchange" }
Q: Jumping to lines in Java I have just now started learning Java and one of the differences I noticed from C++ and VB is that Java has no goto statements, which I tend to use a lot while programming. Is there any way I could jump between lines using another statement? I tried to use break and continue but to no avail (I might be doing something wrong). Here is the code with goto statements and how I want it to operate: public class HelloWorld { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { jump1: System.out.print("What do you want to calculate? "); String method = sc.nextLine(); if (method.equals("tax")) tax(); else { System.out.print("Please input a valid method. \n\n"); goto jump1; } } What is a good replacement for the goto commands? A: A while loop in this instance. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html For this (very specific) instance you could put System.out.print("What do you want to calculate? "); String method = sc.nextLine(); while (!method.equals("tax")) { System.out.print("Please input a valid method. \n\n"); method = sc.nextLine(); } tax(); Obviously this only works if your only expected correct input is "tax", but it's a structure to build on. A: You should avoid "goto" statements in all languages, according to the rules of "structured programming", instead using if-then-else or do or while or for loops to control program flow. Java DOES have a sort of "goto" statement that you COULD use to only slightly modify your code, but consider the while loop below and the break statement, which jumps out of the loop. public static void main(String[] args) { String method = ""; while(! method.equals("tax")){ System.out.print("What do you want to calculate? "); method = sc.nextLine(); if(method.equals("tax")) break; System.out.print("Please input a valid method. \n\n"); } tax(); } The break statement enables your "Please ... valid" statement to display. You could also use this: public static void main(String[] args) { String method = ""; while(! method.equals("tax")){ System.out.print("What do you want to calculate? "); method = sc.nextLine(); } tax(); } I also kind of like this: public static void main(String[] args) { String method = ""; while(1==1){ System.out.print("What do you want to calculate? "); method = sc.nextLine(); if(method.equals("tax") break; System.out.print("Please input a valid method. \n\n"); } tax(); } You might go to the Java tutorials; they're good.
{ "pile_set_name": "StackExchange" }
Q: Are tags considered requirements? I'm new to stack overflow, made a few responses. I responded to a question that was something like: "I need to do X, I found a sed one liner that almost does it, but not quite" And was tagged 'sed'. I assumed the user just wanted a solution and tagged it with sed because it was a possible answer. So I suggested an alternate way using another tool that was more concise and didn't involve regex (another one-liner). I received a down vote for not meeting the requirement of the user. Since I'd like to make sure I conform to good forum etiquette, my question is: Are tags considered hard requirements that should limit the scope of responses? (within reason of course, a .NET question with a .NET tag obviously shouldn't receive a ruby answer). A: Unless the OP specifically requires it in the question, I would say that solving the problem is paramount. If you have a different way of solving the problem that doesn't involve the subject tag, then I think you're ok. That's not to say that someone won't downvote you -- I'm sure it happens all the time. I wouldn't downvote it though unless it were actually wrong or unhelpful. For example, suggesting that they change platforms so that they can use a tool that solves the problem better is probably not all that helpful. Suggesting that they use awk instead of sed, certain could be. To protect yourself from overzealous down voters, you might want to include either a disclaimer: I realize this doesn't address your question exactly, but have you considered... or a solution based on the tag and your alternative using a different tool.
{ "pile_set_name": "StackExchange" }
Q: Jquery doesn't identify the class as a selector I have two Jquery functions where one will insert a new dynamic row to a form on a button click and other function will validate the cell in that row. var currentItem = 11; $('#addnew').click(function(){ currentItem++; $('#items').val(currentItem); var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control" name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>'; $('#data').append(strToAdd); }); Here I take the class name productSelect as the identifier for the second function to make validation. But it didn't recognize the class and the validation is not working for the rows which I add to the form by the above function. $('.productSelect').change(function () { var elementID = $(this).attr("id"); var numberPart = elementID.split("t", 2); if ($(this).val() != null ) { $('#quantity'+ numberPart[1]).prop('required',true); } }); This is how the entire code looks like <script type='text/javascript'> $(document).ready(function() { $('.productSelect').change(function () { var elementID = $(this).attr("id"); var numberPart = elementID.split("t", 2); if ($(this).val() != null ) { $('#quantity'+ numberPart[1]).prop('required',true); } }); var currentItem = 11; $('#addnew').click(function(){ currentItem++; $('#items').val(currentItem); var strToAdd = '<tr><td><select class="form-control select2 productSelect" name="product'+currentItem+'" id="product'+currentItem+'" style="width: 100%"> <option disabled selected value> -- select a Product -- </option>'+ <?php foreach ($productData as $product) { echo "'<option value=" . $product->product_id . ">" . $product->product_name . "</option>'+";}?> '</select> </td><td><input class="form-control quantitySelect" name="quantity'+currentItem+'" id ="quantity'+currentItem+'"type="text" /></td><td><input class="form-control" name="freeIssue'+currentItem+'" id="freeIssue'+currentItem+'" type="text" /></td> <td align="center"><button class="btn btn-danger" name="close" id="close" onclick="SomeDeleteRowFunction(this)"><i class="fa fa-close"></i></button></td></tr>'; $('#data').append(strToAdd); }); }); </script> A: Use $(document).on.('change', '.productSelect', function (){}) Because method couldn't found the class on document ready
{ "pile_set_name": "StackExchange" }
Q: Selenium - select an input from an angularjs component <md-datepicker ng-model="mc.date.from" required="" md-val=""> <span class="input-group date" style="width:144px"> <input size="16" type="text" class="form-control" autocomplete="off"> <span class="input-group-btn"> <button class="btn btn-default" tabindex="-1" > <i class="glyphicon glyphicon-calendar"></i> </button> </span> </span> </md-datepicker> I have an AngularJs component that contains an input of type text. I have used the following code to enter a date. It fails most of the times when I run the test headless. WebElement fromDate = driver.findElement( By.tagName("md-datepicker")) .findElement(By.tagName("input")); if (fromDate.getAttribute("value").length() > 0) { fromDate.clear(); } fromDate.sendKeys(startDate); There are a few other inputs before the datepicker that I fill in. But when the test reaches datepciker, it fails because it can not find it. How can to fix this issue? Update I have used this method right before the above code. public static void waitUntilVisible(By locator) { final long startTime = System.currentTimeMillis(); final Duration duration = Duration.ofSeconds(2); Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .pollingEvery(duration) .ignoring(StaleElementReferenceException.class); while ((System.currentTimeMillis() - startTime) < 91000) { try { wait.until(ExpectedConditions.presenceOfElementLocated(locator)); break; } catch (StaleElementReferenceException e) { log.info("", e); } } } A: I could only solve this problem with a try a catch block where I catch StaleElementReferenceException. WebElement input; try { input = driver.findElement( By.tagName("md-datepicker")) .findElement(By.tagName("input")); } catch(StaleElementReferenceException e) { input = driver.findElement(By.xpath("//md-datepicker/span/input")); } if (input.getAttribute("value").length() > 0) { input.clear(); } As I have stated in the question, I use waitUntilVisible method to wait for the presence of the input. I asked this question on 29th October 2018. At the time, I was using selenium version 3.14.0. But this approach selects the input neither should you use selenium version 3.141.0.
{ "pile_set_name": "StackExchange" }
Q: Resolve ambigious name in ASP.NET It is annoying typing full name of a class like myNamespace.y.calendar cal = new myNamespace.y.calendar(); (because asp.net already has a class name called calendar in System.web.ui.webcontrolls). So to resolve this we can use like using Calendar = myNamespace.y.calendar; Calendar cal = new Calendar(); But how to do the same thing in asp.net aspx page? A: <%@ Import Namespace="Calendar=myNamespace.y.calendar" %>
{ "pile_set_name": "StackExchange" }
Q: Monitor defined DNS resolutions and change routes while writing back new IPs I have the problem that some FTP servers are not defined by IP anymore. Instead DNS names are provieded, so they may switch servers behind easily, while leaving customers with the problem of handling, because no routers and firewalls can get defined with DNS names (thank god it is this way). I had the idea to write a simple script to monitor defined DNS resolutions and change routes as needed by script. See the resulting scripts underneth in my answers. Thnx to MC ND. I am sure one could optimize my code at several further items :) To test you will need to make a file C:\log\dnstests.txt which contains for example two lines: www.stackoverflow.com=7.7.7.7 www.heise.de=198.252.206.16 This are two nice examples because, first domain does provide an alias after the IP adress which I could filter by find, but second does provide an ip6 additionally which should get filtered too. If someone would show me how to read and write line by line to and from file this could improve stability of script, as if the script breaks, the testfile will almost be empty. So if you change this excessive tested scriptcode be careful to test all possible cases D). Any help would be really appreciated, while I could imagine a lot people could need this script out there and I wondered that nothing was to find? A: Just in case anyone might someday feel the need to set routes by a sheduled script, (including: dails still alive email, IP6 filtering and smart behaviour on loadbalanced IP's to keep old one as long as it is listed). All you need is a file "dnstests.txt" in script directory with syntax: first.domain.tld=1.2.3.4 your.second.tld=5.6.7.8 Here is the code (thanx to MC ND for smart NSlookup filter): @ECHO OFF SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION REM ++++++++++++++++++++++++++++ BLAT EMAIL CONFIG ++++++++++++++++++++++++++++++++++++ set [email protected] set [email protected] set eMailFROM=dnstestscript set server=0.0.0.0 REM you have to install blat of course, here "echo blat ..." is used where it would be REM useful to send an email on interesting items, but it is also sent to shell and log REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM ++++++++++++++++++++++++++++ MAKE DATE ++++++++++++++++++++++++++++++++++++++++++++ for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j REM make timestamp (date reverse) set STAMP=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2%--%ldt:~8,2%-%ldt:~10,2%--%ldt:~12,2%-%ldt:~15,3% set ACTUALDATE=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM ++++++++++++++++++++++++++++ SCRIPT CONFIG ++++++++++++++++++++++++++++++++++++++++ set "XScriptnamE=%~n0" set "XSCRIPTDIR=%~dp0" set "LOGDIR=%XSCRIPTDIR%\%XScriptnamE%" if not exist "%LOGDIR%" mkdir "%LOGDIR%" set "LOG=%LOGDIR%\%XScriptnamE%.log" REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM ++++++++++++++++++++++++++++ SCRIPT ALIVE ++++++++++++++++++++++++++++++++++++++++ REM now tell us once a day that script is up and running set DateLOG=%XSCRIPTDIR%\%XScriptnamE%-date.txt if not exist "%DateLOG%" echo %ACTUALDATE% > %DateLOG% set /p BEFOREDATE=< %DateLOG% if NOT %ACTUALDATE% == %BEFOREDATE% ( echo %ACTUALDATE% > %DateLOG% echo blat %0 -subject "DNS Routes Script is alive and running! OK" -body "DNS-routing-script up and running - DNS routing is OK!" -to %eMailTO% -cc %eMailCC% -f %eMailFROM% %server% ) REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM make errorlooging expand set "XLOGX=xpipex && type xpipex && type xpipex >> %LOG%" REM or make individual run logs REM set "LOG=%LOGDIR%\%XScriptnamE%\%XScriptnamE%-%STAMP%.log" REM not global vars come here set "DNSTESTFILE=%XSCRIPTDIR%\dnstests.txt" REM set GATEWAY here set GW=7.7.7.7 REM to reflect GW changes here a route has to be set with each run if this is needed turn switch to 2 REM otherwise only missing routes get re set by switch 1 (default) set REFRESH-GW=1 REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM do never set something here at errorlog plz otherwise compare of happened errors wont work set errorlog= pushd=%XSCRIPTDIR% REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ echo ================================================== >> %LOG% echo Script run at %STAMP% >> %LOG% REM +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM ++++++++++++++++++++++++++++ START ++++++++++++++++++++++++++++++++++++++++++++++++ REM if the script is run in cmd we see enough information to follow actions but they are written to a log file too for sheduled use REM ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM when a batch script needs to use drives not local, eg shares it always needs special rights, REM means you need to use an account to run the script which is allowed to log on as batch task in REM secpol - (click start type secpol.msc and start it - Select "Local Policies" in MSC snap REM in - Select "User Rights Assignment" - Right click on "Log on as batch job" and select REM Properties - Click "Add User or Group", and include the relevant user.) REM ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM ++++++++++++ make a loop for each line in file ++++++++++++++++++++++++++++++++++++ REM first we test if script is able to set routes and got admin rights REM if delete fails, with false parameter -> script is elevated REM otherwise the missing elevated rights get reported to log echo. echo "if route delete fails, with false parameter -> script is elevated" echo "otherwise the missing elevated rights get reported to console" echo. route delete 999.999.999.999 echo. >> %LOG% echo "if route delete fails, missing elevated rights get reported to log " >> %LOG% echo "otherwise the script is elevated and you find only this text in log" >> %LOG% echo. >> %LOG% route delete 999.999.999.999 >> %LOG% REM read them in different vars to call processing REM check for test file if NOT exist "%DNSTESTFILE%" ( set errorlog=%errorlog% : error dns file not exist : echo blat error dnsfile echo error dnsfile not exist >> %log% ) REM read test file set Counter=1 for /f %%s in (%DNSTESTFILE%) do ( set "Line_!Counter!=%%s" set /a Counter+=1 ) set /a NumLines=Counter - 1 REM make a backup of old test file before nulling it copy /y %DNSTESTFILE% %DNSTESTFILE%.bak 2>&1 > %XLOGX% REM as i found no easy way to rewrite the specific line i choose to read out all lines in vars, REM now we nul the file and rewrite lines later, BE aware if script breaks all lines are lost most times REM instead of only one, so edit it carefully and test carefully all cases possible type NUL > %DNSTESTFILE% REM now use vars to call processing for /l %%r in (1,1,%NumLines%) do ( set "q=!Line_%%r!" echo. >> %log% echo. call :check !q! ) REM did all go well or what did we miss? if NOT "%errorlog%."=="." ( echo. echo blat summary %errorlog%! echo. >> %LOG% echo %errorlog%! >> %LOG% ) REM ++++++++++++++++++++++++++++ END +++++++++++++++++++++++++++++++++++++++++++++++++++ REM next line tells us script did run through code while one may want to save this lines echo ==================script finished================= >> %log% del xpipex break goto :eof REM ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ REM +++++++++++++++++++++++++++++ PROCESSING +++++++++++++++++++++++++++++++++++++++++++ :check REM trim whitespace from beginning and end of line for /f "tokens=* delims=" %%z in ("!q!") do ( set "line=!q!" REM test if line is valid dns AND ip address syntax BUT only informational because of limited regular expression support of findstr and "1234.2.3.4" is also accepted as well formatted address echo !line! | findstr /i /r "^[a-z0-9-]*\.[a-z0-9-]*\.[a-z0-9-]*=[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" >NUL || ( echo blat error in dns test line syntax with: !line! set errorlog=%errorlog% : error in dns test line syntax with: !line! : ) REM test that trimmed line matches at least once "^char=number$" and set vars for test echo !line! | findstr /i "^[a-z]*=[0-9]*$" >NUL && do ( for /f "tokens=1,2 delims==" %%x in ("!q!") do set TESTDNS=%%x&set TESTIP=%%y ) REM trim whitespace from vars set TESTDNS=%TESTDNS: =% set TESTIP=%TESTIP: =% echo testing %TESTDNS% to %TESTIP% echo checking %TESTDNS%: >> %LOG% REM useful to test script REM nslookup %TESTDNS% REM useful to test script REM go get dns resolution and set vars to test and compare set "XIP=" for /f "skip=1 tokens=*" %%a in ('nslookup "%TESTDNS%" 2^>nul ^| findstr /i /r /c:"address[e]*[s]*:.*\." /c:"address[ ]*=.*\." /c:"^[ ][ ]*[0-9].*\." ') do ( rem get nslookup output set "_line=%%a" rem remove spaces set "_line=!_line: =!" rem parse line for /f "tokens=1,* delims=:=" %%b in ("!_line!") do ( rem retrieve the correct section of the line if "%%c"=="" ( set "XTIPX=%%b" ) else ( set "XTIPX=%%c" ) REM again trim whitespace from var set XTIPX=!XTIPX: =! rem test address match to old address if "!XTIPX!"=="%TESTIP%" ( set "XIP=!XTIPX!" goto endRESTESTDNS ) rem if no match, the first address found is saved if not defined XIP set "XIP=!XTIPX!" ) ) :endRESTESTDNS REM if dsn did change if NOT %XIP%==%TESTIP% ( echo %TESTDNS% NOW is %XIP% REM delete the old route and set new one REM first check if the old false ip was set to prevent error if not found netsh interface ipv4 show route | find /i "%TESTIP%" >NUL if errorlevel 1 ( echo blat there was no route for given %TESTIP% from file, routes manipulated or file updated? echo there was no route for given %TESTIP% from file, routes manipulated or file updated? >> %LOG% set errorlog=%errorlog% : there was no route for given %TESTIP% from file, routes manipulated or file updated? : ) else ( Route DELETE %TESTIP% >> %LOG% ) Route ADD -P %XIP% mask 255.255.255.255 %GW% >> %LOG% echo blat route %TESTDNS% was changed from %TESTIP% to %XIP% by script! echo %TESTDNS% was changed from %TESTIP% to %XIP% by script! >> %LOG% REM write it back to the testfile (which was reset above) echo %TESTDNS%=%XIP% >> %DNSTESTFILE% REM fill a log-var to report allover later in mail for example set errorlog=%errorlog% : route %TESTDNS% was changed from %TESTIP% to %XIP% by script! : ) if %XIP%==%TESTIP% ( REM if dns did not change echo ip did not change echo checking if route exist REM now the gateway switch comes in, if set to 1 we check if route exist and if so we go on, otherwise we set the route again if %REFRESH-GW% == 1 ( netsh interface ipv4 show route | find /i "%XIP%" >NUL if errorlevel 1 ( Route ADD -P %XIP% mask 255.255.255.255 %GW% >> %LOG% echo blat %XIP% route was deleted by unknown manipulation and reset by script! echo %XIP% route was deleted by unknown manipulation and reset by script! >> %LOG% set errorlog=%errorlog% : %XIP% route was deleted by unknown manipulation and reset by script! : ) ) if %REFRESH-GW% == 2 ( REM here we check if route was deleted from elsewhere (and report it) but we set it anyway to make shure the gateway gets updated in case it was changed in the var on top netsh interface ipv4 show route | find /i "%XIP%" >NUL if errorlevel 1 ( echo blat %XIP% was deleted by unknown manipulation! echo %XIP% was deleted by unknown manipulation! >> %LOG% set errorlog=%errorlog% : %XIP% was deleted by unknown manipulation! : ) REM first delete the old and then set the new route Route DELETE %TESTIP% >> %LOG% Route ADD -P %XIP% mask 255.255.255.255 %GW% >> %LOG% echo blat route %TESTDNS% was reset by script! ) REM we should not forget to write back the route to our testfile echo %TESTDNS%=%XIP% >> %DNSTESTFILE% ) REM now we tell ourself we are through on all should be fine with the address and route netsh interface ipv4 show route | find /i "%XIP%" >NUL if errorlevel 1 ( echo blat route %XIP% could not be set - ERROR setting route echo route %XIP% could not be set - ERROR setting route >> %LOG% set errorlog=%errorlog% : route %XIP% could not be set - ERROR setting route : ) else ( echo OKI echo OK >> %LOG% ) :EOF
{ "pile_set_name": "StackExchange" }
Q: SQL Azure import slow, hangs, but local import takes 3 minutes I have a not-that-large database that I'm trying to migrate to SQL Azure, about 1.6 gigs. I have the BACPAC file in blob storage, start the import, and then... nothing. It gets to 5% as far as the status goes, but otherwise goes nowhere fast. After 10 hours, the database size appears to be 380 MB, and the monitoring shows on average around 53 successful connections per hour, with no failures. It appears to still be going. I took the same BACPAC to my local machine at home, and I can import the same database in just under three minutes, so I'm making the assumption that the integrity of the file is all good. What could possibly be the issue here? I can't just keep the app I'm migrating offline for days while this goes on. There must be something fundamentally different that it's choking on. A: Ugh, I hate answering my own question, but I figured out what the issue is. It appears to have to do with their new basic-standard-premium tiers (announced April 2014). The database imports to the old web-business levels no problem. Because the new tiers are built around throttling for "predictable performance," they make the high volume transactions of importing crazy slow.
{ "pile_set_name": "StackExchange" }
Q: Re-use PHP SOAP connection if already created? How do I in the easiest way re-use the SOAP connection if it has already been created? The soap connection function could in many cases be run multible times duing one PHP page load so there is not need to re-create the connection if it has been created - it just needs to be re-used. (And sometimes it is not even run at all because it is not needed so it would be a waste of time calling it in the beginning of all PHP page. The function only needs to be run it there is a need to connect.) I know that there other solutions for this problem (when I google it) but I did not manage to understand them. I tried a lot of things but they did not work for me. I even tried storing the SOAP object in a session so the next PHP page that was loaded could re-use the soap connection (from the previous PHP load) but it did not work eighter. The best solution is that the connection is remembered for all PHP pages loads in a browser session and the next best solution is that it remembered for the current PHP page load. Here is my code: protected static function Economic_API() { static $client; $settingsOld = Settings::GetOld(); try { $client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1)); $client->ConnectWithToken(array( 'token' => $settingsOld->economic_token_secret, 'appToken' => $settingsOld->economic_token_app )); } . . . UPDATED CODE: class EcoAPI { static $client; static public function getClient() { if (empty(self::$client)) { self::initClient(); } return self::$client; } static private function initClient() { $settingsOld = Settings::GetOld(); self::$client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1)); self::$client->ConnectWithToken(array('token' => $settingsOld->economic_token_secret, 'appToken' => $settingsOld->economic_token_app)); } } And call it by: $result = EcoAPI::getClient()->Account_FindByNumber(array('number' => intval($accountID))); A: perhaps you could try using a class instead of a function. The connection will be living in your class instance while the public function getClient() is available for the application to use the soapClient connection. class Economic_API { private $client; private $token; private $appToken; public function __construct($token, $appToken){ $this->token = $token; $this->appToken = $appToken; } private function initClient() { $this->client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" => 1, "exceptions" => 1)); $this->client->ConnectWithToken(array( 'token' => $settingsOld->economic_token_secret, 'appToken' => $settingsOld->economic_token_app )); } /** * @returns SoapClient */ public function getClient() { if($this->client === null) { $this->initClient(); } return $this->client; } } $token = '123'; $appToken = "abc" $economicApi = new Economic_API($token, $appToken); $economicApi->getClient()->YourSoapFunction();
{ "pile_set_name": "StackExchange" }
Q: msbproj file writing documentation I'm trying to debug some weirdness that's occurring within a msbproj file we have to automate our build process; I can't find a shred of documentation on writing msbproj files anywhere however, where's the "go-to" resource for msbproj writing? EDIT: The oddity was being caused by differences in the output folder of debug and release builds- but I'm still interested in finding the answer to this question. A: its just msbuild by another name. See the MSDN reference as your start:msdn.microsoft.com/en-us/library/7z253716.aspx
{ "pile_set_name": "StackExchange" }
Q: How to implement a mouse listener that will help drag a circle in java? I am trying to figure out how to complete the assignment below Write a method void move(Point p) for your Circle class that takes a Point and moves the circle so its center is at that point. In the CirclePanel constructor, create a CirclesListener object and make it listen for both mouse events and mouse motion events. Make the CirclesListener class implement the MouseMotionListener interface in addition to the MouseListener interface. This requires two steps: Note in the header that CirclesListener implements MouseMotionListener. Add bodies for the two MouseMotionListener methods, mouseDragged and mouseMoved. In mouseDragged, simply move the circle to the point returned by the getPoint method of the MouseEvent and repaint. Provide an empty body for mouseMoved. I know what I need to do (for the most part), I just can't figure out how to do it. (New to programming). Thank you! public class circlePanel extends JPanel { private final int WIDTH = 600, HEIGHT = 400; private Circle circle; // ------------------------------------------------------------------- // Sets up this panel to listen for mouse events. // ------------------------------------------------------------------- public circlePanel() { addMouseListener(new CirclesListener()); setPreferredSize(new Dimension(WIDTH, HEIGHT)); } // ------------------------------------------------------------------- // Draws the current circle, if any. // ------------------------------------------------------------------- public void paintComponent(Graphics page) { super.paintComponent(page); if (circle != null) circle.draw(page); } // ****************************************************************** // Represents the listener for mouse events. // ****************************************************************** private class CirclesListener implements MouseListener, MouseMotionListener { // --------------------------------------------------------------- // Creates a new circle at the current location whenever the // mouse button is pressed and repaints. // --------------------------------------------------------------- public void mousePressed(MouseEvent event) { if (circle == null) { circle = new Circle(event.getPoint()); } else if (circle.isInside(event.getPoint())) { circle = null; } else { circle.move(getMousePosition()); } repaint(); } // ----------------------------------------------------------------- // Provide empty definitions for unused event methods. // ----------------------------------------------------------------- public void mouseClicked(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public void mouseEntered(MouseEvent event) { setBackground(Color.white); } public void mouseExited(MouseEvent event) { setBackground(Color.blue); } } } Here is the circles class public class Circles { // ---------------------------------------------------------------- // Creates and displays the application frame. // ---------------------------------------------------------------- public static void main(String[] args) { JFrame circlesFrame = new JFrame("Circles"); circlesFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); circlesFrame.getContentPane().add(new circlePanel()); circlesFrame.pack(); circlesFrame.setVisible(true); } } aannnddddd...here is the Circle class public class Circle { private int centerX, centerY; private int radius; private Color color; static Random generator = new Random(); // --------------------------------------------------------- // Creates a circle with center at point given, random radius and color // -- radius 25..74 // -- color RGB value 0..16777215 (24-bit) // --------------------------------------------------------- public Circle(Point point) { radius = Math.abs(generator.nextInt()) % 50 + 25; color = new Color(Math.abs(generator.nextInt()) % 16777216); centerX = point.x; centerY = point.y; } // --------------------------------------------------------- // Draws circle on the graphics object given // --------------------------------------------------------- public void draw(Graphics page) { page.setColor(color); page.fillOval(centerX - radius, centerY - radius, radius * 2, radius * 2); } public void move(Point p) { centerX = p.x; centerY = p.y; } public boolean isInside(Point p) { if (Math.sqrt(Math.pow(p.x - this.centerX, 2) + Math.pow(p.y - this.centerY, 2)) < this.radius) { return true; } else { return false; } } } A: So, basically, based on you code example, you need: Implement the functionality of the MouseMotionListener, this will include the mouseDragged method You need to register the CirclesListener to the circlePanel (JPanel#addMouseMotionListener) When mouseDragged is called, you need to take the Point from the MouseEvent and call Circle#move and repaint the component If you get stuck, best place to start is How to Write a Mouse Listener
{ "pile_set_name": "StackExchange" }
Q: Javascript trigger for load of all elements I have 2 external html pages loaded by this code: <div id="header-div"></div> <div id="footer-div"></div> my js file contains this: $(function () { $("#header-div").load("/AfekDent/header.html"); $("#footer-div").load("/AfekDent/footer.html"); }); I want to run a function when specific element in the header file is created - what trigger can i use for it? It's ok the trigger will occur when all elements will be loaded. thanks! A: Add a callback to your load() call. $(function () { $("#header-div").load("/AfekDent/header.html", function() { console.log('My header was loaded!'); }); });
{ "pile_set_name": "StackExchange" }
Q: how to remove files that could be with lower/upper case how to remove files that could be with lower/upper case for example, the file_name could be: STOCK.Repo or Stock.REPO or stOCK.repo or stock.repo ... etc I would run: rm -f $file_name the goal is to remove file as stock.repo that could be in lower/upper case on remote machine A: For Bash-specific solution: $ shopt -s nocaseglob and then run the rm command. Note to unset this option, use shopt -u nocaseglob For completeness, I would point out an alternative but less elegant solution: $ rm [sS][tT][oO][cC][kK].[rR][eE][pP][oO] A: You can do it using find command find /path/to/directory -type f -iname stock\.repo -exec rm -f {} \; But be very careful. It is working recursively from /path/to/directory. You should consider using maxdepth option, and getting more familiar with this command before running it on production system where permanent damage can be made.
{ "pile_set_name": "StackExchange" }
Q: ArrayIndexOutOfBoundsException: -1 in recursive sorting Am new in Java, I want to know why i have exceptions even though i got the answers i required. Below is the Source code package habeeb; import java.util.*; public class Habeeb { public static void main(String[] args) { Scanner input = new Scanner(System.in); int[] num = new int[30]; int i, count = 0; System.out.println("Enter the integers between 1 and 100"); for (i = 1; i <= num.length; i++) { num[i] = input.nextInt(); if (num[i] == 0) break; count++; } Sorting(num, i, count); } public static void Sorting(int[] sort, int a, int con) { int j, count = 0; for (j = 1; j <= con; j++) { if (sort[a] == sort[j]) count++; } System.out.println(sort[a] + " occurs " + count + " times"); Sorting(sort, a - 1, con); } } And here is the output run: Enter the integers between 1 and 100 1 2 3 2 2 4 5 3 6 1 0 0 occurs 0 times 1 occurs 2 times 6 occurs 1 times Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 3 occurs 2 times 5 occurs 1 times 4 occurs 1 times 2 occurs 3 times 2 occurs 3 times 3 occurs 2 times 2 occurs 3 times 1 occurs 2 times 0 occurs 0 times at habeeb.Habeeb.Sorting(Habeeb.java:18) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.Sorting(Habeeb.java:21) at habeeb.Habeeb.main(Habeeb.java:14) Java Result: 1 A: public static void Sorting(int[] sort, int a, int con){ int j, count=0; for(j=1; j<=con; j++){ if(sort[a]==sort[j]) count++; }System.out.println(sort[a]+" occurs "+count+" times"); Sorting(sort, a-1, con); Should be: public static void Sorting(int[] sort, int a, int con){ if(a<0)return; int j, count=0; for(j=1; j<=con; j++){ if(sort[a]==sort[j]) count++; }System.out.println(sort[a]+" occurs "+count+" times"); Sorting(sort, a-1, con);
{ "pile_set_name": "StackExchange" }
Q: Center Align Contents Of A Page I've been trying to center align the #main div on a page so far, but I have been unsuccessful. The page in question is a generic page. I've been applying the css margin: 0px auto;to the #main div, but I could not make it center align. I wanted the content to be center-aligned on large screens, but the floating menubar to be same. Can anybody help me in achieving this? I am lost. A: Just add this: #main { margin: 0 auto; width: 600px; background-color: #EEEEEE; text-align: center; } So simple HTML example: <div id="main"> <span>Simply dummy text</span> <span>Simply dummy text</span> <span>Simply dummy text</span> </div> You can't do width: 100% because you need to define the width of the element you are centering, not the parent element. EDIT: I created demo on jsFiddle.net here
{ "pile_set_name": "StackExchange" }
Q: Retrieve JSON POST data in CodeIgniter I have been trying to retrieve JSON data from my php file.Its giving me a hard time.This is my code Code in my VIEW: var productDetails = {'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle}; var base_url = '<?php echo site_url() ?>'; $.ajax({ url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart", type: 'POST', data:productDetails, dataType:'JSON', }); Trying to retrieve in my Controller: echo $this->input->post("productDetails"); Outputs Nothing. Here are my headers: Remote Address:[::1]:80 Request URL:http://localhost/CI/index.php/user/Add_to_cart/addProductsToCart Request Method:POST Status Code:200 OK Request Headersview source Accept:application/json, text/javascript, */*; q=0.01 Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8,fr;q=0.6 Connection:keep-alive Content-Length:52 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:ci_session=3E5SPro57IrJJkjs2feMNlmMrTqEXrTNN8UyEfleeothNnHwNxuCZDSx4a7cJZGjj7fyr2KLpj%2BPNJeGRSzSPVmcFHVEdhSk4D47ziOl4eZcTUAZlQrWa3EYIeQJVWxMpiGZS26MEfbSXNmfel9e8TcsJTreZHipvfisrJovbXEAW4Uv%2BwrJRep1KCi1MMaDCVJb9UEinRVcDtYe%2F86jhn7kOj4kraVmVzx%2FsOaO0rAxLyAUtez%2Feaa4zBwpN3Td153sAoIb3WxVHoEj2oKyH5prVHigbIhIBR6XZqjBkM6hjBuoD2OSZ2wgLbp9DEENMoqui4WYyHROBuS2DYiJajblcS0KiFga5k%2FQOODvE7p6n%2BozN5ciDliVjJ4PnJ5PD1GaPEmec5%2FbQSlOHYWZk%2F2Blzw3Nw0EtLL7wKDzzQY%3Df645c36bb3548eb8de915b73f8763d97a47783ce Host:localhost Origin:http://localhost Referer:http://localhost/CI/index.php/user/view_available_books/viewAvailableBooks/5 User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36 X-Requested-With:XMLHttpRequest **Form Dataview** sourceview URL encoded id:234 qty:1 price:0.00 name:dasdadsd2q3e!@!@@ My Response which I can See in Developer tools: Array ( [id] => 234 [qty] => 1 [price] => 0.00 [name] => dasdadsd2q3e!@!@@ ) But in browser, the output is nothing. I am trying to solve it for more than 4 hours now but in vain. print_r($_POST); // outputs nothing echo $data = file_get_contents('php://input'); //outputs nothing echo $id = $this->input->post('productDetails');// outputs nothing My View Code: <script> $('#addtoCart').on('click',function(event){ event.preventDefault(); $(this).attr('disabled',"disabled"); finalprice = $.trim($('#price').val()); finalqty = $.trim($('#quantity').val()); var productDetails = JSON.stringify({'id':ISBNNumber,'qty':finalqty,'price':finalprice,'name':bookTitle}); var base_url = '<?php echo site_url() ?>'; // console.log($); $.ajax({ url: "<?php echo base_url() ?>index.php/user/Add_to_cart/addProductsToCart", type: 'POST', contentType: "application/json; charset=utf-8", data:productDetails, dataType:'html', }); }); </script> Controller Code: function addProductsToCart(){ var_dump(json_decode(file_get_contents("php://input"))); print_r($_POST); // $data = json_decode($_POST["productDetails"]); // var_dump($data); // echo $data = file_get_contents('php://input'); // print_r(json_decode($data)); // $id = $this->input->post('id'); // $qty = $this } A: I had the exact same problem. CodeIgniter doesn't know how to fetch JSON. I first thought is about the encoding Because I use fetch.js and not jQuery. Whatever I was doing I was getting an notting. $_POST was empty as well as $this->input->post(). Here is how I've solved the problem. Send request (as object prop -- because your js lib might vary): method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ ready: 'ready' }) Node: I encode my data of type object into json. jQuery does this by itself when you set the dataType: 'JSON' option. CodeIgniter (3.1 in my case): $stream_clean = $this->security->xss_clean($this->input->raw_input_stream); $request = json_decode($stream_clean); $ready = $request->ready; Note: You need to clean your $this->input->raw_input_stream. You are not using $this->input->post() which means this is not done automatically by CodeIgniter. As for the response: $response = json_encode($request); header('Content-Type: application/json'); echo $response; Alternatively you can do: echo $stream_clean; Note: It is not required to set the header('Content-Type: application/json') but I think it is a good practice to do so. The request already set the 'Accept': 'application/json' header. So, the trick here is to use $this->input->raw_input_stream and decode your data by yourself. A: Although OP seems satisfied, choosen answer doesn't tell us the reason and the real solution . (btw that post_array is not an array it's an object indeed ) @jimasun's answer has the right approach. I will just make things clear and add a solution beyond CI. So the reason of problem is ; Not CI or PHP, but your server doesn't know how to handle a request which has an application/json content-type. So you will have no $_POST data. Php has nothing to do with this. Read more at : Reading JSON POST using PHP And the solution is ; Either don't send request as application/json or process request body to get post data. For CI @jimasun's answer is precise way of that. And you can also get request body using pure PHP like this. $json_request_body = file_get_contents('php://input'); A: I had the same problem but I found the solution. This is the Json that I am sending [{"name":"JOSE ANGEL", "lastname":"Ramirez"}] $data = json_decode(file_get_contents('php://input'), true); echo json_encode($data); This code was tested and the result is [{"name":"JOSE ANGEL","lastname":"Ramirez"}]
{ "pile_set_name": "StackExchange" }
Q: Multiple coloured box plots in R with legends I have a raw data which looks like this: A B C D E F G H I J K L M N O P 1 15.0 20 23.3 26.5 28 29.0 31.8 32.0 32.0 33.8 36.0 38 40 46 47.0 55.0 2 10.0 13 16.0 20.0 10 19.5 14.0 15.0 31.0 15.0 24.6 29 31 46 26.7 38.2 3 18.0 25 29.5 45.0 47 36.5 41.0 38.0 34.5 63.0 43.0 41 42 55 55.0 78.0 4 32.5 60 108.7 88.0 83 65.9 84.9 125.1 62.6 83.0 71.6 53 55 72 88.3 123.8 5 22.0 36 65.0 63.0 60 43.8 53.0 74.0 44.3 71.0 50.3 44 46 62 63.5 96.0 6 10.0 NA NA NA 30 NA NA NA NA 20.0 NA NA NA NA NA NA 7 15.0 NA NA NA 25 NA NA NA NA NA NA NA NA NA NA NA 8 5.0 NA NA NA 40 NA NA NA NA 30.0 NA NA NA NA NA NA These are actually the 2.5, 25, 50, 75 and 97.5 percentile values. I want to create box plots from these with different colours each and then mark the median point with a dot in the boxplot. I tried writing the following commands but got stuck with an error I could not comprehend. Boxplot <- read.csv(file="Boxplots.csv",head=TRUE,sep=",") Boxplot attach(Boxplot) boxplot(Boxplot, las = 2, col = c("sienna","royalblue2","chartreuse3","chartreuse4","chocolate","chocolate1","chocolate2","chocolate3","chocolate4","coral","coral1","coral2","coral3","coral4","cornflowerblue"), at = c(1,2,3,4,5, 6,7,8,9, 10,11,12,13,14,15), par(mar = c(0, 5, 4, 2) + 0.1), names = c("","","","","","","","","","","","","","","")) Kindly help. A: I would (always) steer clear of attach. Especially here because you've already assigned Boxplot to your data, so it's already "attached". The error you're getting is likely due to the length of your col argument being longer than the number of columns. > dat <- read.table(header = TRUE, text = "A B C D E F G 15.0 20.0 23.3 26.5 28.0 29.0 31.8 10.0 13.0 16.0 20.0 10.0 19.5 14.0 18.0 25.0 29.5 45.0 47.0 36.5 41.0 32.5 60.0 108.7 88.0 83.0 65.9 84.9 22.0 36.0 65.0 63.0 60.0 43.8 53.0") > boxplot(dat, col = rainbow(7), medlwd = 0) > points(sapply(dat, median), pch = 19)
{ "pile_set_name": "StackExchange" }
Q: C# CSV file still open when appending I'm trying to allow the user to add another entry to the CSV file my program is building. It is building it out of a database like this: public void CreateCsvFile() { var filepath = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv"; var ListGather = new PaceCalculator(); var records = from record in ListGather.NameGain() .Zip(ListGather.PaceGain(), (a, b) => new { Name = a, Pace = b }) group record.Pace by record.Name into grs select String.Format("{0},{1}", grs.Key, grs.Average()); //reduces the list of integers down to a single double value by computing the average. File.WriteAllLines(filepath, records); } I then am calling it into a datagridview like this: private void button2_Click(object sender, EventArgs e) { CreateExtFile CsvCreate = new CreateExtFile(); CsvCreate.CreateCsvFile(); return; } private void LoadAthletes() { string delimiter = ","; string tableName = "Schedule Table"; string fileName = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv"; DataSet dataset = new DataSet(); StreamReader sr = new StreamReader(fileName); dataset.Tables.Add(tableName); dataset.Tables[tableName].Columns.Add("Athlete Name"); dataset.Tables[tableName].Columns.Add("Pace Per Mile"); string allData = sr.ReadToEnd(); string[] rows = allData.Split("\r".ToCharArray()); foreach (string r in rows) { string[] items = r.Split(delimiter.ToCharArray()); dataset.Tables[tableName].Rows.Add(items); } this.dataGridView1.DataSource = dataset.Tables[0].DefaultView; } A button opens a window which contains fields to add a new entry to the csv file. This is how I am doing this: private void AddToScheduleBtn_Click(object sender, EventArgs e) { string FileName = @"F:\A2 Computing\C# Programming Project\ScheduleFile.csv"; string AthleteDetails = textBox1.Text + "," + textBox2.Text; File.AppendAllText(FileName, AthleteDetails); AddToSchedule.ActiveForm.Close(); } Although this works once, When I try and add another entry to my csv file again it says it is open in another process and the program crashes. When the data first appears in my datagridview, there is an empty row at the bottom which there shouldn't be. What is the best way of allowing me to re-use the process so I can append to the file more than once? A: I think your line, StreamReader sr = new StreamReader(fileName); has the file opened. You want to do the following: string allData = sr.ReadToEnd(); sr.Close(); sr.Dispose();
{ "pile_set_name": "StackExchange" }
Q: How to change the administrator account name from command prompt in Windows Server 2008 Server Core? I'm trying to change the administrator account name on my virtual machine for lab work purposes. I'm running Windows Server 2008 Server Core, therefore I'm only using the standard command prompts. How can I do this? A: If it domain user install Active Directory Administration module for PowerShell. command line: powershell Import-module ActiveDirectory rename domain user - Powershell: Get-ADUser -Identity 'Administrator' | Rename-ADObject -NewName 'Partisan' command line: powershell Get-ADUser -Identity 'Administrator' ^| Rename-ADObject -NewName 'Partisan' var 2: dsquery user -name Administrator | dsmove -newname "Partisan" local administrator - Powershell: Rename-LocalUser -UserName 'Administrator' -NewUserName 'Partisan' command line: powershell Rename-LocalUser -UserName 'Administrator' -NewUserName 'Partisan' var2: wmic UserAccount where Name="Administrator" call Rename Name="Partisan"
{ "pile_set_name": "StackExchange" }