INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Python: os.path.realpath() - how to fix unescaped backslashes? I want to get the path to the currently executed script.I have used `os.path.realpath(__file__)`, however, it returns a string like `D:\My Stuff\Python\my_script.py` without proper backslash escaping! How to escape them?
path = "D:\My Stuff\Python\my_script.py" escaped_path = path.replace("\\", "\\\\") print(escaped_path) Will output D:\\My Stuff\\Python\\my_script.py
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, python 3.4" }
In Azure API Management can i use the subscription-key as part of Request headers instead of Query string parameter? I am migrating a service to Azure API Management. This service is being called from mobile devices (native apps). Problem is that appending the subscription-key to the query string can take much longer for updating the app than just using it in the request headers. So is it possible to use it there?
The subscription key can be passed either in the header or in the URL query parameter. The header is checked first. The query parameter is checked only if the header is not present. The header name is `Ocp-Apim-Subscription-Key` by default though you can change it; the same holds for the query parameter whose default name is `subscription-key`.
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 12, "tags": "azure, azure api management" }
Who sees Twitter messages starting with @? When I do a tweet starting by `@AnotherUser` like this: @AnotherUser Hello I would like to tell you that ... **will the tweet appear in the timeline of my followers?** If so, it would be annoying because the goal is to do a "Direct message" to someone. (Why don't I do a Direct message? Because you cannot do a direct message to someone who doesn't follow you.)
> will the tweet appear in the timeline of my followers? Assuming it's a new tweet, your followers and the followers of the person you're mentioning will see it. If it's an actual reply, only those people who follow you _and_ that person you're replying to will see it. A note: You _can_ direct message someone who doesn't follow you if they've turned on the "Anyone Can send messages" feature. * * * Sources: * Here's how Twitter @mentions are changing * Twitter Is Finally Putting an End to Tweets That Start with “.@” * Twitter blog: Coming soon: express even more in 140 characters
stackexchange-webapps
{ "answer_score": 2, "question_score": 1, "tags": "twitter, twitter direct message" }
Number of unique pairings of k values. So to make this clear, this is not just n choose 2. what im talking about is related to this: Combination of splitting elements into pairs but also all pairs less than 6. so basically for 3 values 1,2,3 you have 3 pairings: $${(1,2),3}, $$ $${(2,3),1},$$ $${(1,3),2}$$ for 4 values you have all single pairs and 2 left over: $${(1,2),3,4},$$ $${(1,3),2,4},$$ $${(1,4),2,3},$$ $${(2,3),1,4},$$ $${(2,4),1,3},$$ $${(3,4),1,2}$$ all double pairings: $${(1,2),(3,4)},$$ $${(1,3),(2,4)},$$ $${(1,4),(2,3)}$$ so a total of 6+3 = 9 pairings. for 5 there is: 1 pair,3 left over and 2 pairs, 1 leftover and so on. I'm wondering if there is a closed formula for this and I am looking for the value of 13. I would really appreciate the help.
You can get a formula (although maybe not very closed-form, you would definitely want a computer to do this for you) via that logic. First with one pairing, you have $n \choose 2$ possibilities. For 2 pairs, you have ${n\choose2} {n-2\choose 2}$, but notice that this has an order given to the two pairs, so we divide by 2!. For 3 pairs, you get $\frac1{3!}{n\choose2}{n-2\choose2}{n-4\choose2}$, and so on. So, you can write the answer as a sum. From a quick calculation, you can find the values here: < So for 13, there are 568503 pairings.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "combinatorics, extremal combinatorics" }
Binding dynamically created combobox to property on viewmodel I'm looking to bind a ComboBox created at runtime to a property on the ViewModel. I've tried something along these lines combobox.SetBinding(ComboBox.SelectedValueProperty, new Binding("WCSettings.ViewModels.WinCAPSIniViewModel.selectedItem") { Source = combobox.SelectedValue, Mode = BindingMode.OneWayToSource }); The binding only needs to go one way (View --> ViewModel), so the value can be stored in a database. 'combobox' is the instance of the ComboBox being created.
Binding the `SelectedValue` property of a ComboBox and at the same time setting the `Source` of the binding to the same property doesn't make sense. You need to have an instance of the view model and use that as the binding source. And unless you also set the `SelectedValuePath` property of the ComboBox, you should bind the `SelectedItem` property. WCSettings.ViewModels.WinCAPSIniViewModel viewModel = ... combobox.SetBinding(ComboBox.SelectedItemProperty, new Binding("selectedItem") { Source = viewModel , Mode = BindingMode.OneWayToSource }); And just in case you forgot, `selectedItem` needs to be a public property in class WinCAPSIniViewModel.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, wpf, mvvm, binding, combobox" }
Attempting to use an IF VLOOKUP in a conditional formatting formula and getting invalid formula I've got a list of data validated options that pull from another sheet in the spreadsheet (e.g. a list of options on a hidden sheet to make the drop down menu nice and neat) and I want to conditionally uncover checkboxes for options on the list that need them, but the conditional formatting doesn't like my `IF VLOOKUP` to uncover the square. Right now I have it so the square is by default background colored black with the 'text' in the box black too, so the checkboxes are hidden. If you select an option with a checkbox needed, I want the formatting to clear (white background, normal text) so you see the checkbox as intended. I've tried a few google searches but nothing seemed to clear it up for me. =IFERROR(IF(VLOOKUP(A42,'Mastery Data Table'!$A$25:$D$156,3,FALSE)=1,TRUE,FALSE),FALSE) I'm using `IFERROR` because some options have no data in column 3 at all.
when referencing another sheet in CF you need to wrap it into `INDIRECT`: =IFERROR(IF(VLOOKUP(A42, INDIRECT("'Mastery Data Table'!$A$25:$D$156"), 3, 0)=1, TRUE, FALSE), FALSE)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "if statement, google sheets, vlookup, google sheets formula, gs conditional formatting" }
How to deploy Open Policy Agent in a Google Kubernetes cluster I'm new to k8s, and I want to deploy OPA in the same pod as of my application in Google Kubernetes engine. But I don't know how to do this.Are there any references that I can refer more details about this ? Could you please help me figure out the steps I should follow ?
It should similar as deploying to any Kubernetes cluster as documented here. The difference could be you may want to use a LoadBalancer type service instead of NodePort.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "kubernetes, google kubernetes engine, open policy agent" }
How to solve inequalities which have absolute value inside absolute value? I know how to solve if I have something like this: $$|2x + 3| - |1 - x| \geq 3$$ But I don't know how to solve something like this: $$|x + |3x + 9|| \geq 3$$ Anyone can show me how to start solving this type of absolute value in inequalities?
It is the same as you do it when you have only one absolute sign. I would do the following; $x + |3x+9| \geq 3$ or $x + |3x+9| < -3$ $|3x+9| \geq 3-x$ or $|3x+9| < -3-x$ case 1. $|3x+9| \geq 3-x$ case 2. $|3x+9| < -3-x$ Let's consider case 1 first, **case 1.** $|3x+9| \geq 3-x$ $3x+9 \geq 3-x$ or $3x+9 < -(3-x)$ $4x \geq -6$ or $ 2x < -12$ $x \geq -3/2$ or $x < -6$. Now consider case 2. **Case 2** $|3x+9| < -3-x$ $3x+9 < -3-x$ or $3x-9 \geq 3+x$ $x < -3$ or $x \geq -3$ Now for the final answer, you have to consider 4 regions of $x$ values; $x \geq -3/2$ or $x <-6$ or $x <-3$ or $x >= -3$ That is, the answer is : $(-\infty , -6) \cup [-3, \infty)$ Hope this helps you. Thanks.
stackexchange-math
{ "answer_score": 0, "question_score": 2, "tags": "inequality" }
Mirroring with regex in wget I'm using wget and trying to mirror all 98 folders on a website. What would be the syntax to do "wget -mk Thanks.
for i in $(seq 1 98);do echo " -mki -
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "regex, wget" }
How do you get WPF to work like Forms at design time? A bit new with WPF...It seems like not matter what I change with horizontal and vertical alignment, WPF has a mind of its own when resizing my controls in design time. I created a new Window, placed a couple of buttons and text boxes and whenever i change the size of the window all the controls get resized. Is there a way to lock it down or am I missing something obvious?
The layout you are using might be a Grid. Try replacing that with a **_Canvas_** and you will get the similar behavior as win forms design. Suggestion: When we use WPF the adavantage we can get is the resizability and be able to dynamically arrange(Change) controls inside a layout etc.. So Try using dynamic layouts than static layouts like "Canvas"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "wpf, controls, resize" }
What happens to fields not named by a designated initializer? In C99 (and not in C++), it's possible to initialize structs using this syntax: struct info { char name[8+1]; int sz; int typ; }; struct info arr[] = { [0] = { .sz = 20, .name = "abc" }, [9] = { .sz = -1, .name = "" } }; What happens to the unspecified fields?
They are zeroed. From the C99 standard §6.7.8 (Initialization)/21, > If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, **the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.**
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 19, "tags": "c, initialization, designated initializer" }
Prerendering d3 and key functions I'm using webpack's prerender-spa-plugin to prerender `d3` code. When I serve the prerendered html to the client using the same javascript code there's one place where I'm rebinding new data using a key function, like so: svg.selectAll("g") .data(data, d => d.name) // TypeError: cannot read property name of undefined .call(myPlot); I believe this happens because the prerendering step does not save bound data to the html DOM elements, so the rebinding on the first join cannot access the `name` field because the selection has no bound data. What's a good workaround for this?
I've found a solution for now, but I'll wait a few days before accepting my own answer in case anyone has a better solution. My solution has two parts: 1. Handle `undefined` in the data join key function so that data can be bound to the prerendered DOM elements by falling back to an index-join. 2. If using transitions, make sure entering elements are initialized at their final positions so that they don't animate from a default (usually 0) value. This makes sure the served pre-rendered HTML is correct. So here's the code: svg.selectAll("g") .data(data, d => d ? d.name : undefined) // fall back to an index join given a prerendered DOM without bound data .join(enter => enter.append("g").call(myPlot)) // entering elements don't transition .transition() .call(myPlot);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, d3.js, webpack, prerender" }
Function that takes a nested list of strings and returns a new nested list with all strings capitalized? This will capitalize them but only if there are no nested lists. t = ['this','that', ['other']] def capitalize_nested(t): res = [] for s in t: res.append(s.capitalize()) return res print capitalize_nested(t) I can't figure out how to get it to print out a nested list having all of the strings start with a capital letter. I must be missing something obvious, this just has me stumped.
Use a recursive solution (and using list comprehensions also helps make it more compact): def capitalize_nested(t): if isinstance(t, list): return [capitalize_nested(s) for s in t] else: return t.capitalize() For example: print capitalize_nested(['this', 'that', ['other']]) # ['This', 'That', ['Other']]
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 6, "tags": "python, function, capitalize" }
How to register an AppleScript as a potential default web browser? I've written an AppleScript that I want to set as the default browser. I've added a `CFBundleDocumentTypes` section to the p-list (copied from Safari) and rebuilt the launch services database, but that didn't work. The script doesn't show up in the Safari default browser list. If I choose it manually in that preferences dialog, it's ignored, and Safari becomes the default browser.
Have you tried adding the `CFBundleURLTypes` and the sub-key `LSIsAppleDefaultForScheme`? <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>Web site URL</string> <key>CFBundleURLSchemes</key> <array> <string>http</string> <string>https</string> </array> <key>LSIsAppleDefaultForScheme</key> <true/> </dict> </array> Not sure that it will help, but I have noticed these keys in the info.plist of all the apps that I have checked that show up in that browser list.
stackexchange-apple
{ "answer_score": 4, "question_score": 5, "tags": "macos, applescript" }
Can't get viewDataField to work in MVC 3 DropDownList control I cannot figure out why the properties won't set for this control. Here's the control code: @Html.DropDownList("SetViewModel[" + i + "].Value", new SelectList(@Model.Datasource.Where(c => c.listId == setting.Datasource).Select(c => c.value), "value", "description", setting.Value)) The error I continue to get is: **"DataBinding: 'System.String' does not contain a property with the name 'value'. "** But the property names seem to be "value" and "description." How can I confirm that I have the right property names? The Model.Datasource traces back to the ORM which has properties of "value" and "description." When I step through the code and hover over the setting.Datasource text I see properties called "value" and "description." I'm very confused. Has anyone dealt with this before? Thank you!
You're trying to pass a set of objects, not strings. Remove the `Select` call.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net mvc 3, drop down menu, razor" }
Seed for $RANDOM environment variable in bash I am working on a bash script that uses the `$RANDOM` environmental variable as an input in a simulation. The variable does what it say, give random integers, and I as far I understand it is taken from `/dev/random`. However I would like to have a reproducible simulation, then the pseudo-random generator should be initialized with a seed; is it possible to have a seed for the `$RANDOM` variable in bash?
From the man page: RANDOM Each time this parameter is referenced, a random integer between 0 and 32767 is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDOM is unset, it loses its special properties, even if it is subsequently reset. Note that assigning a value to `RANDOM` actually seeds it; the assigned value won't be the next value returned. $ RANDOM=1341 $ echo $RANDOM $RANDOM $RANDOM 26571 16669 28842 $ echo $RANDOM $RANDOM $RANDOM 14953 18116 2765 $ RANDOM=1341 $ echo $RANDOM $RANDOM $RANDOM 26571 16669 28842 $ echo $RANDOM $RANDOM $RANDOM 14953 18116 2765
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 6, "tags": "bash, random, seed" }
WR Line while swimming Watching the Olympics I have found the swimming very interesting. I've noticed that while the swimmers are swimming the TV Channel (BBC) projects a line across the width of the pool saying WR (World Record) at the end. I'm a bit unsure about this line, I know it's to show where the swimmers would need to be at to get the World Record but is the line showing where the swimmer who holds that world record was at that point or is it showing the required place through out? e.g. say the 100m WR was 50 seconds, then the line would progress 10m every 5 seconds.
I'm pretty sure it shows the world record pace, rather than the position of the holder at that point in the race - i.e. it advances at a constant speed. Unless the TV company had exact positional data on every world record swim, it would be impossible to plot the position of the swimmer. The only reference I can find is at < which doesn't seem authoritative, while the page at < in the final section, talks about the line but doesn't mention the specific question asked. EDIT: See the second bullet point from <
stackexchange-sports
{ "answer_score": 7, "question_score": 5, "tags": "records, olympics, swimming" }
best way to create/split string to tags In my php application user able to enter the tags(like here while ask question). I assume it will be regexp, and I used one - mb_split('\W+', $text) - to split by non-word characters. But I want to allow users to enter characters like "-,_,+,#" etc which are valid ones to be in url and are common. Is there exiting solutions for this, or may be best practicles? thanks.
Use the explode() function and separate by either spaces or commas. Example: $string = 'tag1 tag-2 tag#3'; $tags = explode(' ', $string); //Tags will be an array
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 5, "tags": "php, regex" }
How to link two sentences? I have the following sentences: > Anyone can use stock footage. and > Only you know how to use it correctly. I am wondering if it makes sense to combine them as such > Anyone can use stock footage, only you know how to use it correctly. I am implying that even though these stock footage may be free it still takes talent to select the right one and put them together.
### You should add a _but_ after the comma > Anyone can use stock footage, **but** only you know how to use it correctly. Reading a _but_ basically makes people ignore most of what has been said before and focus their attention on what is being said after the _but_. This way you can emphasize that while anyone can use the footage it takes someone with a certain amount of experience in the specific domain or talent to use the footage correctly or efficiently.
stackexchange-writers
{ "answer_score": 1, "question_score": 1, "tags": "creative writing, style, technique, structure, word choice" }
What's a polite way to ask if the interview would be face-to-face or Skype? A company just asked me if I'm available for an interview but did not mention whether it's a face-to-face or Skype. I wanted to ask if she wants a Skype interview or prefers I went to her office? I'm currently out of state, so I can only do Skype interviews.
Just be honest and clear, without an elaborate explanation. Explain that you are out of states and that you would know if it is possible to have the interview via Skype. Also, I suggest you propose them to have a face-to-face interview when you come back, as an alternative given the Skype interview is not an option. You say they reached you via e-mail, so you should ask how/where the interview is taking place when you reply to them (given that you confirm your desire of being interviewed).
stackexchange-workplace
{ "answer_score": 4, "question_score": 1, "tags": "interviewing, internship" }
The Twenty Doors (ROOM 9) This is part of The Twenty Doors series. The previous one is The Twenty Doors (ROOM 8) The next one is The Twenty Doors (ROOM 10) * * * When you go into Room 9, there is a strange hint, signed by 'Dr. X': > Duplicates, go forth! The hint key is keyed with a key of key! ovnr wPraor o aZcdsua fretsfdes > \- Dr. X There is a rather confusing hint: `The hint key is keyed with a key of key! Sfb lkgm ygofbq vkr trba ex sfb Dbqlkmr gm VVG. Sfks'r sfb nmjx fgms xnt'qb dbssgmd ex abygofbqgmd sfgr rsqgmd!` And, last, the keypad: ` [1][2][3][4][5] [ENTER] ` The next door will be added when this door is solved!
The hint on the wall _Sfb lkgm ygofbq vkr trba ex sfb Dbqlkmr gm VVG. Sfks'r sfb nmjx fgms xnt'qb dbssgmd ex abygofbqgmd sfgr rsqgmd_ is: > **The main cipher was used by the Germans in WWI. That's the only hint you're getting by deciphering this string** using Keyed Caesar with key **KEY** _ovnr wPraor o aZcdsua fretsfdes_ decrypted is: > **Press four to advance forwards** using the UBCHI cipher with key **KEYKEY** To get to the next room, we must press: > **4**
stackexchange-puzzling
{ "answer_score": 3, "question_score": 4, "tags": "cipher" }
Swift SHA1 function without HMAC i try to get SHA1 working in swift. without using CommonCrypto since it is not default in swift. please see < (since it's a little to big to post) if i run a test case in Xcode: func test_sha1() { XCTAssertEqual(sha1("test"), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3") } it will fail, and return `2d891cc96e32c32e8d26704d101208b954f435a5` i got the hash with: $ php -r "echo sha1('test');echo(PHP_EOL);" a94a8fe5ccb19ba61c4c0873d391e987982fbbd3 i think the problem is that in the javascript file they use `>>>` and i don't know what this operator is. So i have used `>>`. i hope someone can help. Thanks in advance
I've got a solution, there was something wrong with the rotate function. i have changed the rotate function to func rotate(n: Int, _ s: Int) -> Int { return ((n << s) & 0xFFFFFFFF) | (n >> (32 - s)) } and now it works.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, swift, sha1, commoncrypto" }
Getting fat arrow behaviour when passing function references If I'm passing a function in ES6: methodAcceptsFunction(this.myFunction); ...is there a way in ES6 to avoid having to call `.bind()` on it similar to the fat arrow behaviour? methodAcceptsFunction(() => { this.myFunction(); }); In the first case, `this` is bound to the function. But in the second, `this` is more in line with class-style programming.
> is there a way in ES6 to avoid having to call `.bind()` on it similar to the fat arrow behaviour? No there is not. > similar to the fat arrow behaviour The way arrow functions work is that their environment simply doesn't have a `this` value, so `this` is looked up in the parent environment. It is not possible to modify the characteristics of a function environment of an existing function.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "ecmascript 6" }
php dom problem hello I'm new to PHP programming and I migrated from ASP .net to PHP.. I have a div just like below `<div id="mydiv"></div>` what I wanted to do is just to change the text and html content(like some name or any data in it) in it. What I imagine is just like mydiv=>innertext="some value"; Thanks, GURU
Are you trying to modify the div in the same page as the php? I don't think that's possible. PHP runs at the server, and only sees content between the php tags. If you're modifying dom content, it seems like javascript/jQuery is a better approach for this. Otherwise, if you're modifying content that is hosted already, and plan output it to a different page, then you can use this: PHP Simple HTML DOM Parser
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
If-Statement going crazy (or me?) This is one of my parameters of my bash script. But it seems that there's something going wrong. Bash script: case "${1}" in --api ) if ( "${2}" == "US" ); then sparkEndpoint=" shift elif ( "${2}" == "EU" ); then sparkEndpoint=" shift else echo -e ${parameterNotSpecified} echo -e ${usageApi} break fi shift ;; [...] Console output: ./fn_sendmail.sh --api EU ./fn_sendmail.sh: Zeile 95: EU: Kommando nicht gefunden. ./fn_sendmail.sh: Zeile 98: EU: Kommando nicht gefunden. You called an option but didn't specified it! Usage of --api --api [eu,us] Description: Sets the API endpoint for Sparkpost Necessary: No Default: EU
1) Use [] instead of () 2) Use = instead of == See the comment of @GordonDavisson to understand why
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "bash" }
Joining Multiple Large Tables I have three tables Table T1: Columns {a,b,c}, combination {a,b} is unique in Table T1 Table T2: Columns {a,c,d}, combination {a,c} is unique in Table T2 Table T3: Columns {a,c,e}, combination {a,c} is unique in Table T3 where {a,b,c} are strings and {d,e} are numbers I want my output to be Table T4: Columns {a,b} where e/d < x. Tables T1,T2,T3 are all very large (millions of rows), so the way I implemented this is by doing an left join on table T1 T2 and saving the results to a temp table, then doing an left join on tables T1 T3 and saving the results, then doing an left join of the results and finally combining these temp tables into 1 final table. My question is, is there a better/more efficient way to do this without blowing up the database?
Have you tried just doing this the straight-forward way? select t1.a, t1.b into t4 from t1 join t2 on t1.a = t2.a and t1.c = t2.c join t3 on t1.a = t3.a and t1.c = t3.c where t3.e / t2.d < x Storing millions of records in temp tables isn't good for performance or storage...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, sybase" }
How to get the files from amazon s3 cloud storage I am using `scandir()` function to scan the directory from the cloud. This function working in the local system but not worked in the sever. I have run this function using php code in the server i het the following error Warning: scandir(https:// xxxx/yyyy/folder/): failed to open dir: No such file or directory Warning: scandir(): (errno 2): No such file or directory Warning: Invalid argument supplied for foreach() How to solve this error..
You have to access the S3 Bucket for getting files from cloud server.. Refer this
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, amazon s3" }
Editing LaTeX with Emacs - search for unused \ref When writing a .tex document, I often have labeled equations. When finishing the document, I sometimes find that I haven't referenced all of the equations. So, I need to look for the equations which I haven't referenced, and disable numbering for those equations. How can I do this in Emacs? Basically, I need to search for all \label{*}. Then, for each * I find, let me know if there is less than 1 corresponding \ref{*}. Thanks. (I guess it really is time for me to learn LISP).
_Hacky_ Perl, suitable for a one-off. Neither tested nor proved correct. The capture regex may grab both the entire match and the () match, I don't recall offhand. If it does, grab the odds for the job. use strict; use warnings; #standard slurp my ($fh, $file); open $fh, "<", "mydatafile" or die("$!:mydatafile"); { local $/ = undef; $file = <$fh>; close $fh; } #grab all captures. my @labels = ($file =~ /\\label{(.*?)}/msg); #hashes are easier for existence checks my %labels = map {$_ => 1 } @labels; my @refs = ($file =~ /\\ref{(.*?)}/msg); my %refs = map {$_ => 1 } @refs; foreach (keys %labels) { print "Error, $_ not referenced\n" unless $ref{$_}; }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "emacs, latex" }
How to make an AJAX call using Rails on an Action other than Create or Destroy I want to create an AJAX call on an action, let's call it seen, so that a field in my database gets updated on a click. This is a follow-up question to a previous response I got yesterday, so bear with me because I am rather inexperienced. <%= button_to "Click me!", :action => "some_action", :remote => true %> Which will send an AJAX request back to the server, in which you need to handle in your controller def some_actoin // Update your database here respond_to do |format| format.js { render 'somepartial' } end end Does this answer essentially mean that I need to create a route associated with the def some_action? If so what format should this route take. I don't want the user to navigate away from the page, I just simply want to update one div on the current page.
You've got a good start. When that button is clicked rails/the server will send an HTTP request to that controller/some_action. It will hit that action method where you need to save to the database. From there it will respond with javascript (hence the format.js). The javascript file it is responding with (assuming you are using jquery and not prototype) will be called some_action.js.erb . Within that file you put all of your jquery function calls etc that you want to occur once that ajax request has returned. EDIT: To further clarify with the routes. You need to be able to access controller/some_action as normal. This means that there needs to be a route defined: match 'controller/some_action' => "controller#some_action" however you don't need to do anything extra to tell rails its a remote route.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, sql, ruby on rails, ruby, ajax" }
Compiling CUDA SDK V4.1.28 For Linux? When trying to compile the most recent CUDA SDK from Nvidia (version 4.1.28) for linux, I get the following error: > error: identifier "CURAND_STATUS_DOUBLE_PRECISION_REQUIRED" is undefined My google-fu yields only similar problems, and not solutions. I have an older version of the SDK (version 4.0.17) which compiles fine. So this might be a bug in the SDK, or there is/are environment variable(s) I didn't set.
Not really an "answer", but an ugly quick fix is to comment out the line 328. It doesent impact my program, but there is no guarantee that it does not affect yours.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "compilation, cuda, nvidia" }
Parsing a JSON string of 50,000+ characters into a javascript object I'm trying to evaluate a string of 50,000+ characters from an ajax GET request using jquery. On smaller datasets, the code will evaluate it correctly, but firefox throws an error "Unterminated string literal". After some digging, I tried using external libraries from JSON.org, replacing \n, \r\n, and \r with an empty string (on the server), and encapsulating the eval() with parentheses. Here is some of the client-side code (javascript): < <\- Here I've used an external library to do it After looking through firebug, I noticed that the json string returned by the server was not complete, and was cut off at 50,000 or so characters. I know for a fact the server is returning a valid json string because I dumped it to a file before sending it to the client, but the client ends up receiving a truncated version. Why is this happening? Is there any way around this?
Turns out the NetworkStream I used in my c# server could not have a buffer that large, so I just wrote half of the buffer, flushed it, and wrote the other half. Thanks for helping guys.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "javascript, jquery, ajax, string, json" }
How to check if a label is bold with Selenium WebDriver using Java? Please find below the sample HTML code: <div class="form-element email-address" id="gmail-address-form-element"> <label id="gmail-address-label"> <strong> Choose your username </strong> <input type="text" maxlength="30" autocomplete="off" name="GmailAddress" id="GmailAddress" value="" spellcheck="false"> <span class="atgmail">@gmail.com</span> </label> I need to verify "Choose your username" label is bold with Selenium WebDriver. Appreciate if the language used is java.
You can use the getComputedStyle to get the style of the element. Use `font-Weight` to check if it is bold or not JavascriptExecutor js = (JavascriptExecutor) driver; WebElement element = driver.findElement(By.cssSelector("#gmail-address-label > strong")); String fontWeight = (String) js. executeScript( "return getComputedStyle(arguments[0]).getPropertyValue('font-Weight');", element); if (fontWeight.trim().equals("bold")) { System.out.println("Is Bold"); } else { System.out.println("Not Bold - " + fontWeight); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, selenium, selenium webdriver" }
Focal Length of Camera View according to Distance I'm working on an app related to Augmented Reality. It has a gallery that let you select the picture and frame and then a Live Camera Preview shows you how it'll look on your wall. In this live preview use set its distance from wall i.e. `1 meters to 6 meters` and the picture adjusts accordingly and shows in the live camera view. For now I'm using the assumed values like: case 1: self.imageObject.frame = CGRectMake(self.imageObject.frame.origin.x , self.imageObject.frame.origin.y, 180, 180); break; Suppose if the initial size of all the images is `200x200` pixels so what will be the formula from which I can get the exact value that if frame size is `200x200` at `1m` and when it taps `2m` the size changes to the exact 2m value of frame just like a real focal value. Its like distance to pixels conversion what I'm thinking.
This link might help you. What you need to do is you should know the camera focal length of iPhone camera. It'll be different for 5s, 6 or 6 plus. For a lens of focal length `f` corresponding to lens power `P` an object distance of `o` will produce an image at `i` The linear magnification will be `M`. The formula is `1/object distance + 1/image distance = 1/focal length`. Visit the link to have a more clear idea.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, frame, pixel, cgrectmake" }
Simple jQuery selector does not work I have no Idea why this selector does not work. The HTML element is simply: <div id="myDiv">Original Text</div> and the script I am using is simple: <script language="javascript" src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#myDiv").innerHTML = "Replaced Text"; }); for some reason this does not work, while two other options does work: **Option 1:** document.getElementById("myDiv").innerText = "This will work!" **Option 2:** $("#myDiv").get(0).innerHTML = "This will work as well!" Every tutorial I was reading is saying that the selector will simply work if I use $(#id) as I did. Any ideas?
`$("#myDiv")` is jQuery object, you can't set its `innerHTML` property because it doesn't have one. Use the jQuery method `.html()` or `.text()` $("#myDiv").html("Replaced Text"); Option 1 works because it's just plain JS - you select the element and set its property. Option two works because you get the DOM element from the jquery object and set its property - also valid.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "jquery, jquery selectors" }
Haskell if statement is not working properly Very simple code. It will get the third last item from a list. list numbers = if length numbers > 3 then numbers!!(length numbers - 3) else "length must be greater than 2" When i try to run it on the GHCI I keep getting this error however, *Main> list [2,3,4] <interactive>:65:7: No instance for (Num [Char]) arising from the literal `2' Possible fix: add an instance declaration for (Num [Char]) In the expression: 2 In the first argument of `list', namely `[2, 3, 4]' In the expression: list [2, 3, 4]
The types of the two expressions in the `then` and `else` clause must match. Since one side of the branch returns a list element, and the other side returns a string, ghci concludes that the list elements must be strings. But you specified `[2,3,4]`, whose elements are numbers. Hence the complaint: it doesn't know how to turn a number into a `String`. Consider returning a `Maybe` or `Either` value instead: list numbers = if length numbers > 3 then Right (numbers!!(length numbers - 3)) else Left "length must be greater than 2" -- sic: 3, not 2
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "list, haskell, if statement" }
Should I use accented characters in URLs? When one creates web content in languages different than English the problem of search engine optimized and user friendly URLs emerge. I'm wondering whether it is the best practice to use de-accented letters in URLs -- risking that some words have completely different meanings with and without certain accents -- or it is better to stick to the usage of non-english characters where appropriate sacrificing the readability of those URLs in less advanced environments (e.g. MSIE, view source). "Exotic" letters could appear anywhere: in titles of documents, in tags, in user names, etc, so they're not always under the complete supervision of the maintainer of the website. A possible approach of course would be setting up alternate -- unaccented -- URLs as well which would point to the original destination, but I would like to learn your opinions about using accented URLs as _primary_ document identifiers.
When faced with a similar problem, I took advantage of URL rewriting to allow such pages to be accessible by either the accented or unaccented character. The actual URL would be something like And a rewriting+character translating function allows this reference to load the same resource. So to answer your question, as the _primary_ resource identifier, I confine myself to 0-9, A-Z, a-z and the occasional hyphen.
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 68, "tags": "unicode, internationalization, friendly url, diacritics" }
Clarification about the ZFC's axiom 0. Let's consider the "axiom 0" of ZFC: $\exists x (x=x)$ I "think to" it as "there exist something which is equal to itself, in other words there exist at least something". But on the notes where I am studying I find: "There exists at least a set". My question is: what is the correct interpretation? If the latter, why $x$ must be a set and can't be a proper class, for example? Thanks in advance.
In $\sf ZFC$ objects of the universe are called sets. Something exists if it is an object of the universe, so if an axiom of set theory says that something exists, we say that there is a set with such and such properties. (The same it true for other theories, $\sqrt 2$ is a real number since it exists in the real numbers, where as $\sqrt{-1}$ is not a real number for similar considerations. The difference is that we have some "absolute" understanding of what is a real number, but we don't have such understanding regarding sets.) So what does the axiom tells us? Really just that some set exists. The universe is not empty.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary set theory" }
Is there a beamer auto-indent program? > **Possible Duplicate:** > Tool for cleaning LaTeX code Beamer presentation files are very structures, they have sections, in which you find subsections, which include frames that have titles and then itemizations lists consisting of many items. It would be nice to have a program that auto-indents the _input_ file based on this structure. I have output of the following sort in mind: \begin{frame}{title} {subtitle} \begin{itemize} \item My first item \item My second item \item My third and very very long third item which occupies more than my pre-specified line length which is (say) 80 characters. \item My fourth item comprising a description \begin{description} \item[First Item] Described here. \end{description} \end{itemize} \end{frame}
You don't need a special program for that. Just use an good editor. Vim, Emacs are able to auto-indent. Others maybe too. If you have not so well formatted code, you have to reformat the code. I can only speak for Vim. Here you just have to mark the code you want to reformat and then press z= Give it a try.
stackexchange-tex
{ "answer_score": 2, "question_score": 0, "tags": "beamer, editors, tools, sourcecode, cleanup" }
Is it possible to take images of extrasolar planets? Is is possible with today's technology, to take a photo of an extra-solar planet? This applies not only to the visual wavelength (380-780 nm), but any wavelength.
Yes. Here is the first image of an extrasolar planet taken from 2005: <
stackexchange-space
{ "answer_score": 12, "question_score": 8, "tags": "imaging" }
Round off floating point number to two decimal places in CLIPS CLIPS gives a floating point number upto many decimal places. e.g CLIPS> ( / 4 3) 1.33333333333333 How do I get a value rounded off to two decimal places (1.33 in this case)
CLIPS (6.31 6/12/19) CLIPS> (bind ?n (/ 4 3)) 1.33333333333333 CLIPS> (/ (integer (* ?n 100)) 100) 1.33 CLIPS> (deffunction precision (?num ?digits) (bind ?m (integer (** 10 ?digits))) (/ (integer (* ?num ?m)) ?m)) CLIPS> (precision ?n 2) 1.33 CLIPS> (precision ?n 4) 1.3333 CLIPS> (precision ?n 0) 1.0 CLIPS>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "clips" }
Set up MS cluster 2016 with multi forest domain i am trying to set up a two node MS cluster 2016 with cross forest. currently i am having two separate domains and having trust between domains. like a.com and b.com domains and trust enabled between them. One server is in a.com and another server is in b.com, i want to enable a MS cluster between them. i know we can do Domain-Detached Cluster setup using local accounts. is there any way using with domain account to setup this cluster between the forest.
You can deploy Multi-domain Cluster (Domain-independent cluster). The major thing is to configure DNS-suffix. Domain-independent cluster cannot be created without using local Administartor account. For more detail follow the link: <
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "windows server 2016, failovercluster, windows cluster" }
Why is my NSString variable outputting "1" when using ofstream? Here is what I have so far: minute++;//this code is in a for loop where this variable is being incremented NSString *minuteString; NSDate *currentDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MM/dd/YY"]; NSString *dateString = [dateFormatter stringFromDate:currentDate]; if(minute < 10){ minuteString = [NSString stringWithFormat:@"%@ 00:0%d:00",dateString,minute]; } if(minute > 10){ minuteString = [NSString stringWithFormat:@"%@ 00:%d:00",dateString, minute]; } ofs << minuteString << ","; When I use `NSLog(@"%@",minuteString)`, the correct string is outputted. However, when the stream outputs to the CSV file I have setup, the output is the number 1. I am not sure why this is occurring.
Because C++ std::ofstream can not handle ObjectiveC classes. You need to convert NSString to std::string to be able to use ofstream. Something like: std::string std_str([ ns_str UTF8String ] ) ; ofs << std_str; std::ofstream is from the standard C++ library. NSString is from ObjectiveC library. Different libraries and different programming languages. They weren't designed to work together. You can mix these things in your code because your compiler understands them, but you need to provide a bridge. It is a good idea to mix languages together on a library level, not on a lower level. That is if you have one cleanly separated piece of functionality implemented in ObjectiveC (e.g. GUI) and another in C++ (e.g. game physics, business logic) then you create a thin layer to pass data between libraries. Otherwise, use a single language.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ios, objective c" }
Is it possible to loop a vimeo video in AMP-HTML? The problem I have with amp-vimeo is that once the video finishes it goes onto vimeo's 3 x 3 "suggested videos". I am trying to get it to loop to keep showing the video I want to be shown, is there a way of doing this? Or are there solutions to avoid seeing the suggested videos. Possibly an image once the video finishes? I've tried adding in loop like amp-video documentation hoping that it may work for both with no success. `<amp-vimeo data-videoid="x" layout="responsive" autoplay width="500" height="281"> </amp-vimeo> `
Upon checking `<amp-vimeo>` component, the attribute `loop` is not supported. I would like to suggest to use `<amp-video>` that has an attribute `loop`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "amp html" }
Why is my button not an object? Is it because it is in the header? When I run this code var button=document.getElementById("button") if (navigator.userAgent.indexOf('iPhone') != -1) { button.style.left = 250; } The error is result of expression is not an object. The object "button" is in the css file and it is the only one named button. What am I doing wrong? Does it have something to do with the button being in the header? I'm using dashcode.
Try var button=document.getElementById("button").object `getElementById` gives you the HTML DOM node for the button; you have to access its `object` to do all of the fancy Dashcode stuff to it. (I stumbled around with the same question for a while!)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "button, getelementbyid, dashcode" }
Inline NOT operator using boolean I have this snippet of code: if (bool) { return <code that outputs bool>; } else { return !<same code that outputs bool>; } Is there a way to convert the above to something like this so that I don't have to write the code twice? return (bool? !! : !) <code>;
Found it! return bool === <code> I wrote down a truth table and saw this code T F +-+- T|T|F bool +-+- F|F|T Which is the same table as bool = code
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, boolean operations" }
Is the long billion (one million million) still used over the short billion (1000 million)? I read that, in the USA, one billion is considered to be 1×109 (1 000 000 000). In Mexico, it's 1×1012 (1 000 000 000 000). Are both values used by American English speakers?
One billion is 10^9. One trillion is 10^12. This use is standard for English speakers in the USA, Australia, Canada and in the UK. The "short" scale was adopted by the UK government in 1974, but some older speakers may prefer the long scale. There is the potential for confusion, especially among speakers of other languages (Spanish in the USA or French in Canada) who use the long scale in their native language, so it would not be impolite to ask to confirm.
stackexchange-ell
{ "answer_score": 2, "question_score": 4, "tags": "american english, numbers" }
Generating shortcode and displaying in admin area Basically I'm writing a plugin to create sliders. Upon installing this plugin, it creates a custom post type called 'sliders' and populate them with ACF. I've also created shortcode to display slider on pages/post. Shortcode works like this -> [slider id=12] , and this will display slider with the id of 12. What I'm trying to find a way of displaying the shortcode in the admin area which users can just copy instead of looking for ID number. Here's the example. ![enter image description here]( Thanks.
Assuming `sliders` is your CPT slug, you can use `manage_sliders_posts_columns` to add column head. add_filter('manage_sliders_posts_columns', 'wpso_custom_columns_head'); function wpso_custom_columns_head($defaults) { $defaults['shortcode'] = 'Shortcode'; return $defaults; } After adding column heading, now we need to add content for the column. Use `manage_sliders_posts_custom_column` hook. Using this you can echo shortcode. add_action('manage_sliders_posts_custom_column', 'wpso_custom_columns_content', 10, 2); function wpso_custom_columns_content( $column_name, $post_ID ) { if ( 'shortcode' === $column_name ) { echo '[shortcodename id="' . $post_ID . '"]'; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, wordpress, plugins, shortcode, wordpress shortcode" }
Changing the type of the elements in a nested list I have the object `tableaux :: [[[Int]]]` and I want to change it to `[[[Int32]]]`. I do: int32ToInt :: Int32 -> Int int32ToInt = fromIntegral tableaux32 = map (\y -> map (\x -> map intToInt32 x) y) tableaux Is there a better way?
Consider that `(\x -> map f x)` is simply `map f`. How many times do you see this pattern in your function? I see it twice.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "haskell" }
Percentage distribution of column occurence? I am looking for a way to calculate the distribution of column values in my table. e.g. if I have two rows containing "red" and "blue", each should have 50%. I want to count the occurence of `col` and compare that to the overall amount of rows. My attempt: SELECT log_domain, count(log_domain), count(log_domain) over(), ROUND( COUNT(log_domain) / COUNT(*) OVER() ,2) AS percentage FROM logs GROUP BY log_domain Any help? Thank you!
Just pay attention to integer division. I often just multiply by 1.0: SELECT log_domain, COUNT(*), COUNT(*) OVER (), ROUND(COUNT(*) * 1.0 / SUM(COUNT(*)) OVER (), 2) as ratio FROM logs GROUP BY log_domain; I also notice that the denominator needs to be `SUM(COUNT(*))` rather than `COUNT(*)`. Your version just divides by the number of rows in the result set -- that is, the number of values of `log_domain`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, postgresql" }
Does android have a slider view? Hi i was wondering if android has view that responds to user slides. If you want to know exactly what i mean there is one in the galaxy tab for unlocking the phone and muting/activating sound on the bottom of the screen. Seems like the iPhone slide to unlock feature. Thanks in advance I appreciate the help!
GestureOverlayView might help you. See also: < <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, view, slider" }
"Но ведь... и ведь", - забыла правило про запятые > Пусть для современников Христос существовал повсюду и церковь не была его резиденцией или местом вынесения приговора, но ведь не Христос, а епископ занимал почётное место на троне, и ведь не Христу приносилась здесь жертва – она освящалась для верующих. Запятая перед "и ведь"... У нас что - ССП? "Христос/епископ занимал", "жертва приносилась"?
Я думаю, здесь сложное предложение с разными видами сочинительной, подчинительной и бессоюзной связи. К двум простым, связанным сочинительным союзом И, относятся два однородных уступительных придаточных (Пусть для современников Христос существовал повсюду и церковь не была его резиденцией или местом вынесения приговора). Поэтому между ЭТИМИ придаточными не ставим запятую. Но только ВТОРОМУ простому предложению (ведь не Христу приносилась здесь жертва) противопоставлено последнее простое (она освящалась для верующих). Поэтому после "троне" стоит запятая.
stackexchange-rus
{ "answer_score": 2, "question_score": 1, "tags": "пунктуация" }
entity framework navigation property with object from database Question has Author. When adding a new question, I take the author from the database with getCurrentUser(); Question q=new Question(); q.Author=getCurrentUser(); context.Questions.Add(q); this generates The EntityKey property can only be set when the current value of the property is null. because Author already has a value for Id. How should I specify that the author is already in the database?
You must use the same context instance for both adding the question and loading the user if you want this simple code to work. If you want to use two context instances you must modify your code: Question q=new Question(); User u = getCurrentUser(); context.Users.Attach(u); q.Author = u; context.Questions.Add(q); In some cases it can be also necessary to detach user from the context in `getCurrentUser` method.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "entity framework" }
Solve for $z$ : $(z+1/z)^n=1$ I have solved that $z+1/z= \cos (2k\pi/n) + i \sin (2k\pi/n)$ where $k$ is integer, then how can I continue?
One may continue as follows: setting $\omega = e^{2 \pi i /n}, \tag 1$ we see that $\omega^k = e^{2k \pi i / n} = \cos \dfrac{2k\pi}{n} + i \sin \dfrac{2k\pi}{n}, \; 0 \le k \le n - 1, \tag 2$ so with $z + \dfrac{1}{z} = \omega^k, \tag 3$ we write $z^2 - \omega^k z + 1 = 0, \tag 4$ and apply the quadratic formula: $z = \dfrac{\omega^k \pm \sqrt{\omega^{2k} - 4}}{2}, \; 0 \le k \le n -1. \tag 5$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "complex analysis" }
Rails 3 MySQL query question My **Job** model has **id** and **percentage** fields (among others). **percentage** may be `nil`. I would like to set a default **percentage** here: class JobsController def new ... @job.percentage = <what should be here?> ... end end It should be calculated like this: * Take the percentage of the latest job (a job with max **id** ), which **percentage** isn't `nil`. * If there are no jobs, or all jobs **percentage** is `nil`, it should be 23. What is the easiest method to calculate this ?
You should probably do this in your `Job` model: [Update] Added a test for `new_record?` in the callback, since percentage can legitimately be `nil`; we don't want to override it if it's been previously set as such. class Job < ActiveRecord::Base after_initialize :calculate_default_percent # other stuff private def calculate_default_percent if self.new_record? conditions = { :conditions => "percentage NOT NULL" } self.percentage = Job.last(conditions).nil? ? 23 : Job.last(conditions).percentage end end end
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, ruby on rails, ruby on rails 3" }
Sort according to parameters Rails I need to **sort** a query according to the value sent in the `sort` parameter. A `sort` value starting with `-` indicates that the sort should be `desc`. Examples: * `url/employee?sort=name` should sort by `name` using `asc` * `url/employee?sort=-name` should sort by `name` using `desc` * `url/employee?sort=last_name` should sort by `last_name` using `asc` * `url/employee?sort=-age` should sort by `age` using `desc` in Ruby on Rails
You need to check if your parameter value contains a `-` at the beginning of the string; if it does, remove it and sort using `:desc`, if it doesn't just sort using `:asc`. Assuming you have a model named `Employee` and controller named `EmployeeController` with an `index` action, you can do the following: # employee_controller.rb def index attribute = params["sort"].sub("-", "") order = define_order(params["sort"]) @employees = Employees.all.order(attribute => order) end private def define_order(attribute) attribute.start_with?("-") ? :desc : :asc end
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -2, "tags": "ruby on rails" }
Get drive letters from physical disk number under WinPE I have a WinPE iso copied to an USB stick. In the WinPE environment the user enters a physical disk number. I want to create a warning if this physical disk looks like the WinPE disk. My solution is to check whether the folders on it corresponds to the WinPE disk content. To do this I need the drive letter in order to `Test-Path`. It looks like this solution Combine `Get-Disk` info and `LogicalDisk` info in PowerShell?. But it does not work in WinPE environment: Some WMI doesn't work in Windows PE. How can I check the content of the selected physical disk?
I've got something better for you, in the registry it stores what drive letter it booted from. HKLM\SYSTEM\CurrentControlSet\Control\PEBootRamdiskSourceDrive **Edit** To clarify if the you booted WinPE from a flash drive and it got assigned D:, then the value of that entry would be D:
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "powershell, winpe" }
Button group in IOS I would like to create a button group in style with this in IOS.!enter image description here I have tried with a static uitableview but that did not work due to static cells has to be embedded directly within a tableviewcontroller and I want some text and other stuff in this view as well. And if it is possible I would like to do this from the storyboard mostly. But if its not possible I can do it programmatically. Thanks in advance for any suggestions
The best way to do this is with a `UITableView` with the style `UITableViewStyleGrouped`. See this question: Here. Since you want more dynamic behavior, I'd recommend placing the `UITableView` in the storyboard, then making an outlet to your `UIViewController` subclass code. Make your `UIViewController` both a `<UITableViewDelegate>` and a `<UITableViewDataSource>`, and set the contents and behavior of your "buttons"(actually cells) programatically.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "iphone, ios, uibutton" }
Avoiding switch loop Will I have loop problems with this topology because S2 and S3 are both connected to S1 and s4 ? !enter image description here
Without STP, yes you would have a loop. Make sure that STP is enabled and configured correctly, though, and you won't need to worry about loops.
stackexchange-serverfault
{ "answer_score": 9, "question_score": 1, "tags": "networking, switch, spanning tree" }
Is there an alternative to System.Windows.ResourceKey to use in MonoTouch? I need to use ResourceKey for the key in my Dictionary and was wondering if there was a similar class I could use in MonoTouch?
I think you just need to use a string. If you need to use other things as a key (like a System.Type in WPF), then create your own class to handle this. I'm not sure if this work is worth it, however.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, iphone, dll, xamarin.ios, monodevelop" }
How can I assign a struc to a void pointer passed through the paramters? In my code I have a struc struct Test { int a; int b; char c; }; With my function: int TestFunction(void* ptr){ struct Test test; test.a = 0; test.b = 1; strcpy(c,"hello"); return 0; } Now to link the temp struc to the void ptr I passed in I have struct Test* temp = (struct Test*)ptr; struct Test test = *temp; Is this the correct way to link strucs with void ptrs? Is there an easier way?
Since you want to be able to modify the struct pointed to, your sample code is not appropriate. What it does is create a local copy of the pointed-to struct and modifies the local copy instead of the original object. What you want to do, rather, is this: int TestFunction(void *ptr) { struct Test *test = ptr; test->a = 0; test->b = 1; return 0; } The `a->b` syntax is equivalent to `(*a).b`, meaning that it refers to whatever `test` points to.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c, void pointers" }
T-SQL: INSERT INTO I have the following in T-SQL: INSERT INTO tblAttMain(Site, FirstName, LastName) SELECT Site, FirstName, LastName FROM tblAttTmp WHERE Site = @Site What I am doing here is copying columns from `tblAttTmp` into the `tblAttMain` table. Note the select statement can return hundreds of rows. `tblAttTmp` has a primary key called ID to specify the specific ID for that record. If for each interaction of of the select if there is an error, I like to spit out what the `tblAttTmp`'s ID was and create a string so that I can see all of the ID's which need to be fixed. Not sure how to do as the select is a one shot deal.
It sounds like you would rather implement this solution as a cursor. Using the cursor, you can do each insert one at a time instead of as a bunch and do things during each iteration. DECLARE @Cursor CURSOR FOR SELECT Site, FirstName, LastName FROM tblAttTmp WHERE Site = @Site DECLARE @CurrentSite <DataType> DECLARE @CurrentFirstName <DataType> DECLARE @CurrentLastName <DataType> OPEN @Cursor FETCH NEXT FROM @Cursor INTO @CurrentSite, @CurrentFirstName, @CurrentLastName WHILE @@FETCH_STATUS = 0 BEGIN -- INSERT using @CurrentSite, @CurrentFirstName, @CurrentLastName -- Use a Try/ Catch block to catch errors FETCH NEXT FROM @Cursor INTO @CurrentSite, @CurrentFirstName, @CurrentLastName END CLOSE @Cursor DEALLOCATE @Cursor
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql server, tsql" }
Find all duplicate cells, Identify if value exist that matches the duplicate, Fill in next column of the duplicate row cell has value of 0 This is a little complex, but if anyone can help. I would be greatful. ![enter image description here]( What I want to do is: 1. Find duplicate values in column A (sku) 2. If a value exist in column D for that duplicate cell 3. Fill column E with the value in D IF column C = 0 Thanks in advance
You should be able to do this by entering the following formula into E2 with `CTRL + SHIFT + ENTER` (prior to Excel 365) and then copying it down: `=IFERROR(IF(C2=0,INDEX($D$2:$D$20,MATCH(1,(A2=$A$2:$A$20)*(""<>$D$2:$D$20),0)),""),"")` Adjust `$A$20` and `$D$20` to the full length of your ranges. The important part is `(A2=$A$2:$A$20)*(""<>$D$2:$D$20)`. This produces an array with `1` for each row where `$A$2:$A$20` equals `A2` and `$D$2:$D$20` is not empty, and `0` for all others. The first (and here: only) match will result in `5`, which we'll use within `INDEX` to get the value (to be returned only when `C2=0`). The `IFERROR` rectifies any `#N/A errors`. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "excel" }
nohup SBCL ubuntu couldn't read from standard input On Ubuntu I compiled sbcl 1.0.35 with threading. I can happily use sbcl from the command line and my hunchentoot website works with threading but when I logout it's gone. When I attempt to nohup sbcl nohup ./src/runtime/sbcl --core output/sbcl.core I get (SB-IMPL::SIMPLE-STREAM-PERROR "couldn't read from ~S" # 9) I've attempted various combinations of redirecting the standard input to /dev/null or a file and using the script command line option but I don't quite get what is going on. How do I start sbcl from the command line on linux with nohup and keep my repl(website) running?
Dmity-vk sent me on the right track, thank you. SBCL tries to start a repl when you start it up, and reads from the standard in. When you use `nohup` the standard in is redirected and cannot be read. SBCL then drops to the debugger which tries to read from standard in ... hence the endless loop. The `--script` tag comes close to solving this except that it has a `(quit)` once the script has been read. So I put an endless loop in my script and voila. so on an ubuntu server with sbcl this should let you start a hunchentoot server sudo nohup ./run-sbcl.sh --script foo.lisp > /dev/null 2> /dev/null & where foo.lisp has as its last lines something like (defvar *alive* t) (loop (sleep 1000) (if (not *alive*) (quit)))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "linux, lisp, sbcl, nohup" }
как вывести из массива картинку ссылкой? Есть массив. Как вывести все картинки по адресам media_url ссылками на permalink? Array ( [data] => Array ( [0] => Array ( [media_url] => [permalink] => ) [1] => Array ( [media_url] => [permalink] => )...
Пробегаться по массиву в цикле и выводить его элементы: <?php foreach ($data as $item): ?> // $data['data'] ??? <a href="<?= $item['permalink']; ?>" target="_blank"> <img src="<?= $item['media_url']; ?>" /> </a> <?php endforeach; ?>
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
How to pass a struct from C++ to C? Updated: main.h typedef struct { float x; float y; float z; }vec3; const int sizeOfGrid = 20000; vec3 *grid[sizeOfGrid];//assume initialized main.cpp #include "main.h" extern "C" void cudaTranslate(vec3 *x); void display() { cudaTranslate(grid); } lineCuda.cu #include <stdio.h> #include <assert.h> #include <cuda.h> #include "main.h" extern "C" void cudaTranslate(vec3 *x) { } getting: main.obj : error LNK2005: "struct vec3 * * grid" (?grid@@3PAPAUvec3@@A) already defined in lineCuda.obj fatal error LNK1169: one or more multiply defined symbols found
Move grid to main.cpp. Pass it to lineCuda.cu. Problem solved. Updated: main.h typedef struct { float x; float y; float z; }vec3; const int sizeOfGrid = 20000; main.cpp #include "main.h" vec3 *grid[sizeOfGrid];//assume initialized extern "C" void cudaTranslate(vec3 *x); void display() { cudaTranslate(grid); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, c, arrays, cuda" }
Sql 2005 get latest entry from a group of data ## Problem: I have a set of data that keeps track of history of communication between clients. So each client has their own activity history (notes, emails..etc). I need to get the latest entry from each client's activity history, where each row is the latest entry from a client's activity. So every row is unique on **client id** and we can call each activity, **"description"**. Each activity has a date, and some other jargon like subject, body. ## Activity Table activityid | clientid | subject | body | datemodified Thanks!
You're not giving us much to go off of but here is a shot in the dark: SELECT ClientId, body, MAX(DateModified) FROM Activity GROUP BY ClientId, body
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql, tsql" }
Router in front of Untangle UTM I want to put a pfSense router in front of my Untangle UTM. There is only one thing I am not too sure about. If the Untangle box will sit behind another router and run OpenVPN, all I need to do to route traffic to the Untangle through the pfSense is add a static route on the pfSense box and open the port used by OpenVPN right? Right now the Untangle box is the router.
In most cases, not even a route. A port map/forward entry on the pfSense to the Untangle should be all that is needed.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 2, "tags": "routing, openvpn, pfsense, untangle" }
How to enable clickable notifications for pidgin? > **Possible Duplicate:** > How to make Gwibber notifications clickable? I want to make the notifications ballons for pidgin clickable, so I can click on it and it should take me throgh direct to the chat window. Is this possible? I'm using Ubuntu 11.10.
Install Guifications via Synaptic Package Manager, !enter image description here Once Installed go to "Tools/Plugins and choose "Guifications",activate it and click on "Configure Plugin" in order to set your preferences. You can set the position, stack, and other display options, the same as Mouse behavior. !enter image description here Additionally you can set which notifications you want to be notified about and get themes to enhance your GUI notifications. _Note: You might need to disable current notification popups in order not to receive duplicated notifications._ Good luck!
stackexchange-askubuntu
{ "answer_score": 5, "question_score": 4, "tags": "notification, pidgin" }
Getting the size of the image of a .NET module I got the instruction pointer from a thread in a .NET process and now I'd like to determine in which module in that process it resides. So I was thinking to get the loaded modules of the process and check for each of them if: Module's Base address <= ip < Module's Base address + Module's size. What I wanted to know is: How can I get the size of a .NET module? (preferablly in C++)
When you check the instruction pointer when executing .NET code, it will be either in the CLR module, or in the module's JIT-compiled code. Neither of these are interesting for you, especially since the JIT compiled CLR code can be thrown away, recompiled, dynamically optimized... there is no such thing as the 'size' of a .NET module.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, .net, image size" }
Conditions present after solving for x The question asked me to solve $\dfrac {x^2+2x-8}{x^2-x-2}=3$ The answer is $x=0.5$, which I worked out, but in the answers it says that I must state the condition that $x≠2$ to get full marks. Why is this condition present? How can I recognise when a condition exists, when I encounter similar problems?
When solving this equation you assume that $x^2-x-2\ne{0}\implies{}x\ne{}-1,2$. In general while solving an equation make sure that the denominator is not equal $0$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "quadratics, fractions" }
Resize a Graphics Path on MouseMove In GDI+ and C#, I have created a Table using Graphics Path using AddRectangle and AddLine Methods !enter image description here Now during my Mouse Move, I would like to resize/move this complete Table. I can iterate over all Sub-Paths and re-calculate everything during mouse move, but I was wondering is there any method by which I can move or resize this complete Graphics Path in one Go.
Well, there is GraphicsPath.Transform. Matrix m = new Matrix(); m.Scale(scaleX, scaleY, MatrixOrder.Append); m.Translate(offsetX, offsetY, MatrixOrder.Append); path.Transform(m); It's probably not good to transform a path too many times, though, given that GDI+ uses only single-precision floats. I'd suggest keeping an original path that you transform as needed. Or you could edit the transform on a Graphics object before you draw, or rebuild your path before every draw. You'll get the same result however you do it. A transformed path isn't going to draw any faster than a new one, and the time it takes to build the path is probably negligible. So I'd guess that recalculating is simplest to write, and it has no disadvantage that I can think of.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, gdi+" }
how to cast each row of type varchar to array? So I have this problem. I have a table called Orders, where i have a column product_id, but it's of the type varchar, because there can be many of them e.g. '12,3,4,345'. They are all sepearted with ',' But my question is how can I cast in query each row of varchar to array? I tried it with the string_to_array function, but it only casts one row. I need to cast all of the rows in the given table. My code SELECT o.product_id, string_to_array( (select product_id from orders), ',' ) as array from orders o ; I am working in IntellIJ, using JDBC driver on postresql database.
It would be nice if you attach sample data and expected output. So far, I understood your problem, that you want to "put" the contents of each line into an array. SELECT product_id, (string_to_array(product_id, ',')::int[]) as array from orders; Check out my dbfiddle and let me know if the result is different from what you want.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "arrays, database, postgresql, casting" }
C# Linq String[] list minus from String[] list Let's say string[] admins = "aron, mike, bob"; string[] users = "mike, katie, sarah"; How can I take the users and strip out anyone from the admins. the result should be "katie, sarah"; (mike was removed) Is there a nice Linq way to do this?
// as you may know, this is the right method to declare arrays string[] admins = {"aron", "mike", "bob"}; string[] users = {"mike", "katie", "sarah"}; // use "Except" var exceptAdmins = users.Except( admins );
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 9, "tags": "c#, linq" }
Upload repository on compiled I'm just wondering if there is a way (Linux / Unix) to update a Github repository when a particular file has compiled successfully? So for example, I have a repository called 'Work' and if I compiled the file `main.cpp` and if it compiles successfully it automatically synchronises the file / repository on Github. I hope this makes sense and someone can help me :)! Thankss :)
> I'm just wondering if there is a way (Linux / Unix) to update a Github repository when a particular file has compiled successfully? If you can get and analyze results of running gcc (exit-code or grepping output), you can do **what you want** in rather easy and small (2-3-liner) shell script, can't see any troubles here. From my side I see your workflow as not bullet-proof (if you push sporadically, you have good chances to lost a lot of local work in case of disaster), just for sake I'll prefer "push all, tag compilable changeset"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "linux, git, unix, github" }
MySQL Added additional columns to my table, how to update table How can I load data from a file without replacing the existing columns but just adding missing values? For example if I already had a table and one of the rows would be Id: 25, username: john, password: #hash And then I add new columns `bday`, `height`, `surname` to my database and populate a `csv file` with them. Is it possible to load those into a file without changing the `id's` of the users?
The simplest way is based on import the data in a new temporary table and then perform the update on the orginal table for the column you need join the rows between the 2 tables eg . table1 (id, key1, col1, col2_added) table_temp(id, key1, col1, col2) once you imported the files in table_temp you can update table1 join table_temp = table1.key = table_temp.key set col2_add = col2;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql" }
jQuery: missing ] after element list I have that error in the code below. What's wrong ? I have no ideas left. missing ] after element list [object XMLHttpRequest] $(function () { setInterval($.post('/Sale/UpdatePrice', {SaleId : @Model.Id}, function(data){ $('#mPrice').val(data); } ) ,5000); //refresh every 5 seconds }); C# public JsonResult UpdatePrice(int SaleId) { ... return Json(NewPrice, JsonRequestBehavior.AllowGet); //NewPrice is a decimal number }
Sorry for being Capt. Obvious here, but it seems that the JSON returned is missing a ] to end the array, Can you please post the JSON?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Why is AddOLEObject so slow in MS Word I am programmatically inserting OLE objects into a MS Word table using the following method call: table.Cell(row, column).Range.InlineShapes.AddOLEObject(CLASS, FILE, ...) The problem is that the call is too slow. It takes more than a second to add an OLE object to the document. What could slowing this down? I am sure it is dependent on the application associated with the object? Any ideas to speed it up, even a little? Thanks.
Doing an OLE insertion is never really fast because there is a lot involved (for example, unless you are inserting as an icon, a display image of the object will be needed). It's likely to be much quicker if the object is created by an in-process object (cf. one of the old ActiveX forms controls). If you're using an object server such as Excel, Word has to start Excel for each insertion. Not quick. You may be able to speed things up by starting the server independently at the beginning, and by switching off screen updates in Word, but I think you'll need to run some performance tests.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "vba, performance, ms word, ole" }
min function returning value that is not the smallest/least I'm trying to get the index of the smallest number in a list, confused by this result..... nums = [4,0,100] smallest = min(enumerate(nums)) print("smallest = ", smallest) Printout: smallest = (0,4) Shouldn't it be: smallest = (1,0)
You need to use `key=lambda x: x[1])` to say `min` function to check for the minimum value present in the second index, by default it checks in the first index, in which you are having an index value. So, it results `(0,4)` which is obvious. Try this, >>> min(enumerate(nums), key=lambda x: x[1]) (1, 0)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, min" }
Toggle tab navigation without using jquery and javascript I want to navigate between menu tabs and display content without using any java script and j query . because, when java script disabled from the browser its does not work. I have attached image for menu tab. can anybody help Thanks Sanjeev
See my answer here: Is it possible to have tabs without javascript Yes, it's possible, but it won't work everywhere (yet!)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, css, jsp" }
How can I format a special section title? I want to make my section titles look like the ones in this figure. However I have no idea what font that is, or how to only change the font for the tiles and sections etc. or how to get the fancy box. Is there a way to figure this out? Any pointer or direct solution is appreciated. !enter image description here
\documentclass[english]{scrbook} \usepackage[T1]{fontenc} \usepackage{kpfonts} \usepackage[utf8]{inputenc} \usepackage{babel} \renewcommand\thesection{\protect\rule{1ex}{1ex} \thechapter.\arabic{section}} \begin{document} \begingroup \def\rule#1#2{}%% Kill the \rule from the TOC \tableofcontents \endgroup \chapter{foo} \section{General Tools} The role of distributed \ldots \end{document} !enter image description here !enter image description here
stackexchange-tex
{ "answer_score": 1, "question_score": 2, "tags": "fonts, formatting" }
Glitchy graphics on the load screen I updated my kernel, and the system seems to be working just fine. Everything is stable, I just get glitchy graphics when the system is loading. The "loading" text glitches through the Gnome loading screen. Should I be worried about it? I'm using an NVidia gtx 980 with 370.23 drivers
From the comments: > **Me:** Does it show a text-based Ubuntu loading screen on a black background? > > **You:** yes exactly that. it shows that and the gnome screen at the same time, only glitching where the text is, but the system after boot works just fine Edit: only shows about 5-10 lines and boots in to the log in screen Don't worry about it at all. That simply means that the kernel upgrade broke KMS, which was a feature only very recently added anyway. All that means is that the driver handoff for the boot screen isn't working properly. **But, that has ZERO effect on anything after the system is booted. So you're fine.** * * * If you want to try to fix it, you can try following this answer, but as always, no guarantees.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 2, "tags": "16.04, gnome, kernel" }
Why log likelihoods are additive and !log likelihoods are multiplicative Reading accepted answer for Why we consider log likelihood instead of Likelihood in Gaussian Distribution by user jokek states that total likelihood is product of likelihoods. If apply log to likelihoods then total likelihood is sum instead of product. Why applying log function to likelihoods change computing total likelihood from product to sum ? What is the intuition behind this ?
Simply because $\log (ab)=\log(a)+\log(b)$.
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "statistics, logarithms, machine learning" }
How to test correct return String in Try construct after exception was thrown? I want to test if there was an `IOException` thrown and if the correct `String` value of "[ ]" is returned. I'm only able to check the exception message and other stuff but I cannot assert the "[ ]" def readJsonFile(myJson: String): String = Try { FileSystems.getDefault().getPath(myJson) } match { case Success(path) => new String(Files.readAllBytes(path)) case Failure(ioe: IOException) => "[]" case Failure(e) => sys.error(s"There was a problem with: $e") } I checked `assertThrows[IOException]` and `intercept[IOException]` but they only let me check for common exception stuff but not for the return value in case this kind of exception was thrown. Am I overlooking something? What's the easiest way to accomplish it?
The problem here is that `IOException` is thrown outside of `Try`. If you read the file inside `Try`, it may satisfy your expectation: def readJsonFile(myJson: String): String = Try { Files.readAllBytes(FileSystems.getDefault().getPath(myJson)) } match { case Success(bytes) => new String(bytes) case Failure(ioe: IOException) => "[]" case Failure(e) => sys.error(s"There was a problem with: $e") }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "scala, tdd, scalatest" }
c# function coding guideline i need to pass values from one class to another and asked me what is the best way. What do you think? a) public string getValue(){ string returnValue; ClassA myClass = new ClassA(); returnValue= myClass.getValue(); return returnValue; } b) public string getValue(){ return new ClassA().getValue(); } I don't know if there is a problem with b like bad programming style... Thank you!
The compiler will almost certainly reduce "a" down to "b" _anyway_ in release mode. There is a case for adding intermediate variables if you are likely to want to debug with break-points at that location. But IMO "a" adds very little. I'd use "b". Of course, you could also argue that the `new ClassA()` instance adds very little, and a static method should be provided instead. And then at that point the method **itself** is providing very little, and the caller should just call the static `ClassA.GetValue()` itself.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c#, coding style" }
Getting data based on location and a specified radius **Scenario:** I have a large dataset, with each entry containing a location (x,y - coordinates). I want to be able to request every entry from this dataset that is within 100m within this dataset and have it returned as an array. How does one go about implementing something like this? Are there any patterns or framework that recommended? I've previously only worked with relational or simple key-value type data.
The data structure that solves this problem efficiently is a k-d tree. There are many implementations available, including a node.js module.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js, database design, graph, geolocation" }
unable to confirm transaction Hi just today I started to get this error when trying to do anything on devnet: Error: unable to confirm transaction. This can happen in situations such as transaction expiration and insufficient fee-payer funds This includes just doing: solana airdrop 1 on the terminal. Some things work, e.g. solana balance shows a sensible value, but I can't seem to do anything with transactions. The airdrop doesn't go through, it just sits there for a while and then I get that error. Any suggestions?
At the time of your posting, there are some issues with `devnet` that are prevent transactions from going through. If you are using `devnet` and running into these issues, you may just have to wait until they are resolved. You can try running the same code using the local host validator or on `testnet` to make sure the problem is not with your code, and is in fact with the current devnet troubles.
stackexchange-solana
{ "answer_score": 1, "question_score": 0, "tags": "confirmation" }
Как установить generic-pae ядро на Ubuntu? Я новый пользователь Ubuntu и по-неопытности установил версию x86-x64 версию Ubuntu 18.04 LTS. 4Gb ОЗУ мне мало. Недавно узнал, что можно расширить это значение до 64Gb, если установить ядро generic-pae. Как это сделать? Или как можно перенести Ubuntu на x64? Сохранив все свои данные?
Я не так все понял и сейчас проверить версию системы введя в терминале команду uname -m Мне вывелось x86_64, что означает, что версия 64-битная и никаких плясок с ОЗУ не нужно проводить, потому что скорее всего битое гнездо для ОЗУ.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ubuntu" }
ConcurrentDictionary and IDictionary I noticed that ConcurrentDictionary implements the IDictionary interface, yet despite that the interface supports Add, ConcurrentDictionary doesn't have that function. How does this work? I thought interfaces imposed functionality on the implementing classes...
It is using explicit interface implementation. Here is an example. interface IFoo { void Foo(); } class FooImplementation : IFoo { void IFoo.Foo() { } } If you assign or cast a `ConcurrentDictionary` to `IDictionary`, you can use all the methods defined there.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c# 4.0" }
How to use gatsby-image and contentful I'm trying to handle the retina images in a Gatsby project. My content provider is Contentful. I'm uploading the 2x images. I'm currently using the Gatsby-images plugin. To get the correct image I'm using: images{ fluid{ ...GatsbyContentfulFluid_withWebp } } I also using the tag that supposes to handle retina images. <Img fluid={image.fluid} alt="" class="mw-100 d-inline-block" /> But.. at the end of the day. I'm getting the wrong images. I'm getting the 800w so It seems that I'm getting one breakpoint behind the image.
**I've solved the issue.** There were two issues, by default Gatsby Plugin Sharp (< uses quality 50 and maxWidth 800px. I just update qualify 100 and maxWidth of 2500 since I was waiting for bigger images. fluid(maxWidth: 2500, quality: 100){ ...GatsbyContentfulFluid_withWebp }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "gatsby, gatsby image" }
swift - using replaceRange() to change certain occurrences in a string Say I have a string, and I want to change the first "a" in that string to an "e" in order to get the correct spelling. let animal = "elaphant" Using `stringByReplacingOccurrencesOfString()` will change every "a" in that string to an "e", returning: elephent I am trying to get the index of the first "a" and then replacing it using `replaceRange()`, like so: let index = animal.characters.indexOf("a") let nextIndex = animal.startIndex.distanceTo(index!) animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e") However, this code gives me the following error: Cannot assign value of type '()' to type 'String' I have been trying to find a way to convert nextIndex into an `Int`, but I feel like I've got this whole method wrong. Help?
This is is what you want to do: var animal = "elaphant" if let range = animal.rangeOfString("a") { animal.replaceRange(range, with: "e") } `rangeOfString` will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil. we need to unwrap the optional and the safest way is with an `if let` statement so we assign our range to the constant `range`. The `replaceRange` will do as it suggests, in this case we need `animal` to be a `var`.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "ios, xcode, string, swift" }
find enclosed plus NP > Dear Mr. Potter, > > We are pleased to inform you that you have been accepted at Hogwarts School of Witchcraft and Wizardry. **Please find enclosed a list of all necessary books and equipment**. > > Term begins on September 1. We await your owl by no later than July 31. > > Yours sincerely, > > Minerva McGonagall, > Deputy Headmistress > > _\-- Harry Potter and the Sorcerer's Stone by J.K. Rowling_ Is the clause like the below on OALD: “Please find enclosed a cheque for £100”, or is it interpreted otherwise: like enclosed is object predicative -- object [list of all necessary books and equipment.] + object predicative [enclosed]?
It is like the OALD example that you have provided. It's a formal term generally used in mail to mention something that is sent along with the letter.
stackexchange-ell
{ "answer_score": 1, "question_score": -1, "tags": "grammar" }
how to change the image position by finger in java android I use the code below to display an image in the screen. ImageView img = (ImageView) findViewById(R.id.imageView1); img.setImageResource(R.drawable.car); I want to let the user, to reposition it by finger to any place. which one I can use? 1. `setOnTouchListener` 2. `onDrag` This is when I have two cars. and the background is another bitmap image.
You can do so. But its a bit complicated. Have a look at this great tutorial: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "android, image, position" }
Is it possible to add a dot in a variable name in Javascript? I'm using`console.log(value)` however when I use `console.log()` If I wanted to play around with stuff and make it do other things is there a way I can create a function like... `var console.log = (function() { // something }`
You could create a wrapper for the `console.log` function and then only use your wrapper to write to the console: function myCustomConsoleLog() { // do stuff with your arguments console.log(arguments) } Now instead of calling `console.log(vars)` you would make a call to `myCustomConsoleLog(vars)`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript" }
Type '{}' is not assignable to type 'number' So I understand the idea behind async/await is just a prettier way to use promises but apparently I'm not understanding it correctly. async function a(): Promise <number> { return 5; } This is fine, returns a promise that is resolved with result 5. async function a(): Promise <number> { return await new Promise(resolve => { resolve(5); }); } > error TS2322: Type '{}' is not assignable to type 'number'. > Property 'includes' is missing in type '{}'. From what I understand, await will wait for the promise to resolve and return the result, which in this case is 5 and should work as the above example?
By default the `new Promise()` is equivalent to `new Promise<{}>`. You inner Promise returns not a number, but an object. You need to ensure to compiler that it is a Promise with the type number. Replace `await new Promise` with `await new Promise<number>` async function a(): Promise<number> { return await new Promise<number>(resolve => { resolve(5); }); } And check your code also, I think you can work with your code without the middle Promise async function a(): Promise<number> { return await 5; }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "javascript, typescript, async await" }
Replacement compiler for Qt Creator? I like Qt Creator as an IDE, but the built-in compiler is slower than dirt. Can I replace it, and if so, with what? Developing on Windows but targeting multiple Mac as well.
By default on Windows the compiler is mingw, a port of GCC. Qt also contains support for the Visual Studio compilers, which you can switch to. The only full-fledged C++ compiler on Macintosh is GCC. C++, especially with template heavy code, is _slow_ to compile. There is no avoiding this. In my experience, Visual Studio is not appreciably faster on complex code bases over GCC.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "c++, qt, qt creator" }
what if you an your opponent die at the same times Suppose my opponent and I have a life total of 1. I play a blood toll harpy. And we each lose one life. What happens?
The game is drawn the next time a player gets priority. See also: If I simultaneously kill my opponent and deck myself at the same time, is the game drawn? which covers effectively the same question.
stackexchange-boardgames
{ "answer_score": 3, "question_score": 1, "tags": "magic the gathering" }
How to embed this Processing sketch on Tumblr? I have a Processing sketch that I'd like to embed on my Tumblr. I've followed the instructions on this post for doing so, but all I get is an empty canvas and my script showing up as text. I definitely have the required code they mention in my blog's header tags and have enabled plaintext/HTML as my text-editor. My code matches their format and I stripped all the returns out of the Processing sketch - is there some Tumblr-magic I've neglected, or is there an easier way of doing this?
Same problem! What worked for me was to put a div at the beginning (before canvas...) and a /div at the end (after /script) when you are in the html editor. !CODE !RESULT Or maybe you could try with this "tumbleryfier" found at <
stackexchange-webapps
{ "answer_score": 2, "question_score": 2, "tags": "tumblr" }
PHP example of the Heroku JSON REST API? I'm trying to get the app process status with the REST API and am having a bit of trouble getting it to return good data $ch = curl_init( ); curl_setopt( $ch, CURLOPT_URL, ' // No clue what to put here. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true); curl_setopt( $ch, CURLOPT_USERPWD, ":yesthisismyrealapikeyanditworks"); // trust me on this line :) curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json')); //total guess curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt( $ch, CURLOPT_POSTFIELDS, ' // where myapp is actually my app name // Getting results return curl_exec($ch); This hasn't returned anything useful. I'm new to JSON and curl, so go easy on me please. Thanks. Dave
$ch = curl_init( ); curl_setopt( $ch, CURLOPT_URL, ' curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true); curl_setopt( $ch, CURLOPT_USERPWD, ":yesthisismyrealapikeyanditworks"); return curl_exec($ch);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, json, heroku" }
What are other ways to share a tmux session between two users? I'm looking for a clean and easy way to share a tmux session with another user on the same machine. I've tried the `-S socket-path` option, but it requires opening up all permissions of the socket-path before someone else can connect to the session. It works, but it's a little cumbersome. For example: # Me $ tmux -S /tmp/pair $ chmod 777 /tmp/pair # Another user $ tmux -S /tmp/pair attach This works, but both users now share the same tmux configuration (the configuration of the user who initiated the session). Is there a way to allow the two users to use their own tmux config and their own individual tmux key bindings? For bonus points, ideally, it would also be nice to give read-only access of the tmux session to other users.
From < > wemux enhances tmux to make multi-user terminal multiplexing both easier and more powerful. It allows users to host a wemux server and have clients join in either: > > Mirror Mode gives clients (another SSH user on your machine) read-only access to the session, allowing them to see you work, or > > Pair Mode allows the client and yourself to work in the same terminal (shared cursor) > > Rogue Mode allows the client to pair or work independently in another window (separate cursors) in the same tmux session. > > It features multi-server support as well as user listing and notifications when users attach/detach. It is a shellscript wrapper over tmux - no compiling necessary.
stackexchange-unix
{ "answer_score": 56, "question_score": 138, "tags": "users, tmux" }
Cannot delete array I am new to programming and I cannot figure out how to delete and array. int* array = new int[5]; I tried to delete the array like this delete array[5]; but I get an error: cannot delete expression of type 'int' I also tried delete [5]array; but I got an error: error: expected expression How do I delete an array? I don't know what else to do? Thanks in advance for any help. It is very appreciated.
Use the following: delete [] array; // Delete an array array = 0; // Clear array to prevent using invalid memory reference
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "c++" }