text
stringlengths
64
81.1k
meta
dict
Q: Using two datasets in a single report using SQL server reporting service I need to show a report of same set of data with different condition. I need to show count of users registered by grouping region, country and userType, I have used drill down feature for showing this and is working fine. Also the reported data is the count of users registered between two dates. Along with that I have to show the total users in the system using the same drill down that is total users by region, country and usertype in a separate column along with each count (count of users between two date) so that my result will be as follwsinitialy it will be like Region - Country - New Reg - Total Reg - User Type 1 - UserType2 + Region1 2 10 1 5 1 5 + Region2 3 7 2 4 1 3 and upon expanding the region it will be like Region - Country - New Reg - Total Reg - User Type 1 - UserType2 + Region1 2 10 1 5 1 5 country1 1 2 1 2 - - country2 1 8 1 8 - - + Region2 3 7 2 4 1 3 Is there a way I can show my report like this, I have tried with two data sets one with conditional datas and other with non conditional but it didn't work, its always bing total number of regiostered users for all the total reg columns A: I have solved this problem by taking all the records from DB and filtering the records to collect new reg count by using an expression as following =Sum(IIF(Fields!RegisteredOn.Value >Parameters!FromDate.Value and Fields!RegisteredOn.Value < Parameters!EndDate.Value , 1,0))
{ "pile_set_name": "StackExchange" }
Q: QR with link and more info I´m trying to find a way to put a web link in a QR code, but with more info in the final, so when I try to capture with a Standard QR Reader it will jump to my link, but when I read it with my Android app, I will take just the data that I need. EG - If I want to go to Facebook and have another String in the link. www.facebook.com+hello I just need to know how to encode the link to make this work. Thanks! Regards A: You can add your additional info at the end of the link after an #, but if the website you linked use # with parameters you would be out of luck. Example: http://www.mywebsite.com/#myadditionalinfo=test
{ "pile_set_name": "StackExchange" }
Q: Robust image URL linking from CSS? Is there a good way to robustly link to an image in CSS in grails? Originally, I had image paths set to /images/blah, which worked great until the application needed to be deployed in a different context. Is there a better way to link to images than manually specifying the path to the images relative to the css file? This leaves me with crap like ../../../images/blah, which breaks as soon as the CSS file moves unless you move the file within a smart IDE. This is also ugly as hell. A: You can try using Grails tag libraries with the GSParse plugin to have css and js parsed as a gsp file: http://nerderg.com/GSParse http://grails.org/plugin/gsp-arse
{ "pile_set_name": "StackExchange" }
Q: Filtering date after max date SQL I have a table with values en date/timstamps. This table is dbo.meterdata.value. The output that i want to see is as followed: The latest date/timestamp (Max) but only the ones where te latest date/timestamp is last week. My Query is: SELECT dbo.meter.DataImportCode ,dbo.meter.NAME ,dbo.company.NAME ,dbo.meter.MeterNumber ,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum' ,dbo.MeterOperator.Description ,dbo.meter.CumulativeReadings FROM dbo.meter LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID JOIN DBO.Site ON dbo.meter.SiteID = dbo.site.SiteID JOIN DBO.Company ON dbo.site.CompanyID = dbo.company.CompanyID JOIN DBO.MeterOperator ON dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID --WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() ) AND dbo.meterdata.RoundedTimeStamp IS NOT NULL GROUP BY dbo.meter.DataImportCode ,dbo.company.NAME ,dbo.meter.NAME ,dbo.meter.MeterNumber ,dbo.MeterOperator.Description ,dbo.meter.CumulativeReadings Example of the unfilterd result: Example Thank you for help and support A: Try the following: select dbo.meter.DataImportCode, dbo.meter.Name, dbo.company.Name, dbo.meter.MeterNumber,MAX(dbo.meterdata.RoundedTimeStamp) AS 'laatste datum', dbo.MeterOperator.Description, dbo.meter.CumulativeReadings from dbo.meter LEFT OUTER JOIN DBO.MeterData ON dbo.meter.MeterID = dbo.meterdata.MeterID JOIN DBO.Site on dbo.meter.SiteID = dbo.site.SiteID JOIN DBO.Company on dbo.site.CompanyID = dbo.company.CompanyID JOIN DBO.MeterOperator on dbo.meter.MeterOperatorID = dbo.MeterOperator.MeterOperatorID --WHERE (select (dbo.meterdata.roundedtimestamp) from dbo.MeterData) < DateAdd(DD,-7,GETDATE() ) --AND dbo.meterdata.RoundedTimeStamp is not null GROUP BY dbo.meter.DataImportCode, dbo.company.name, dbo.meter.Name, dbo.meter.MeterNumber, dbo.MeterOperator.Description, dbo.meter.CumulativeReadings HAVING [laatste datum] < DateAdd(day,-7,GETDATE()) If I understood you right, what you want to do is filter out the data after it has been grouped. This is done using the HAVING clause of the SELECT statement, as the above query depicts.
{ "pile_set_name": "StackExchange" }
Q: batch execute iPython Notebook with command line argument? I'm using nbconvert to execute an iPython notebook via the command line (as in this answer): ipython nbconvert --to=html --ExecutePreprocessor.enabled=True RunMe.ipynb Is it possible to pass command line arguments to be accessed from within the notebook (like sys.argv)? This would let me reuse the same notebook in different contexts. A: You can access environmental variables instead. I have yet to come across a way to use command line arguments directly.
{ "pile_set_name": "StackExchange" }
Q: async foreach in jquery I am trying to display some charts using c3js. And I have come across the problem of having a need for "pausing" a foreach loop with a async operation in the loop. I can hack it by a adding an empty alert which allows the "work" to be completed (see the alert in code below). How do I unhack this and make it work? The showData function is called when pressing a button. selectedFiles = []; function showData(){ displayChart(selectedFiles,function(cols){ alert("");//fixme //display chart chart = c3.generate({ bindto: '#chart', data: { columns: cols, type:'bar'}, bar: { width: { ratio: 0.5 } } }); }); } function displayChart(files,completionHandler) { var columns = []; $.each(files, function( index,value) { //create array with file name, and averageDuration var fileName = value + ".json"; var averageDuration; $.getJSON(fileName, function(json) { averageDuration = json.averageDuration; var col = [value,averageDuration]; columns.push(col); }); }); completionHandler(columns); } A: since ajax is async, you can't use it like that function displayChart(files, completionHandler) { var src = $.map(files, function (value) { var fileName = value + ".json"; return $.getJSON(fileName); }); $.when.apply($, src).done(function (data) { var columns; if (files.length > 1) { columns = $.map(arguments, function (array, idx) { return [[files[idx], array[0].averageDuration]] }); } else { columns = [ [files[0], data.averageDuration] ] } completionHandler(columns); }) } Demo: Fiddle
{ "pile_set_name": "StackExchange" }
Q: Is there a case statement in Haml-Coffee? I'd like to do the following in Haml-Coffee: - case msg.type - when "usertext" = msg.body - when "direct" = msg.content.kbcontent_body But I get an error "Reserved word "case"" I suspect it's not supported by Haml-Coffee actually. A: Before the question was edited, it's main phrase had been: Is there a case statement in HAML? The answer is: in vanilla Haml there indeed is case! %p - case 2 - when 1 = "1!" - when 2 = "2?" - when 3 = "3." A: There isn't a case statement in CoffeeScript. You want switch — the case keyword is the JavaScript equivalent of when, and like many dropped JavaScript keywords is reserved in CoffeeScript. Also, I'm not 100% positive and don't have Haml-Coffee to test right now, but I think you'll need to indent the body of the switch.
{ "pile_set_name": "StackExchange" }
Q: How to declare database connection variable globally in Swift I need to initialize a variable to connect to an SQLite database in Swift. I am using the SQLite.swift library and need to connect to the database with this line: let db = try Connection("path/to/db.sqlite3") However, this line by itself will not work because it needs to be surrounded with a try/catch block. Try/catch blocks will not work unless they are defined within methods or functions, so now we have public func connectToDB() { do { let path = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true ).first! let db = try Connection("\(path)/db.sqlite3") } catch { print("error connecting to database") } } However, this doesn't allow me to access the variable from other methods in the same file, which is what I need to do. Global let declarations also require initialization, so that means it cannot be set globally. How can I access this object from other methods within the class? A: You could do this: let db = try! Connection("path/to/db.sqlite3") // db is a Connection but the app dies if there was an error. Or you could do this: let db = try? Connection("path/to/db.sqlite3") // db is an Optional<Connection> and nil if there was an error. Or you could do this: let db = { () -> Connection in do { return try Connection("path/to/db.sqlite3") } catch { do { return try Connection() // transient in-memory database } catch { fatalError() } } }() // invoke this closure immediately You can do whatever you like in the closure to handle an error case.
{ "pile_set_name": "StackExchange" }
Q: Issue with namespaces in XSLT Translation *I found out that the issue seems to be because of the line xmlns="http://sample.com/task/1.0" There was no namespace assigned and when I added one (ns1) things seemed to translate the way I wanted to. My revised question would be "Why was not having a namespace assigned there a problem, and if I were to want to change that in many files, how would I do that?" I am new to XSLT but am trying to take an XML document and turn it into RDF. My approach was to just start with a simple translation to pull out some XML terms in plain text to start off. I took an XML file, stripped it of namespaces, and was able to get things to display properly. In this iteration, I added the namespaces back to the XML file, but kept them from being referenced in tags. I also added them to the XSL file. When I run the translation, I only get the text that I wrote before the values. However, when I change the xsl:template match to be anything beyond "/*", I get the values but not the text. Here is the code XML: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <getCollectiveTaskResponse xmlns="http://sample.com/task/1.0" xmlns:ns2="http://sample.com/commonElements/1.0" xmlns:ns3="http://sample.com/individualTask/1.0" xmlns:ns4="http://sample.com/collectiveTask/1.0" xmlns:ns5="http://sample.com/xsd/handle" xmlns:ns6="http://sample.com/appinfo/1"> <collectiveTask> <generalInformation> <number>13</number> <title>Quarterback</title> <name>Dan Marino</name> </generalInformation> </collectiveTask> And here is the XSL: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://sample.com/task/1.0" xmlns:ns2="http://sample.com/commonElements/1.0" xmlns:ns3="http://sample.com/individualTask/1.0" xmlns:ns4="http://sample.com/collectiveTask/1.0" xmlns:ns5="http://sample.com/xsd/handle" xmlns:ns6="http://sample.com/appinfo/1"> <xsl:template match="/getCollectiveTaskResponse"> Number:<xsl:value-of select="collectiveTask/generalInformation/number"/> Title:<xsl:value-of select="collectiveTask/generalInformation/title"/> Name:<xsl:value-of select="collectiveTask/generalInformation/name"/> </xsl:template> </xsl:stylesheet> A: If you are using an XSLT 2 or 3 processor then to make your template <xsl:template match="/getCollectiveTaskResponse"> Number:<xsl:value-of select="collectiveTask/generalInformation/number"/> Title:<xsl:value-of select="collectiveTask/generalInformation/title"/> Name:<xsl:value-of select="collectiveTask/generalInformation/name"/> </xsl:template> work you need to put xpath-default-namespace="http://sample.com/task/1.0" on your xsl:stylesheet element.
{ "pile_set_name": "StackExchange" }
Q: How to pass class variable between activities? I created a class Telnet and I inicialize it on the Mainactivity. Now I want to access the telnet I inicialized in the MainActivity in all other activities of the project. What I am doing is creating a get function: public Telnet getMyTelnet() { return telnet; } And then just call it wherever I want. When I call it in fragments I do it like this: MainActivity activity = (MainActivity) getActivity(); telnet = activity.getMyTelnet(); The problem is when I need it in another activity. How can I do it? I tried this but no luck. MainActivity a = new MainActivity (); telnet = a.getTelnet(); A: In android there are two ways to achieve send and receive objects bebtween Activities: they must: Serializable (Implment object as Serializable) or Parcelable (Implement object as Parcelable) you will need to implement Parcelabel and add the following methods to the class a constructor with a parcel as parameter public Telnet(Parcel in) { readFromParcel(in); } override the writeToParcel method @Override public void writeToParcel(Parcel dest, int flags) { // write each field into the parcel. When we read from parcel, they // will come back in the same order dest.writeString(strVar); // to write your string variables dest.writeInt(intVar); // to write your int variables } a method for read from Parcel private void readFromParcel(Parcel in) { strVar= in.readString(); intVar= in.readInt(); } a parcel creator public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Telnet createFromParcel(Parcel in) { return new Telnet(in); } public Telnet[] newArray(int size) { return new Telnet[size]; } }; @Override public int describeContents() { return 0; } then your Telnet class is ready to be transfer to another activities. Now use it: in the main act do: Telnet obj = new Telnet(); // Set values etc. Intent i = new Intent(this, MyActivity.class); i.putExtra("your.package.Telnet", obj); startActivity(i); and in the second activity do: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle b = getIntent().getExtras(); Telnet obj = b.getParcelable("your.package.Telnet"); }
{ "pile_set_name": "StackExchange" }
Q: How to get response status code in axios? Standard solutions doesn't work I have this axios code and I can't reach response status code. What is wrong here? I get 'undefined' instead of 201, for example. Thanks in advance! axios.post('endpoint', { body }) .then((response) => { console.log(response.status); }) A: In case of error you have to catch the result axios.post('endpoint', { body }) .then((response) => { // do something }) .catch((error) => { console.log(error.response.status) })
{ "pile_set_name": "StackExchange" }
Q: MediaRecorder No blobs are defined I created a script that allows me to record a video from the canvas with the id "imacanvas". But the problem is that no blobs were created. I think the problem is that the function handleDataAvailable isn't executed. But I don't know why?? Thanks for your help :) var recordedBlobs; var recorder; var stream; function handleDataAvailable(event) { console.log("0"); if (event.data && event.data.size > 0) { recordedBlobs.push(event.data); console.log("1"); } } function startRecord(){ recordedBlobs = []; var canvas = document.getElementById('imacanvas'); stream = canvas.captureStream(60); try { recorder = new MediaRecorder(stream); } catch (e) { console.error('Exception while creating MediaRecorder: ' + e); alert('Exception while creating MediaRecorder: ' + e + '. mimeType: ' + options.mimeType); return; } recorder.ondataavailable = handleDataAvailable; recorder.start(10); } function stopRecord() { recorder.stop(); console.log('Recorded Blobs: ', recordedBlobs); } function download() { var blob = new Blob(recordedBlobs, {type: 'video/webm'}); var url = window.URL.createObjectURL(blob); var a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = 'test.webm'; document.body.appendChild(a); a.click(); setTimeout(function() { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 100); } A: In order to be able to activate the stream captured by HTMLCanvasElement.captureStream(), you need to have initialized its context, and drawn on it. This must be done before you call captureStream(). const chunks_before = []; const stream_before = c.captureStream(60); try { const rec_before = new MediaRecorder(stream_before); rec_before.ondataavailable = e => chunks_before.push(e.data); rec_before.onstop = e => console.log('before : ', chunks_before.length); rec_before.start(); setTimeout(() => { if (rec_before.state === 'recording') rec_before.stop(); }); } catch (e) { console.log('before failed'); } // simply doing this allows us to do it c.getContext('2d').fillRect(0, 0, 20, 20); const chunks_after = []; const stream_after = c.captureStream(60); const rec_after = new MediaRecorder(stream_after); rec_after.ondataavailable = e => chunks_after.push(e.data); rec_after.onstop = e => console.log('after : ', chunks_after.length); rec_after.start(); setTimeout(() => { if (rec_after.state === 'recording') rec_after.stop(); }, 1000); <canvas id="c"></canvas>
{ "pile_set_name": "StackExchange" }
Q: Why did this jetty connector folder mysteriously appear in my files? Today I opened my laptop and navigated to a folder called "work," which I use only to store documents. I noticed that a new subfolder is inside it, called "jetty-0.0.0.0-31415-internal-connector-_internal-connector-any-" that was not there yesterday. I did not create this folder, nor did I install any new software in the last week. The folder contains only another folder called "jsp" which is empty. When I googled "jetty-0.0.0.0-31415-internal-connector-_internal-connector-any-" the only result was from a server belonging to MIT, which also has this folder inside a directory called "work." Where could this have come from? Could it mean I have a virus of some kind? Thanks for any help. A: That would be a standard Jetty directory for the temporary folder on a specific webapp for a running Jetty server. The filename ... jetty-0.0.0.0-31415-internal-connector-_internal-connector-any- tells you .... jetty - a jetty temporary directory 0.0.0.0 - listening on all network interfaces 31415 - listening on port 31415 internal-connector - using a custom network connector (quite unusual) _internal-connector - using context path /internal-connector any - accepting any virtual host provided Based on the /internal-connector and the port 31415 I'd say this is a temporary directory from the MATLAB project. If you happen to be building MATLAB (or related projects related to MATLAB) these directories might also be coming from the actual testcases of those projects you are building.
{ "pile_set_name": "StackExchange" }
Q: Can I use multiparty for a single route in my express app? I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible? A: You can supply middleware to a single route by doing this: var multipartyMiddleware = function (req,res,next){ //put your code to parse multipart here and call "next" when done } app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){ //do normal business logic in this route and send the response }) If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this: app.use(express.bodyParser()) with this: app.use(express.json()) app.use(express.urlencoded()) This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded. see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54
{ "pile_set_name": "StackExchange" }
Q: ducttape sometimes-skip task: cross-product error I'm trying a variant of sometimes-skip tasks for ducttape, based on the tutorial here: http://nschneid.github.io/ducttape-crash-course/tutorial5.html ([ducttape][1] is a Bash/Scala based workflow management tool.) I'm trying to do a cross-product to execute task1 on "clean" data and "dirty" data. The idea is to traverse the same path, but without preprocessing in some cases. To do this, I need to do a cross-product of tasks. task cleanup < in=(Dirty: a=data/a b=data/b) > out { prefix=$(cat $in) echo "$prefix-clean" > $out } global { data=(Data: dirty=(Dirty: a=data/a b=data/b) clean=(Clean: a=$out@cleanup b=$out@cleanup)) } task task1 < in=$data > out { cat $in > $out } plan FinalTasks { reach task1 via (Dirty: *) * (Data: *) * (Clean: *) } Here is the execution plan. I would expect 6 tasks, but I have two duplicate tasks being executed. $ ducttape skip.tape ducttape 0.3 by Jonathan Clark Loading workflow version history... Have 7 previous workflow versions Finding hyperpaths contained in plan... Found 8 vertices implied by realization plan FinalTasks Union of all planned vertices has size 8 Checking for completed tasks from versions 1 through 7... Finding packages... Found 0 packages Checking for already built packages (if this takes a long time, consider switching to a local-disk git clone instead of a remote repository)... Checking inputs... Work plan (depth-first traversal): RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./cleanup/Baseline.baseline (Dirty.a) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./cleanup/Dirty.b (Dirty.b) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Baseline.baseline (Data.dirty+Dirty.a) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Dirty.b (Data.dirty+Dirty.b) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Clean.b+Data.clean+Dirty.b (Clean.b+Data.clean+Dirty.b) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Data.clean+Dirty.b (Clean.a+Data.clean+Dirty.b) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Data.clean (Clean.a+Data.clean+Dirty.a) RUN: /nfsmnt/hltfs0/data/nicruiz/slt/IWSLT13/analysis/workflow/tmp/./task1/Clean.b+Data.clean (Clean.b+Data.clean+Dirty.a) Are you sure you want to run these 8 tasks? [y/n] Removing the symlinks from the output below, my duplicates are here: $ head task1/*/out ==> Baseline.baseline/out <== 1 ==> Clean.b+Data.clean/out <== 1-clean ==> Data.clean/out <== 1-clean ==> Clean.b+Data.clean+Dirty.b/out <== 2-clean ==> Data.clean+Dirty.b/out <== 2-clean ==> Dirty.b/out <== 2 Could someone with experience with ducttape assist me in finding my cross-product problem? [1]: https://github.com/jhclark/ducttape A: So why do we have 4 realizations involving the branch point Clean at task1 instead of just two? The answer to this question is that the in ducttape branch points are always propagated through all transitive dependencies of a task. So the branch point "Dirty" from the task "cleanup" is propagated through clean=(Clean: a=$out@cleanup b=$out@cleanup). At this point the variable "clean" contains the cross product of the original "Dirty" and the newly-introduced "Clean" branch point. The minimal change to make is to change clean=(Clean: a=$out@cleanup b=$out@cleanup) to clean=$out@cleanup This would give you the desired number of realizations, but it's a bit confusing to use the branch point name "Dirty" just to control which input data set you're using -- with only this minimal change, the two realizations of the task "cleanup" would be (Dirty: a b). It may make your workflow even more grokkable to refactor it like this: global { raw_data=(DataSet: a=data/a b=data/b) } task cleanup < in=$raw_data > out { prefix=$(cat $in) echo "$prefix-clean" > $out } global { ready_data=(DoCleanup: no=$raw_data yes=$out@cleanup) } task task1 < in=$ready_data > out { cat $in > $out } plan FinalTasks { reach task1 via (DataSet: *) * (DoCleanup: *) }
{ "pile_set_name": "StackExchange" }
Q: A spectral theorem for a skew-Hermitian complex matrix Sorry if this is a duplicate, but I tried searching on this but only found results dealing with skew symmetric real matrices. So $A\in\mathbb{C}^{n\times n}$ is called skew-Hermitian if $A^*=-A$. I'm trying to formulate a spectral theorem for these kind of matrices. It is not difficult to see $A$ is normal, thus there exists a $U\in O_n(\mathbb{C})$ such that $U^*AU=\Lambda$, where $\Lambda$ is a diagonal matrix with the eigenvalues of $A$ as its diagonal elements. Also, by quickly writing out, with $(\lambda,v)$ a pair of an eigenvalue and corresponding eigenvector, we see that the inner product $\langle A^*v,v\rangle=\langle v,Av\rangle$ implies $-\overline\lambda=\lambda$ and thus $\mathrm{Re}(\lambda)=0$. It is well known that if $A\in\mathbb{R}^{n\times n}$ is skew symmetric, that all eigenvalues come in pairs, and proofs can be found on this site. However, is this also true for $A\in\mathbb{C}^{n\times n}$ such that $A^*=-A$? Thus is $\lambda$ is an eigenvalue, is $-\lambda$ also an eigenvalue? And if so, how to prove this? I couldn't think of a proof. I'm looking for a hint, proof or a counterexample. A: A skew symmetric matrix (over any field) is a matrix that satisfies $A^\top=-A$. (If the field has characteristic two, some people also require that $A$ has a zero diagonal.) A complex matrix $A$ that satisfies $A^\ast=-A$ is known not as a skew-symmetric matrix, but as a skew-Hermitian matrix. The eigenvalues of a skew-Hermitian matrix do not necessarily occur in pairs. E.g. in the scalar (i.e. $1\times1$) case, $i$ is skew-Hermitian and it is the only eigenvalue of itself. For higher dimensions, consider $\operatorname{diag}(i,2i,\ldots,ni)$ for instance.
{ "pile_set_name": "StackExchange" }
Q: Is there any evidence as to whether the Tardis translation circuits work without power? It occurred to me recently that in the episode "The Doctor's Wife", it was remarkable that the people in that episode continued to understand each other's languages without difficulty even though the TARDIS was completely powered down. I see two ways out of this problem: The TARDIS translation/telepathic circuits operate automatically and continuously, even if the TARDIS itself is powered down. House was providing his own translation for them -- plausible, since he clearly had telepathic control over his inhabitants and had encountered plenty of Time Lords before. (2) is reasonable, but this can't be the first time (1) has been an issue. We know from "The Christmas Invasion" that the TARDIS translation circuits fail if the Doctor is out of commission. But are there any other instances where the TARDIS has been out of commission, but the translation circuits continued to work? (I assume the Doctor himself speaks English fluently.) A: In the classic Doctor Who story 'Masque of Mandragora', the fourth Doctor tells Sarah that translation is a 'Timelord Gift' that he 'allows her to share'. This could possibly suggest that at least some of the translating ability comes via the Doctor himself. This is not entirely unlikely, as we know that he has some telepathic abilities. I'm more of a classic Who fan than of the new stuff, and certainly I've always understood that the power came from the Doctor himself, not from his TARDIS. It's probably worth mentioning that according to the Two Doctors, the Doctor has Symbiotic Nuclei with the TARDIS, so perhaps there's some biological link between the two.
{ "pile_set_name": "StackExchange" }
Q: Hashtable how to get string value without toString() How could I get the string value from a hashtable without calling toString() methode? example: my class: public class myHashT : Hashtable { public myHashT () { } ... public override object this[object key] { get { return base[key].ToString(); <--this doesn't work! } set { base[key] = value; } } } In an other class: myHashT hT; string test = hT["someKey"]; it works with hT["someKey"].toString(); but I need it without calling ToString() and without casting to (string). A: You could use System.Collections.Generic.HashSet. Alternately use composition instead of inheritance ie. have hashtable be your private field and write your own indexer that does ToString(). public class myHashT { public myHashT () { } ... private Hashtable _ht; public string this[object key] { get { return _ht[key].ToString(); } set { _ht[key] = value; } } }
{ "pile_set_name": "StackExchange" }
Q: Use React to build a todo-list, but it has unexpected results This is my practice demo, it's about todo list. You can see, when I confirm a task. It's will be gone, but next task state is checked. How can I fix? Thanks in advance. code: import React, { Component } from 'react'; import InpuText from './component/InpuText'; class Note extends Component { constructor(props) { super(props); this.state = { inputdata: 'no data', noteData: '' } } componentWillMount() { if(localStorage.getItem('note')) { this.setState({ noteData: JSON.parse(localStorage.getItem('note')).details }) } } getInputValue(getValue) { this.setState({ inputdata: getValue }) if(localStorage.getItem('note')) { this.state.noteData.push({ text: getValue }) let note = { details: this.state.noteData } localStorage.setItem('note', JSON.stringify(note)); }else { let note = { details: [] } note.details.push({ text: getValue }) this.setState({ noteData: note.details }) localStorage.setItem('note', JSON.stringify(note)); } } finish(index, e) { console.log(e.target.checked) if(e.target.checked === true) { this.state.noteData.splice(index, 1) this.setState({ noteData: this.state.noteData }) let note = { details: this.state.noteData } localStorage.setItem('note', JSON.stringify(note)); } } render() { return ( <div> notepad <InpuText getInputValue={this.getInputValue.bind(this)}/> {/* <p>input data:{this.state.inputdata}</p> */} <div>todo</div> { this.state.noteData ? <ul> {this.state.noteData.map((notes, i)=>( <li key={i}> {i}:{notes.text} <input type="checkbox" onChange={this.finish.bind(this, i)}/> </li> ))} </ul> : <p>no task</p> } <div>done</div> <ul> <li>123</li> </ul> </div> ); } } export default Note; finish() is handle Array to remove the finish task. A: I think this is due to a couple of things: You use the item's index (i) as the react key. This is bad practice, because the key is not stable. As an example, consider you have three items - their keys would be 0,1,2. Then you mark the middle one as completed, rendering only two items with keys 0 and 1. However these items had keys 0 and 2 respectively during the last render, which generally means that the reconciliation will be messed up. See https://facebook.github.io/react/docs/reconciliation.html for details. In short, the keys need to stay the same between renders. You don't specify any value for the checkbox, therefore it is uncontrolled (https://facebook.github.io/react/docs/uncontrolled-components.html), meaning that it gets checked/unchecked freely as you click on it. These two points together lead to the behavior that you see: you click the item, it gets checked (since the input is uncontrolled), then in the following render it gets reconciled with the wrong item (because of the index-based key). To fix this, don't use collection index as key, use some immutable unique ID from the actual items (if there is no ID, add one). Also, set the checkboxes value prop rather than leaving them uncontrolled. You could e.g. add an isComplete property to every item in the model and set the checkbox value prop to it.
{ "pile_set_name": "StackExchange" }
Q: Retrieving json data from http request in swift I'm new to swift and thus the question. I want to wrap my http calls into a function of this signature. func httpPost()-> Any This code works but how can I wrap this code in the functio signature I want. let headers = [ "Content-Type": "application/json", "cache-control": "no-cache" ] let parameters = [ "client_id": "xxx", "client_secret": "yyy" ] as [String : Any] let postData = try? JSONSerialization.data(withJSONObject: parameters, options: []) var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData let session = URLSession.shared let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in guard let data = data else {return} do{ try validate(response) let json = try JSONSerialization.jsonObject(with: data, options: []) }catch{ print(error) } //print(String(describing: data)) } dataTask.resume() I want to return the json object as Any here A: You can't return a direct value in an asynchronous function until you block the thread which is a bad idea , so you want a completion func httpPost(completion:@escaping(_ ret:Any?,err:Error?) -> Void) let headers = [ "Content-Type": "application/json", "cache-control": "no-cache" ] let parameters = [ "client_id": "xxx", "client_secret": "yyy" ] as [String : Any] let postData = try? JSONSerialization.data(withJSONObject: parameters, options: []) var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData let session = URLSession.shared let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in guard let data = data else { completion(nil,error) return } do{ try validate(response) let json = try JSONSerialization.jsonObject(with: data, options: []) completion(json,nil) }catch{ print(error) completion(nil,error) } //print(String(describing: data)) } dataTask.resume() } To call httpPost { (json,error) in print(json) } also it's better to cast the json as [Any] / [String:Any] for Array/ Dictionary response respectively
{ "pile_set_name": "StackExchange" }
Q: controllers in web frameworks ? [ruby, Grails, etc..] How do they work? So the thing that I want to do is direct the login page to the admin page(e.g: "admin.gsp") if username "admin" is entered and password "pass" is entered. or direct it to the user page if username "user" and password "pass" is entered However I do not understand how exactly controller works. So when you redirect the page to a specific controller and specific method, how do you make it redirect it to a specific page. What code do you implement inside that method ? to explain my question better. Below we have the code for controller User, with an if else statement depending on what the user typed in the login boxes. package file_download class UserController { def index() { //code that directs the page to username page, let's call it or user.gsp } def login = { if(params.username == "admin" && params.password == "pass") { session.user = "admin" redirect(controller:"admin",action:"admin") } else if(params.username == "user" && params.password == "pass") { session.user="user" redirect(controller:"user",action:"index") } else { flash.message = "login failed" } redirect(controller:"user",action:"login") } def logout = { session.user = null redirect(action: 'index') } } now here, we have the admin controller, with the action index, that should have a code implemented to direct the page to... admin.gsp, or admin.html, watever the admin page is called package file_download class AdminController { def index() { //code that takes us to admin page let's call it admin.gsp } } How do we exactly do that ? I need a little bit of an explanation on controllers. Thank you. Please ask if you need more clarification on the question as I will edit it. A: I think you are having wrong assumptions. In Grails (I don't know rails) when you go to the login page, let's say /app/user/login then, at FIRST the controller method is being called (def login()), so your logic shouldn't go there, it should actually do nothing and by convention it will end up rendering login.gsp. Next, your user fills in his username/pass and submits form, there goes the second request let's say to /app/user/auhtenticate and here's where your logic should go and the redirects will work as you expect So basically - controller method is called first and (unless you specify gsp to be rendered or do a redirect) after the method is executed, the gsp view is being rendered
{ "pile_set_name": "StackExchange" }
Q: How to use decodable protocol with custom type values in Swift? I have 2 types of response depending on my reuest: First one: { "status": "success" "data": { "user_id": 2, "user_name": "John" } } And second one is: { "status": "error", "data": [], } I am using struct like that: struct ValyutaListData:Decodable { let status: String? let data: [String]? } But if response is first type response, then an error occured. Because In first Type response data is not array. It is Json object. Then i use structure like that: struct ValyutaListData:Decodable { let status: String? let data: Persondata? } struct Persondata: Decodable{ let user_id: Int? let user_name: String? } If response is second type response, the error will be occured. What kind of of structure should use for dynamic type JSONs? Thanks. A: One reasonable solution is an enum with associated type(s) struct User : Decodable { let userId: Int let userName: String } enum Result : Decodable { case success(User), failure enum CodingKeys: String, CodingKey { case status, data } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let status = try container.decode(String.self, forKey: .status) if status == "success" { let userData = try container.decode(User.self, forKey: .data) self = .success(userData) } else { self = .failure } } } And use it do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let result = try decoder.decode(Result.self, from: data) switch result { case .success(let user): print(user) case .failure: print("An error occurred") } } catch { print(error) }
{ "pile_set_name": "StackExchange" }
Q: Add view to the top view controller Im trying to add a UIView to the UIView that is currently showing. This is the code I've come up with: UIWindow *window = [UIApplication sharedApplication].keyWindow; UINavigationController *nav = window.rootViewController; UIViewController *viewController = [[nav viewControllers]lastObject]; NSLog(@"La clase: %@", [viewController class]); [viewController.view addSubview:self.infoMsg]; The problem is that I dont see that UIView, the value of the variable viewController is correct, but I don't see the view added on that view... Thanks [EDIT] I just checked and If for example instead of add as a subview infoMsg which is a UIView that I have syntesized, and I add a UIView that I create just before adding it adds correctly why is that? why can't I add an attribute of my object? A: You have to still create the view before adding it, no matter if it's a property or just a local variable. I don't see where you initialize self.infoMsg. It's probably nil. Try this: NSLog(@"%@", self.infoMsg == nil ? @"It's nil" : @"It's not nil"); If it's nil, that that's your problem.
{ "pile_set_name": "StackExchange" }
Q: Two players combine to stop the third A game is played on a $100\times 100$ board between three players, $A$, $B$, and $C$, in this order. Each turn, the player must paint a cell adjacent to (at least) one of the sides of the board. The player cannot paint a cell adjacent to a painted cell, or a cell symmetric to a painted cell with respect to the center of the board. The player who cannot paint loses. Can $B$ and $C$ combine to make $A$ lose? My thought is that $B$ and $C$ could combine by, supposing there is an $x$- and $y$-axis with the center of the board as the origin, having $B$ paint the cell symmetric to what $A$ painted with respect to the $x$-axis, and similarly for $C$ and the $y$-axis. This would make $A$ lose because $A$ cannot paint the cell symmetric with respect to the origin. But the strategy doesn't work, because if $A$ paints a cell adjacent to an axis, the cell on the other side of the axis adjacent to it cannot be painted. A: Hint: The problem was misleading you by presenting the game on a rectangular board, causing you to look for rectangular symmetries. Really, the game is just being played on a ring of 396 cells, where each cell is adjacent to its neighbors and its opposite. Since 396 is a multiple of 3, this ring has trilateral symmetry, which is more helpful since this is a three player game. Please have another go using this hint, the solution is rather beautiful and satisfying to find.
{ "pile_set_name": "StackExchange" }
Q: PHP - empty $_POST and $_FILES - when uploading larger files I have a following problem, I have HTML form that uploads a file with some extra information. But it allows to upload files that only less then 10MB. But when user tries to upload something bigger, both $_POST and $_FILES array are empty (I expected that $_POST will have some values and $_FILES will have some values but will indicate that there is an upload error). There is a few questions (empty $_POST, $_FILES) like that, but I didn't find any solution, or explanation for it. HTML form: <form enctype="multipart/form-data" method="post" action="upload.php"> <p> <input type="hidden" name="MAX_FILE_SIZE" value="10000000" /> <input type="file" name="image" /> </p> <p> <input type="text" name="other_field" /> </p> </form> upload.php print_r($_POST); // array() print_r($_FILES); // array() exit; It works fine, if file size is under 10MB (file size limit is 10MB), and I don't want to increase it, I just want to capture an error in PHP. Updated (explanation/solution) from PHP site From PHP site (I missed this section): http://us.php.net/manual/en/ini.core.php#ini.post-max-size Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. , and then checking if $_GET['processed'] is set. A: As noted in the edited question $_POST and $_FILES are empty when PHP silently discards data (happens when the actual data is bigger than post_max_size). Since HTTP header and $_GET remain intact those can be used to detect the discards. Option a) if(intval($_SERVER['CONTENT_LENGTH'])>0 && count($_POST)===0){ throw new Exception('PHP discarded POST data because of request exceeding post_max_size.'); } Option b) Add a GET parameter that tells whether POST data is present. A: Run phpinfo() and check to make sure your upload_max_filesize and post_max_size directives are large enough. http://us.php.net/manual/en/ini.core.php#ini.upload-max-filesize http://us.php.net/manual/en/ini.core.php#ini.post-max-size
{ "pile_set_name": "StackExchange" }
Q: Как правильно произвести инициализацию драйвера SQLITE JDBC в JAVA Не могу никак подключить драйвер JDBC. Выходит сообщение о том, что не нашел класс. Хотя в зависимости все нормально, GRADLE сам скачал библиотеку. Что делать ума не приложу. ![Код][1] ![Зависимость][2] ![Зависимость][3] A: Проблема скорее всего в том, что ваш sqlite-jdbc не находится в classpath. Откройте структуру проекта (Ctrl + Shift + Alt + S), там перейдите в Artifacts. В папке WEB-INF создайте папку lib и туда положите библиотеку sqlite-jdbc. Теперь она будет в classpath. Пример (изображение) Также рекомендую регистрировать драйвер следующим способом: DriverManager.registerDriver(new Driver()); Где new Driver() - именно тот SQLite драйвер. При использовании этого способа регистрации драйвера, у вас не будет ошибки на уровне выполнения программы, только на уровне компиляции, что более эффективно.
{ "pile_set_name": "StackExchange" }
Q: Protractor: How to use browser.sleep inside of element.all(locator).each(eachFunction) Expecting: elem[0] text to print, sleep, elem[1] text to print, sleep, etc... Actual: is printing out the text for each element then executing browser.sleep once at the end. Once I get this working I would like to actually click on each link and assert a corresponding profile page is loaded. I should also mention that I have SELENIUM_PROMISE_MANAGER: false and am using mocha describe.only('clicking each user in the list', () => { it('should display the correct profile page', async () => { await element.all(by.repeater('user in currentNode.children')).each(async (elem)=> { console.log(await elem.getText()) await browser.sleep(5000) }); }) }); A: Looks like this did the trick describe.only('clicking each user in the list', () => { it('should display the correct profile page', async () => { const elements = await element.all(by.repeater('user in currentNode.children')); for (const element of elements) { const text = await element.getText() await browser.sleep(1000) console.log(text) }
{ "pile_set_name": "StackExchange" }
Q: AWS Lambda - Is it possible to restrict an IAM role to create functions with a particular prefix? I'm adding an IAM role for a SaaS vendor, who has read-only access except for the ability to create Lambda functions. Initially they requested a broad set of permissions for Lambda: "Statement": [ { "Action": [ "lambda:CreateFunction", "lambda:DeleteFunction", "lambda:InvokeFunction", "lambda:UpdateFunctionCode", "lambda:UpdateFunctionConfiguration" ], "Effect": "Allow", "Resource": "*" }, I am uncomfortable with allowing this kind of access over resources they don't own, i.e. our business-critical functions. When I raised this with them, they said that all their functions will be prefixed with their company name (e.g. company_prefix), so I thought I might be able to do this: ... "Resource": "arn:aws:lambda::<account>:function:company_prefix*" ... But reviewing the policy in the console editor suggests a problem: Is this not going to work? Is it possible to restrict Lambda function permissions in this way? A: Yes, IAM does support resource-level permissions for Lambda. I tested a variant of your policy on a new IAM user. For Lambda function names matching the wildcard, I was successful. For non-matching function names I got AccessDeniedException. I did not test all the listed Lambda actions (just GetFunctionConfiguration because it was simple to test) so please test that this does what you need. Note: when you test this you will need to be patient as IAM policy changes do not always take effect immediately.
{ "pile_set_name": "StackExchange" }
Q: SQL: how do i order by a field if its not null else use another field i want to sort my Posts by dtModified (datetime modified) if its not null (post modified b4), else sort by dtPosted (datetime posted) A: You can use COALESCE: ORDER BY COALESCE(dtModified, dtPosted) Another option is to use the MySQL specific function IFNULL instead of COALESCE. Testing on MySQL: CREATE TABLE table1 (dtModified DATETIME NULL, dtPosted DATETIME NOT NULL); INSERT INTO table1 (dtModified, dtPosted) VALUES ('2010-07-31 10:00:00', '2010-07-30 10:00:00'), (NULL , '2010-07-31 09:00:00'), ('2010-07-31 08:00:00', '2010-07-30 10:00:00'); SELECT dtModified, dtPosted FROM table1 ORDER BY COALESCE(dtModified, dtPosted) Results: dtModified dtPosted 2010-07-31 08:00:00 2010-07-30 10:00:00 NULL 2010-07-31 09:00:00 2010-07-31 10:00:00 2010-07-30 10:00:00 A: It seems like I'm giving this advice three times a week here on SO, maybe I should just give up and let it go :-) Nah, I don't think so: Don't use per-row functions in your column calculations (or order by clauses) if you want your database to scale well. You should check performance for your particular case (measure, don't guess) but doing calculations when reading the database will generally affect your ability to scale (this won't matter for your address book database but the shops I work in have huge amounts of data). The number of "how do I get my DB to go faster?" questions far outweighs the number of "how do I use less space?" ones. It's a well-trodden path to sacrifice disk space for performance. The right time to do calculations is when the data changes. That way the cost of the changes is amortised across all reads. My advice is to create another column such as dtLastAction to contain the ordering value then use an insert/update trigger to set it to the same as dtModified if not null, or dtPosted if dtModified is null. Technically, this violates 3NF but that's okay if you know what you're doing, and the triggers guarantee data consistency in that case. Then index on the dtLastAction column and see the speed of your queries improve at the (lesser) cost of some extra work during inserts and updates. I say lesser because the vast majority of database tables are read more often than written (obviously this method is useless if your particular situation is one of the very rare exceptions). Alternatively, for this particular case, you could set dtModified and dtPosted to the same value when creating the entry, meaning that dtModified will never be null. You can still detect posts that have never been modified by the fact that these two datetime values are identical.
{ "pile_set_name": "StackExchange" }
Q: Doping and inter plane coupling for cuprates I'm not very familiar with high-Tc and I have naive questions on cuprates materials (CuO2). It seems common that everyone treats it as a 2D material for good reasons: in undoped system, there are two outer-shell electrons bond with oxygen atoms, which is a Mott-insulator. And people have derived the effective hamiltonian of antiferromagnet (AFM) for Mott-insulator $H = J \sum_{<ij>} S_i \cdot S_j$ as interactions within the plane. My questions: 1) If we increase the doping, how does the hopping strength $t$ and $U$ change in the Mott insulator picture? Is the effective spin hamiltonian still valid in certain 2D regions? My naive picture is wherever there is doping atom, there is no such interaction near that doped region. But I could imagine, $t$ and $U$ change completely and our perturbation theory for AFM doesnt work anymore. 2) Is there any coupling between the planes? (I know it seems two electrons are out of option for bonding. But maybe there are other effective and weaker coupling?) A: First question 1) If we increase the doping, how does the hopping strength t and U change in the Mott insulator picture? Is the effective spin hamiltonian still valid in certain 2D regions? My naive picture is wherever there is doping atom, there is no such interaction near that doped region. But I could imagine, t and U change completely and our perturbation theory for AFM does'nt work anymore. parameters and filling There are two different concepts: model and filling. First of all, what you said about $t$ and $U$ is "Hubbard model", $$H=-t\sum_{i,j}c_i^\dagger c_j+h.c.+\sum_i Un_{i,\uparrow}n_{i,\downarrow}$$ which describes interacting electrons with Hilbert space for each site: empty, single occupation, double occupation. And $U$ is just the energy cost for double occupation. Most important point is such model can describe system both strong coupling (large-U) and weak coupling (large-U), both half-filling and doping. And the choosing parameters and filling is independent. In the other words, we can let the system keep strong coupling(large $U$ and small $t$), but changes its filling (e.g. from half-filling to only single electron). Effective model However, the independent of filling and parameters is correct just for the Hubbard model, including both spin fluctuation and charge fluctuation. The standard paradigm in condensed matter theory is to derive low-energy effective model since most of time we only care about low-temperature physics, i.e. high-energy states is hard to be excited at low-temperature, so that we can project out these high-energy states to obtain an "effective model" with smaller Hilbert space, which can only describe the low-energy physics. However, the projection depends on both parameters and filling. In details, if we only consider the strong coupling (i.e. cuprates are actually the typical case for strong coupling, large-$U$), the high-energy states are those with double occupation due to large-$U$ cost so that we need to project them. For half-filling, such projection means every electrons should stay at its sites and can not hopping since hopping will always connect single occupation with double occupation for hal-filling, which is so-called "Mott insulator". For this phase(actually the parent of cuprates), systems only contains spin interaction, thus we can write an effective model including only spin-exchange interaction: $$H=J \sum_{<i j>} S_{i} \cdot S_{j}$$ But as you said, when we dope the "Mott insulator", the hopping electrons/holes actually can hop so that we need to add back the kinetic term, i.e. $-t\sum_{i,j}c_i^\dagger c_i +h.c.$ . However, such process is not trivial since the projection also introduce the non-double occupation constraints, so that the resulting effective Hamiltonian now is: $$H=P_s(-t\sum_{i,j}c_i^\dagger c_i) P_s+h.c.+J \sum_{<i j>} S_{i} \cdot S_{j}$$ where $P_s$ is non-double occupation constraints: $$n_{i\uparrow}+n_{i\downarrow}\leq1$$ but after all, when you dope the Mott insulator, the kinetic part(change fluctuation) will be partially restore. Also, the parameters $J$ depends on both $t$ and $U$: $$J=-\frac{t^2}{U}$$ This new model is called "t-J" model, if you are interested in the details for projection from Hubbard model to t-J model, Ch.3. Auerbach, Interacting electrons and quantum magnetism is a good reference. So, answer your first question in one sentence: when you increase dopping, $t$ and $U$ don't change, spin-exchange interaction remains but there also exist an additional partially hopping terms, where the projection in this term is highly affected by the number of dope. Supplement The goal of non-double occupation is to project out the high-energy sector. But this constraint is just apparent for hole-doping system (i.e. number of electrons smaller than half-filling) since we know the high-energy sector is just the states with double-occupation: But for electron-doping system, this picture and the form of constraint seems strange since there always exists double-occupation states. To unify this problem, it is important to note that the "high-energy" is relative, and the "lowest" states for such system is: first add one electron in each site, then put the additional electrons in the double-occupation states. In the other words, there exists at least one electron in each site. Thus, the high-energy sector is the states which contains at least one site without any electrons(at least one empty site). Now, the constraint can be considered as : $$n_{i\uparrow}+n_{i\downarrow}\geq1$$ Second Question Is there any coupling between the planes? (I know it seems two electrons are out of option for bonding. But maybe there are other effective and weaker coupling?) Yes, there exists some other coupling, like phonon. And, there also exist spin-exchange interaction between layers.
{ "pile_set_name": "StackExchange" }
Q: How does Steam decide when to update my games? I have a few game updates automatically scheduled on Steam. What I don't get is how Steam decides when to update a game. The scheduled updates range from tonight at 3AM, Wednesday at 2:35 to 8th of July at 1:30. Is there any information as to how Steam prioritizes updates? And if so, is it possible for me to add a global schedule for downloads (let's say, start updates for everything on Thursdays at 3 o'clock)? I'm aware that there are settings for individual games but just having everything ready to go at a certain time would be really useful. Also, knowing how it prioritizes which game to update first would be good information to have. A: Sadly for now there is no auto-update for each specific day. If you would like to do this then you will do the following: You will have to go to Steam section above STORE and then hover over it. Then you will find the settings and then you will have to edit the auto-update time for (num)AM-(num)AM. Then you will set the time and save the settings, after that You can remove the check mark in the days you don't want to update games in.. You will manually do this.. Also don't worry it will save the update time so the next day you will just go to the same download settings and add the check mark again Also for prioritizing you will have to go to the library, click that gear icon in the selected game you want to prioritize, and then Choose properties. Then go to updates and choose from dropdown menu: High Priority - Always update this game before others, Choose it and it's done. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Move multiple images on a page in different directions I have multiple images on a page that are loaded dynamically using PHP. I want them to all move in different directions across the screen. So far what I have, the images move in a random direction but all in the same position. PHP: <?php foreach($logos as $logo) { $logoName = $logo['Logo_Link']; ?> <img class="imglogo" src="images/<?php echo $logoName ?>" /> <?php } ?> JS: $(document).ready(function() { animateDiv(); }); function makeNewPosition($container) { // Get viewport dimensions (remove the dimension of the div) $container = ($container || $(window)); var h = $container.height() - 50; var w = $container.width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh, nw]; } function animateDiv() { var $target = $('.imglogo'); var newq = makeNewPosition($target.parent()); var oldq = $target.offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $('.imglogo').animate({ top: newq[0], left: newq[1] }, speed, function() { animateDiv(); }); } function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest / speedModifier); return speed; } A: I just made a loop in the animateDiv function animateDiv(); function makeNewPosition($container) { // Get viewport dimensions (remove the dimension of the div) $container = ($container || $(window)); var h = $container.height() - 50; var w = $container.width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh, nw]; } function animateDiv() { var $target = $('.imglogo'); for(let i=0; i<$target.length; i++){ var newq = makeNewPosition($($target[0]).parent()); var oldq = $($target[0]).offset(); var speed = calcSpeed([oldq.top, oldq.left], newq); $($('.imglogo')[i]).animate({ top: newq[0], left: newq[1] }, speed, function() { animateDiv(); }); } } function calcSpeed(prev, next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest / speedModifier); return speed; } .imglogo{ width: 40px; height: 40px; background-color: blue; position: relative; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="imglogo"></div> <div class="imglogo"></div> <div class="imglogo"></div> <div class="imglogo"></div> <div class="imglogo"></div> <div class="imglogo"></div> <div class="imglogo"></div>
{ "pile_set_name": "StackExchange" }
Q: MySQL: Table name with UTF characters I'm having a hard time creating a table in MySQL with UTF characters. I am completely lost on how to solve this one. There's only two special characters in this particular table name: 1F4D2 LEDGER (http://www.unicode.org/charts/PDF/U1F300.pdf) 274E ❎ NEGATIVE SQUARED CROSS MARK (http://www.unicode.org/charts/PDF/U2700.pdf) Code: CREATE TABLE `_❎` (id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT); Message: Invalid utf8 character string: '_❎' This works, however: SELECT _utf8'_❎' A: Take a look at the following page: http://dev.mysql.com/doc/refman/5.1/en/identifiers.html The problematic char is 1F4D2, as the documentation states: Permitted characters in quoted identifiers include the full Unicode Basic Multilingual Plane (BMP), except U+0000: ASCII: U+0001 .. U+007F Extended: U+0080 .. U+FFFF ASCII NUL (U+0000) and supplementary characters (U+10000 and higher) are not permitted in quoted or unquoted identifiers. A: If you're using MySQL 5.5.3 or later I would set your character set to utf8mb4
{ "pile_set_name": "StackExchange" }
Q: What are the parameters pass onto fn in ExtJS? Here is the definition of prompt in ExtJS: Ext.window.MessageBox.prompt( title, msg, [fn], [scope], [multiline], [value] ). It is clear that fn is a function. But I'm always confused what parameters will be passed onto the fn. How can I find it out? A: It's in the docs, scroll down to the fn parameter: http://docs.sencha.com/ext-js/4-1/#!/api/Ext.window.MessageBox-method-show Parameters buttonId : String The ID of the button pressed, one of: ok yes no cancel text : String Value of the input field if either prompt or multiline is true opt : Object The config object passed to show.
{ "pile_set_name": "StackExchange" }
Q: Mosfet amp spike in SPICE when connecting power When powering this circuit I get a 150 microsecond rush of current at 120 amps. Is this a real issue with mosfets? Additional info: I've been playing with N and P channel slow start mosfet circuits and on some of the P channel ones I get spikes just like that if my resistors are in certain ranges. I stripped this one down and really expected it to not have a spike in this configuration. A: The inrush current is mostly due to the 500uF cap you have. If you downsize it (or add some series resistance to it), you will see the current spike go down. Whether or not this is an issue depends on what the datasheet says—there's a pulsed current maximum spec. Also, the reason your mosfet is conducting—as shown in the schematic—is because of the body diode. This is an N-channel mosfet so you'd need a voltage at the gate such that \$V_{GS}\$ is high enough to turn it on. This means \$V_G\$ needs to be greater than supply voltage you connected directly at the nmos' source. The mosfet is off in the shown configuration (gate is grounded) but the body diode is forward biased. If this is a high side switch application so a pmos is an easier choice.
{ "pile_set_name": "StackExchange" }
Q: How to play video file in jmeter I have wordpress site with video player(JW player). I want to load test using jmeter. But i dont know how to do that? A: JMeter doesn't act like a browser hence it won't "play" the video via JWPlayer. If you need to check whether your wordpress deployment will be able to serve video content and the video content itself is being hosted by you it is possible to simulate hundreds and thousands of users which are downloading videos. If you look into wordpress page source you will see something like <span class="jwvideo" id="hero-video_media" style="opacity: 1; visibility: visible;"> <video x-webkit-airplay="allow" webkit-playsinline="" src="https://content.jwplatform.com/videos/XjiIpRcb-1080.mp4"></video> </span> You're interested in https://content.jwplatform.com/videos/XjiIpRcb-1080.mp4 bit as this is the URL of the video file. You can easily get the URL with the XPath Extractor using the following query: //video/@src And use simple HTTP Request sampler to simulate video download.
{ "pile_set_name": "StackExchange" }
Q: Linq to objects - Search collection with value from other collection I've tried to search SO for solutions and questions that could be similar to my case. I got 2 collections of objects: public class BRSDocument { public string IdentifierValue { get; set;} } public class BRSMetadata { public string Value { get; set;} } I fill the list from my datalayer: List<BRSDocument> colBRSDocuments = Common.Instance.GetBRSDocuments(); List<BRSMetadata> colBRSMetadata = Common.Instance.GetMessageBRSMetadata(); I now want to find that one object in colBRSDocuments where x.IdentifierValue is equal to the one object in colBRSMetadata y.Value. I just need to find the BRSDocument that matches a value from the BRSMetadata objects. I used a ordinary foreach loop and a simple linq search to find the data and break when the value is found. I'm wondering if the search can be done completely with linq? foreach (var item in colBRSMetadata) { BRSDocument res = colBRSDocuments.FirstOrDefault(x => x.IdentifierValue == item.Value); if (res != null) { //Do work break; } } Hope that some of you guys can push me in the right direction... A: Why not do a join? var docs = from d in colBRSDocuments join m in colBRSMetadata on d.IdentiferValue equals m.Value select d; If there's only meant to be one then you can do: var doc = docs.Single(); // will throw if there is not exactly one element If you want to return both objects, then you can do the following: var docsAndData = from d in colBRSDocuments join m in colBRSMetadata on d.IdentiferValue equals m.Value select new { Doc = d, Data = m }; then you can access like: foreach (var dd in docsAndData) { // dd.Doc // dd.Data }
{ "pile_set_name": "StackExchange" }
Q: Using a macro to create new function LookUpConcat but it crashes I need to join text from cells together into one cell. I found this macro which was written sometime ago, which may be my problem, that creates a new function in excel called LookUpConcat. The first time I copied it into my VBA and create the formula =LookUpConcat($B$2,Usage!$AA$2:$AA$5000,$AG$2:$AG$5000," ") it seemed to worked great. Then it start crashing and giving me a #NAME error, so I started fresh. Now it says it has a compile error at each of the = signs in the beginning. (String = " ", Boolean = True,....) Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRange As Range, _ Delimiter As String = " " , MatchWhole As Boolean = True, _ UniqueOnly As Boolean = False, MatchCase As Boolean = False) Dim X As Long, CellVal As String, ReturnVal As String, Result As String If (SearchRange.Rows.Count > 1 And SearchRange.Columns.Count > 1) Or _ (ReturnRange.Rows.Count > 1 And ReturnRange.Columns.Count > 1) Then LookUpConcat = CVErr(xlErrRef) Else If Not MatchCase Then SearchString = UCase(SearchString) For X = 1 To SearchRange.Count If MatchCase Then CellVal = SearchRange(X).Value Else CellVal = UCase(SearchRange(X).Value) End If ReturnVal = ReturnRange(X).Value If MatchWhole And CellVal = SearchString Then If UniqueOnly And InStr(Result & Delimiter, Delimiter & ReturnVal & Delimiter) > 0 Then GoTo Continue Result = Result & Delimiter & ReturnVal ElseIf Not MatchWhole And CellVal Like "*" & SearchString & "*" Then If UniqueOnly And InStr(Result & Delimiter, Delimiter & ReturnVal & Delimiter) > 0 Then GoTo Continue Result = Result & Delimiter & ReturnVal End If Continue: Next LookUpConcat = Mid(Result, Len(Delimiter) + 1) A: Those equals signs you reference are designating default values for those parameters in case you pass nothing to the function for that variable. Excel doesn't want you to assign a default value without explicitly declaring those parameters as optional. Change the following line: Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRange As Range, _ Delimiter As String = " " , MatchWhole As Boolean = True, _ UniqueOnly As Boolean = False, MatchCase As Boolean = False) To: Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRang As Range, _ Optional Delimiter As String = " ", Optional MatchWhole As Boolean = True, _ Optional UniqueOnly As Boolean = False, Optional MatchCase As Boolean = False) Can I assume you have an End If followed by an End Function after this code?? After those changes, it compiles on my machine.
{ "pile_set_name": "StackExchange" }
Q: Can you use GlVertexAttribPointer without shaders According to the following wiki page: OpenGL Wiki Page It says "One of the requirements is to use shaders.". Is this true? To use GlVertexAttribPointer do I have to use shaders? I'm just starting out in OpenGL and just want to keep things simple for now, without having to introduce shaders at such an early stage of development. I will be using GLSL eventually, but want to get each feature "working" before adding any new features to my code. Thanks A: Yes, it's true, you need shaders to use generic vertex attributes, if not, how would OpenGL know that attribute 0 is normals, 1 is position and 2 is texture coordinates? There is no API for doing that in the Fixed Function pipeline. It might work, but that's just luck, not defined behaviour.
{ "pile_set_name": "StackExchange" }
Q: SQL return both table rows separately I have two tables and want to return both table's rows. Both tables do not have any relation. Table 1 has columns userid, name, and other columns... and Table 2 has only two columns id, name. I want both table results in one query result set. Table results: userid name and other columns from Table 1. id name and NULL, NULL should show as Table 2 do not have extra columns. A: Use a union select userid, name, col1, col2, col3 from table1 union all select id, name, null, null, null from table2
{ "pile_set_name": "StackExchange" }
Q: File get contents and string replace for multiple files I have a number of files, alpha.php, beta.php and gamma.php in a folder named test. I need to get the contents of these three files and and replace a string in them with another string. To replace everything in the folder, this worked: foreach (new DirectoryIterator('./test') as $folder) { if ($folder->getExtension() === 'php') { $file = file_get_contents($folder->getPathname()); if(strpos($file, "Hello You") !== false){ echo "Already Replaced"; } else { $str=str_replace("Go Away", "Hello You",$file); file_put_contents($folder->getPathname(), $str); echo "done"; } } } But I don't want to process all the files in the folder. I just want to get the 3 files: alpha.php, beta.php and gamma.php and process them. Is there a way I can do this or I have to just get the files individually and process them individually? Thanks. A: Just foreach what you want: foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) { $file = file_get_contents("./test/$filename"); if(strpos($file, "Hello You") !== false){ echo "Already Replaced"; } else { $str = str_replace("Go Away", "Hello You", $file); file_put_contents("./test/$filename", $str); echo "done"; } } You don't need the if unless you really need the echos to see when there are replacements: foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) { $file = file_get_contents("./test/$filename"); $str = str_replace("Go Away", "Hello You", $file); file_put_contents("./test/$filename", $str); } Or you can get the count of replacements: $str = str_replace("Go Away", "Hello You", $file, $count); if($count) { file_put_contents("./test/$filename", $str); } On Linux you could also try exec or something with replace or repl as they accept multiple files.
{ "pile_set_name": "StackExchange" }
Q: Python regex matching all but last occurrence So I have expression such as "./folder/thisisa.test/file.cxx.h" How do I substitute/remove all the "." but the last dot? A: To match all but the last dot with a regex: '\.(?=[^.]*\.)' Using a lookahead to check that's there another dot after the one we found (the lookahead's not part of the match).
{ "pile_set_name": "StackExchange" }
Q: Set a default value in a decimal column How do you set a default value in a decimal column in Rails? I've tried both the following, using Rails 3 and Postgresql, but after each one the console tells me the default values are still nil. If I set the value from the console, there's no problem, but it doesn't seem to work in the migration. #Attempt 1 add_column :providers, :commission, :decimal, :precision=>6,:scale=>4,:default=>0.1 and #Attempt 2 add_column :providers, :commission, :decimal, :precision=>6,:scale=>4,:default=>BigDecimal("0.1") Many thanks for your help! A: It turns out I also need to set :null=>false The following code worked: add_column :providers, :commission, :decimal, :precision=>6,:scale=>4,:default=>0.1, :null => false
{ "pile_set_name": "StackExchange" }
Q: Linux - grep to exclude all words in front searched pattern For example, whey I type: grep Eth test.sh I will get Summary: Ethernet settings tool for PCI ethernet cards Say if I only need my searched pattern and exlucde all words ahead Ethernet settings tool for PCI ethernet cards How can I do this in grep? A: With GNU grep: grep -Po '\KEth.*' test.sh Output: Ethernet settings tool for PCI ethernet cards
{ "pile_set_name": "StackExchange" }
Q: how to change primary node on mongo replica set without losing cursor Today, the primary machine's loading is extremely high on a replica set. Users complain about query/insert operations are very slow. So I tried to change the priority of node to make secondary/primary exchanged: cfg = rs.conf() cfg.members[0].priority = 1 cfg.members[1].priority = 0.5 rs.reconfig(cfg) Then, 2 users complained about their program get exception from running cursor lost. Is there any way to avoid the running cursor lost when primary node changed? A: As at MongoDB 3.4, when a primary transitions to a non-primary state (eg. as the result of an election) all active connections are dropped so they can be re-established on the new primary. Cursor state is specific to a given mongod, so you cannot resume a cursor on a different member of the replica set. A recommended area to investigate would be why your primary was heavily loaded and why a change in primary would have reduced the load significantly. Generally electable secondaries in the same replica set should be identically provisioned in terms of hardware resources, so exchanging server roles should have pushed similar load onto the new primary. If the load was coming from suboptimal queries that were terminated on the former primary (or due to other resource contention), you could perhaps have avoided reconfiguring your replica set by finding and addressing the root cause. The MongoDB manual has some information on how to Evaluate Performance of Current Operations. You should also implement a monitoring solution (if you haven't already) in order to capture a baseline of normal activity and help identify metrics that change significantly when your deployment is under load. If you have long running queries which are likely to be interrupted by a restart you could consider: Adding some logic to your application to restart the query using criteria from the last document seen while iterating. Using secondary reads for these queries if your use case can tolerate eventual consistency. Before doing so, it's worth reading Can I use more replica nodes to scale?.
{ "pile_set_name": "StackExchange" }
Q: 2 Timers start simultaniously - VB.Net i have been trying to make LolTimer but that does not matter. For some reason when i click btnStartDragon both timers start running. If i click the btnStartBaron, this only starts the BaronTimer. I hope you can help me with this code(its in vb.Net): Public Class Loltimer 'Dragon Timer----------------------------------------------------------------------------------------------------------------------------------- Private Sub Loltimer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Timers Timer1.Interval = 1000 '// tick every second. '// textbox1 = Hours, textbox2 = Minutes, textbox3 = Seconds txtDragMin.Text = "6" : txtDragSec.Text = "00" Timer2.Interval = 1000 '// tick every second. '// textbox1 = Hours, textbox2 = Minutes, textbox3 = Seconds txtBaronMin.Text = "6" : txtBaronSec.Text = "00" End Sub Private Sub btnStartDragon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartDragon.Click 'Start timer If Timer1.Enabled = False Then Timer1.Start() btnStartDragon.Text = "Running" txtDragMin.Visible = True txtDragSec.Visible = True lblDragonSpawn.Visible = False End If End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick If txtDragMin.TextLength < 2 Then txtDragMin.Text = "0" & txtDragMin.Text '// format from "0" to "00" '// verify Minutes. If txtDragMin.Text > "00" And txtDragSec.Text = "00" Then txtDragMin.Text -= 1 txtDragSec.Text = "60" End If If txtDragSec.TextLength < 2 Then txtDragSec.Text = "0" & txtDragSec.Text '// format from "0" to "00" '// verify Seconds. If txtDragSec.Text > "00" Then txtDragSec.Text -= 1 'Spawned If txtDragMin.Text = "00" And txtDragSec.Text = "0" Then Timer1.Enabled = False lblDragonSpawn.Visible = True txtDragMin.Visible = False txtDragSec.Visible = False txtDragMin.Text = "6" : txtDragSec.Text = "00" btnStartDragon.Text = "Start" End If End Sub '-------------------------------------------------------------------------------------------------------------------------------- 'Baron Timer----------------------------------------------------------------------------------------------------------------------------------- Private Sub BtnStartBaron_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStartBaron.Click, btnStartDragon.Click 'Start timer If Timer2.Enabled = False Then Timer2.Start() BtnStartBaron.Text = "Running" txtBaronMin.Visible = True txtBaronSec.Visible = True lblBaronspawn.Visible = False End If End Sub Private Sub timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick If txtBaronMin.TextLength < 2 Then txtBaronMin.Text = "0" & txtBaronMin.Text '// format from "0" to "00" '// verify Minutes. If txtBaronMin.Text > "00" And txtBaronSec.Text = "00" Then txtBaronMin.Text -= 1 txtBaronSec.Text = "60" End If If txtBaronSec.TextLength < 2 Then txtBaronSec.Text = "0" & txtBaronSec.Text '// format from "0" to "00" '// verify Seconds. If txtBaronSec.Text > "00" Then txtBaronSec.Text -= 1 'Spawned If txtBaronMin.Text = "00" And txtBaronSec.Text = "0" Then Timer2.Enabled = False lblBaronspawn.Visible = True txtBaronMin.Visible = False txtBaronSec.Visible = False txtBaronMin.Text = "6" : txtBaronSec.Text = "00" BtnStartBaron.Text = "Start" End If End Sub End Class A: You have too many handlers: Private Sub BtnStartBaron_Click(ByVal sender As Object, ByVal e As EventArgs) _ Handles BtnStartBaron.Click, btnStartDragon.Click Try changing it to: Private Sub BtnStartBaron_Click(ByVal sender As Object, ByVal e As EventArgs) _ Handles BtnStartBaron.Click
{ "pile_set_name": "StackExchange" }
Q: Validators in Spring MVC We use @Min, @Max, @NotNull etc annotations for server side validations in spring MVC.Thses annotations should be place in Model Class.suppose i want to apply such annotations when needed, i dont want to apply such annotations in Model class. For example. I have an class Person with properties Name,Gender,Email. If I put @NotNull annotation on email property then it will get apply globaly, if my requirment get changed like if in my system there are two persons Student and Teacher and for Teacher registration email is optional but for Student its not null then how can i achive this. can i apply validation annotations dynamiclly in case of above example- If UserRegistration is For Teacher Then Email is optional. If UserRegistration is For Student Then Email is Mandatory. A: To achieve this behaviour I suggest to use groups with dynamically activation. Look at my example bellow. Person.java: class Person { @NotNull(groups = StudentChecks.class) @Email private email; // other members with getters/setters public interface StudentChecks { } } In this case @NotNull constraint will be executed only when StudentChecks group is activated. To activate validation group by condition Spring offers special annotation @Validated. StudentController.java: @Controller public class StudentController { @RequestMapping(value = "/students", method = RequestMethod.POST) public String createStudent(@Validated({Person.StudentChecks.class}) Person student, BindingResult result) { // your code } } More details you can find there: Validating groups Javadoc of @Validated annotation
{ "pile_set_name": "StackExchange" }
Q: Pass a parameter to a ViewModel and show its data I have created an application which uses WPF and MVVM following this article from CodeProject. I have a view, TVSeriesView, which has a TVSeriesViewModel. These two are connected using a DataTemplate which is done following the article. <DataTemplate DataType="{x:Type Implementation:TVSeriesViewModel}"> <TVSeriesLibrary:TVSeriesView /> </DataTemplate> The idea is to pass my model, the TVSeries, to this ViewModel as I have a property named TVSeries in the ViewModel. When this property is set, I will populate other properties such as Title, Cover and so on. These properties are meant to be binded to controls in the view. public class TVSeriesViewModel : ViewModelBase, ITVSeriesViewModel { private TVSeries _tvSeries; private string _title; private ImageSource _cover; public TVSeries TVSeries { get { return this._tvSeries; } set { this._tvSeries = value; } } public string Title { get { return this._title; } set { this._title = value; OnPropertyChanged("Title"); } } public ImageSource Cover { get { return this._cover; } set { this._cover = value; OnPropertyChanged("Cover"); } } } First and foremost, does this sound like the right way to do it? Next, does anyone know how to pass a parameter (a TVSeries object) to the ViewModel when the TVSeriesView is shown? And lastly, does anyone know how I can directly access resources in the view? For example if I don't want to use data binding but instead want to set the image directly like this: myImage.ImageSource = myImageSource A: The View and ViewModel together are one of the possible representations of the Model. You can pass a repository handle which would be eventually responsible for data access or Concrete/abstract object of Model through Dependency Injection via Constructor or Dependency Injection, via property/method or In more crude way you can write a DB access code in your VM (obviously it's not suggested.) I would prefer as the order given here. Your code is doing the third option.
{ "pile_set_name": "StackExchange" }
Q: jQuery while using find function its children returns the attribute with undefined $("table.overview-table td.orange.white").each(function(){ if($(this).attr("rowspan") > 0) { var childrens = $(this).parent().next("tr").find("*"); for(x = 0; x < childrens.length; x++) { console.log(childrens[x].attr("workerid")); } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table table-responsive table-bordered overview-table" border=1> <thead> <tr> <th class="dark" style="width: 50px;">Tijd</th> <th class="dark">Kapper 1</th> <th class="dark">Kapper 2</th> </tr> </thead> <tbody class="overview_table_td"> <tr> <th scope="row">03:15</th> <td class="grey" onclick="make_app("2017-06-19","03:15","Kapper 1","148","1","1")"></td><td class="orange" onclick="make_app("2017-06-19","03:15","Kapper 2","196","1","0")" rowspan="0" data-time="03:15:00" workerid="196"></td> </tr> <tr> <th scope="row" class="dark">03:30</th> <td class="grey" onclick="make_app("2017-06-19","03:30","Kapper 1","148","1","1")"></td><td class="orange white" onclick="show_app("4614")" rowspan="2" data-time="03:30:00" workerid="196">test</td> </tr> <tr> <th scope="row">03:45</th> <td class="grey" onclick="make_app("2017-06-19","03:45","Kapper 1","148","1","1")"></td><td class="orange" onclick="make_app("2017-06-19","03:45","Kapper 2","196","1","0")" rowspan="0" data-time="03:45:00" workerid="196"></td> </tr> </tbody> </table> While i m fetching children element's attribute at that time below error is showing Uncaught TypeError: childrens[x].attr is not a function Looking for help A: You should use $(childrens[x]).attr("workerid") instead of childrens[x].attr("worked") $(element) Selects the HTML element so that you can you can get/set properties/attributes of that element through jquery. function rowspan_treatment(){ $("table.overview-table td.orange.white").each(function(){ if($(this).attr("rowspan") > 0 && $(this).attr("rowspan") !== "undefined") { var childrens = $(this).parent().next("tr").find("*"); for(x = 0; x < childrens.length; x++) { console.log($(childrens[x]).attr("workerid")); } } }); } $("table.overview-table td.orange.white").each(function(){ if($(this).attr("rowspan") > 0) { var childrens = $(this).parent().next("tr").find("*"); for(x = 0; x < childrens.length; x++) { if($(childrens[x]).attr("workerid") != undefined){ console.log($(childrens[x]).attr("workerid")); } } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table table-responsive table-bordered overview-table" border=1> <thead> <tr> <th class="dark" style="width: 50px;">Tijd</th> <th class="dark">Kapper 1</th> <th class="dark">Kapper 2</th> </tr> </thead> <tbody class="overview_table_td"> <tr> <th scope="row">03:15</th> <td class="grey" onclick="make_app("2017-06-19","03:15","Kapper 1","148","1","1")"></td><td class="orange" onclick="make_app("2017-06-19","03:15","Kapper 2","196","1","0")" rowspan="0" data-time="03:15:00" workerid="196"></td> </tr> <tr> <th scope="row" class="dark">03:30</th> <td class="grey" onclick="make_app("2017-06-19","03:30","Kapper 1","148","1","1")"></td><td class="orange white" onclick="show_app("4614")" rowspan="2" data-time="03:30:00" workerid="196">test</td> </tr> <tr> <th scope="row">03:45</th> <td class="grey" onclick="make_app("2017-06-19","03:45","Kapper 1","148","1","1")"></td><td class="orange" onclick="make_app("2017-06-19","03:45","Kapper 2","196","1","0")" rowspan="0" data-time="03:45:00" workerid="196"></td> </tr> </tbody> </table>
{ "pile_set_name": "StackExchange" }
Q: Bounty showing up even though kills were hidden In one save file for Skyrim, I had killed two people, and I was completely hidden both times. But after I got home, I had a bounty on my head in Whiterun. Is this a glitch that can be fixed, or am I gonna have to restart my whole game? Of course, I'm only level 7, so I don't think I'll care much A: Crime Witness Bounty witness is not the same as combat detection, combat detection is affect by sneak skill, invisibility, light etc but witness is by LOS. Therefore there is a chance that your kill is witnessed by another person but he/she is unable to see you in combat. This can be prevented by cutting the LOS by covering nearby NPCs with baskets for similar item before committing the crime, or waiting for the target to be clearly isolated before killing. Clearing Bounty Bounty of killing can be removed by silencing all witnesses, if you remember where you got the bounty from you can return and kill possible witnesses near the area and if you managed to kill all who witnessed your crime the bounty will clear - careful not to accumulate more in the process. If the witness is essential and cannot be killed you can go to jail and serve your term by talking to any guards of the hold, since your level is low the amount of exp in each skill to be lost during jail term will probably not be too much. Alternatively you can pay your own bounty with any guard but remember to stash any stolen item before you do or they will be confiscated.
{ "pile_set_name": "StackExchange" }
Q: Strange tag-badge behavior for scala tag Some users that have overcame the mark of 400 points quite a long time ago still haven't got their silver badges. Is it a bug, or I miss something. https://stackoverflow.com/tags/scala/topusers https://stackoverflow.com/users/9815/daniel-spiewak https://stackoverflow.com/users/354067/vasil-remeniuk A: From the badges?tab=tags page: You must have a total score of 400 in at least 80 non-community wiki answers to achieve this badge. So if they've answered less than 80 questions they won't get the badge. Checking the top users page I see that Daniel has answered 79 questions and Vasil 72, so indeed they don't qualify.
{ "pile_set_name": "StackExchange" }
Q: JQuery .html method character encoding I have a similar problem to this: jQuery AJAX Character Encoding but any solution mentioned there works for me. I've made three easy files to show the problem: PHP File: //prueba.php echo "nº one two € áéíóú"; JavaScript File (I use JQuery) //Javascript file function prueba() { $.ajax({ type: "GET", contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1", url: "prueba.php", }).done(function( data ) { $("#prueba").text(data); //$("#prueba").html(data); //It does the same encoding error }); } ** HTML File:** <html> <head> <title>E-COMMERCE</title> <meta content="text/html; charset=iso-8859-1" http-equiv=Content-Type> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <script src="javascript/jquery.js" type="text/javascript"></script> <script src="javascript/javascript.js" type="text/javascript"></script> </head> <body> <a href="javascript:prueba()">Prueba</a> <div id="prueba"></div> </body> </html> And when you click the link Prueba it shows: Prueba n� uno dos � ����� The current website works perfectly but it does not use ajax and it is in the same server where i am doing this, so How can I tell to jquery to return ISO-8859-1 instead of whatever it is returning? I know that the ideal is to use always utf-8 but changing to utf-8 it will give us some problems we cant afford right now. A: To make the browser use the correct encoding, you have to add an HTTP header to the php page : header("Content-Type: text/plain; charset=ISO-8859-1"); or you could put the encoding in a meta tag of the html: <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
{ "pile_set_name": "StackExchange" }
Q: Organizing photos for archival purposes, what format for metadata? For long term archiving, what metadata format(s) are most likely to be readable in 10, 20, or 30 years? Currently I archive photos by directory in a tree structure starting with year at the top level. The structure is YYYY/MM/DD/image.format. So it looks like something like this: ├── 1999 │   └── 01 │   ├── 01 │   │   └── eb2a.jpg │   └── 02 │   └── piEc3.JPG ├── 2000 │   └── 01 │   ├── 01 │   │   ├── IMG_0001.JPG │   │   ├── IMG_0012.JPG The advantages of this system include: No single directory will contain too many files and cause slowdowns due to filesystem limitations. It's easy to locate photos by date. It's simple and there are lots of tools that can sort photos this way based on EXIF data. This system will most likely still be readable in 30 years as long as one regularly transitions the data to the latest filesystems. The disadvantages include: There is no way to tag/organize photos other than by date. Images that have incorrect or missing EXIF data have to be sorted manually. You have to remember dates in order to find anything. In terms of longevity, I can think of no other system that is comparable in terms of suitability for archiving. Plain text files with metadata may work, but any current software to create/update such files may not be around in the future. That being said, are there any metadata formats that can be used in conjunction with this system that are highly likely to still be around? Propriety formats are out of consideration on the grounds that there is no guarantee that any company will be around and continue to support any particular proprietary format. The ideal metadata format should have properties such as: Easy for humans to read without the use of special software (i.e. a plain text format with simple markup/formatting) Wide support among current software Based on a standard (e.g. something like EXIF) Does anything like this exist? If not, where should I look for inspiration to create such a format? A: Keep your current date-based organizational scheme for files Add XMP metadata to the files, including keywords, titles, and descriptions Use a database to collect this centrally, and allow search and presentation based on the metadata This has all of the organizational advantages you cite, with few disadvantages. XMP is XML-based, so not quite human-readable, although it's okay in pinch — and there is a huge amount of software support, and it is standards-based. It is at least as futur-proof as your image files themselves. You can even do basically this with existing commercial software like Lightroom.
{ "pile_set_name": "StackExchange" }
Q: Windows Forms Webbrowswer control with IDownloadManager I'm using the Systems.Windows.Forms.Webbrowser control and need to override the download manager. I've followed the instructions here to subclass the form and override CreateWebBrowserSiteBase() /// <summary> /// Browser with download manager /// </summary> public class MyBrowser : WebBrowser { /// <summary> /// Returns a reference to the unmanaged WebBrowser ActiveX control site, /// which you can extend to customize the managed <see ref="T:System.Windows.Forms.WebBrowser"/> control. /// </summary> /// <returns> /// A <see cref="T:System.Windows.Forms.WebBrowser.WebBrowserSite"/> that represents the WebBrowser ActiveX control site. /// </returns> protected override WebBrowserSiteBase CreateWebBrowserSiteBase() { var manager = new DownloadWebBrowserSite(this); manager.FileDownloading += (sender, args) => { if (FileDownloading != null) { FileDownloading(this, args); } }; return manager; } } In the DownloadWebBrowserSite, I implement IServiceProvider to provide an IDownloadManager when requested. /// <summary> /// Queries for a service /// </summary> /// <param name="guidService">the service GUID</param> /// <param name="riid"></param> /// <param name="ppvObject"></param> /// <returns></returns> public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) { if ( (guidService == Constants.IID_IDownloadManager && riid == Constants.IID_IDownloadManager )) { ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(IDownloadManager)); return Constants.S_OK; } ppvObject = IntPtr.Zero; return Constants.E_NOINTERFACE; } The DownloadManager is taken from the example above. /// <summary> /// Intercepts downloads of files, to add as PDFs or suppliments /// </summary> [ComVisible(true)] [Guid("bdb9c34c-d0ca-448e-b497-8de62e709744")] [CLSCompliant(false)] public class DownloadManager : IDownloadManager { /// <summary> /// event called when the browser is about to download a file /// </summary> public event EventHandler<FileDownloadEventArgs> FileDownloading; /// <summary> /// Return S_OK (0) so that IE will stop to download the file itself. /// Else the default download user interface is used. /// </summary> public int Download(IMoniker pmk, IBindCtx pbc, uint dwBindVerb, int grfBINDF, IntPtr pBindInfo, string pszHeaders, string pszRedir, uint uiCP) { // Get the display name of the pointer to an IMoniker interface that specifies the object to be downloaded. string name; pmk.GetDisplayName(pbc, null, out name); if (!string.IsNullOrEmpty(name)) { Uri url; if (Uri.TryCreate(name, UriKind.Absolute, out url)) { if ( FileDownloading != null ) { FileDownloading(this, new FileDownloadEventArgs(url)); } return Constants.S_OK; } } return 1; } } The problem is that the pmk.GetDisplayName returns the initial URL, not the URL of the item to be downloaded. If the URI points to a dynamic page, such as http://www.example.com/download.php, I'm not getting the actual file to be downloaded. I need to get the URL from the header so that I get the actual file I'm supposed to be downloading. Google indicates that I have to create a IBindStatusCallback implementation that also implements IHttpNegotiate and IServiceProvider to respond to IID_IHttpNegotiate, so that I can see the IHttpNegotiate.OnResponse. I've managed to implement that, however, QueryService only seems to ever ask for IID_IInternetProtocol and never IID_IHttpNegotiate. Any advice would be great. A: Your missing a call to: CreateBindCtx. Add the following to your DownloadManager: [DllImport("ole32.dll")] static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc); Then make sure you call this before registering your callback. I have implemented this in your Download() method as follows: public int Download(IMoniker pmk, IBindCtx pbc, uint dwBindVerb, int grfBINDF, IntPtr pBindInfo, string pszHeaders, string pszRedir, uint uiCP) { // Get the display name of the pointer to an IMoniker interface that specifies the object to be downloaded. string name; pmk.GetDisplayName(pbc, null, out name); if (!string.IsNullOrEmpty(name)) { Uri url; if (Uri.TryCreate(name, UriKind.Absolute, out url)) { Debug.WriteLine("DownloadManager: initial URL is: " + url); CreateBindCtx(0, out pbc); RegisterCallback(pbc, url); BindMonikerToStream(pmk, pbc); return MyBrowser.Constants.S_OK; } } return 1; } With this in place, your IHttpNegotiate implementation will be called and you'll have access to the response headers.
{ "pile_set_name": "StackExchange" }
Q: Test class for importing a csv file Here i am tried to write a test class for importing csv file.THere is no code coverage.Plese help me on this. public class adminPriorSale { public list<Distributor_Prior_Sales__c> accon{get;set;} public Distributor_Prior_Sales__c agnt{get;set;} public Integer PriorSale{set;get;} public id tobeEdited{get; set;} public string deleteid{get;set;} public boolean editSection {get;set;} public ApexPages.StandardController stand; Public String retURL{get;set;} //To import file public Blob csvFileBody{get;set;} public string csvAsString{get;set;} public String[] csvFileLines{get;set;} public adminPriorSale(apexpages.standardcontroller controller ) { retURL = ApexPages.currentPage().getParameters().get('retURL'); this.stand=controller; tobeEdited = controller.getId(); agnt = new Distributor_Prior_Sales__c(); accon = New List<Distributor_Prior_Sales__c>(); accon= [select id,Name,SMS_sales_amount__c,SMS_Year__c,Customer__c,Calculation_Type__c from Distributor_Prior_Sales__c]; csvFileLines = new String[]{}; } public PageReference EdittheSection() { PageReference ref=new PageReference('/apex/adminPriorSale1?retURL=/apex/Admin'); ref.setRedirect(true); update accon; return ref; } private void LoadData() { accon= [select id,Name,SMS_sales_amount__c,SMS_Year__c,Customer__c,Calculation_Type__c from Distributor_Prior_Sales__c WHERE (owner.id =: userinfo.getuserid())]; } // Import CSV file to list of record public void importCSVFile(){ try{ csvAsString = csvFileBody.toString(); csvFileLines = csvAsString.split('\n'); for(Integer i=0;i<csvFileLines.size();i++){ Distributor_Prior_Sales__c prisale = new Distributor_Prior_Sales__c () ; string[] csvRecordData = csvFileLines[i].split(','); prisale.SMS_Year__c= csvRecordData[0] ; prisale.SMS_sales_amount__c= Decimal.valueof(csvRecordData[1]); prisale.Customer__c= csvRecordData[2]; prisale.Calculation_Type__c = csvRecordData[3]; accon.add(prisale); } upsert accon; } catch (Exception e) { ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,e.getMessage()); ApexPages.addMessage(errorMessage); } } public void save1() { update accon; } public void DeleteSale() { Distributor_Prior_Sales__c del_task=new Distributor_Prior_Sales__c(id=deleteid); delete del_task; accon=[select id,Name,SMS_sales_amount__c,SMS_Year__c,Customer__c,Calculation_Type__c from Distributor_Prior_Sales__c]; } public pagereference saveRecord() { List<Distributor_Prior_Sales__c> discLocal=accon.clone() ; List<Distributor_Prior_Sales__c> discLocal2=new List<Distributor_Prior_Sales__c>(accon); integer i=0; for(Distributor_Prior_Sales__c sale:accon){ if(sale.SMS_sales_amount__c==null && sale.SMS_Year__c ==null && sale.Customer__c ==null && sale.Calculation_Type__c==null ) { discLocal2.remove(i); } else if(sale.SMS_sales_amount__c==null || sale.SMS_Year__c ==null || sale.Customer__c ==null || sale.Calculation_Type__c==null ) { ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,'You must enter all required fields'); ApexPages.addMessage(msg); return null; } i++; } upsert discLocal2; PageReference pageRef = new PageReference('/apex/adminPriorSale?retURL=/apex/Admin'); pageref.setRedirect(true); return pageref; } public PageReference cancel() { PageReference pg1=new PageReference('/apex/adminPriorSale?retURL=/apexAdmin'); pg1.setRedirect(true); return pg1; } public void addrow() { Distributor_Prior_Sales__c proSale = new Distributor_Prior_Sales__c(); proSale.SMS_sales_amount__c= (agnt.SMS_sales_amount__c); proSale.SMS_Year__c =(agnt.SMS_Year__c ); proSale.Customer__c=(agnt.Customer__c); proSale.Calculation_Type__c=(agnt.Calculation_Type__c); accon.add(proSale ); } } And it test class is @isTest(seeAllData=true) private class test_adminPriorSale { static testMethod void test_adminPriorSale() { Distributor_Prior_Sales__c t1= new Distributor_Prior_Sales__c (); t1.Name='test1'; t1.SMS_sales_amount__c =123; t1.SMS_Year__c='2012'; insert t1; String csvContent = 'test1',123,'2012','I Architects','Estimated Prior sales'; PageReference pageRef = Page.adminPriorSale; // Adding VF page Name here pageRef.getParameters().put('id', String.valueOf(t1.id));//for page reference Test.setCurrentPage(pageRef); ApexPages.currentPage().getParameters().put('RecordType','adminPriorSale'); ApexPages.StandardController sc = new ApexPages.standardController(t1); adminPriorSale controller = new adminPriorSale(sc); controller.save1(); controller.saveRecord(); controller.addrow(); controller.DeleteSale(); controller.editSection = true; controller.EdittheSection(); //controller.LoadData(); controller.cancel(); controller.importCSVFile(); } static testMethod void test_adminPriorSale2() { Distributor_Prior_Sales__c t1= new Distributor_Prior_Sales__c (); t1.Name='test1'; //t1.SMS_sales_amount__c =123; //t1.SMS_Year__c='2014'; insert t1; Distributor_Prior_Sales__c t2= new Distributor_Prior_Sales__c (); t2.Name='test1'; t2.SMS_sales_amount__c =123; t2.SMS_Year__c='2014'; insert t2; PageReference pageRef = Page.adminPriorSale; // Adding VF page Name here pageRef.getParameters().put('id', String.valueOf(t1.id));//for page reference pageRef.getParameters().put('retURL', String.valueOf(t1.id));//for page reference Test.setCurrentPage(pageRef); ApexPages.currentPage().getParameters().put('RecordType','adminPriorSale'); ApexPages.StandardController sc = new ApexPages.standardController(t1); adminPriorSale controller = new adminPriorSale(sc); controller.saveRecord(); controller.cancel(); } static testMethod void test_adminPriorSale3() { Distributor_Prior_Sales__c t1= new Distributor_Prior_Sales__c (); t1.Name='test1'; //t1.SMS_sales_amount__c =123; //t1.SMS_Year__c='2014'; insert t1; PageReference pageRef = Page.adminPriorSale; // Adding VF page Name here pageRef.getParameters().put('id', String.valueOf(t1.id));//for page reference Test.setCurrentPage(pageRef); ApexPages.currentPage().getParameters().put('RecordType','adminPriorSale'); ApexPages.StandardController sc = new ApexPages.standardController(t1); adminPriorSale controller = new adminPriorSale(sc); controller.cancel(); controller.editSection = true; controller.EdittheSection(); } } It is giving 64% code coverage.not covering the importing csv file part.someone please help me on this. A: You code never actually get the CSV from anywhere: You declare: public Blob csvFileBody{get;set;} Then later you: csvAsString = csvFileBody.toString(); Within a try catch block so it throws an error as you never actually set the value of the csvFileBody NOTE This is WHY assertions in test classes are extremely important. You are concerned with covering lines but if you were asserting results, for example, when executing IMportCSVFile in your test, assert that there are no page messages and query and assert that Distributor_Prior_Sales__c records were created. In doing that you would know that it is actually working or not (error thrown since in try catch) instead of just covering lines.
{ "pile_set_name": "StackExchange" }
Q: Run new process as admin and read standard output I want to allow users to run a command line utility as administrator from within my non-admin program and for my program to get the output. The utility is third-party but is distributed with my programme. I can redirect the output of a program and I can run a program as administrator but I can't do both at the same time. The only thing that I can get to work at the moment is using cmd.exe to redirect the output to a file, e.g.: using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Reflection; string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string utilityPath = Path.Combine(appDirectory, "tools", "utility.exe"); string tempFile = Path.GetTempFileName(); Process p = new Process(); // hide the command window p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.FileName = "cmd.exe"; // run the tool, redirect the output to the temp file and then close. p.StartInfo.Arguments = " /C \"\"" + utilityPath + "\" > \"" + tempFile + "\"\""; p.StartInfo.Verb = "runas"; // run as administrator p.Start(); p.WaitForExit(); // get the output, delete the file and show the output to the user string output = File.ReadAllText(tempFile); File.Delete(tempFile); MessageBox.Show(output); This has two problems: 1) it uses a temporary file and 2) the UAC is for cmd.exe rather then utility.exe. There must surely be a better way to do this? A: Instead of executing through a new cmd, try executing the utility directly. And instead of redirecting to a file, redirect the standard output to read it from your program. In order to run as admin, you'll need to use the admin username and password (taken from here). You'll need to set your method as unsafe: unsafe public static void Main(string[] args){ Process p = new Process(); p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // set admin user and password p.StartInfo.UserName = "adminusername"; char[] chArray = "adminpassword".ToCharArray(); System.Security.SecureString str; fixed (char* chRef = chArray) { str = new System.Security.SecureString(chRef, chArray.Length); } p.StartInfo.Password = str; // run and redirect as usual p.StartInfo.FileName = utilityPath; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); string output = p.StandardOutput.ReadToEnd(); Console.WriteLine(output); p.WaitForExit(); }
{ "pile_set_name": "StackExchange" }
Q: Custom JSON serialization of sensitive data for PCI compliance We have to log incoming requests and outgoing responses for our web service. This includes JSON serialization of each object so they can be stored in a database. Some information is considered sensitive (such as Social Security Numbers, credit card numbers, etc.) and we cannot include these in our logs per PCI compliance. Right now we're manually replacing the values with a placeholder value (e.g. "[PRIVATE]") but this only works with string properties. Some data, such as a Date of Birth is not stored as a string so this doesn't work as the replacement of the property value happens before the serialization. The big problem is that it is too easy for someone to forget to do remove the sensitive data before logging it, which is highly undesirable. To remedy this, I was thinking of creating a custom attribute and placing it on the property and then having the JSON serialization routine look for this attribute on each property and if it exists, replace the serialized value with a placeholder such as "[PRIVATE]". Right now we are using the System.Web.Script.Serialization.JavaScriptSerializer for our serialization. Obviously it knows nothing of my custom attribute. How would I go about changing the serialization process so any data decorated with my custom "SensitiveData" attribute is replaced with a placeholder value? I'm not against using a different serializer but was hoping I could leverage the features of an existing one instead of writing my own. A: Here's my solution, although it may need minor tweaks: My custom JsonConverter: using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Reflection; public class SensitiveDataJsonConverter : JsonConverter { private readonly Type[] _types; public SensitiveDataJsonConverter(params Type[] types) { _types = types; } public override bool CanConvert(Type objectType) { return _types.Any(e => e == objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var jObject = new JObject(); var type = value.GetType(); foreach (var propertyInfo in type.GetProperties()) { // We can only serialize properties with getters if (propertyInfo.CanRead) { var sensitiveDataAttribute = propertyInfo.GetCustomAttribute<SensitiveDataAttribute>(); object propertyValue; if (sensitiveDataAttribute != null) propertyValue = "[REDACTED]"; else propertyValue = propertyInfo.GetValue(value); if (propertyValue == null) propertyValue = string.Empty; var jToken = JToken.FromObject(propertyValue, serializer); jObject.Add(propertyInfo.Name, jToken); } } jObject.WriteTo(writer); } Here's my custom attribute: using System; [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)] public class SensitiveDataAttribute : Attribute { } We use it like this: string serialized; try { serialized = JsonConvert.SerializeObject(value, new SensitiveDataJsonConverter(value.GetType())); } catch // Some objects cannot be serialized { serialized = $"[Unable to serialize object '{key}']"; } Here's a test class I try to serialize: class Person { public Person() { Children = new List<Person>(); } public List<Person> Children { get; set; } [SensitiveData] public DateTime DateOfBirth { get; set; } public string FirstName { get; set; } public string LastName { get; set; } [SensitiveData] public string SocialSecurityNumber { get; set; } public Person Spouse { get; set; } } This seemed to work great until I added the Spouse and Children properties but I was getting a NullReferenceException. I added this to the WriteJson method which corrected the problem: if (propertyValue == null) propertyValue = string.Empty;
{ "pile_set_name": "StackExchange" }
Q: You tried to execute a query that does not include the specified expression Sorry if the question seems low level but I was never formally taught Access and everything I know I've just sort of muddled into. Basically, I am trying to make a crosstab query where the column and row headers are both the names of airports that the charity airline I'm interning for flies to. I'm trying to make it where the column and rows are both airport names and the value is the distance between the two calculated through the latitude and longitude (both contained within the same table as the airport names). I'm calculating distance with this little expression [Sqr((Lat2-Lat1)^2+(Long2-Long1)^2)] but when I put that in I get the error message: You tried to execute a query that does not include the specified expression. Ultimately my expression looks like this: Sqr(([Airstrip List January 2017]![Latitude]-[Airstrip List January 2017]![Latitude])^2+([Airstrip List January 2017]![Longitude]-[Airstrip List January 2017]![Longitude])^2) I think what I'm doing wrong is I'm telling Access to look in the table to find the lat and long whereas I should be telling it to look based of what the header and columns are. Sorry if this seemed very rambly but I am very new to this kind of stuff... Any and all help appreciated. A: Your crosstab query needs to be set up as follows: Add the table Airstrip List January 2017 into the query twice, but do not have any join between them. Give the two tables aliases (show Properties and then when you click on a table the first Property is the Alias). Call one of them Start and the other one End Put the airfield name from the Start table as the first column in the grid. Set Total as Group By and Crosstab as Row Heading. Put the airfield name from the End table as the second column in the grid. Set Total as Group By and Crosstab as Column Heading. Set the third grid column to Distance: Sqr(([Start].[Latitude]-[End].[Latitude])^2+([Start].[Longitude]-[End].[Longitude])^2) with the Total set as Sum and the Crosstab set as Value Run the query!
{ "pile_set_name": "StackExchange" }
Q: Uso de IN y OUT en Procedimientos Almacenados Un procedimiento almacenado como tal es una rutina que contiene sentencia(s) sql a las cuales se tiene acceso del modo siguiente CALL nombrePA(); Un ejemplo sencillo que tenemos sobre un PA es como el siguiente DELIMITER // CREATE PROCEDURE fetchAll() SELECT * FROM users; // Invoco o llamo al PA por medio de CALL CALL fetchAll(); EXPLICACIÓN Se crea un delimitador con la doble diagonal // por que el símbolo de punto y coma lo contiene la sentencia SQL dentro del PA Sin embargo sabemos que no todas las sentencias SQL, son estáticas(es decir que no requieran de valores dinámicos) Es aquí donde entran en uso los valores de tipo: IN: Son los valores que espera recibir el PA para otorgarlos a la query que tiene por dentro, procesarla y devolver un resultado OUT: Este valor existe en el PA pero puede ser modificado dentro de este mismo A: Para poder utilizar valores dinámicos dentro de un PA debemos tener presente es necesario también indicar el tipo de dato a procesar; EJEMPLO 1 CON IN El siguiente código funcionará por que el PA espera un valor de entrada de tipo VARCHAR y al momento de invocarlo pasamos un valor en formato de cadena de texto acorde a CREATE PROCEDURE fetchAll(IN email VARCHAR(40)); CALL fetchAll("[email protected]"); EJEMPLO 2 CON IN Para este ejemplo vamos a consultar todos los posts asociados a un usuario por un id especifico, donde como podemos notar en el WHERE pasamos un valor dinámico en forma de variable que se llama ìdDinamico: DELIMITER // CREATE PROCEDURE fetchAll1(IN idDinamico INT) SELECT nameUser, namePost FROM users JOIN posts ON users.id = posts.user_id WHERE users.id = idDinamico; // CALL fetchAll1(1); EJEMPLO 3 CON OUT En el siguiente escenario, vamos a utilizar un valor OUT para poder asignar el total de posts asignados a un usuarios en una variable llamada totalPosts haciendo uso de INTO DELIMITER // CREATE PROCEDURE fetchAll2(IN nameDinamico VARCHAR(40), OUT totalPosts INT) SELECT nameUser, COUNT(namePost) INTO nameDinamico, totalPosts FROM users JOIN posts ON users.id = posts.user_id WHERE users.nameUser = nameDinamico; // CALL fetchAll2("gatito", @totalPosts); SELECT @totalPosts;
{ "pile_set_name": "StackExchange" }
Q: Creating a tree from Parent/Child relation represented in a flat table I have a C# List of following fields which are returned by a stored procedure: CarrierId ParentCarrierId Name Descrition 1 NULL A AA 2 1 B BB 3 1 C CC 4 3 D DD 5 NULL E EE I need to construct a nested object list out of this output So each object of Carrier should have list of all it's children. Can anyone help me construct a LINQ code to accomplish this? Desired Result: CarrierId = 1 |__________________ CarrierId = 2 | |__________________ CarrierId = 3 | | |___________________ CarrierId = 4 CarrierId = 5 Desired result should be as mentioned above the following code arrange things in tree but a child still appears in the list c.Children = carrierList.Where(child => child.ParentCarrierId == c.CarrierId).ToList(); CarrierId = 1 | |__________________ CarrierId = 2 | |__________________ CarrierId = 3 | |___________________ CarrierId = 4 | CarrierId = 2 | CarrierId = 3 | CarrierId = 4 | CarrierId = 5 I don't want this behavior. If something appeared as Child it should be removed from root. A: This is what you need. First, start with the source data: var source = new [] { new { CarrierId = 1, ParentCarrierId = (int?)null, Name = "A", Description = "AA", }, new { CarrierId = 2, ParentCarrierId = (int?)1, Name = "B", Description = "BB", }, new { CarrierId = 3, ParentCarrierId = (int?)1, Name = "C", Description = "CC", }, new { CarrierId = 4, ParentCarrierId = (int?)3, Name = "D", Description = "DD", }, new { CarrierId = 5, ParentCarrierId = (int?)null, Name = "E", Description = "EE", }, }; Then, create a lookup by ParentCarrierId: var lookup = source.ToLookup(x => x.ParentCarrierId); Now we need an output structure: public class Carrier { public int Id; public List<Carrier> Children = new List<Carrier>(); public string Name; public string Description; } Then, a build function to pop all of the carriers out by ParentCarrierId: Func<int?, List<Carrier>> build = null; build = pid => lookup[pid] .Select(x => new Carrier() { Id = x.CarrierId, Name = x.Name, Description = x.Description, Children = build(x.CarrierId), }) .ToList(); NB: It's recursive so it needs to be defined with the initial = null. Finally we build: List<Carrier> trees = build(null); This gives:
{ "pile_set_name": "StackExchange" }
Q: ST_Buffer conundrum I have a table in Postgresql with a geom_multiline column which, as the name suggests, is of type MULTILINESTRING and a second column geom_buffer which is a MULTIPOLYGON type. When I perform this query: UPDATE locparktable SET geom_buffer = ST_Multi(ST_Transform(ST_Buffer(st_transform(geom_multiline,2248),200), 4326)) I get this error: Error : ERROR: Geometry type (MultiLineString) does not match column type (LineString) I have dropped and readded geom_buffer multiple times I even at one point added it as a generic GEOMETRY type to see if that would help and it did not. I'm at the end of my knowledge and Googling is failing to provide any useful help. Does anyone know what might be causing this error? The only thing I can think of (though I have not yet verified it) is that there may be MULTILINESTRING data in our geom_line (LINESTRING) column for a feature that we're trying to update with this query (No, I don't know how that would happen, but let's say it did). Does anyone know if that would cause this error? A: You need to convert from Multi-linestring to linestring using ST_Dump as follows UPDATE locparktable SET geom_buffer = ST_Dump(ST_Multi(ST_Transform(ST_Buffer(st_transform(geom_multiline,2248),200),4326))).geom Note: geom is the name of geometry column, it may be different in your case. Just have a look at the results of st_dump(geom_multiline) to be sure.
{ "pile_set_name": "StackExchange" }
Q: Period of a trigonometric series What is the period of the function represented by the series $a_1 cos x+a_2cos2x+a_3cos3x+...$ I guess it is $2\pi$. Am I right? A: You are not right, not in general. First of all, the series in question may not even converge so talking about its period would make no sense. But let's assume the series converges to a function $f(x)$ The period is at most $2\pi$, in the sense that $f(x+2\pi)=f(x)$ without a doubt. But, for example, if $a_1=a_3=a_4=\dots=0$, then $f(x+\pi)=f(x)$ as well, and the period of $f$ is $\pi$.
{ "pile_set_name": "StackExchange" }
Q: Javascript window.open returns undefined I have a Rails 3.2 site and am using a javascript print routine that has suddenly stopped working. Here's my print routine code: function print() { var mywin = window.open('', '', ''); mywin.document.write('<body><link href="/assets/application.css" media="all" rel="stylesheet" type="text/css" />' + document.getElementsByClassName('fields')[0].innerHTML + '</body>'); mywin.print(); mywin.close(); return false; } Code has been running fine for months, but now whenever you try to print it just prints two blank pages. It throws an error on the second line, cannot read property 'document' of undefined, and inspection reveals that mywin is undefined. Googling didn't yield any worthwhile results, so anyone have any clue why this is happening? A: The window.open function returns undefined if browser settings blocked that new window from being created. Your only option is to check for a truthy value, otherwise show a message that browser settings are blocking the window from being opened. var win = window.open(...); if (win) { win.document.write(...); } else { alert("Your browser prevented the window from opening."); } A: I had the same problem in a non-rails environment. I am using node's http-server, working on localhost. The trouble was that Chrome was automatically blocking pop-ups from localhost. I went to the settings and added "localhost" as an exception, and now everything works great! Hope this helps
{ "pile_set_name": "StackExchange" }
Q: How do I Show a SPList item Name in an Email sent by a timerJob? I need to send an Email with a list items name of the rows my caml query picks out. I have this code: SPQuery filter = new SPQuery(); filter.Query = string.Format("<Where><Leq><FieldRef Name=\"Revisionsdatum\" /><Value Type=\"DateTime\">{0}</Value></Leq></Where>", DateTime.Today.AddDays(14).ToString("yyyy-MM-ddThh:mm:ssZ")); SPListItemCollection items = yourList.GetItems(filter); foreach (var i in items) { string from = string.Empty; string smtpAddress = string.Empty; string to = "[email protected]"; string subject = "Dudate is coming"; string body = "<h1>Hello!</h1><p>In to weeks an importent dudates comes({0}) with the name {2}.";//Here I would like to ad the dudate and the ListItems Name but how? // get a reference to the current site collection's content database SPWebApplication webApplication = this.Parent as SPWebApplication; SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId]; // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database SPWeb rootWeb = contentDb.Sites[0].RootWeb; SPList listjob = rootWeb.Lists.TryGetList("Tasks"); // Get sender address from web application settings from = rootWeb.Site.WebApplication.OutboundMailSenderAddress; // Get SMTP address from web application settings smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address; // Send an email if the news is approved bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null); } I would bee greatfull for your answer! A: You can get it as follows: foreach (SPListItem item in items) \\ items is your SPListItemCollection { var fieldValue = item["Field Name"].ToString(); }
{ "pile_set_name": "StackExchange" }
Q: Does a drainage pipe need to be continuously sloped? I need to move water from the back yard to the front yard, to combat the monsoon season, in which a 50 gallon container in the backyard can fill up in 1-2 minutes. I bought some 4" piping, and will have it collect water in a drain in the higher back yard, and divert it in a half-circle around the house to the lower front yard. I'm finding that due to the length of the pipes, about 150 feet, it is difficult to make it continuously downhill. There already is a slight slope of 1" per 10 feet horizontally. Is there any issue if the pipe is not perfectly sloped, and in places goes slightly higher than before, so long as all of the pipe is lower than the entry drain? A: It's true that, so long as the exit is lower than the entrance, water will find its way through the pipe even if there are low points in the path. However, as others have noted, debris could accumulate in those low points. So the answer to your specific questions "does it need to be continuously sloped" is a squishy "yes.. unless you're willing to install mitigations." One mitigation you could consider is one or more sump pits/traps/catch basins along the path. Here's a sketch from Dejana Industries: This construction is specifically designed to catch debris in storm water systems. That's not what you're after, so we can modify the design a bit. Run pipe with a continuous slope at a sufficiently steep grade so that debris will carry along well. When you reach a point that the pipe is getting too deep in the ground, install a catch basin there. Take an exit pipe out of the pit at a level higher than the inlet and proceed to the destination. During a storm water will fill the catch basin. Eventually the water level will rise high enough to flow out the exit pipe. Some debris will settle in the basin; other debris will float up and flow out the exit. Construct the basin to be leaky so that after the storm the water remaining in the basin slowly drains away. That'll minimize the chance of breeding mosquitos or odors. From time to time you'll have to clean out the debris from the bottom of the basin, but it's better to have it there than in some unknown and inaccessible section of pipe buried in the yard! A: If you are in a climate where the water can freeze it is a definite problem. If not, there is still the potential for debris and sediment to settle in the low sections and eventually clog the pipe. A: Your fix is to make like a Roman Aqueduct and support the lower "dips" so that the pipe runs at a more-consistent downward angle. This will also make the water flow faster, flushing possible sediments without a chance to block up. Aim for a straight run of pipe with the same drop over distance, rather than a specific angle. Start by supporting the pipe with wood or stone and once its well-aligned, consider more permanent solutions like concrete.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between dispersion and diffusion? What is the difference between dispersion and diffusion? Currently I believe, that diffusion is the mixture of molecules due to Brownian motion. So I read everywhere, that it happens with magnitude of the concentration gradient, and from higher concentration to lower concentration, cf. Fick's law. It also seems that diffusion and dispersion happens always together, and that dispersion has something to do with the concentration gradient, and that the molecule transport by dispersion is of magnitudes bigger compared to diffusion. What I am asking is, what exactly is dispersion with regard to molecule transport? A: Dispersive mass transfer, in fluid dynamics, is the spreading of mass from highly concentrated areas to less concentrated areas. It is one form of mass transfer. Dispersive mass flux is analogous to diffusion, and it can also be described using Fick's first law: $$J=-E\frac{dc}{dx}$$ where c is mass concentration of the species being dispersed, E is the dispersion coefficient, and x is the position in the direction of the concentration gradient. Dispersion can be differentiated from diffusion in that it is caused by non-ideal flow patterns (i.e. deviations from plug flow) and is a macroscopic phenomenon, whereas diffusion is caused by random molecular motions (i.e. Brownian motion) and is a microscopic phenomenon. Dispersion is often more significant than diffusion in convection-diffusion problems.
{ "pile_set_name": "StackExchange" }
Q: Stick div to top of page when start scrolling I have tried to make a div (id="hoe") that sticks to the top of the from the moment the user scrolls. before scrolling, the div is located under the header. Unfortunately, i can't get it to work after lot's of trying. Any tips and help on what I do wrong is greatly appreciated. Here is my code in a test version: <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <style type="text/css"> #header { background-color: blue; width: 100%; height: 125px; } #hoe { background-color: red; height: 180px; width: 100%; z-index: 9999; top: 125; position: fixed; } #een { margin-top: 180px; background-color: green; height: 700px; width: 100%; } </style> <script type="text/javascript"> $(document).ready(function() { if ($('body').hasClass('lock')) { bar_pos = $('#hoe').offset(); if (bar_pos.top >= (125+180)) { $('#hoe').css('top', 0); //document.getElementById("hoe").style.top="0"; also tried this } }); }); </script> </head> <body class="lock"> <div id="header"> </div> <div id="hoe"> </div> <div id="een"> </div> </body> </html> A: I've modified your code and created a fiddle here: http://jsfiddle.net/UcX4A/ There was a surplus bracket in your javascript $(document).ready(function() { if ($('body').hasClass('lock')) { bar_pos = $('#hoe').offset(); if (bar_pos.top >= (125+180)) { $('#hoe').css('top', 0); //document.getElementById("hoe").style.top="0"; also tried this } }); <<< Surplus bracket }); Also, the "scroll" event wasn't attached to anything, so wasn't being evaluated. I changed your: $(document).ready(function() { To a: $(window).scroll(function() {
{ "pile_set_name": "StackExchange" }
Q: Java - JUnit - testing methods - MultipleMarkersError I have just started learning JUnit testing. I have to write test for methoods below. I started from testting zero(). Can you tell me what i do wrongly there? And leave some helpful examples how should i test rest of this methods? private Accumulator a; int acc; public void test() { Kalkulator test = new Kalkulator(); int result = test.zero(); // my error: MULTIPLE MARKERS assertEquals(0,result); } // Methoods public void setAccumulator( Accumulator a ){ this.a = a; acc = a.get(); } public Accumulator getAccumulator(){ return a; } public int get(){ return acc; } public void zero(){ acc = 0; } //***get*** public int get() { return acc; } A: You can't set result to test.zero() because zero() has a void return type. If you want to test something using JUnit, you need to annotate the method you're testing with @Test. In test(), you should change assertEquals() to Assert.assertEquals(). Take a look at the JUnit Assert API. http://junit.sourceforge.net/javadoc/org/junit/Assert.html
{ "pile_set_name": "StackExchange" }
Q: Sql query to find Id tagged to multiple rows I have a student table with the below structure. StudentId StudentName SubjectId 123 Lina 1 456 Andrews 4 123 Lina 3 123 Lina 4 456 Andrews 5 Need to write a query to get the studentId where the subjectid is equal to 1,3 and studentid is not equal to 4 Select studentId from student where subject Id='1' and SubjectId ='3' and subjectId ='4' . Output studentId should be 123 But it does not work out. Any help is appreciated A: Try with grouping: Select studentId from student where subject_Id in ('1', '3', '4') group by studentId having count(distinct subject_Id) = 3 Note: You might consider changing ('1', '3', '4') to (1, 3, 4) if subject_Id field is of type int. Note2: distinct keyword inside count should be used in case you have duplicate subject_Id values per studentId.
{ "pile_set_name": "StackExchange" }
Q: Tricky sequences and series problem For a positive integer $n$, let $a_{n}=\sum\limits_{i=1}^{n}\frac{1}{2^{i}-1}$. Then are the following true: $a_{100} > 200$ and $a_{200} > 100$? Any help would be thoroughly appreciated. This is a very difficult problem for me. :( A: $$\begin{gather}a_n = 1 + \underbrace {\frac{1}{2} + \frac{1}{3}}_{2\text{ terms}} + \underbrace {\frac{1}{4} + \frac{1}{5} + \frac{1}{6} + \frac{1}{7}}_{4\text{ terms}} + \ldots + \underbrace { \frac{1}{2^{n -1}} + \frac{1}{2^{n -1}+1} + \ldots + \frac{1}{2^n -1}}_{2^{n-1}\text{ terms}}\\ > 1 + 2\cdot\frac{1}{4} + 4\cdot\frac{1}{8} + \ldots + 2^{n-1}\cdot\frac{1}{2^{n}} \\ =1 + \underbrace { \frac{1}{2} + \frac{1}{2} + \ldots + \frac{1}{2}}_{(n-1) \text{ terms}} = 1 +\frac{n-1}{2} = \frac{n+1}{2}. \end{gather} $$ Thus, $a_n > \frac{n+1}{2}.$ On the other hand, $$a_n < 1 + 2\cdot\frac{1}{2} + 4\cdot\frac{1}{4} + \ldots + 2^{n-1}\cdot\frac{1}{2^{n-1}} = 1+(n-1 )= n,$$ so the inequality $a_{100} > 200$ cannot be true.
{ "pile_set_name": "StackExchange" }
Q: How do I convert spaces to underscores in Perl? I am writing a code to create files named after one column in an array, and then have all the common values of another column within it. I have successfully done this, but now I would like to eliminate the white space in-between the file names and convert it into underscores. How do I do that? #!/usr/local/bin/perl use strict; my @traitarray; my $traitarray; my $input ; my %traithash ; my $t_out ; my $TRAIT; my $SNPS; open ($input, "gwas_catalog_v1.0-downloaded_2015-07-08") || die () ; while(<$input>) { @traitarray = split (/\t/); $TRAIT = $traitarray[7]; $SNPS = $traitarray[21]; if (!exists $traithash {$TRAIT}) { open ($t_out, ">outputFiles/".$TRAIT.".txt"); print ($t_out "$SNPS\n"); $traithash {$TRAIT} = 1 ; push (@traitarray, $TRAIT) ; } else { print $t_out "$SNPS\n"; } } foreach ($traitarray) { close "$TRAIT.txt"; } I have tried looking for an answer but many of the questions either include something else as well, or how to go about this within the bash terminal, something I am not comfortable with yet, as I am still new to coding. The file is 10947980 lines, and has 33 columns. A: You're presumably talking about the file you open with this open ($t_out, ">outputFiles/".$TRAIT.".txt") You can do that using the transliterate operator first tr/ /_/ and your open call would be better written like this my $outfile = "outputFiles/$TRAIT.txt"; $outfile =~ tr/ /_/; open my $t_out, '>', $outfile or die qq{Unable to open "$outfile" for output: $!}; A: I assume you're referring to the value in the $TRAIT var which is then used as part of the new filename. $TRAIT = $traitarray[7]; $TRAIT =~ s/\s+/_/g;
{ "pile_set_name": "StackExchange" }
Q: How to make softer, more natural lighting? I'm trying to recreate this image: This is what I have so far: The lighting doesn't look as soft and natural as the first picture. Lighting has always been that hurdle I can't jump across, but now it's starting to become more of an issue. Right now I am just using two emission planes for the light source. https://drive.google.com/file/d/0BzgDIjhDOu6EbGVhZEtHQ2d1V3M/view?usp=sharing A: The reference image is a studio lit still life. There are two "Soft Boxes" camera left and a spot light on the background. Probably a black card camera right to prevent light from filling in the shadows. It appears a relatively long lens was used to compress the scene and emphasize the shallow depth of field. Here is how I recreated the scene in Blender with a camera focal length of 150mm.
{ "pile_set_name": "StackExchange" }
Q: putting marker at the ending of line in google-map i've drawn a line in google-maps using latitude and longitude . also i've put a marker blue.png at the begining of the line. can anyone please tell me how to put a marker red.png at the ending of line in google-map red.png - http://maps.google.com/mapfiles/ms/micons/red.png http://jsfiddle.net My code is as given below function initialize() { var center = new google.maps.LatLng(10.012552, 76.327043); var myOptions = { zoom: 16, center: center, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, navigationControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var polylineCoordinates = [ new google.maps.LatLng(10.013566, 76.331549), new google.maps.LatLng(10.013566, 76.331463), new google.maps.LatLng(10.013503, 76.331313), new google.maps.LatLng(10.013482, 76.331205), new google.maps.LatLng(10.013419, 76.330926), new google.maps.LatLng(10.013334, 76.330712), new google.maps.LatLng(10.013313, 76.330411), new google.maps.LatLng(10.013292, 76.330175), new google.maps.LatLng(10.013228, 76.329854), new google.maps.LatLng(10.013144, 76.329553), new google.maps.LatLng(10.013059, 76.329296), new google.maps.LatLng(10.012996, 76.329017), new google.maps.LatLng(10.012869, 76.328802), new google.maps.LatLng(10.012785, 76.328545), new google.maps.LatLng(10.012700, 76.328223), new google.maps.LatLng(10.012679, 76.328030), new google.maps.LatLng(10.012658, 76.327837), new google.maps.LatLng(10.012637, 76.327600), new google.maps.LatLng(10.012573, 76.327322), new google.maps.LatLng(10.012552, 76.327043) ]; var polyline = new google.maps.Polyline({ path: polylineCoordinates, strokeColor: '#FF3300', strokeOpacity: 2.0, strokeWeight: 5, editable: false }); polyline.setMap(map); var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png"); new google.maps.Marker({ position: polylineCoordinates[polylineCoordinates.length - 1], icon: icon, map: map, clickable: false }); } initialize(); A: The blue marker that you have added is at the end of the line considering you have used the following line . position: polylineCoordinates[polylineCoordinates.length - 1], This takes the last coordinate from the polyline array. To add an icon to the start of the polyline you can use. position: polylineCoordinates[0], Added the following code after the blue marker which adds a red marker to the start of polylin. var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png"); new google.maps.Marker({ position: polylineCoordinates[0], icon: icon, map: map, clickable: false }); } Tested this on the jsfiddle link you provided and it works perfectly.
{ "pile_set_name": "StackExchange" }
Q: Get user total purchased items count in Woocmmmerce I'm trying to figure out a function which get current user total number of purchased items (not total sum but items) across as all placed orders. So far I have found this (which doesn't work) - but again this function should get total sum and not items. Been trying to edit it to work but no success so far. public function get_customer_total_order() { $customer_orders = get_posts( array( 'numberposts' => - 1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => array( 'shop_order' ), 'post_status' => array( 'wc-completed' ) ) ); $total = 0; foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order ); $total += $order->get_total(); } return $total; } Any ideas? A: Updated (Taking in account the item quantity) The following very lightweight function will get the total purchased items count by a customer: function get_user_total_purchased_items( $user_id = 0 ){ global $wpdb; $customer_id = $user_id === 0 ? get_current_user_id() : (int) $user_id; return (int) $wpdb->get_var( " SELECT SUM(woim.meta_value) FROM {$wpdb->prefix}woocommerce_order_items AS woi INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id INNER JOIN {$wpdb->prefix}posts as p ON woi.order_id = p.ID INNER JOIN {$wpdb->prefix}postmeta as pm ON woi.order_id = pm.post_id WHERE woi.order_item_type = 'line_item' AND p.post_type LIKE 'shop_order' AND p.post_status IN ('wc-completed') AND pm.meta_key LIKE '_customer_user' AND pm.meta_value LIKE '$customer_id' AND woim.meta_key LIKE '_qty' " ); } Code goes in function.php file of your active child theme (or active theme). Tested and works. USAGE Example 1) Display the current user total purchased items count: <?php echo '<p>Total purchased items: ' . get_user_total_purchased_items() . '</p>'; ?> 2) Display the total purchased items count for a given user ID: // Here the user ID is 105 <?php echo '<p>Total purchased items: ' . get_user_total_purchased_items(105) . '</p>'; ?>
{ "pile_set_name": "StackExchange" }
Q: How to decode() with a subset of 'ascii'? I get bytecode data (b'something') which I try: to .decode('ascii') to check if this is ASCII text. The problem is that In [11]: b'\x00\x0c\x00'.decode('ascii') Out[11]: u'\x00\x0c\x00' so what is recognized as "text" is not really what I want (which are 32 to 126 ASCII codes). Is there a way to use a subset of 'ascii' for the decoding? A: in python 2: def test_if_ascii(text): if isinstance(test, unicode): raise TypeError('hey man, dont feed me unicode plz') return all(32 <= ord(c) <= 126 for c in text) in python 3 almost the same, just unicode is call 'str', and bytes are called 'bytes' def test_if_ascii(text): if isinstance(test, str): raise TypeError('hey man, dont feed me unicode plz') return all(32 <= ord(c) <= 126 for c in text)
{ "pile_set_name": "StackExchange" }
Q: After Pregnancy: exercise to close gap in vertical muscles in abs In "What to Expect When You're Expecting" after birth of baby, it advises to close the gap in your vertical ab muscles before going back to a strenuous routine. My questions are: 1) checking for the gap: I think this is going to be pretty easy to tell? Just palpating my abs to see if there is a gap (soft spot) in the middle of my belly? 2) the description for the work-out to close this gap is: "While on your back ("the basic position") inhale, cross your hands over your abdomen, using your fingers to draw the sides of your ab muscles together as you breathe out, pulling your belly button inward toward the spine while raising your head slowly. Exhale as you lower your head." I've translated this to: Inhale, raise head (so abs are clenched), massage abs inward as you exhale and lower head. Is that right? Does anybody have recommendations for other "closing the gap" exercises? 3) I had a pretty strong core before pregnancy, what if I can't detect a gap? Should I just do some "closing" exercises just to be sure? Should I see a sports doctor to verify? Thanks for the feedback! A: Seeing a doctor is always recommended if you have any health questions. Being a man, I've never been pregnant, so I can't testify to any of this, but according to what I've read I would definitely advise doing some of the "gap-closing" exercises before going back to a full workout routine. When you're pregnant, the muscles elongate and stretch, and the area in the center becomes weak. It's called "diastasis recti". It is possible that your abdominal muscles may not have separated during pregnancy. You should be able to feel a ridge running vertically up your abdomen if they have, and that ridge should become more pronounced if you strain or flex your abs. Pregnancy-Info.net suggests the following exercises: Lie on your back with your knees bent and feet flat on the floor. Work to bring your navel as close as possible to your spine, so it looks as if your stomach is "caving in". Hold this for a minute or two, while continuing to relax and breathe. Lie on your back with your knees bent and feet flat on the floor. Place both of your hands on your abdomen, fingers pointing towards your pelvis. Exhale and lift your head off of the floor, while pressing down with your fingers. (the exercise from your question) Lie on your back with your knees bent and feet flat on the floor. Exhale and extend one leg out in front of you. Wait for your abdomen to contract, and then inhale and place your leg back on the floor. Alternate legs. Wrap a long towel around your stomach with the ends in front of your abdomen. Do a crunch. As you raise your shoulders and head off of the ground, pull the ends of the towel towards one another. These exercises are meant to be a low-stress muscle building technique to prevent tearing or injuring the muscles or tendons in their weakened state. You should not do any abdominal exercises until after your stitches have been removed and your scars are healed if you had a cesarean section. Your shortened description of the exercise would be correct.
{ "pile_set_name": "StackExchange" }
Q: Do ESFs have different abilities? As a member of the Vanu Sovereignty, I know that the Scythe has a speed-boosting ability, but it looks like the TR Mosquito has landing gear or something, which I don't seem to have. What's that do? I assume that the NC has a third? A: Short answer: No. Longer answer: All Empire-Specific Fighter aircraft (Scythe, Mosquito and Reaver) start with the same basic afterburner ability. The acceleration and top speed this ability can achieve vary between specific fighters and can be altered by that aircraft's Performance certifications. If the pilot has invested points into the appropriate Utility Slot certifications, they may also be able to equip additional abilities, such as the Scout Radar (nearby enemies shown on map), Decoy Flares (disrupts missile lock-on attempts), Ejection System (pilots can bail out safely) and Fire Suppression System (removes the effects of critical damage). The abilities are the same across all factions. Other abilities are also available in the Defense Slot category, such as Composite Armor, Nanite Auto Repair System and Vehicle Stealth. These are passive systems that do not need to be activated.
{ "pile_set_name": "StackExchange" }
Q: val and def in Scala In Scala when we do like: val fIncr: (x: int) => x+1 My understanding is that here we are defining a function literal. Scala compiler would compile it into a class extending trait Function1 and in run-time it is instantiated and function value is assigned to fIncr. What happens if I define a similar function as method: def mIncr(x: Int) = x+1 Is this too compiled to a class? Edit: scala> val double = (i: Int) => { | println("I am here") | i * 2 | } double: Int => Int = $$Lambda$1090/773348080@6ae9b2f0 scala> double(4) I am here res22: Int = 8 scala> val evenFunc: (Int => Boolean) = { | println("I am here"); | (x => x % 2 == 0) | } I am here evenFunc: Int => Boolean = $$Lambda$1091/373581540@a7c489a scala> double res23: Int => Int = $$Lambda$1090/773348080@6ae9b2f0 scala> evenFunc res24: Int => Boolean = $$Lambda$1091/373581540@a7c489a scala> evenFunc(10) res25: Boolean = true scala> def incr(x:Int) = x+1 incr: (x: Int)Int scala> incr <console>:13: error: missing argument list for method incr Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing `incr _` or `incr(_)` instead of `incr`. incr ^ double and evenFunc are function variables and we have assigned function literals to them.But as output shows, when we call double, println statement is also executed.But evenFunc doesn't execute println statement, except when defined. incr is defined with keyword def, so its behaviour is as expected. A: When you do it using def, def mIncr(x: Int) = x+1 It is method in Scala. Method has not its own identity. It always belongs to a class. But when you do it using val, val mIncr = (x: Int) => x + 1 It is a function in Scala. Function is a complete object in Scala. It has its own identity. Functions are values in Scala. But Methods are not values. For example, If you write value, it will give you its information. scala> def mIncr(x: Int) = x + 1 mIncr: (x: Int)Int scala> val x = 4 x: Int = 4 scala> x res0: Int = 4 scala> val inc = (x: Int) => x + 1 inc: Int => Int = <function1> scala> inc res1: Int => Int = <function1> scala> mIncr <console>:9: error: missing arguments for method mIncr; follow this method with `_' if you want to treat it as a partially applied function mIncr Notice, when i wrote mIncr, compiler throws an error because it is not a value. Function values used to extend FunctionN trait befor Scala version 2.12 but after release of version 2.12. They don't create anonymous class. Read about it here Functions can be passed around like a parameter of functions. You can not do with methods. When you pass methods, Scala compiler does eta expansion under the hood. Eta expansion means it converts your method into a function value.
{ "pile_set_name": "StackExchange" }
Q: Check/Unckeck all, no layout change HTML/JavaScript I'm trying to create a basic website, but I have some difficulties with one aspect. I have some box to let the user show what they want or not (mostly layout) and I created a check/uncheck all button. The problem I'm having is that when I click manually on the boxes, the layout change correctly, but when I click on the check all button, nothing happens. I probably missed something, but I don't see what. Here is part of the html, and the JavaScript code associated that I'm trying to fix: function checkAll1() { var inputs = document.querySelectorAll('.control-path'); for (var i = 0; i < inputs.length; i++) { inputs[i].checked = true; } this.onclick = uncheckAll1; } function uncheckAll1() { var inputs = document.querySelectorAll('.control-path'); for (var i = 0; i < inputs.length; i++) { inputs[i].checked = false; } this.onclick = checkAll1; } var el = document.getElementById("checkall1"); el.onclick = checkAll1; <label class="control control-checkbox"> Show Planes flying <input class="control-path" id="pfshow" type="checkbox" onchange="planfly();"/> <div class="control_indicator"></div> </label> <label class="control control-checkbox"> Show planes on ground <input class="control-path" id="pfgroushow" type="checkbox"onchange="plangr();"/> <div class="control_indicator"></div> </label> <input type="button" id="CheckUncheckAll" value="Check/Uncheck all" /> A: No need to use 2 functions that essentially do the same thing, just keep a state on the button, and that should be enough, like: var checkButton = document.querySelector('#CheckUncheckAll'); var checkBoxes = Array.from( document.querySelectorAll('.control-path') ); // this event will handle any clicks to the button checkButton.addEventListener('click', function(e) { // newState has checked true by default, inverts per click var newState = (e.target.getAttribute('data-checkstate') || 'false') === 'false'; // set all the checkboxes to true checkBoxes.forEach(cb => cb.checked = newState); // save the current checkstate e.target.setAttribute('data-checkstate', newState); }); checkBoxes.forEach( cb => cb.addEventListener('click', function() { var checkedItems = checkBoxes.reduce( (total, cb) => total + (cb.checked ? 1 : 0), 0 ); if (checkedItems === 0) { // no items are checked, save that part checkButton.setAttribute('data-checkstate', false ); } else if (checkedItems === checkBoxes.length ) { // all items are checked, save that part checkButton.setAttribute('data-checkstate', true ); } } ) ); // stubs function planfly() {} function plangr() {} #CheckUncheckAll[data-checkstate=false]:before, #CheckUncheckAll:not([data-checkstate]):before { content: '☑ check all'; margin: 3px; padding: 5px; } #CheckUncheckAll[data-checkstate=true]:before { content: '☐ uncheck all'; margin: 3px; padding: 5px; } <label class="control control-checkbox"> Show Planes flying <input class="control-path" id="pfshow" type="checkbox" onchange="planfly();"/> <div class="control_indicator"></div> </label> <label class="control control-checkbox"> Show planes on ground <input class="control-path" id="pfgroushow" type="checkbox"onchange="plangr();"/> <div class="control_indicator"></div> </label> <button type="button" id="CheckUncheckAll"></button> So what really happens here is that your button will keep a state of the global checkstate, and will invert it according to your made clicks. A small thing I added was to handle individual boxes that get clicked, and if suddenly no check boxes are checked anymore that the state of the button gets handled accordingly. The css changes then also help in visualizing so that a user will know what will happen upon clicking the button, instead of guessing which of the 2 would happen ;)
{ "pile_set_name": "StackExchange" }
Q: libGDX project update with use of git I am working on a libGDX projects month ago, so there are several new versions of the framework. I have read, it is useful to update framework's files, but I have many classes, many assets. How can I update only the framework to the latest version? A: On the official wiki, this is the recommended way. However, I have found a new way to do the same thing. It may be a good way if you do not wish to open up your gradle file. open your libgdx setup gdx-setup.jar file (mine is the latest at this time 1.5.5). Setup your parameters the way you setup for your other old project. Make sure that you have set the destination to a different location than your old project (DON'T overwrite your old project because you will need it, and is a good backup) Open the project up in whatever editor you use. This is the important Section. You said that you wanted to keep your old classes and assets Copy your assets and classes from your previous project to the new project.You can even copy your old code from your old project*; NOTE: Libgdx update 1.5.5 updates the following parameters. If you have anything that applies to the following you need to rewrite [1.5.5] -> Added iOS ARM-64 bit support for Bullet physics -> 3D Animation, NodeAnimation keyframes are separated into translation, rotation and scaling -> Added capability to enable color markup from inside skin json file. -> Exposed method ControllerManager#clearListeners on Controllers class -> Net#openURI now returns a boolean to indicate whether the uri was actually opened. -> DefaultShader now always combines material and environment attributes -> Added ShapeRenderer constructor to pass a custom shader program to ImmediateModeRenderer20. -> API Change: Group#toString now returns actor hierarchy. Group#print is gone. -> Added SpotLight class, see https://github.com/libgdx/libgdx/pull/2907 -> Added support for resolving file handles using classpaths (ClasspathFileHandleResolver) Hope this helped you.
{ "pile_set_name": "StackExchange" }
Q: Disable inline editing for full grid in jqGrid How can I disable inline editing mode while I click on any row in jqGrid.? onSelectRow: function(id) { $("#toolbar").setColProp('mt_desc',{editable:false}); }, I got this one solution. but I think it's not feasible to add for every column name and add them into function. Whenever I click on edit button in actions, at that time Inline mode should be enable otherwise It must be disable. How can I do this? Can anybody please help me ? A: I got answer for question, I am posting this answer over here. Cause it may be helpful for you. You can disable every cell of row while you click on any cell using onSelectRow. onSelectRow: function(id) { if (id && id !== lastSel) { $("#toolbar").jqGrid('restoreRow',lastSel); var cm = $("#toolbar").jqGrid('getColProp','Name'); cm.editable = false; lastSel = id; } }, I got my solution. Thanks
{ "pile_set_name": "StackExchange" }
Q: problema al asignar un valor a mi input con jquery - k.fn.init(1) estoy intentando asignarle un el valor de mis rows de mi datatable a un input, pero tengo la siguiente situacion, al darle un console.log a la variable que me entrega el valor deseado, este me muestra correctamente este valor, pero al momento de asignar ese valor a mi input, me recibe esto k.fn.init(1) dejo a continuación el console.log del valor deseado (n_clase) y lo que recibe mi input (clase) Codigo var dt = $("#horarioPracticoEditar_dt").DataTable(); var n_clase = parseFloat(dt.rows().count()) + 1; var clase = $('#numero_clase').val(n_clase); console.log( [ n_clase, clase ]); console.log (2) [3, k.fn.init(1)] 0: 3 1: k.fn.init [input#numero_clase] length: 2 __proto__: Array(0) por cierto, también intente de esta forma y obtuve el mismo resultado var clase = $('#numero_clase').val(parseFloat(dt.rows().count()) + 1); A: Problema: El principal problema es la idea errónea de que devuelve $('#numero_clase').val(n_clase);. $('#numero_clase').val(n_clase); devuelve el objeto modificado para su posterior uso Y objeto.val() devuelve correctamente el value actual Solución: En vez de utilizar la salida de $('#numero_clase').val(n_clase); utilizar $('#numero_clase').val(); sin parametros para que devuelva correctamente la propiedad value. De está forma esa parte de código quedaría así: $('#numero_clase').val(n_clase); var clase = $('#numero_clase').val(); Api jquery -> val()
{ "pile_set_name": "StackExchange" }
Q: Could not load type 'ADODB._Recordset_Deprecated' from assembly 'ADODB, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Look, im facing aproblem, it started to give me some headache because im looking and looking and still not luck. I have to execute a method of a DLL from C#, this DLL was created like 4 years ago in VB 6.0 and it is registered in COM. It uses ADOB.Recordset as returning type of the method that I have to execute (no source code avaialble :S) I've been searching how to load and execute that DLL. I was having problems first loading it, I couldn't load it with Server.CreateObject, Assembly.Load, Assembly.LoadFrom so I tried to add it from references of the COM and the visual Studio Imported it in the Bin Folder with the name Interops.[Name of Dll] When Y try to use it, it gives me compile error it says: Error 1 No overload for method 'SelArregloCobertura' takes '6' arguments The parameters are correct, within its type and everything. Pretty sure of this So I tried to execute it with Reflection this is the code : ADODB.Recordset rs = new ADODB.Recordset(); string strRamo = "70"; string strSubramo = "01"; string strOficina = "070"; int iClaveSolicitud = 7118; string strModulo = "0"; int iInciso = 1; Poliza.clsdNTCoberturaClass oClass = new Poliza.clsdNTCoberturaClass(); MethodInfo miSelArregloCobertura = oClass.GetType().GetMethod("SelArregloCobertura"); miSelArregloCobertura.Invoke(oClass, new object[] { "70", "01", "070", 7118, "0", 1 }); //oClass.SelArregloCobertura(strRamo, strSubramo, strOficina, iClaveSolicitud, strModulo, iInciso); (I commented up the line that gives me the compile error) And the error is different, is not that compile error it gives me the error in the question Could not load type 'ADODB._Recordset_Deprecated' from assembly 'ADODB, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. When I go to the metadata of the dll it seems like this. [Guid("757AC98D-3800-406F-BA47-AEDAF2EBBCDB")] [TypeLibType(2)] [ClassInterface(0)] public class clsdNTCoberturaClass : _clsdNTCobertura, clsdNTCobertura { public clsdNTCoberturaClass(); [DispId(1610809344)] public virtual ADODB._Recordset_Deprecated SelArregloARenovar(string dFecha1, string dFecha2, string strNumOfic, short strCveAge, string strRamo); [DispId(1610809347)] public virtual ADODB._Recordset_Deprecated SelArregloCobertura(string strRamo, string strSubRamo, string strNumOfic, int lCveSol, string strModulSol, int lCveInc); [DispId(1610809348)] public virtual ADODB._Recordset_Deprecated SelArregloCobEst(string strRamo, string strSubRamo, short intCveInc, short intAnio, int lNumRec, string strOficRecl); [DispId(1610809349)] public virtual ADODB._Recordset_Deprecated SelArregloCobEstim(string strRamo, string strSubRamo, short intCveInc, short intAnio, int lNumRec, string strOficRecl); [DispId(1610809346)] public virtual ADODB._Recordset_Deprecated SelArregloNvaCobertura(string strRamo, string strSubRamo, string strNumOfic, int lCveSol, string strModulSol, int lCveInc, short intAnio, string strOficRecl, string intnumrec); [DispId(1610809345)] public virtual ADODB._Recordset_Deprecated SelCobertura(string strRamo, string strSubRamo, string strCveCober); [DispId(1610809350)] public virtual ADODB._Recordset_Deprecated SelEstCobertura(string strRamo, string strSubRamo, short intAnio, string strOficRecl, int lNumRec, short intCveInc, string strCveCober); } So I think there is a problem with the importing step, Anyone have an idea of how to make this works, or there is another form to load execute a method from a dll who is registered in COM? Any help would be really apreciated. Thanks in advance. A: Check Breaking change in MDAC ADODB COM components in Windows 7 Service Pack 1 Warning: this is a looooooooong post, your browser will hang for a while. Update: Microsoft made a decision to revert back the type library and spin off the new interfaces, see Windows 8 Developer Preview build contains the complete fix of the ADO typelib issue
{ "pile_set_name": "StackExchange" }
Q: restart and IndexOutOfBoundsException strange reason, How can I avoid this in the future? In 99% of cases working properly, sometimes as the application is minimized and I reopen it gets exception: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException for (int i = 0; i < list.size(); ++i) { description.setText(list.get(i).getStreet()); //this line Exception } I run this in onStart() method: What is the reason? How can I avoid this in the future? A: Using list within different threads can be a reason. If you are using not synchronized List implementation replace it with synchronized one: List list = Collections.synchronizedList(new ArrayList()); or Vector , or CopyOnWriteList . Edited: Thanks for the comments! They are correct. The simplest for me seems to be use CopyOnWriteArrayList and iterate over it with for-each loop. Or you can use any other option from this answer: Thread-safe iteration over a collection
{ "pile_set_name": "StackExchange" }
Q: how to create a Form from an object of case class I am using fold method of form as follows def regSubmit = Action { implicit request => userForm.bindFromRequest.fold({ formWithErrors=>BadRequest(views.html.Error("Registration failed")( formWithErrors.errors)) }, { userData=>Ok(views.html.regconf("Registration Successful")(**//here I want to send a Form, not data from the form**)) }) How can I create Form from a tuple or single variable, a class or a case class? A: userForm will (usually?) be defined as a val, so immutable. It holds the mapping (this field name into a variable in this position of this type, ...) When you use bindFromRequest.fold you are not changing userForm, you are using the mapping information in userForm to generate a new instance of your case class, say userData (or a version of the form with errors in it). Each time you execute that method, you will get a new instance of userData. userForm.fill(userData) returns a new form instance, a populated instance of the form, so also does not change userForm itself.
{ "pile_set_name": "StackExchange" }
Q: Swift generic operator I wrote a class like this one: struct Size { var width:Double=0 var height:Double=0 init(width:Double=0,height:Double=0) { self.width=width self.height=height } [...] } Now i want the ability to divide a Size for a certain number, and i would like to use generics to get the function for each type convertible to Double. For example Int, CGFloat, Float But when i insert the function: func /<T>(lhs:Size,rhs:T)->Size { return Size(width:lhs.width/Double(rhs),height:lhs.height/Double(rhs)) } I get the error error: cannot invoke 'init' with an argument list of type '(width: Double, height: Double)' return Size(width:Double(lhs.width/rhs),height:Double(lhs.height/rhs)) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ That is really weird because the list passed is of the exact types defined in the class (Double).. If i rewrite it in this way: func /<T>(lhs:Size,rhs:T)->Size { let drhs=Double(rhs) return Size(width:lhs.width/drhs,height:lhs.height/drhs) } then i get the error: error: cannot invoke 'init' with an argument of type 'T' let drhs=Double(rhs) ^~~~~~~~~~~ which is even weirder because the Swift library file has got a lot of initializers for Double, from Int, or Float types: extension Double { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) init(_ v: Int64) init(_ v: UInt) init(_ v: Int) } extension Double { init(_ v: Float) init(_ v: Float80) } What is wrong in my code? A: In swift generics require type safety which done by constraining it through protocols. This is a much better than in C++ where safety cannot be assumed with generics. Usually, you can use protocols from the Standard Library to implement these generics but unfortunately in your case you will need to define a special protocol and extend all the types that you want to be able to use. I've done it for Int and Float but you can do the same thing with all types you want to use. protocol DoubleConvertible { func toDouble() -> Double } extension Int : DoubleConvertible { func toDouble() -> Double { return Double(self) } } extension Float: DoubleConvertible { func toDouble() -> Double { return Double(self) } } func /<T : DoubleConvertible>(lhs: Size, rhs: T) -> Size { return Size(width: lhs.width / rhs.toDouble(), height: lhs.height / rhs.toDouble()) } The reason you have to do it manually is because none of the standard library protocols (that I know of) define a requirement such that numbers can be converted to a Double.
{ "pile_set_name": "StackExchange" }
Q: Excel VBA - Loop for populating ComboBox that doesn't add duplicates I'm populating a ComboBox on a userform with a loop it adds all the "names" in the first column of a table, that have the same "type" in the second column. I don't want to go into detail, but its possible that the same "name" occurs multiple times. I do not want the loop to add those duplicate values though. I found a few solutions on other forums, but those looked very outdated to me and I feel like this should have an easy fix. (These "outdated" solutions are like 30+ sentence codes, I don't feel like i need that) Can anyone help me further with this? This is the populating loop: With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then 'cbname is the combobox cbName.AddItem .Range(x, 1) End If Next x End With A: Try this: ' Create Dictionary object Dim obj As Object Set obj = CreateObject("Scripting.Dictionary") With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then ' If name doesn't exist in the Dictionary object yet, add the name to the listbox and the Dictionary object If IsEmpty(obj.Item(.Range(x, 1) & "")) Then 'cbname is the combobox cbName.AddItem .Range(x, 1) obj.Item(.Range(x, 1) & "") = .Range(x, 1) End If End If Next x End With The dictionary object allows you to use the name as a key. If the key doesn't exist, it adds the name to the listbox and adds the key. Next time it comes across the same name, that key already exists so it can move on to the next line. A: These "outdated" solutions are like 30+ sentence codes, I don't feel like i need that Though you already have an answer, here is another option using collections Sub Sample() Dim Col As New Collection, itm As Variant With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then On Error Resume Next Col.Add .Range(x, 2).Value, CStr(.Range(x, 2).Value) On Error GoTo 0 End If Next x End With For Each itm In Col cbName.AddItem itm Next End Sub
{ "pile_set_name": "StackExchange" }
Q: Fast way of deleting non-empty Google bucket? Is this my only option or is there a faster way? # Delete contents in bucket (takes a long time on large bucket) gsutil -m rm -r gs://my-bucket/* # Remove bucket gsutil rb gs://my-bucket/ A: Buckets are required to be empty before they're deleted. So before you can delete a bucket, you have to delete all of the objects it contains. You can do this with gsutil rm -r (documentation). Just don't pass the * wildcard and it will delete the bucket itself after it has deleted all of the objects. gsutil -m rm -r gs://my-bucket Google Cloud Storage object listings are eventually consistent, and the bucket delete can't succeed until the bucket listing returns 0 objects. So sometimes it can take some time for the bucket to appear empty after all of the objects are deleted. In this case, you can get a Bucket Not Empty error (or in the UI's case 'Bucket Not Ready') when trying to delete the bucket. The solution is to retry the delete, and gsutil has built-in retry logic to do so. A: Another option is to enable Lifecycle Management on the bucket. You could specify an Age of 0 days and then wait a couple days. All of your objects should be deleted. A: Using Python client, you can force a delete within your script by using: bucket.delete(force=True) Try out a similar thing in your current language. Github thread that discusses this
{ "pile_set_name": "StackExchange" }
Q: Calculator algorithm I'm trying to create a calculator that can peform simpel operations and you should be able to have several values and different operators. It's not done yet so it will be improved later on but right now I have problem with the method that performs the calculation. Before I post the relevant code. The other part is just Swing object instantiation. private class OperatorListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource()== resetButton){ Operators.clear(); Numbers.clear(); actualNumber.setText(""); previousNumbers.setText(""); } else if(e.getSource() == sumButton){ Numbers.add(new Double(actualNumber.getText())); Double Result = performCalculation(Numbers, Operators); actualNumber.setText(String.valueOf(Result)); previousNumbers.setText(""); } else if(e.getSource() == sqrtButton){ } else { /* * The operator numbers handlers. When a operator * button is clicked the number in the lower JTF * is parsed to Double value and added to Numbers * list. Operator added to Operators list. Lower * JTF is cleared.*/ Numbers.add(new Double(actualNumber.getText())); Operators.add(e.getActionCommand()); String currentPriovusNumbers = previousNumbers.getText(); previousNumbers.setText(currentPriovusNumbers + " " + actualNumber.getText() + " " + e.getActionCommand()); actualNumber.setText(""); } } } private double performCalculation(ArrayList<Double> Numbers, ArrayList<String> Operators){ double result = Numbers.get(0); for(int index = 0; index < Numbers.size(); index++){ switch(Operators.get(index)){ case "+": result += Numbers.get(index + 1); break; case "-": result -= Numbers.get(index + 1); break; case "/": result /= Numbers.get(index + 1); break; case "*": result *= Numbers.get(index + 1); break; case "%": result %= Numbers.get(index + 1); break; } } return result; } The error I'm getting is this: Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 at java.util.ArrayList.rangeCheck(ArrayList.java:604) at java.util.ArrayList.get(ArrayList.java:382) at com.calculatorSwing.business.Calculator.performCalculation(Calculator.java:146) at com.calculatorSwing.business.Calculator.access$6(Calculator.java:143) Line 146 is the first switch case statement which lets me know that there is no such index that I try to access but I've checked the Operators list and there is a "+" inside element 0. What is the problem? A: Change your for loop of performCalculation method. From: for(int index = 1; index <= Numbers.size(); index++) To: for(int index = 1; index < Numbers.size(); index++) According to your for loop following ArrayList get will be Exception. Numbers.get(Numbers.size());// will generate IndexOutOfBoundsException.
{ "pile_set_name": "StackExchange" }
Q: Equivalence of two statements on an arbitrary partially ordered set $(A, <)$ Let $(A, <)$ a arbitrary partially ordered set. ( $<$ is irreflexive and transitive) These two statements are equivalent: Every nonempty subset of $A$ that is bounded from above has a supremum in $A$ Every nonempty subset of $A$ that is bounded from below has an infimum in $A$ My attempt: Let the first statement be true and I will try to prove the second follows.(I suspect the second direction will be pretty much the same) Let $C\subset A$ be an arbitrary subset of $A$ that is bounded from below. Let $D$ denote the set of all lower bounds of $C$. So we have $\forall c \in C, \forall d \in D, d < c$. I have to prove that $D$ has the biggest element(definition of infimum). I know that $D$ is a set that is bounded from above, then it follows that $D$ has a supremum, let's denote it by $S$. Now, I know, $(\forall d \in D)( d < S \lor d = S)$. But I don't know how to prove that $S\in D$. Because if $S \notin D$ then $S$ doesn't have to be comparable to any $c \in C$ since the set is partially ordered, then $S$ is definitely not the infimum of $C$ which I think it should be. Thanks in advance! A: Suppose $S\not\in D$. Then $S$ is not a lower bound for $C$ and so there exists $c\in C$ such that $c\lt S$. This is impossible because all elements of $c$ are upper bounds for $D$ so $S$ would not be the least upper bound for $D$. This is a contradiction. Edit: There is a slight problem with this proof due to the fact that the order is a partial order. Thank you to drhab for pointing it out. The fix is simple enough and I can do it without deriving a contradiction. For any $c\in C$ and any $d\in D$, $d\le c$ so $c$ is an upper bound for $D$. Since $S$ is the least upper bound, $S\le c$. Since this is true for every $c\in C$, $S$ is a lower bound for $C$ and hence, is in $D$.
{ "pile_set_name": "StackExchange" }
Q: Is there an elegant, Pythonic way to count processed data? I often have time consuming processing steps that occur within a loop. The following method is how I keep track of where the processing is at. Is there a more elegant, Pythonic way of counting processing data while a script is running? n_items = [x for x in range(0,100)] counter = 1 for r in n_items: # Perform some time consuming task... print "%s of %s items have been processed" % (counter, len(n_items)) counter = counter + 1 A: Yes, enumerate was built for this: for i,r in enumerate(n_items,1): # Perform some time consuming task print('{} of {} items have been processed'.format(i, len(n_items))) The second argument determines the starting value of i, which is 0 by default.
{ "pile_set_name": "StackExchange" }
Q: namespaces in application settings I am migrating an old application to a newer .NET-version. The current application stores arrays with user settings into the registry. In the new application I want to change this mechanism into .NET Application settings (app.config), but I have only figured out so far how to store one-dimensional values in there, for example... My.Settings.myName1 = "John Doe" My.Settings.myMail1 = "[email protected]" My.Settings.myName2 = "Lorem Ipsum" My.Settings.myMail2 = "[email protected]" I guess it is possible somehow to work not only with single values, but with arrays, too, which ideally could be accessed by a namespace, something like this: REM just demo code to display what i want, no idea if something like this works... My.Settings.myContacts(1).Name = "John Doe" My.Settings.myContacts(1).Mail = "[email protected]" My.Settings.myContacts(2).Name = "Lorem Ipsum" My.Settings.myContacts(2).Mail = "[email protected]" Is something similar possible? If not, is there another way how to work with multidimensional values / arrays in the .NET Application settings? A: .NET app settings are key, value pair only. If you want multidimensional values in app.config you should look at implementing your own custom config section. See http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
{ "pile_set_name": "StackExchange" }
Q: What are values of fundamental frequency and the harmonics for the below signal g(t)? We know that a Fourier series formula for any signal $s(t)$ is given as $$\frac {a_0} 2 + \sum \limits _{m=1} ^\infty (a_m \cos \frac {2 \pi m t} T + b_m \sin \frac {2 \pi m t} T)$$ Here,as we see from the formula ,except the DC component and fundamental frequency components there are all harmonics present at right side of the Fourier series formula. Let us consider 4 sinusoidal periodic signal $$x(t),y(t),z(t) and g(t)$$ such that $$x(t)=\cos \frac {1.2*2 \pi t} 8$$ $$y(t)=\cos \frac {1.4*2 \pi t} 8$$ $$z(t)= \cos \frac {1.6 \pi t} 8$$ and $$g(t)=x(t)+y(t)+z(t)$$ Then, How would you apply Fourier series formula for a signal $$g(t)$$ which is nonharmonic? If there are fundamental frequency and harmonics present ,can anybody tell me what are they and their values? A: In general, Fourier coefficients are given by the formulas: $$a_n = \frac{2}{T}\int_{x_0}^{x_0+T}g(x)\cos\left(\frac{2\pi nx}{T}\right)dx\\ b_n = \frac{2}{T}\int_{x_0}^{x_0+T}g(x)\sin\left(\frac{2\pi nx}{T}\right)dx$$ For any integrable \$g(x)\$ on the interval \$[x_0, x_0+T]\$. For periodic functions this interval can correspond to the period of the function, such that the Fourier series will be perfectly equal to the function itself. But the case of your example is very simple - it's just a sum of three cosines, so the \$a_n\$ terms can be calculated directly and there would be three of them. \$b_n\$ would equal to zero, as there is no sine terms.
{ "pile_set_name": "StackExchange" }
Q: Count character occurrences in a string in C++ How can I count the number of "_" in a string like "bla_bla_blabla_bla"? A: #include <algorithm> std::string s = "a_b_c"; size_t n = std::count(s.begin(), s.end(), '_'); A: Pseudocode: count = 0 For each character c in string s Check if c equals '_' If yes, increase count EDIT: C++ example code: int count_underscores(string s) { int count = 0; for (int i = 0; i < s.size(); i++) if (s[i] == '_') count++; return count; } Note that this is code to use together with std::string, if you're using char*, replace s.size() with strlen(s). Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the for loop everytime, but can just use count_underscores("my_string_") in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill. A: Old-fashioned solution with appropriately named variables. This gives the code some spirit. #include <cstdio> int _(char*__){int ___=0;while(*__)___='_'==*__++?___+1:___;return ___;}int main(){char*__="_la_blba_bla__bla___";printf("The string \"%s\" contains %d _ characters\n",__,_(__));} Edit: about 8 years later, looking at this answer I'm ashamed I did this (even though I justified it to myself as a snarky poke at a low-effort question). This is toxic and not OK. I'm not removing the post; I'm adding this apology to help shifting the atmosphere on StackOverflow. So OP: I apologize and I hope you got your homework right despite my trolling and that answers like mine did not discourage you from participating on the site.
{ "pile_set_name": "StackExchange" }
Q: How can I start and 2d Array from index [1][1] instead of [0][0] How can i create an array where the first value is not stored at 0 but instead at 1. This is for a theatre seating program where the rows and columns must start at 1 not 0. Please help!I've Been stuck on this for the past 2 days!! int[] [] myarray = new int [2] [3]; A: This is my best guess at what you want to mimic the orginal array structure in Java using it as a 1 indexed array public class OneIndexed2DArray { int[][] indexedArray; public OneIndexed2DArray(int row, int col) { indexedArray = new int[row + 1][col + 1]; } public int GetValue(int row, int col) throws ArrayIndexOutOfBoundsException { if(row == 0 || col == 0) { throw new ArrayIndexOutOfBoundsException(); } else return indexedArray[row][col]; } public void SetValue(int row, int col, int value) throws ArrayIndexOutOfBoundsException { if(row == 0 || col == 0) { throw new ArrayIndexOutOfBoundsException(); } else indexedArray[row][col] = value; } } Then create it like so int[] [] myarray = new int [2] [3]; becomes OneIndexed2DArray myarray = new OneIndexed2DArray(2, 3); Set a value at [1][1] = 1 myarray.SetValue(1, 1, 1); Get that value int theValue = myarray.GetValue(1,1); Throws an exception if 0 is used as an index to behave as if the 2D array doesn't have 0 index myarray.SetValue(0, 1, 5) returns ArrayIndexOutOfBoundsException myarray.GetValue(1, 0) returns ArrayIndexOutOfBoundsException You'll have to add more functionality to get things like the size and so on but this should get you started.
{ "pile_set_name": "StackExchange" }
Q: jQuery is adding servlet name twice to URL I am trying to complete the tutorial at http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=438 It seems that the servlet is trying to POST the data to http://localhost:8080/WeatherServlet/WeatherServlet ... (WeatherServlet is the name of the servlet - duh). I have the following index.jsp page (which displays fine) <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#getWeatherReport").click(function(){ $cityName = document.getElementById("cityName").value; $.post("WeatherServlet", {cityName:$cityName}, function(xml) { $("#weatherReport").html( $("report", xml).text() ); }); }); }); </script> </head> <body> <form name="form1" type="get" method="post"> Enter City : <input type="text" name="cityName" id="cityName" size="30" /> <input type="button" name="getWeatherReport" id="getWeatherReport" value="Get Weather" /> </form> <div id="weatherReport" class="outputTextArea"> </div> </body> </html> The following WeatherReport.java page package org.ajax.tutorial; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class WeatherReport */ public class WeatherReport extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WeatherReport() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String city = request.getParameter("cityName"); String report = getWeather(city); response.setContentType("text/xml"); PrintWriter out = response.getWriter(); out.println("<weather><report>" + report + "</report></weather>"); out.flush(); out.close(); } private String getWeather(String city) { String report; if (city.toLowerCase().equals("trivandrum")) report = "Currently it is not raining in Trivandrum. Average temperature is 20"; else if (city.toLowerCase().equals("chennai")) report = "It’s a rainy season in Chennai now. Better get a umbrella before going out."; else if (city.toLowerCase().equals("bangalore")) report = "It’s mostly cloudy in Bangalore. Good weather for a cricket match."; else report = "The City you have entered is not present in our system. May be it has been destroyed " + "in last World War or not yet built by the mankind"; return report; } } The following web.xml page <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" > <servlet> <description>Weather Data provider</description> <display-name>Weather Data provider</display-name> <servlet-name>WeatherServlet</servlet-name> <servlet-class>ajaxify.WeatherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WeatherServlet</servlet-name> <url-pattern>/WeatherServlet</url-pattern> </servlet-mapping> </web-app> I am creating a WAR archive and deploying using Eclipse's built in tools (not ant - doubt this matters anyway). A: You're posting to "WeatherServlet" within the jQuery, which is a relative URL - and the original URL is http://server.com/WeatherServlet/index.jsp, so it's no wonder that the URL it builds is http://server.com/WeatherServlet/WeatherServlet Change $.post("WeatherServlet", {cityName:$cityName}, function(xml) { to $.post("index.jsp", {cityName:$cityName}, function(xml) { or whatever jsp you want it to post to.
{ "pile_set_name": "StackExchange" }
Q: Unable to Group on MSAccess SQL multiple search query please can you help me before I go out of my mind. I've spent a while on this now and resorted to asking you helpful wonderful people. I have a search query: SELECT Groups.GroupID, Groups.GroupName, ( SELECT Sum(SiteRates.SiteMonthlySalesValue) FROM SiteRates WHERE InvoiceSites.SiteID = SiteRates.SiteID ) AS SumOfSiteRates, ( SELECT Count(InvoiceSites.SiteID) FROM InvoiceSites WHERE SiteRates.SiteID = InvoiceSites.SiteID ) AS CountOfSites FROM (InvoiceSites INNER JOIN (Groups INNER JOIN SitesAndGroups ON Groups.GroupID = SitesAndGroups.GroupID ) ON InvoiceSites.SiteID = SitesAndGroups.SiteID) INNER JOIN SiteRates ON InvoiceSites.SiteID = SiteRates.SiteID GROUP BY Groups.GroupID With the following table relationship http://m-ls.co.uk/ExtFiles/SQL-Relationship.jpg Without the GROUP BY entry I can get a list of the entries I want but it drills the results down by SiteID where instead I want to GROUP BY the GroupID. I know this is possible but lack the expertise to complete this. Any help would be massively appreciated. A: I think all you need to do is add groups.Name to the GROUP BY clause, however I would adopt for a slightly different approach and try to avoid the subqueries if possible. Since you have already joined to all the required tables you can just use normal aggregate functions: SELECT Groups.GroupID, Groups.GroupName, SUM(SiteRates.SiteMonthlySalesValue) AS SumOfSiteRates, COUNT(InvoiceSites.SiteID) AS CountOfSites FROM (InvoiceSites INNER JOIN (Groups INNER JOIN SitesAndGroups ON Groups.GroupID = SitesAndGroups.GroupID ) ON InvoiceSites.SiteID = SitesAndGroups.SiteID) INNER JOIN SiteRates ON InvoiceSites.SiteID = SiteRates.SiteID GROUP BY Groups.GroupID, Groups.GroupName;
{ "pile_set_name": "StackExchange" }
Q: Stop Vue Components being render in Laravel I have fresh installed Laravel application also I installed npm, now every page I try to load this file will load instead ExampleComponent.vue app.js /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('example-component', require('./components/ExampleComponent.vue')); const app = new Vue({ el: '#app' }); ExampleComponent.vue <template> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Example Component</div> <div class="card-body"> I'm an example component. </div> </div> </div> </div> </div> </template> <script> export default { mounted() { console.log('Component mounted.') } } </script> Question As I don't have plan to use VueJs and I also need to see my actual pages that I'm created, how I stop VueJs of being render in my application? A: In your app.js remove everything after the bootstrap include, then recompile using npm run dev. However, by default Laravel does nothing with Vuejs. Because it has no html elements on the page with id #app. Check your resources/views directory, the default blade file is welcome.blade.php. To be exact about the flow: your routes file indicates how to handle requests and to which controller the controller responsible for the route will (probably) serve a blade view the blade view will be parsed, if it has an #app element and app.js binds Vue to #app Vue will take over. https://github.com/laravel/laravel/blob/master/resources/views/welcome.blade.php
{ "pile_set_name": "StackExchange" }
Q: How to get an attribute of the selected feature and pass it into a URL? As a total Novice with Python, I thought 2 weeks would be enough time to learn how to build some tools for our GIS... I was wrong and I'm running up on a deadline. I am attempting to get a value from a selected feature in geodatabase, and pass that value into a URL link / query after the equals sign. Opening the link to the image viewer works, if I don't try to pass in the field value. After 9 days of reading training manuals my eyes are raw. How can I fix this... import arcpy import pythonaddins import webbrowser from threading import Thread def GetParameterAsText (str.Unit_No): "This prints a passed through string into this function" import str row.getValue(Unit_No) def OpenBrowserURL (): url = 'http://fcweb/caviewer#unit=' webbrowser.open(url,new=2) class CAVButton(object): """Implementation for PythonButton_addin.CAVbutton (Button)""" def __init__(self): self.enabled = True self.checked = False def onClick(self): t = Thread(target=OpenBrowserURL) t.start() t.join() A: You're missing a lot of implementation here, and the code you do have contains syntax and logic errors. Indentation is part of the syntax in Python, so you must be consistent and know when and where to indent. Also you reference variables that have not yet been defined, e.g. str (which is a built-in function, so don't use that name) and row. You need to implement logic to get the desired attribute from the selected feature in the desired layer, as well as to format the URL with that value. Geoprocessing tools and functions automatically honor selections applied to layers in the map, so using that you could pass the name of the desired layer into a SearchCursor and it will only return the selected rows/features. You might want to first check how many features are selected by running a Get Count first and checking that exactly 1 feature is selected, if that is the desired behavior. One slightly tricky part is that you'll need to pass the "unit" value to your OpenBrowserURL function, and to do that you'll need to specify the args or kwargs argument of the Thread constructor. e.g.: def GetSelectedUnit(): """TO DO""" raise NotImplementedError def OpenBrowserURL(unit): url = "http://fcweb/caviewer#unit={0}".format(unit) webbrowser.open(url,new=2) class CAVButton(object): def onClick(self): unit = GetSelectedUnit() t = Thread(target=OpenBrowserURL,args=(unit,)) t.start() t.join()
{ "pile_set_name": "StackExchange" }
Q: Readers-writers problem with writer priority Problem In the book "Little Book of Semaphores", p. 71, there is the following problem: Write a solution to the readers-writers problem that gives priority to writers. That is, once a writer arrives, no readers should be allowed to enter until all writers have left the system. I arrived at a solution, but it's a bit different from the one given in the book. My solution Shared variables: readSwitch = Lightswitch() writeSwitch = Lightswitch() noWriters = Semaphore(1) noReaders = Semaphore(1) Semaphore(1) means a semaphore initialized to 1, and Lightswitch is defined in the book like this: class Lightswitch: def __init__(self): self.counter = 0 self.mutex = Semaphore(1) def lock(self, semaphore): self.mutex.wait() self.counter += 1 if self.counter == 1: semaphore.wait() self.mutex.signal() def unlock(self, semaphore): self.mutex.wait() self.counter -= 1 if self.counter == 0: semaphore.signal() self.mutex.signal() Reader logic: noReaders.wait() noReaders.signal() readSwitch.lock(noWriters) # critical section for readers readSwitch.unlock(noWriters) Writer logic: writeSwitch.lock(noReaders) noWriters.wait() # critical section for writers writeSwitch.unlock(noReaders) noWriters.signal() Book's solution Shared variables: readSwitch = Lightswitch() writeSwitch = Lightswitch() noWriters = Semaphore(1) noReaders = Semaphore(1) Reader logic: noReaders.wait() readSwitch.lock(noWriters) noReaders.signal() # critical section for readers readSwitch.unlock(noWriters) Writer logic: writeSwitch.lock(noReaders) noWriters.wait() # critical section for writers noWriters.signal() writeSwitch.unlock(noReaders) Questions 1) In the reader logic, in my solution, noReaders.signal() immediately follows noReaders.wait(). The idea here is that noReaders behaves as a kind of turnstile that allows the readers to pass through it, but is locked by a writer as soon as one arrives. However, in the book's solution, noReaders.signal() is done after calling readSwitch.lock(noWriters). Is there any reason why my ordering would produce an incorrect behavior? 2) In the writer logic, in my solution, writeSwitch.unlock(noReaders) comes before noWriters.signal(). However, the book places them in the reverse order. Is there any reason why my ordering would produce an incorrect behavior? Edit: additional question I have an additional question. There is something that I am probably misunderstanding about the book's solution. Let's say that the following happens: Reader 1 acquires noReaders (noReaders becomes 0) Reader 2 waits in noReaders (noReaders becomes -1) Writer 1 waits in noReaders (noReaders becomes -2) Reader 3 waits in noReaders (noReaders becomes -3) Reader 4 waits in noReaders (noReaders becomes -4) Reader 1 acquires noWriters (noWriters becomes 0) Reader 1 signals noReaders (noReaders becomes -3; Reader 2 gets unblocked) Reader 2 passes through noWriters lightswitch; signals noReaders (noReaders becomes -2, Reader 3 gets unblocked) In the above situation, it seems that additional readers can keep arriving and entering the critical section although a writer is waiting. Besides, considering that reader and writer are looping, a reader that finished the critical section could loop around and wait on noReaders again, even if there are writers already waiting. What am I misunderstanding here? A: With your solution, the following situation is possible: A new writer comes after writeSwitch.unlock(noReaders) but before noWriters.signal() New writer executes writeSwitch.lock(noReaders) A reader executes readSwitch.lock(noWriters), going into critical section even if there is a writer. The book's solution wakes up waiting writers first before waking up the readers. Your solution wakes up readers first, and also allows readers to queue up at readSwitch.lock(noWriters) so they can run even if there is a writer waiting.
{ "pile_set_name": "StackExchange" }