INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to select a field inside an array inside an object in Javascript I have array of object like this : ![enter image description here]( I need to select only the array which has coreSystemID = 'T24' so I tried `credsArr.find()` it shows my `.find` is not a function. below is my code: var creds = credsArr.find(x => x.coreSystemID === 'T24') And I should use the index value like this - _credsArr[3053]_ , because the index may vary so I need to select the array which has coreSystemID = 'T24'
let keys = Oject.keys(credsArr).filter(key => credsArr[key].coreSystemID==='T24') keys will have all the keys of credsArr having credsArr[key].coreSystemID as 'T24' `let systemT24 = credsArr[keys[0]]` will give you the object you are looking for given that there is only one object with coreSystemID as 'T24'. If you have multiple objects that might have coreSystemID as 'T24' you can map it to a new array like this: let systemT24 = keys.map(key => credsArr[key])
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, arrays" }
Update shared data across indices ElasticSearch I have an two ElasticSearch indexes a companies index and a clients index. Documents in both of these indexes both contain an array of nested user objects, that look identical. If a user object gets updated, I need to be able to update all relevant clients, and companies, that have this user in it. Does ElasticSearch provide some sort of shared data type field, since both indexes basically share some of the same data? Or will I need to use an update by query to do this updating. It seems if there is not already a mechanism for shared data, then updating shared data could get very unwieldy as the ES instance grows.
From what I understand, you are trying to update **relational data** in elasticsearch. Sadly, there is no easy way to do what you want. Parent child or join will not work in your case because you have two indices and there is a limitation where a child document can only have one parent. You can try to move the nested document in a separate index and performs join manually. For more information you can read : * This question * The elasticsearch guide to handle relational data.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "elasticsearch" }
Do face-down creatures with death trigger activate normally? If a face-down creature has a "When this dies [...]" effect (i.e. because of Ixidron), will that effect activate when it dies?
Short answer: Yes, if it had one, but the creature lost that ability when it was turned face-down. * * * "When this dies" is a leaves-the-battlefield ability [603.6c], and leaves-the-battlefield abilities trigger based on their existence, and the appearance of objects, prior to the event rather than afterward [603.3d]. So it doesn't matter what abilities the creature would have if it was face-up or will have in the graveyard; all that matters is what ability it actually does have. Only leaves-the-battlefield abilities the face-down creature has just prior to dying will trigger when it dies. Normally, that wouldn't be any, but some cards (such as Cauldron Haze) could grant them some.
stackexchange-boardgames
{ "answer_score": 6, "question_score": 2, "tags": "magic the gathering, mtg face down cards" }
1 Mbit = ? bytes I always get confused about this. Is there a "standard" conversion of Megabits to bytes? Is it: 1 Megabit == 1,000,000 bits == 125,000 bytes Or: 1 Megabit == 2^20 bits == 1,048,576 bits == 131,072 bytes
Megabits is a unit of measure that comes from TELECOM, not CS. So it is: 1 Megabit == 1,000,000 bits == 125,000 bytes When it's a CS based unit of measure, usually the `1024` rules apply: 1 Megabyte = 1,024 Kilobytes = 1,024 x 1,024 bytes
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 21, "tags": "standards, bit, megabyte" }
using chinese characters as php associative array keys So I tried to use Chinese characters as the keys for my PHP associative array, but then when I print_r'ed the array, it printed out a whole bunch of garbage instead. What needs to be done so that I can use Chinese characters for my PHP array keys? Displaying chinese characters as string work fine though. It's just when I placed them as array keys when it stops working... eg: $j = array(); $j[utf8_encode('')] = 1; $f = array_keys($j); echo utf8_decode($f[0]);
To show case a very simple case of using Chinese character in associate key :- php > $a = array(""=>TRUE); php > var_dump($a[""]); bool(true) php > print_r($a); Array ( [] => 1 ) Here is the example if you apply `utf8_encode` and `utf8_decode`: php > $j = array(); $j[utf8_encode('')] = 1; $f = array_keys($j); echo utf8_decode($f[0]); php > print_r($f); Array ( [0] => 大 /* this is garbled */ ) php > print_r($j); Array ( [大] => 1 /* this is garbled too */ ) One possible way to overcome: php > print_r(utf8_decode(var_export($j, TRUE))); array ( '' => 1, )
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, arrays, utf 8, cjk" }
Get query strings and append to link JavaScript novice, thanks in advance. I'd like to get the the full string of query parameters and append them all to a link in the body. The link in the body will send the user to a registration website so I'd need those query strings to carry over to the next site. I'm thinking this would be the best way to do it, if not, please advise. Example: ` I'd like go grab `?utm_source=Twitter&utm_medium=HostedEvent&utm_campaign=Event2015` and add it to a link in the body Link: `<a href=" query strings here dynamically">Register</a>`
Assuming the link in the html link does not have other parameters and that you add a class to it so we can target it <a href=" class="copy-url-params">Register</a> Then you need the following script $(function(){ var urlparams = window.location.search; $('.copy-url-params').prop('href', function(idx, current){ return current + urlparams; }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
Rails Controller list if condition is false in another controller i have a problem whit my def in controller def wait @evaluations3 = Affiliation.where("go_auth =true") and Affiliation.evaluation.where("ready = false") I want to show only affiliatedes with this 2 conditions = true
This solve my problem def wait @evaluations3 = Evaluation.includes(:affiliation).where("go_auth = true").where("ready = false").references(:affiliation) end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, controller" }
How could I draw 4 mosfets in a same line? (attached picture) !enter image description here I only know how to do one and in a unique line. How is it possible to put four together and well spaced as the picture I am showing? what I did until now: \usepackage{circuitikz} \begin{document} \begin{center} \begin{circuitikz} \draw (0,0) node[ nmos ] {}; \end{circuitikz} \end{center} \end{document}
You mean something like: !enter image description here ## Code: \documentclass{article} \usepackage{circuitikz} \begin{document} These are the symbols for mosfets: \medskip \begin{circuitikz} \draw (0,0) node[ nmos ] {}; \draw (4,0) node[ pmos ] {}; \ctikzset{tripoles/mos style/arrows} \draw (2,0) node[ pmos ] {}; \draw (6,0) node[ pmos ] {}; \node [align=center] at (1,-1) {nmos}; \node [align=center] at (5,-1) {pmos}; \end{circuitikz} \end{document}
stackexchange-tex
{ "answer_score": 3, "question_score": 3, "tags": "horizontal alignment, circuitikz, circuits" }
Documentum connector in SharePoint 2016 Today My manager was asked me for **Documentum connector** in SharePoint 2016, can anyone explain briefly or any understandable reference document on "Documentum connector". Thanks in Advance
SharePoint can basically integrate with external data in any connected system. But it requires advanced configuration and often custom development as well. Fortunately, there are many third-party vendors who can help you. I have not scanned the market thoroughly for Documentum connectors - but looks like EMC has their own connector for SharePoint. You might also take a look at the Documentum connector from BA Insight. Layer2 can also help connect SharePoint to external systems.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 1, "tags": "sharepoint enterprise, 2016" }
Switches and numbers You have a hundred, labeled, bulbs, turned off and a hundred, labeled, buttons. When you begin pressing the button nº1, all bulbs turn on. When you then press the button nº2 all pair bulbs, begining by the 2n, turn off. When you press the button nº3, begining by the 3rd bulb, and all those which are multiples of 3, change their state. The ones that were off, light on, the ones turned of, go off. You do the same by every button, finally having pressed, by order, all buttons from the first to the 100th. Question is, how many bulbs will be turned on at the end of the process? Which ones will it be? EDIT: As pointed out, this puzzle resembles Nerds, Jocks, and Lockers, being the question I asked a somehow simplyfied version of it. I'll leave the question as it is, in case anybody wants to try with this one. Of course, if that's not the case, I'll eventually end up closed.
> 10 lights are on - 1,4,9,16,25,36,49,64,81,100 A light is on if toggled an odd number of times (from before any switches are pressed) and off if toggled an even number of times > As each switch affects bulbs at positions that are integer multiples of the switch's position, the number of integer factors that each bulb has are what determines its end state. > Square numbers have the property that one of their factors is repeated (e.g. 1,3,3,9 for 9) - as each button is pressed only once, that state change isn't repeated, so the square-numbered bulbs are left lit at the end That's a horribly convoluted description, but I couldn't come up with a more succinct way to summarise it
stackexchange-puzzling
{ "answer_score": 1, "question_score": 0, "tags": "mathematics, logical deduction, number theory" }
What's a tuple in normal English? A _tuple_ in mathematics is a sequence of numbers (n1, n2, n3). In databases, a _tuple_ is a single row of data from a table. What is a _tuple_ in normal everyday English, or where does the word come from? Is there a concrete real-life object from which this word is derived? WordNet does not have a definition.
The word derives from the extended series of single, double, triple, quadruple, quintuple,..., where named multiples beyond five are generally words that end in "tuple". The natural (Latin-derived) words peter out pretty quickly, and mathematics needs more terms than a simple bipedal meat unit can easily memorize, so the term " _n_ -tuple" was coined. Computer science took that ball and ran with it, dropping the " _n_ -" altogether. In other words, "tuple" has no meaning in everyday English.
stackexchange-english
{ "answer_score": 57, "question_score": 22, "tags": "meaning" }
How to plot a histogram of a single dataframe column and exclude 0s I have a huge dataframe that looks like this: Date value 1 2022-01-01 00:00:00 0.000 2 2022-01-01 01:00:00 0.000 3 2022-01-01 02:00:00 0.000 4 2022-01-01 08:00:00 0.058 5 2022-01-01 09:00:00 4.419 6 2022-01-01 10:00:00 14.142 I want to only plot in a histogram the column 'value' but without the 0 values. How do I do that? I have tried : plt.hist(df['value' >0], bins=50) plt.hist(df['value' =! 0], bins=50) but no luck. Any ideas? Many thanks
There's a syntax error with `df['value' > 0]` \-- needs to be either `df[df['value'] > 0]` or `df[df.value > 0]`. The idea is that you create a boolean index with `df.value`: >>> df.value > 0 0 False 1 True 2 False 3 True 4 True 5 True Name: value, dtype: bool And then use that index on `df` to retrieve the `True` indexes: >>> df[df.value > 0] date value 1 2022/01/01 0.100 3 2022/01/01 0.058 4 2022/01/01 4.419 5 2022/01/01 14.142 On the plotting side, you can also plot directly with pandas: >>> df[df.value > 0].plot.hist(bins=50)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, dataframe, matplotlib, histogram" }
Reading specified line using Perl program and command-line arguments So, let's say I am writing a Perl program: ./program.perl 10000 < file I want it to read the 10000th line of "file" only. How could I do it using input redirection in this form? It seems that I keep getting something along the lines of 10000 is not a file. I thought this would work: #!/usr/bin/perl -w $line_num = 0; while ( defined ($line = <>) && $line_num < $ARGV[0]) { ++$line_no; if ($line_no == $ARGV[0]) { print "$line\n"; exit 0; } } But it failed miserably.
If there are command-line arguments, then `<>` opens the so-named files and reads from them, and if not, then it takes from standard-input. (See "I/O Operators" in the perlop man-page.) If, as in your case, you want to read from standard-input whether or not there are command-line arguments, then you need to use `<STDIN>` instead: while ( defined ($line = <STDIN>) && $line_num < $ARGV[0]) {
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "linux, perl" }
How to carry over a workflow variable to another workflow? SP 2010 I have a workflow variable that collects email addresses called from a dozen of if-else statements. However, I have created another workflow that needs to reference that aforementioned workflow variable. ( They are from 2 different lists ). Is there a way to do this? Especially because the variable has a number of strings in it - the email addresses?
You could create a column that houses the variable. Make it a single line of text, and then you can pick it up in the next workflow by referencing the ID of the list item. Depending on how the two lists are related, you could also create a list that is the joining list to create the variable.
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 1, "tags": "sharepoint enterprise, sharepoint designer" }
ext3 will trim be supported? Current linux kernel version supports trim however Debian Squeeze uses an old version that does not. As I understand, the trim support is in the linux kernel itself and not a specific filesystem. Therefore, will ext3 support trim in the new kernel? If it does not, will it support it in the future?
All layers of the storage stack have to support trim. After all only file system layer knows, which blocks are safe to be wiped. This post on the ext4 developers list with patch for elements of trim functionality in ext3 strongly suggest that such work is being done already.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 1, "tags": "debian, linux, debian squeeze" }
Get Opportunity with Opportunity Line Items How can I use the salesforce api to get a list of opportunities such that each opportunity contains it's opportunity line items?
Well the SOQL it would be something like this- [Select Id, (Select Id From OpportunityLineItems) From Opportunity] Once you get that, you would have to loop through a list of items under each Opportunity record. Hope this answers your question.
stackexchange-salesforce
{ "answer_score": 6, "question_score": 2, "tags": "api, opportunity, opportunity lineitem" }
How to get file list from a Debian package using eptlib libraries? Simple question: I have loaded an Apt package record with libept. There is a method to get file list? It should sound like record.GetFileList(); and it should return a vector string like the output of dpkg -L packagename
The libept main developer (Petr Rockai) explain me that unfortunately, at this time, libept have no such method. What they do in Adept is this: QString flfilename = "/var/lib/dpkg/info/" + u8(t.package()) + ".list"; QFile flfile(flfilename); QTextStream flInStream(&flfile); while (!flInStream.atEnd()) { QString line = flInStream.readLine(); // do stuff with line } flfile.close();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, debian, apt" }
Inserting href class to JS file (using createLink) Any ideas? I have a javascript file that is pulling in data - all well and good. However - I'd like to add a href class to the data that is outputted via AJAX. var craeteLink = function(cellValue, text) { return jQuery('<a/>', { href: cellValue, text: text, target: "_blank", rel: "nofollow" })[0].outerHTML; The above is the snippet of code that I believe makes the JS do its' magic with creating links but does anyone know the code to get the class to work? I tried class: but that didnt work.... Thanks!
Alternative solution is return jQuery('<a></a>', { href: cellValue, text: text, target: "_blank", rel: "nofollow" }).addClass('yourclassnamehere').[0].outerHTML; Maybe this will help: Use JQuery to build an anchor * * * Actually I tried putting class and it works for me: < return jQuery('<a></a>', { href: cellValue, text: text, target: "_blank", rel: "nofollow", class: "testclass", })[0].outerHTML;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
CSS selector not functioning as expected In the following simple document: div+p { color: red; } <div> <p>Hi Caitlin! Welcome to CSS!</p> </div> The text between the 'p' (paragraph) tags is NOT displayed in red despite being the children of the div element. The '~' selector does not function either, but '>' performs as expected. I'm using Chrome 49 on a Windows machine.
`+` is the adjacent **sibling** combinator. The `div` and `p` have a parent/child relationship (`>` is the child combinator while a space is the descendant combinator) not a brother/sister relationship (which would be `<div></div><p></p>`).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css" }
If $mn+1$ is a multiple of $24$, prove that $m+n$ is also a multiple of 24. Please use UK pre-uni methods only (at least at first). Thank you.
Two facts: * If $m$ is odd, then $8\mid m^2-1=(m-1)(m+1)$ because $m-1,m+1$ are consecutive even integers so $4$ divides one of them. * If $3\nmid m$ then $3\mid m^2-1=(m-1)(m+1)$ because $3$ divides (exactly) one of the three consecutive integers $m-1,m,m+1$. Now if $24\mid mn+1$, then $m$ is odd and not divisible by $3$, so $24=3\cdot8\mid m^2-1$ and $$24\mid m\times(mn+1)-n\times(m^2-1)=m+n.$$
stackexchange-math
{ "answer_score": 7, "question_score": -4, "tags": "divisibility" }
CodeIgniter Custom Router help Am very new to CI, So I want to know that one feature listed below will be done via CI Router, then How? Feature: Q1. I need to show my users profile in such a way that `mysite.com/johhn` `mysite.com/raju.radha` `mysite.com/johhn1`. Q2. Other Urls are `mysite.com/photo/3434`, `mysite.com/album/3443` etc etc. I know this can be achieved by using `$route` . for the Q2 this is the solution $route['photo/:num'] = "photo/photo_list"; $route['album/:num'] = "album/album_list"; and what is the solution for Q1?? Thanks in advance !!!
Route: $route['(:any)'] = "profile/view/$1"; Controller: class Profile extends CI_Controller { function view($username) { echo $username; } } Edit: Commenter made the great point that this will need to be the last route directive in the file to prevent it from overriding all of the other routing rules.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "codeigniter, frameworks, url rewriting, url routing, codeigniter url" }
How is $\frac{1}{2n} \leq \sin (\frac{1}{n}) \leq \frac{1}{n} $ How is $\frac{1}{2n} \leq \sin (\frac{1}{n}) \leq \frac{1}{n} $ I know that $\sin \theta \leq \theta, \theta$ very small But if take $ f(x) = \sin (\frac{1}{x}) - \frac{1}{2x}, f'(x) = \frac{-1}{x^2} \cos (\frac{1}{x}) + \frac{1}{2x^2} $ But if i take $x=\frac 4\pi, x \in (0, \pi/2), $ i am getting $f'(x) < 0$ which should be other way around. Am I missing something? I got this doubt while reading Does $\sum_{n=1}^\infty(-1)^n \sin \left( \frac{1}{n} \right) $ absolutely converge? If i say since $\sin (x)$ converges to $x$, i will have $\sin x$ values slightly less than $x$ and slightly more than $x$. But it depends on whether $f(x)$ is increasing/decreasing (local maxima or local minima) Pls clarify
We know that for $x=\frac1n>0$ $$x-\frac16x^3\le \sin x \le x$$ refer to [Proving that $x - \frac{x^3}{3!} < \sin x < x$ for all $x>0$ ] and $$\frac12x\le x-\frac16x^3 \iff \frac12x-\frac16 x^3\ge 0 \iff x^2\le 3 \iff0<x<\sqrt 3$$ which is true since $0<x=\frac1n \le 1$.
stackexchange-math
{ "answer_score": 6, "question_score": 3, "tags": "real analysis, sequences and series, trigonometry" }
Get the file name of the current ES module Is it possible to get the file name of the current JavaScript module? // item.mjs function printName() { console.log(...); // >> item or item.mjs }; If not, why not? Sandboxing, etc.
You are looking for the (proposed) `import.meta` meta property. What exactly this object holds depends on the environment, but in a browser you can use // item.mjs function printName() { console.log(import.meta.url); // } You can extract the file name by parsing that with the `URL` interface, e.g. console.log(new URL(import.meta.url).pathname.split("/").pop())
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 8, "tags": "javascript, ecmascript 6, es6 modules" }
Gradle, mavenLocal() and --refresh-dependencies When declaring the following into my build.gradle: repositories { mavenLocal() } I can re-deploy similar Maven Artifacts (similar = with the exact same version) to Maven local, Gradle will pick up the latest which has been installed, without the need of using `--refresh-dependencies` If, instead of declaring a `mavenLocal()` repository, I'm declaring a Maven Remote Repository, then I'll have to include `--refresh-dependencies` in order to be 100% sure I'm getting the latest of a published version. No problem here, this is expected ... However, I don't understand why the same is not true for a `mavenLocal()` repository. I couldn't find any explanation in the documentation: Declaring a changing version. Does anyone have any hints?
Caching is disabled for local repositories. The paragraph The case for mavenLocal() from the _Declaring repositories_ enumerates the various downsides of using `mavenLocal()` and explains the behavior you observe: > To mitigate the fact that metadata and/or artifacts can be changed, Gradle does not perform any caching for local repositories
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "maven, gradle, repository" }
Application of l'Hopital's Rule in a past paper In an old exam paper the following solution is given: $$\lim_{r \to 0}\cfrac{\sin\left(\cfrac{\mu_1\cdot r}{R}\right)}{\mu_1\cfrac{r}{R}}\overset{l'Hopital}{=}\cfrac{\cfrac{1}{R}\cos\left(\cfrac{\mu_1\cdot r}{R}\right)}{\mu_1\cfrac{1}{R}}=\frac{1}{\mu_1}$$ My understanding of l'Hopital is that the result should be $1$: $$\lim_{r \to 0}\cfrac{\sin\left(\cfrac{\mu_1\cdot r}{R}\right)}{\mu_1\cfrac{r}{R}}=\cfrac{\cfrac{\mu_1}{R}\cos\left(\cfrac{\mu_1\cdot r}{R}\right)}{\mu_1\cfrac{1}{R}}=1$$ Is this a mistake or have I misunderstood something?
You are right. One might also substitute $\frac{\mu_1r}{R}=: h$ and then ends up with $\lim_{h\to 0}\frac{\sin h}h=1$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "calculus, derivatives" }
Google Chart: weekly schedule Any suggestions on how I can use Google Chart API to display a weekly schedule? For example, a store's hours of operation: * Sunday, 9am-5pm * Monday, 9am-9pm * Tuesday, 9am-9pm * Wednesday, 9am-9pm * Thursday, 9am-9pm * Friday, 9am-12nn, 3pm-9pm * Saturday, 9am-10pm Looking for examples, code snippet, or general advice.
You could use a stacked bar chart with two plots. Hours on the Y axis. Week days on the X axis. First bar chart has start times. Second bar chart has end times (minus start times). The trick: Make the color of the first bar chart the same as the chart background color so you can't see it. Then, you'll just see the second bar chart. I would start with 24 hour time first. If you get that to work, you can replace the times with text labels (ie 2 PM). Caveat: I haven't tried this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google visualization" }
Show small window with image from CLI What the problem in this code i've written ? using System; using System.Windows.Forms; public class stfu { public static void Main() { Console.WriteLine("Hello Toxic world!"); var f = new Form(); f.FormBorderStyle = FormBorderStyle.None; f.Controls.Add(new PictureBox() { ImageLocation = @"image.png",Dock = DockStyle.Fill}); f.Show(); Console.ReadLine(); } } form not responding. . .
You need invoke Application.Run() method to properly process window's messages: var f = new Form(); // init form here Application.Run(f);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#" }
Set the field "Last Modified By" in the office DOCX file metadata -Apache POI 3.9- With POIXMLProperties.getCoreProperties() and POIXMLProperties.getExtendedProperties() I can set all the metadata values ​​except "Last Modified By", Is there any way to set it? Thanks for advance.
I'm using POI 3.10-beta1 and it works for me, i.e. you can set it directly in the `PackageProperties`: import java.util.Date; import org.apache.poi.openxml4j.opc.*; import org.apache.poi.openxml4j.util.Nullable; public class LastModifiedBy { public static void main(String[] args) throws Exception { OPCPackage opc = OPCPackage.open("lastmodifed.docx"); PackageProperties pp = opc.getPackageProperties(); Nullable<String> foo = pp.getLastModifiedByProperty(); System.out.println(foo.hasValue()?foo.getValue():"empty"); pp.setLastModifiedByProperty("user"+System.currentTimeMillis()); pp.setModifiedProperty(new Nullable<Date>(new Date())); opc.close(); } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "apache poi, apache tika" }
Invalid Host Header when using elasticsearch client When using the elasticsearch client (from the elasticsearch npm version 15.4.1), the AWS elasticsearch service complains about an Invalid Host Header. This happens for every request even though they work. I double-checked the configuration for initializing the elasticsearch client and the parameter "host" is correctly formed. let test = require('elasticsearch').Client({ host: 'search-xxx.us-west-1.es.amazonaws.com', connectionClass: require('http-aws-es') }); I expected to get a clean ElasticsearchRequest without a corresponding InvalidHostHeaderRequests (I can see these logs on the Cluster health dashboard of the Amazon Elasticsearch Service).
Found the problem. When using elasticsearch library to connect to an AWS ES cluster, the previous syntax can lead to problems, so the best way to initialize the client is specifying the entire 'host' object as follows: host: { protocol: 'https', host: 'search-xxx.us-west-1.es.amazonaws.com', port: '443', path: '/' The problem here is that probably AWS ES Cluster expects the host field inside the host object and this leads to the "Invalid Host Header" issue. Hope this will help the community to write better code. Refer to < for reference.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "node.js, amazon web services, elasticsearch, aws lambda" }
Red Gate SQL Compare vs. VS2010 Ultimate I used to use SQL2000 and Red Gate SQL Compare 3.2 and I was a happy camper. I wouldn't worry about tracking the changes that I make to the dev database until all the coding was done and I needed to compile a list of scripts to bring the prod db in sync with the prod. This is where SQL Compare and to some degree, SQL Data Compare, were invaluable in 1. pointing out the differences and even more importantly, 2. helping me generate the SQLs to bring the prod db in sync with the dev db. I see that VS2010 Ultimate allows me to compare two schemas, but does do #2? I believe it is suppose to but it ain't obvious to me how to do that. Any kick in the right direction would be an immediate vote up or better. ty.
Yes, it does (2). To achieve this, run the comparison (Data/Schema Compare/New Schema Comparison), choose the objects you want to update, and then right click on the grid or go to the Data/Schema Compare menu and select Refresh Update script. If you can't see an upgrade script now, select Show Schema Update Script which is in the same menu. If you want a more user-friendly and versatile tool, please consider trying SQL Compare 8! (I'm the product manager)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 8, "tags": "sql server, visual studio 2010, version control, sqlcompare" }
Convert String to Color int String ColorString = "Color.BLUE"; int colorint = Integer.parseInt(ColorString); ... views.setTextColor(R.id.tvConfigInput, colorint); Why does this crash? in the logcat i get `java.lang.numberformatexception: Invalid int "Color.BLUE"` I kinda think its at the conversion from string to int it's wrong, because if i just set the int like this: int colorint = Color.BLUE; it works.. but what's wrong with it i don't know. THANKS very much
The constant value of `Color.Blue` is: -16776961 (0xff0000ff). You are not parsing an int, your are just trying to parse a string and convert it into a int(which won't work). "Color.BLUE" is not an Integer, but `Color.BLUE` will eventually return a constant value. You need to do this in order to get it right: int colorInt = Color.BLUE; views.setTextColor(R.id.tvConfigInput, colorInt); Edit: String ColorString = "BLUE"; int colorInt = Color.parseColor(ColorString); views.setTextColor(R.id.tvConfigInput, colorInt);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, android, string, int, remoteview" }
AlertDialog's items not displayed I create an `AlertDialog` with an `AlertDialog.Builder` and set some items with `setItems()`. The dialog is shown but I cannot see any of the items. All I see is the message. final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity); dialogBuilder.setMessage("Pick a color"); dialogBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do anything you want here } }); dialogBuilder.create().show(); If I set the `PositiveButton`, I can see that button just fine. I also tried setting `MultiChoiceItems` and `SingleChoiceItems` but neither of these work either.
Use `setTitle` instead of `setMessage` which sets message body and overrides the items list.
stackexchange-stackoverflow
{ "answer_score": 191, "question_score": 55, "tags": "android, android alertdialog" }
Find $\lim_{(x,y)\rightarrow (0,0)} \frac{e^{1-xy}}{\sqrt{2x^2+3y^2}}$. I am trying to calculate $\lim_{(x,y)\rightarrow(0,0)}\frac{e^{1-xy}}{\sqrt{2x^2+3y^2}}$, or show that the limit does not exist. **Thoughts:** In the limit $(x,y) \to (0,0)$, it seems that the numerator is tending to a constant value $e$, while the denominator tends to zero, so the required limit might be infinity. However, I am not sure how to obtain a suitable lower bound to show this. I also tried to show that the limit does not exist, without much luck. Approaching the origin along the $x$-axis would give: $\lim_{x\to 0}\frac{e}{x\sqrt{2}}$, and along the $y$-axis would give $\lim_{y\to 0}\frac{e}{y\sqrt{3}}$. Both these limits tend to infinity. Approaching $(0,0)$ along $y=x$ also suggests the same.
Yes you are right, since numerator tends to $e$ and the denominator to $0^+$ we can easily conclude that the limit is $\infty$, indeed eventually by squeeze theorem $$\frac{e^{1-xy}}{\sqrt{2x^2+3y^2}}\ge \frac 1{\sqrt{2x^2+3y^2}} \ge \frac 1{\sqrt 3\sqrt{x^2+y^2}}\to \infty$$
stackexchange-math
{ "answer_score": 3, "question_score": 1, "tags": "calculus, multivariable calculus" }
React triggering navigation from nested components I am new to React/RN and understand how navigation works, but don't really see a best practices for how to trigger navigation from a trivial component, like a random button somewhere, that should trigger a route change. Let's say this button is nested under a set of elements who are under a `<Tab.Navigator>` who are under a set of `<Stack.Navigator>`, etc. A couple screen layouts deep. This element cannot access `this.props.navigation`. So my idea is to send upwards. But this could mean passing an `onPress` handler like, 5 or 6 layers down. Is this the correct way? Should I only pass it from the parent closest to a navigator, or all the way to `App.tsx`?
If you can not use the `<Link>` component, then you should use the history object. For example, the `useHistory` hook will return it ( whenever you will import ), so your component can be nested as hell. import { useHistory } from 'react-router-dom' function HomeButton() { const history = useHistory() function handleClick() { history.push('/home') } return ( <button type="button" onClick={handleClick}> Go home </button> ) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs" }
Process a heavy function by GPU in C# I have a heavy function in C# that process an image with image processing, How can I run it on GPU?
Try using one of the NET CIL/GPU compilers: Alea GPU (< or Altimesh (< They work and but have some limitations. I have been developing Campy (< a free and open source compiler that will work with most NET frameworks, but it's not yet ready. You will need to parallelize your code in any case. You could use Cudafy (< but I would not recommend it since it has not been updated since April 2015, and does not support CUDA 8 or 9.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, image processing, gpu" }
How to change a date format in JavaScript I have a date in following format: 13 Dec,2021 12:59:58 and I want to change it into: 13-12-2021 pls suggest some fix
Convert it do a `Date`, get the make a string out of the components. The month needs to add 1 since for some reason, months are zero-indexed (January == 0, February == 1, ..., December == 11) const dateString = "13 Dec,2021 12:59:58"; const getNewString = (dateString) => { const date = new Date(dateString); return `${date.getDate()}-${date.getMonth()+1}-${date.getFullYear()}`; } console.log(getNewString(dateString));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, date" }
How can I get phone serial number (IMEI) I want to get phone serial number by programming to registration configuration of my application and number of users and phones that my app has been installed on them. Can I get that? and can I get phone model that my app has been installed on them?
pls refer this < TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); mngr.getDeviceId(); add `READ_PHONE_STATE` permission to `AndroidManifest.xml`
stackexchange-stackoverflow
{ "answer_score": 60, "question_score": 17, "tags": "android" }
Can't find /etc/passwd For some reason, every time I need to go to passwd or even shadow, It does not allow me. For example: cd /etc/passwd Output: `cd: not a directory: /etc/passwd` Same thing with shadow. Because of this, I can not find my users and their passwords. Does anyone have solutions? I am not sure if I accidentally deleted the directory with rmdir or not but I doubt. Also, I deleted all the files in my virtual box and it was still not there when I started up a fresh one. Do I need to download another .ova for it??? Also, it was **Kali linux** for the Virtualbox I was using
You are using `cd`. This allows you to change to a directory. `/etc/passwd` is not a directory. You can see that with: $ file /etc/passwd /etc/passwd: ASCII text $ ls -l /etc/passwd -rw-r--r-- 1 root root 3281 Feb 9 06:43 /etc/passwd Note that the first character on the `ls` response is a `-`. If `/etc/passwd` were a directory it would be a `d`. Instead, you'll want to use something other than `cd` to read the file. This could be `cat /etc/passwd` to read it, or `sudo vipw` to open it in an editor for editing. The same thing exists for `/etc/shadow`, except it typically contains password hashes, so it is not world-readable. You'll need `sudo cat /etc/shadow` to read it, and `sudo vipw -s` to edit it.
stackexchange-unix
{ "answer_score": 4, "question_score": -4, "tags": "shell, kali linux, virtualbox, cd command" }
Java random number Beginner question here: I tried creating a random number using this code int rand = (int) Math.random()*10; however, i kept receiving 0 as the answer when printing to screen only after putting parenthesis like so int rand = (int)(Math.random()*10); did the number show properly. Can anyone explain the logical reason for this that I missed?
The code int rand = (int) Math.random()*10; is equivalent to int rand = ((int) Math.random()) * 10; So the value of `Math.random()` is converted to an `int`. Because that value **is between 0 and 1 (1 excluded)** it **is converted** always **to zero**. So (int) Math.random()*10 --> ((int) Math.random()) * 10 --> 0 * 10 --> 0
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, random, numbers, generator" }
Why do the definitions of \quad, etc. have \relax in them? Plain Tex defines `\quad` so: \def\quad{\hskip1em\relax} Why is the `\relax` there? It's usually used as a token that can't be expanded, serving as a "do nothing" operation after macro expansion is finished. But that use seems redundant, because it follows a command, namely `\hskip`. The macro is defined alongside `\enskip` and `\qquad` in plain.tex, and in Latex in `ltspace.dtx`. An idle question, but I guess the reason for it will be worth knowing.
So that \quad doesn't eat following text while assembling the argument of \hskip: \documentclass{article} \begin{document} \def\quad{\hskip1em\relax} \quad plus 1em text \def\quad{\hskip1em} \quad plus 1em text \end{document}
stackexchange-tex
{ "answer_score": 26, "question_score": 22, "tags": "tex core, expansion, plain tex" }
Filtering and Sorting results with WebSockets? I'm fairly new to both node.js & socket.io but I've built a websocket end point that pushes simple data to a front end. **Example:** `{ name : "Bob", eyes : "green", score : 100, fav : "true" }` Easy enough using node.js/socket.io ( _so easy!!_ ) but my question is: Is there a way to filter and/or sort the data prior to being pushed to the client side? I realize that I could do this with JS in the browser, but if I have 600 people being pushed and the end user only wants people with "green" eyes it seems like a waste to push the 550 users that don't have green eyes to the browser just to then strip them out.
After quite a bit of research and playing, I've concluded that the best method to accomplish this would be to setup socket "channels" for each filter point. Using my initial post as an example, I'd have a channel for green, blue, brown (etc) eyes and then subscribe users to that channel based on their requirements. Filtering would then be done on the client side to ensure no duplicates show in the list/grid.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "node.js, websocket, socket.io" }
How to do an Update based on the maximum entry of another table Lets say I have a table called Boxes, and another called BoxStateRegistry with the box state os that box plus a timestamp. **Boxes** BoxId Size -----|----| 1 | 3 | 2 | 5 | **BoxStateRegistry** id BoxId Datetime State ---|-----|------------|--------| 1 | 1 | 04/03/2009 | Closed | 2 | 1 | 05/03/2009 | open | 3 | 2 | 04/03/2009 | Closed | 4 | 2 | 05/03/2009 | open | 5 | 2 | 06/03/2009 | Closed | Meanwhile I decided to add another column in the Boxes table to have its latest state there. How can i update the new column in orther to have the correct value? I tried this with no success: UPDATE Boxes Set state = (SELECT TOP 1 t.State FROM BoxStateRegistry t WHERE t.BoxId = BoxId ORDER BY t.DateTime DESC) What is the correct way to do this kind of update?
If you really wanted to do this, you may use an update join: WITH cte AS ( SELECT TOP 1 WITH TIES BoxId, State FROM BoxStateRegistry ORDER BY ROW_NUMBER() OVER (PARTITION BY BoxId ORDER BY Datetime DESC) ) UPDATE b SET State = t.State FROM Boxes b INNER JOIN cte t ON b.BoxId = t.BoxId; As the comments have suggested, you might instead want to create a view which displays the state of the boxes in the first table, rather than doing an actual update. You could use the above CTE in my answer to do that: SELECT b.*, t.State FROM Boxes b INNER JOIN cte t ON b.BoxId = t.BoxId; The main problem with the update approach is that every time the registry table changes, you might be forced to update the boxes table.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "sql server" }
Finding the column index where a row changes values in R dataframe/Datatable Suppose I have the following dataframe: DF <- data.frame(Col1=c(2,2,1),Col2=c(2,7,5),Col3=c(9,6,4)) I would like to know 2 things: * how can I get another field stating the index of the column where that row changes values. Hence, for the first row we'd get 1 and 3, and for the second and third rows, 1, 2 and 3. * How to get a field of the "before and after"? for the first case, something like 2 -> 9, for the second and third, 2->7, 7-> 6 and 1 ->5, 5->4, respectively.
What about this: x <- sapply(1:NCOL(df), function(x) rle(df[x,])$values) Output of x: [[1]] Col2 Col3 1 2 9 [[2]] Col1 Col2 Col3 2 2 7 6 [[3]] Col1 Col2 Col3 3 1 5 4 Then if you'd like the full range of before/after values, you could use: lapply(x,function(i) paste0(i,collapse="->")) [[1]] [1] "2->9" [[2]] [1] "2->7->6" [[3]] [1] "1->5->4"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r" }
sql-dump failing when run as cron I have a shell script that executes `drush sql-dump`, compresses the result and then sends it to a backup server. It works fine when run from the command line as root but it is failing silently and dispatching an empty file when run as part of a scheduled cron job. This script has worked previously for me on another website as a cronjob and so I am somewhat confused what would be wrong now. I work with Drupal 8.3.1 and Drush Version 8.1.11. Any suggestions?
After much frustration I have resolved the issue and will post the answer in case it is of use. Cron seems to not always have access to the same PATH information as when a normal user - or even root - runs a drush command in a command line. The solution came from comment #7 in this drush thread. You need the path to drush. You can find this with the command: which drush In my case it was `/usr/local/bin/drush` Then add the path info to the top of the shell script. export PATH=$PATH:/usr/local/bin And then it worked perfectly. Additionally, it appears if your local mail is not set up correctly cron discards output from scripts which is why the `drush: command not found` error was not turning up in logs. To make sure you get logs from cron configure it for local mail. See this post.
stackexchange-drupal
{ "answer_score": 3, "question_score": 1, "tags": "drush, cron" }
Sort array of strings without converting them into integer I have an array of strings expressing integer values: array = ["0934", "123", "934", "0123"] I want to sort the array without converting the strings into integers. The expected output is: array = ["0123", "123", "0934", "934"] Please suggest how I can do that.
If you cannot convert a string to an integer within Array#sort_by!'s block, you could pad the strings to the left with zeroes (using String#rjust) so they are all the same length, then sort on those padded strings. n = array.map(&:size).max #=> 4 array.sort_by! { |s| s.rjust(n, '0') } #=> ["123", "0123", "0934", "934"] Note array.map { |s| s.rjust(n, '0') } #=> ["0934", "0123", "0934", "0123"]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "ruby, string, sorting" }
Downloading flask-generated html page I want to put a button on a flask-generated web page and let a user download the html page as a file when the user clicks the button. What I imagine is something like saving the rendered html into `BytesIO` and send it via `send_file`, but I can't find how to save the rendered page into a file object. How can I do that?
You could try something like this: import StringIO from flask import Flask, send_file, render_template def page_code(): strIO = StringIO.StringIO() strIO.write(render_template('hello.html', name='World')) strIO.seek(0) return send_file(strIO, attachment_filename="testing.txt", as_attachment=True) It is not tested but should give you an idea.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 5, "tags": "python, html, flask" }
php include and include_once really quick question does php 5 still support include_once because I am getting some unusual characters "..." when I use include_once but not when I use include
"..." is not a PHP error message. Any other symptoms? Btw you could use include if you go for performance.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php" }
C# trying to extract URLs from a webpage that have extentions .com, .net and .org I am trying to extract .com, .net and .org links from a single webpage that contains various numbers of these. I am just learning about Regex using C#, but I am not sure how to setup a pattern that looks for the just .com, .net and .org extensions. Then print those urls with those endings. Any suggestions or websites that you can direct me to help me would be great. here is what i got so far WebClient client = new WebClient(); string extPattern = @"?.com|?.net|?.org; //but i think i am not doing this right. string source = client.DounloadString(url) //read the Url and store the pages. //then not sure what to do. Thanks
Try this regex: string extPattern = @"( Anyway this is not the perfect way to achieve your goal because url are very different (could have http or https, with or without www).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, regex" }
Putting Two Consecutive Lines into One Line with Perl / AWK I have a data like below: abcd join abcd efgh join efgh I want to join the two consecutive pair into one line. Resulting: abcd join abcd efgh join efgh How can I do it in Perl/AWK?
$ sed 'N;s/\n/ /' input.txt abcd join abcd efgh join efgh
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 4, "tags": "linux, perl, unix, text, awk" }
How to handle IDE project files with git-svn I'm using git-svn and there are IDE project files in the svn repository. Everytime I start my IDE it modifies project files a bit and they are marked as changed in the status display. And then if I try to do a git svn rebase to update my working tree to have the latest changes from the svn it fails as I have local modifications on the project files and I have to stash the changes. How can I ease my workflow so I wouldn't have to stash/stash apply everytime I haven't really modified anything?
Create a simple git alias which does what you want ( _untested_ ): [alias] safe-svn-rebase = "git stash 'preparing to rebase'; git svn rebase; git stash pop"
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "git, git svn" }
Scanner.skip() in Java I'm very new to Java and trying to understand the Scanner class. I'm using the example code to learn about the skip(String Pattern) method of the Scanner class. I tweaked the code a little and changed it to import java.util.*; public class ScannerDemo { public static void main(String[] args) { String s = "Hello World! 3 + 3.0 = 6.0 true "; // create a new scanner with the specified String Object Scanner scanner = new Scanner(s); // changed the string to skip scanner.skip("World"); // print a line of the scanner System.out.println("" + scanner.nextLine()); // close the scanner scanner.close(); } } The output I was expecting is Hello ! 3 + 3.0 = 6.0 true But I get `NoSuchElementException`. Can some one point out my mistake please.
It's not nextLine that is giving you exception, but the skip("World"). When the Scanner start, it is pointing to the "H" in "Hello Word...", that is the first letter. Then you tell him to skip, and must give a regulare expression for the skip. Now, a good regular expression to skip to after the word "World" is : scanner.skip(".*World"); ".*World" means "Every character any number of times followed by World". This will move the scanner to the "!" after the "Hello World", so nextLine() will return ! 3 + 3.0 = 6.0 true The "Hello" part has been skipped, as per skip.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "java" }
Travis conditional on branch after_success In my travis script I have the following: after_success: - ember build --environment=production - ember build --environment=staging --output-path=dist-staging After both of these build, I conditionally deploy to S3 the one that is appropriate, based on the current git branch. It works, but it would save time if I only built the one I actually need. What is the easiest way to build based on the branch?
use the `test` command as used here. after_success: - test $TRAVIS_BRANCH = "master" && ember build All travis env variables are available here.
stackexchange-stackoverflow
{ "answer_score": 35, "question_score": 15, "tags": "travis ci" }
toString returning same String for every object of a particular class? Are there any future problems if my toString returns String static reference:- public static String example = "any problem"; @Override public String toString() { // TODO Auto-generated method stub return example; }
Because Strings are immutable no caller can change the underlying String reference any other caller has; therefore it is safe. However, it's not very useful since that value is shared by all instances of the class - why not just use `return this.getClass().getName();` if that's what you want?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, string, object, static, return" }
Prevent app to crash when I open multitask When my app is launched, and I double tap on the home button to display the bottom bar containing all the running application (multitasking), My App crashes, and I have no idea where it can come from !! Any help please ?
Ok, I found it, actually I had nothing in the stack nor in the console log, except a "Program ended with exit code: 255", but that's I quit the application in the applicationWillResignActive, using exit(-1). Thanks anyway
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "iphone, ios, multitasking" }
evaluate $\phi(50!)$ I want to evaluate $\phi(50!)$, where $\phi$ is the Euler totient function, so i take the factorization in primes of $50!$ $$2^{47}\times 3^{22}\times 5^{12}\times 7^8\times 11^4\times 13^3\times 17^2\times 19^2\times 23^2\times 29\times 31\times 37\times 41\times 43\times 47$$ then i use multiplicativity of $\phi$ and the properties $\phi(p)=p-1$ and $\phi(p^k)=p^{k-1}(p-1)$ for every prime $p$ and i get $$\phi(50!)=4218559200885839042679312107816703841788854953574400000000000000$$ I'm asking for some smarter way to compute values of $\phi$ for great numbers, possibly not involving prime factorization
$$\phi(50!)=50!\prod_{p\le 50\,,\,\,p\text{ a prime}}\left(1-\frac{1}{p}\right)$$ The above is based on the following lemma: **Lemma:** If $$\Bbb N\ni n=\prod_{i=1}^kp_i^{a_i}\;\;,\;\;0<a_i\in\Bbb N\;,\;\;p_i\,\,\text{primes}$$ is the prime decomposition of $\,n\,$ , then $$\phi(n)=n\prod_{i=1}^k\left(1-\frac{1}{p_i}\right)$$
stackexchange-math
{ "answer_score": 4, "question_score": 4, "tags": "analytic number theory" }
Proof that Conditional Expectation of Sum is Sum of Conditional Expectations \begin{eqnarray*} E\left[\left.\left(X+k\right)\right|\left(X+k\right)>0\right] & = & E\left[k\left|\left(X+k\right)>0\right.\right]+E\left[X\left|\left(X+k\right)>0\right.\right] \end{eqnarray*} $k$ is a constant and $X$ is a random variable that could be discrete, continuous and having any distribution. Does the above equality hold and if so, please provide the proof. # QUESTION ORIGIN Please note, I have assumed the above equality is correct in the proof to the related question here, but would be keen to know if there a formal proof or any cases where this would not hold. Conditional Expected Value of Product of Normal and Log-Normal Distribution
This is just linearity of expectation. \begin{align} \text{E}(X + k \mid X + k > 0) &= \frac{\text{E}(X + k \, ; \, X + k > 0)}{P(X + k > 0)} \\\ &= \frac{\text{E}(X\, ; \, X + k > 0) + k P(X + k > 0)}{P(X + k > 0)} \\\ &= \text{E}(X \mid X + k > 0) + k. \end{align}
stackexchange-stats
{ "answer_score": 2, "question_score": 0, "tags": "probability, self study, conditional probability, conditional expectation" }
How to split a string at a specific character but not replace that character? I want to split at every ';' and every '{' from the string below: // string $str = 'abc;def;ghi{jkl;}if('mno') {pqr;}'; // expression $pattern = "/[;{\(]/"; $result = preg_split($pattern); print_r($result); It splits at the point of every ';' and '{' but these characters are also removed which I don't want. I used explode() function though it splits, but also replace that character. And how to multiple splitting in a string? expected result should look like that. array ( 0 => "abc;", 1 => "def;", 2 => "ghi{", 3 => "jkl;", 4 => "}if('mno') {", 5 => "pqr;", 6 => "}", ) Please guide me thanks.
You can use Lookahead and Lookbehind Zero-Length Assertions. Example: // string $str = "abc;def;ghi{jkl;}if('mno') {pqr;}"; // expression $pattern = "/(?=[;{\(])/"; $result = preg_split($pattern, $str); $result is a array like array ( 0 => "abc", 1 => ";def", 2 => ";ghi", 3 => "{jkl", 4 => ";}if", 5 => "('mno') ", 6 => "{pqr", 7 => ";}", )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, regex, laravel, string, split" }
If $\sum\limits_{i=1}^{n}a_{i}^{2}=−1$. Show that if $c\in F$ $\exists$ $b_{1}, \dots , b_{k}$ of $F$ satisfying $c =\sum\limits_{i=1}^{k}b_{i}^{2}$. > Let $F$ be a field of characteristic other than $2$ in which there exist elements $a_{1}, \dots , a_{n}$ satisfying $\sum\limits_{i=1}^{n}a_{i}^{2}=−1$. Show that for any $c\in F$ there exist elements $b_{1}, \dots , b_{k}$ of $F$ satisfying $c =\sum\limits_{i=1}^{k}b_{i}^{2}$. I really dont know how to prove that, so needing some help ;)
**Hint.** $$c=\left(\frac{1+c}{2}\right)^2-\left(\frac{1-c}{2}\right)^2$$
stackexchange-math
{ "answer_score": 4, "question_score": -1, "tags": "abstract algebra, field theory" }
How to remove the comma seperated part of the column record from the oracle table We have the oracle table called "Names" which has approximately 10k records. The table has one of the column as "ID". Now this column is totally messed up and the records looks somewhat similar to the following. ID A.011 A.012 A.013 B.014 B.015 B.016 A-B-C X_Y_Z randomName OtherName Now, what we have decided is to remove the dot(.) seperated portion of the record and leave the other records as is for now. So the record should look like ID 011 012 013 014 015 016 A-B-C X_Y_Z randomName OtherName
You could use this statement: update names set id=regexp_replace(id,'^[^\.]+\.','') as you see here, ids without `.` are simply untouched: select regexp_replace('tst234','^[^\.]+\.','') from dual and here a test with a `.` select regexp_replace('A.0234','^[^\.]+\.','') from dual
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, oracle" }
String replace all that not mach regex This is my javascript regex: `/^(\d+\.?\d{0,2})$/` My target is to replace all inputs according to it. Is that possible? Example: 123a.12 => 123.12 aaa12aa => 12 12.aaa13 => 12.13 12.aaa => 12 12.555 => 12.55 12.... => 12 12. => 12 12.35.12.14 => 12.35 12.aaa.2.s.5 => 12.25 I was using `str.replace(/^(\d+\.?\d{0,2})$/, '')` but with no success
You can replace the first `.` with a placeholder, I have used `|`. Then, remove any characters that are not digits or the placeholder. Finally, replace your placeholder with `.`. Then, remove anything past 2 decimal places: const num = (s) => { const clean = s.replace(".", "|").replace(/[^\d|]/g, '').replace('|', '.'); return parseInt(clean * 100) / 100; } const tests = [ "123a.12", "aaa12aa", "12.aaa13", "12.aaa", "12.555", "12....", "12.", "12.35.12.14", "12.aaa.2.s.5" ]; tests.forEach(test => console.log(test + " => " + num(test)));
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, regex" }
Why aren't Python dicts unified? After reading this question, I noticed that S. Lott might have liked to use an “ordered defaultdict”, but it doesn't exist. Now, I wonder: Why do we have so many dict classes in Python? * dict * blist.sorteddict * collections.OrderedDict * collections.defaultdict * weakref.WeakKeyDictionary * weakref.WeakValueDictionary * others? Why not have something like this, dict(initializer=[], sorted=False, ordered=False, default=None, weak_keys=False, weak_values=False) that unifies everything, and provides every useful combination?
One issue is that making this change would break backward-compatibility, due to this type of constructor usage that exists now: >>> dict(one=1, two=2) {'two': 2, 'one': 1}
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 13, "tags": "python" }
If $\Sigma \vdash \phi$ implies $\Sigma \vdash \varphi$ then $\Sigma \vdash \phi \to \varphi$ on propositional logic? My main aim is to prove or disprove that if $\Sigma \vdash \phi$ implies $\Sigma \vdash \varphi$ then $\Sigma \vdash \phi \to \varphi$ where $\Sigma$ donotes a set of sentences in propositional logic. $\Sigma \vdash \phi$ means there is a deduction from $\Sigma$ where the deduction is a sequence $( \alpha_0 , \dots , \alpha_n)$ with $a_i$ is either in $\Sigma$ or a consequence of MP (that is, for some $j,k<i$ $\alpha_k = \alpha_j \to \alpha_i$ and $\alpha_i$ follows from them) or a tautology. I'm completely stuck now. I tried to prove it but have no idea on how to bring $\phi$ to a deduction sequence. And I also tried to make a counterexmaple but no simple one I could find. Even in my mere intuition, I cannot clearly judge whether it is true or false. (I also thought of employing Completeness and Soundness Thm..)
Take Σ here to be just the axioms of propositional logic, and take $\phi$ to be some propositional atom $p$. Then Σ ⊢ $\phi$ is false, and thus "Σ ⊢ $\phi$ implies Σ ⊢ $\varphi$" is true for any $\varphi$. Now take $\varphi$ to be some other atom $q$. $[p \rightarrow q]$ is not a tautology. If a formula is not a tautology, then it is not provable from Σ, because of the soundness metatheorem. So, Σ ⊢ $(\phi \rightarrow \varphi)$ is false. Thus, "if Σ ⊢ ϕ implies Σ ⊢ φ then Σ ⊢ $(\phi \rightarrow \varphi)$" is false in general. (In fact $p,q$ need not be atoms; they can be taken to be any independent formulas. That is, formulas such that for each pair of truth values $(b_1,b_2)$, there is at least one valuation for which $p$ and $q$ take values $b_1$ and $b_2$ respectively.)
stackexchange-math
{ "answer_score": 7, "question_score": 8, "tags": "logic" }
How to reference an InputField in Unity 5 using C# I want to reference an `InputField` within Unity 5 using C#, but cannot figure out how to. My goal is to take the text from the `InputField` when a button is clicked and use that text as a variable within other parts of the project. I've tried using `GameObject.Find("IPInput").GetComponent<Text>();` but that doesn't seem to work. I am using `UnityEngine.UI` so it's not that.
I think you're confusing the static `Text` component with `InputField`. Try this: InputField field = GameObject.Find("IPInput").GetComponent<InputField>(); Debug.Log(field.text); Side note, it's not very efficient to query by GameObject name so depending on what you're doing, you might want to just add this field to your component handling the button click: public InputField field; Then drag the input field into there in the inspector, and you won't have to call `GameObject.Find()` or `GetComponent()`. Much better than hard-coded object names.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, unity3d, unity5.3" }
Yes/no: Do odd integers form a subring of $\mathbb{Z}$? Do odd integers form a subring of $\mathbb{Z}$? My attempt: Yes, from this answer My logic is that if $n$ is any integer (odd/even) the set of all multiples of $n$ is a subring $n\mathbb{Z}$ of $\mathbb{Z}.$
Indeed, the following statement is true: > if $n$ is any integer, then the set of all multiples of $n$ is a subring of $\mathbb Z$. However, you have the set $A$ of all **odd** integers. For which integer $n$ does the set $A$ equal the set of all multiples of $n$? If you cannot find such a value $n$, then the statement outlined above cannot be used to prove that $A$ is a subring.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "abstract algebra, group theory, ring theory" }
intel compiler buggy remarks for variadic templates? I use intel compiler, and since intel doesn't really support -Wall I use -Wremarks for warnings... I have this simple code which just makes a certain object.. template<typename... Args_t> static inline Obj makeObj(Args_t&&... args) { auto obj = std::make_shared<Obj>(args...); // probably can forward but doesn't matter.. return obj; } I get this remark: remark #869: parameter "args" was never referenced is this a bug? anyone seen this?
This is just a bugged warning that was already reported in the Intel forum. It doesn't have any particular meaning as the code is completely okay (although you should consider perfect forwarding).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, intel, compiler warnings, variadic templates, icc" }
Может ли юла катиться? Катится юла - применимое выражение? Может ли юла катиться? Катится юла - применимое выражение?
Думаю, что нет. Катится предмет лишь в одном направлении, как шар для боулинга. При этом катящийся предмет делает это за счёт оборотов по поверхности. Зато юла может КАТАТЬСЯ. Разница этих слов в том, что катающийся предмет, во-первых, может попеременно двигаться в разных направлениях (как юла), во-вторых, вовсе не обязательно совершает движение за счёт собственного вращения по поверхности (как катающийся наездник). В Вашем случае я бы заменил "катится юла" на "ездит/движется/кружит/вращается юла" и даже на "ходит юла". В художественном тексте можно пойти дальше и говорить том, что юла даже танцует (если позволяет выбранный стиль). **Однако.** Катится юла всё-таки может, но только в том случае, когда она упала на бок и катится уже лежа, как колесо, на поверхности.
stackexchange-rus
{ "answer_score": 1, "question_score": 0, "tags": "грамотная речь" }
Push rejected, failed to detect set buildpack git://github.com/CHH/heroku-buildpack-php I would like to push a new app to Heroku using `git push heroku master`. After successful authentication have got following error. > remote: Building source: remote: remote: -----> Fetching set buildpack > git://github.com/CHH/heroku-buildpack-php... done remote: > > remote: !Push rejected, failed to detect set buildpack > git://github.com/CHH/heroku-buildpack-php `detect` file: #!/bin/bash if [ -f "$1/composer.lock" ]; then echo "PHP (composer.json)" && exit 0 elif [ -f "$1/index.php" ]; then echo "PHP (classic)" && exit 0 else exit 1 fi
This buildback is deprecated, you should use official `Heroku` buildpack instead.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "git, heroku, buildpack" }
Separating pairs of points in R^n Let $A$ be a set of $2k$ points in $\mathbb{R}^n$ such that no open set in $\mathbb{R}^n$ of diameter $2$ contains more than $k$ of these points. What is the largest possible distance $r_n>0$ one can guarantee so that for all $k$ we can pair up $2k$ points under the mentioned condition so that each pair of points is at least $r_n$ apart? It is not difficult to show that $1\leq r_n \leq 2$ ($2$ comes from just taking $|A|=2$ and proving that one can always have them at distance $1$, one can build a distance graph so that two point from $A$ are joined if they are at least $1$ apart - such graph has minimum degree at least $k$ and so has a Hamilton cycle).
Consider a regular $2k-1$-gon of diameter $2$, meaning the distance between the two most distant vertices is $2$. Then only $k-1$ vertices can be in any set of diameter less than two, becsuse any set of $k$ vertices contains a maximum-distance pair. So the set of vertices plus the center form a set satisfying your condition. As $k$ goes to $\infty$, the polygon approaches a circle of radius $1$, so $r_n=1$ for $n\geq 2$.
stackexchange-mathoverflow_net_7z
{ "answer_score": 6, "question_score": 6, "tags": "co.combinatorics, graph theory, mg.metric geometry" }
Linking library with G++ Sorry for asking this newbie question but I can't get off this s***t... In the same directory I have 4 files : `ctacs.ini`; `ct_api.h`; `libctacs.a` and `main.cpp`. My cpp file contains `#include "ct_api.h"` and when I try to compile with : `g++ -lctacs main.cpp -o main` I got undefined references to the functions which are defined in my library -__- Could you please tell what did I wrong ? I search on the internet but the option `-lctacs` seems to be the right way to proceed... Thank you very much
Some compilers and linkers resolve references to functions by searching the object files/sources files/libraries left-to-right on the command line. This means that files that call externally-defined functions should appear _before_ the object files/libraries/source files that contain their definitions. You happen to have a linker that does indeed depend on this ordering. You need to put the library _after_ `main.cpp` so that the function definitions can be found: g++ main.cpp -lctacs -o main
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "hyperlink, g++" }
What is a good, lightweight database to use for a small F# winforms project? I have a project I'm thinking of doing in F#, but I'm still very new to the language. I'll need a simple database, hopefully something easy to use. Would sqlite work well for an F# project? Other suggestions?
SqlLite is a very popular lightweight database engine that supports a .Net binding layer which is accessible from F#. It probably the best option for your scenario. This CodeProject article details how to use C# to bind to SqlLite and is easily transferable to an F# scenario * <
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "database, f#" }
pandas apply function with arguments I have one function that takes three arguments. And here's the heading. def count_ones(num, total_bits, group_size): And I am trying to apply this function to data column. But it is not returning what I expected. Could anyone help me out on this problem? total_bits are 60 and group_size is 12. df['events'] = df['data'].apply(count_ones, args =(60, 12))
Pass the arguments as kwargs to `apply`: df['events'] = df['data'].apply(count_ones, total_bits=60, group_size=12)
stackexchange-stackoverflow
{ "answer_score": 36, "question_score": 17, "tags": "python, pandas" }
understanding set-pnplistitempermission I am trying to use the following cmdlet in the pnp module on O365 and one of the parameters for the cmdlet is `-identity` -Identity The ID of the listitem, or actual ListItem object Type: ListItemPipeBind Position: Named Accept pipeline input: True Accept wildcard characters: False The parameter says the ID of the listitem **or** the listitem object, I am trying to put the name instead of the ID So changing `-identity` from Set-PnPListItemPermission -List 'Test' -Identity 1 -User '[email protected]' -AddRole 'Contribute' -ClearExisting To Set-PnPListItemPermission -List 'Test' -Identity "TestFolder" -User '[email protected]' -AddRole 'Contribute' -ClearExisting The script runs on both occasions with no errors but the permission is only changed when -identity is the ID, am I missing something here? ![enter image description here]( <
By list item object, it means passing the `Microsoft.SharePoint.Client.ListItem` object. You are currently passing string which will not work. You need to use `Get-PnPListItem` to get the list item and then pass it to the `Set-PnPListItemPermission` command. To do that, you can use it as below: $listItem = Get-PnPListItem -List 'Test' -Id 1 or passing CAML query, something like $listItem = Get-PnPListItem -List 'Test' -Query "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>TestFolder</Value></Eq></Where></Query></View>" And then Set-PnPListItemPermission -List 'Test' -Identity $listItem -User '[email protected]' -AddRole 'Contribute' -ClearExisting Reference - Get-PnPListItem
stackexchange-sharepoint
{ "answer_score": 3, "question_score": 1, "tags": "sharepoint online, powershell, office 365, pnp, pnp powershell" }
Changing parameters for include files with CMake I'm trying to set up a toolchain for CMake and have made some progress (it's getting the right compiler and all), but I've run into a problem with the -I (include directories directive). The compiler I'm using doesn't understand -I, it understands -i. What I don't understand is where to change this so that CMake builds the makefile with the -i rather than the -I. Any help would be greatly apprecaited
Somewhere in your CMakeLists.txt file, you should add the following line: set(CMAKE_INCLUDE_FLAG_C "-i") This will change your include flag from the default of `-I` to `-i`. Do `CMAKE_INCLUDE_FLAG_CXX` for C++. I say this with the caveat that you might want to wrap this in a `if` that only does this for the Cosmic compiler. * * * CMake sets this to `-I` by default in the file `CMakeGenericSystem.cmake`... search your cmake install dir this file and you will see the CMake defaults for several settings inside. If a compiler has to modify this, it will be in the `Compiler` folder in the same dir as `CMakeGenericSystem.cmake`. I'm willing to bet that there is nothing implemented in the `Compiler` folder for the Cosmic compiler.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "cmake" }
Subgroup of the centralizer On pg.124 of Abstract Algebra by Dummit and Foote the observation is made that In any group $G$, $<\hspace{0.2mm}g \hspace{0.2mm}> \hspace{1mm} \le \hspace{1mm} C_G(g)$ I am having a difficult time proving this observation to myself. The book gives a particular example but does not provide any proof or general explanation.
To make it trivial write down with words: $$\langle g\rangle \le C_g(g)\iff \text{any power of $\,g\,$ commutes with $\;g\;$}$$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "abstract algebra" }
Laravel: How can I authenticate a user by e-mail, where the e-mail address is stored in a separate table? I'm creating a website using Laravel and I wish to use the Auth middleware. To let users add multiple e-mail addresses and phone numbers, so they have backup options for recovery etc., I'm storing them in separate tables from the main `users` table. Looking closer at the Authentication documentation and skimming through some of the classes used for the authentication, I'm unsure how I might specify that the e-mail and phone number should be retrieved from their respective tables rather than the `users` table (`email_addresses` and `phone_numbers`). If anyone could tell me how to set this up, or at least point me in the right direction, I would be super grateful. Don't need to have it spelled out, but if someone know which files I need to edit that would help a lot.
Get your user record by email from emails table: `$record = Emails::where('email', $email)->first();` if($record){ //if this email is valid you will get the user record if(auth()->validate(['id' => $record->user_id, 'password' => $input['password']])) auth()->loginUsingId($record->user_id) else echo 'Invalid password'; } else { echo 'User not present!' }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, authentication, laravel 5" }
Specify "Accept:" header parameter in a GWT JSONP request Is it possible to specify the `Accept:` header parameter in a GWT JSONP request? I'm using the `JsonpRequestBuilder` class.
JSON-P is about adding a `<script>` element to the page (the server will then return JavaScript that will callback a JS function of yours with some data); there's no way to tweak the request made by the browser in this case.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, gwt, jsonp" }
Check Activity info in the MyFirebaseMessagingService when App is in foreground I am working on a chat app. I am retrieving chats directly from the server. I am listening for new nodes. So, If, the app is in foreground and the notification is from the same user with whom I am talking. I don't want to show the notification. How can I check in Service which Activity is running in foreground and content of that activity.
You can use SharedPreferences to save current running activity of your app in onResume, onPause. like below: @Override public void onPause() { super.onPause(); PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isCurrent", false).commit(); } @Override public void onDestroy() { super.onDestroy(); PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isCurrent", false).commit(); } @Override public void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isCurrent", true).commit(); } and then in your service: if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isCurrent", false)) { return; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, firebase, android service, firebase cloud messaging, android notifications" }
Delete child record if a field of parent is updated using trigger My code is: trigger ClassCustomStatus on Class__c (before update) { Set<Id> classSet = new Set<Id>(); for(Class__c c : Trigger.new){ if(c.Custom_Status__c == 'Reset'){ classSet.add(c.Id); } } list<student__C> s = [SELECT id FROM Student__c WHERE class__c IN:classSet]; Delete s; } Here I am getting one exception this: ![enter image description here]( How can delete child records which are from **student__c** And How can I update a field of parent which is **Class__c** Please help
Use `after update` to make sure that the record isn't already pending any changes. The rest of your code is fine.
stackexchange-salesforce
{ "answer_score": 0, "question_score": 0, "tags": "apex, trigger, delete" }
How to split string and push in array using jquery var string = 'a,b,c,d'; var array = []; As we can see above I have one string values with separator* _(,)_ *. I want to split these values and wants to push in the array. At last I want to read my array by using for loop. Please suggest.
Use the String.split() var array = string.split(',');
stackexchange-stackoverflow
{ "answer_score": 49, "question_score": 11, "tags": "javascript, jquery" }
Count occurence of values for every possible pair I have a list of ids and places where these ids have been. Now I want to find pairs of ids that have most places in common. My data frame looks like this: id place Dave Paris Dave Moscow Dave New York Joe New York Joe Tokyo Stuart Paris Stuart Moscow Stuart New York Stuart Tokyo The results should look like this: pair1 pair2 count Dave Joe 1 Dave Stuart 3 Joe Stuart 2 I tried split to divide the data: temp = split(df$name, df$place) So I now have the places grouped, but I didn't get further. The original dataset has about 100.000 unique ids. Can anybody help me to find a good and fast solution? Thanks!
You may try library(reshape2) tbl <- crossprod(table(df1[2:1])) tbl[upper.tri(tbl, diag=TRUE)] <- 0 res <- subset(melt(tbl), value!=0) colnames(res) <- c(paste0('pair',1:2), 'count') row.names(res) <- NULL res # pair1 pair2 count #1 Joe Dave 1 #2 Stuart Dave 3 #3 Stuart Joe 2 Or another option is Subdf <- subset(merge(df1, df1, by.x='place', by.y='place'), id.x!=id.y) Subdf[-1] <- t(apply(Subdf[-1], 1, sort)) aggregate(place~., unique(Subdf), FUN=length) # id.x id.y place #1 Dave Joe 1 #2 Dave Stuart 3 #3 Joe Stuart 2
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "r" }
Recolor image in Windows 10 Universal App C# Working on an app and as part of it I need to recolour it to match the phones accent color. What I have is a gray scale image with transparent sections and want to change it the colored. * The white sections will be the pure accent color * Gray sections will be the accent color faded * Black sections will be black I've done this in the past, but never with a universal app. Any help or suggestions would be great. Thanks,
You can use Lumia Imaging SDK to apply some basic effects on your image. If it doesn't fit your requirement. You can use Win2D to work on your picture. You can find a good example of Win2D by this link: Shawn's Terrific Universal App for photogRaph Tweaking.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "c#, image, bitmap, windows 10 universal" }
Assigning a string to a JavaScript var from django I have the following template: var url = {{url}}; $.getJSON(url... and the following view: return render_to_response('template.html', {"url":"/this/url/"}) but for some reason javascript does not treat this as a `string`. Is there a reason why? What is the syntax that I should be using?
This line in your template: var url = {{url}}; Will become this: var url = /this/url; There are no quotes in the template, and there are no quotes in the string, so there are no quotes in the output. You should use this: var url = "{{url}}"; or even better: var url = "{{url|escapejs}}"; so that special characters will be treated properly.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "javascript, jquery, python, django" }
TextJoin like function based on a condition in on SQL Trying to figure out if it is possible to do a textjoin like function in SQL based on a condition. Right now the only way I can think of doing it is by running a pivot to make the rows of the column and aggregating them that way. I think this is the only way to transpose the data in SQL? **Input** This would be a aql table (tbl_fruit) that exists as the image depicts SELECT * FROM tbl_fruit ![enter image description here]( **Output** ![enter image description here](
Below is for BigQuery Standard SQL (without specifically listing each column, thus in a way that it scales ...) #standardSQL select `Group`, string_agg(split(kv, ':')[offset(0)], ', ') output from `project.dataset.table` t, unnest(split(translate(to_json_string((select as struct t.* except(`Group`))), '{}"', ''))) kv where split(kv, ':')[offset(1)] != '0' group by `Group` If to apply to sample data from your question - output is ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, function, google bigquery, pivot, transpose" }
Allowing simple footer customisation in settings? So, I want to give the client the ability to edit the footer, copyright & legal area. This isn't worth it's own content or block. I don't think.... Is is possible to add a text entry field into setting to customize the footer area or alike areas on the website.
In Drupal 6, the Site information settings page at /admin/settings/site-information has a "Footer Information" field that meets your description above. If this field is not empty, and you do a major upgrade of your D6 site to D7, then your footer information will be moved into a block called "Footer message". While it would be possible to re-implement the "Footer Information" field from D6 in D7 with a custom module, or in the settings for your theme (which would be even easier) I think it is clear that D7 designers felt that using a block for this purpose was the best and most general solution.
stackexchange-drupal
{ "answer_score": 1, "question_score": 1, "tags": "7" }
Using session_name() in PHP - Cannot Access Data When I use: session_name( 'fObj' ); session_start(); $_SESSION['foo'] = 'bar'; Subsequently loading the page and running: session_start(); print_r( $_SESSION ); doe not return the session data. If I remove the session_name(); it works fine. Does anyone know how to use sessions with a different session name? **UPDATE** : If I run the above code, as two page loads, and then change to: session_name( 'fObj' ); session_start(); print_r( $_SESSION ); I can access the data. However, if it will only work if I first load the page without the line: session_name( 'fObj' );
In light of nwolybug's post I think this must be due to some environmental settings. I can get this to work via doing the following: if( $_COOKIE['fObj'] ) { session_id( $_COOKIE['fObj'] ); session_start(); } var_dump( $_SESSION );
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 9, "tags": "php, session variables, session cookies" }
Clojure, concat multiple sequences into one The following line: `(repeat 4 [2 3])` gives me this: `([2 3] [2 3] [2 3] [2 3])` How do I create one vector or list from the above list of vectors so that I get this?: `[2 3 2 3 2 3 2 3]` Thanks
> (flatten x) > Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat sequence. > (flatten nil) returns nil. (flatten (repeat 4 [2 3])) ;(2 3 2 3 2 3 2 3)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "clojure" }
Why am I getting ORA-00937 error using only aggregate functions? Here is a sample of what I'm trying to do: SELECT COUNT(T1.FIELD) + ( SELECT COUNT(T2.FIELD) FROM TABLE2 T2 ) FROM TABLE1 T1 I don't see a need for group by clause in here.
Aggregate functions, but not on the same object, in a subquery, with addition. Use this: SELECT (SELECT COUNT(T1.FIELD) FROM T1) + (SELECT COUNT(T2.FIELD) FROM T2) FROM DUAL;
stackexchange-dba
{ "answer_score": 3, "question_score": 2, "tags": "oracle, select, aggregate" }
How do I change the PostgreSQL data directory in the OpenGeo Suite 4.5? I am using OpenGeo Suite and I would like to move the PostgreSQL databases files to a different drive than my operating system. The default location installed by OpenGeo Suite is in the "C:\ProgramData\" directory, but I would like for it to be "F:\db\". Some websites suggest that the data directory location can be changed by adding -D "F:\db\" to the ImagePath value of the PostgreSQL service key in the registry. However, for me this did not change where PostgreSQL is looking, and I have restarted the service several times. Since OpenGeo customized the service and registry key names, I am afraid that they may have also customized the PostgreSQL service itself to prevent the changing of the data directory. Does anyone have any knowledge of this?
I was able to force PostgreSQL to use the data folder F:\db\ by creating the following batch file (and manually turning PostgreSQL on/off): start "" /min "C:\<PostregreSQL>\bin\pg_ctl.exe" start -D "F:\db" -w I found this solution here: <
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "postgresql, boundless suite" }
How to open Colorbox jquery plugin modal window from asp.net code behind? I have an asp.net `listview` control with a `asp:button` in its `itemtemplate`. I want to open `Colorbox` when it is clicked and certain conditions satisfied (that is why I have trouble with calling onclientclick) and the Colorbox will show an iframe. I tried many diffrent ways and googled alot but none of the answers were useful to me because all of them were suggesting `onclientclick` event instead on onclick. I'm using a code like below to open an href link in Colorbox modal dialog: <script> $(document).ready(function () { $(".ajax").colorbox(); $(".iframe").colorbox({ iframe: true, width: "50%", height: "500px" }); }); </script> But I can't make it work from code-behind inside a `itemcommand` event of an asp.net listview. Can you please suggest a solution?
Here is what I came into finally: <asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClientClick=" OpenCBox();" /> <script type="text/javascript"> function OpenCBox() { $.colorbox({ href: '<%# Eval("EditLink") %>', iframe: true, width: "50%", height: "500px", transition: "elastic", onClosed: function () { parent.location.reload(true); } }); return true; } </script>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, asp.net, listview, colorbox, code behind" }
How do I make setters and getters for JList and DefaultListModel? (Java) I am writing a program that uses several custom `jpanels` to essentially make a Word-pad. This `jpanels`is supposed to allow the user to select a color from a Color-chooser and add or remove it from a `jlist`. In order for the window that will use the `jpanels`to be able to get the data from the `jpanels`, I was instructed to make setters and getters for my DefaultListModel and `jlist`. I have no idea how to do this with these types. I have seen examples of setters and getters for parameterized ArrayLists, and that seemed promising, but I still don't understand how to apply it to the listModel and `jlist`. private ArrayList<String> stringlist = new ArrayList<String>(); public ArrayList<String> getStringList() { return stringlist; } public setStringList(ArrayList<String> list) { stringlist = list }
Check this. if we have a `JList` and a `DefaultListModel` JList listvariable= new JList(); DefaultListModel model= new DefaultListModel<>(); Now these are the getter and setter methods for the same: public DefaultListModel getModel() { return model; } public void setModel(DefaultListModel model) { this.model = model; } public JList getListvariable() { return listvariable; } public void setListvariable(JList listvariable) { this.listvariable = listvariable; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, swing, jlist, getter setter, defaultlistmodel" }
Remover caractere de um valor gerado Tem como pegar um valor gerado, checar quantos caracteres tem e remover caso necessário? Exemplo: Se o valor for de apenas 4 caracteres (ex: 1844) ele ignora, porém se passar de 4 caracteres uma função remove os caracteres para ficar apenas 4, tipo se tiver 6 caracteres (ex: 184455) remove 2 para ficar apenas 4 novamente.
Faça assim function remove_chars(num) { var str_num = String(num); if(str_num.length > 4) { var removals = str_num.length - 4; str_num = str_num.slice(0, -removals); } if(isNaN) { return str_num; } return parseInt(str_num); } console.log(remove_chars(325325)); Nota: Se tiver a certeza que são sempre números, pode retirar `if(isNaN) {return str_num;}`
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "javascript" }
how to update pymongo from version 2.7 to 3.6 I run the command `pip freeze | grep "pymongo"` in my Mac OS ,it show the version `pymongo==2.7.2` I want to update my pymongo from version 2.7 to 3.6
Follow the below steps, 1. First download the zip file from < as what version you want (I download the latest version 3.6.1). 2. Move to the download folder. 3. Unzip the folder using command tar -xzf pymongo-3.6.1.tar.gz 4. Install the python-3.6.1 sudo python -m pip install ../../Downloads/pymongo-3.6.1
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "python, pymongo" }
List to Map of List using java streams I have a class Company public class Company { private String companyid; private List<Employee> employees; } Which is related to Employee in One2Many relationship public class Employee { private String employeeId; private Company company; } I am supplied with a list of employees and I want to generate a map like `Map<companyId, List<Employee>>` using java streams as it has to be performant. employees.stream().collect( Collectors.groupingBy(Employee::getCompany, HashMap::new, Collectors.toCollection(ArrayList::new)); But the problem is I can't call something like Employee::getCompany().getCompanyId() How can I do this. Any suggestions are welcome
Use a lambda expression instead of a method reference: Map<String,List<Employee> output = employees.stream() .collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId(), HashMap::new, Collectors.toCollection(ArrayList::new))); Or simply: Map<String,List<Employee> output = employees.stream() .collect(Collectors.groupingBy(e -> e.getCompany().getCompanyId()));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, java 8, java stream" }
How can I adapt the width of an Image retrieved by URL to a View container in React Native? I would like to retrieve an image from an url, and insert it inside a `View` adapting the size to the container. This is an `expo` where I tried to do it. < How you can see there are 3 columns having the same width(flex 1), in the first there is the image. I wish this `Image` was contained inside the `View`, adapting the width to the container and maintaining the correct aspect ratio. Any suggestions?
You need to change `src` to `source` in your `<Image />`: <Image source={{uri: ' resizeMode='contain' style={styles.image} /> **Output:** ![Output]( **Working Demo:** <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "react native, react native image" }
Update JSON attribute after scope variable update I have the following JSON array in my controlle $scope.companyExcelColumns = [ { label: 'Name', checked: true, disabled: true, id:'nameExcel' }, { label: 'value', checked: true, disabled: $scope.records > 1000 ? true : false, id: 'valueExcel' } ]; Initially the $scope.records is 0, later on it is changing but the the disabled attribute is not updating, is there a workaround ? Thanks
this is not a common angular question but rather a programming question. of course value of disabled will not change. it is calculated once and done for. You could use $watch and watch changes on $scope.records object. when this object changes you can reassign value of disabled. $scope.$watch('records', function(){ disabled = $scope.records.length > 1000})
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "angularjs, angularjs scope" }
Convert INT column values to an empty string using ISNULL I need to convert column ID of INT data type to a empty string ['']. I should not modify the source column data type, but need to convert it in my transformation in the other table. The ID column is "nullable" as it has null in it.This is my code. CREATE TABLE #V(ID INT) ; INSERT INTO #V VALUES (1),(2),(3),(4),(5),(NULL),(NULL) ; SELECT CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS ID_Column FROM #V; this returns: ID_Column 1 2 3 4 5 NULL NULL when I modify my CASE statement it as follows: CASE WHEN CAST(ISNULL(ID,'') AS VARCHAR(10)) = '' THEN '' ELSE ID END AS ID_Column it returns: ID_Column 1 2 3 4 5 0 0
Is this what you want? select coalesce(cast(id as varchar(255)), '') from #v; You have to turn the entire result column into a single column. If you want a blank value, then the type is some sort of character string. In your examples, the `else id` means that the result from the `case` is an integer, which is why you are getting either `0` or `NULL`.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "sql, sql server 2008, type conversion, isnull" }
Why does this function return the largest integer less than or equal to √n? I've been asked this question by my teacher. The function I'm talking about is the following: SqrtFloor[n_Integer] := Module[{a = n, b = Quotient[n + 1, 2]}, While[b < a, a = b; b = Quotient[a^2 + n, 2 a]]; a] I understand the code, but I don't know what is the mathematical concept behind it. Why does it return the largest integer less than or equal to √n?
This is a discretized version of Newton's Method where f(x) = x^2 - a, which has a zero at x = Sqrt[a]. Wikipedia With initial guess x = n, (x^2 + n)/(2 x) decreases at each step until x <= Sqrt(n).
stackexchange-mathematica
{ "answer_score": 2, "question_score": 0, "tags": "number theory" }
Can gmail (smtp.gmail.com) post incoming mails to my application instead of my applications pulls the mail? I am using smtp.gmail.com to send mails. I want to read/parse mails in my application. I know how to pull the mails, there are API libraries to handle that. It is bit over do for my application. Instead, is there any way gmail can post mails to my application like sendgrid does ?
If you want to get emails from a gmail account, and want a webhook to do such, you could use Context.io's Webhook Feature. However, at the maximum volume you'll be able to send out with Gmail, I'd recommend looking toward an email service provider's free plan. If you're familiar with SendGrid already SendGrid's Free Plan will give you access to both low volume sending, and the Parse webhook. Other email service providers will give you the same functionality on their free plans, as well (e.g. Mailgun). **Disclaimer** : I am a SendGrid employee.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "gmail, sendmail, sendgrid" }
Find particular CheckListItem in CheckBoxList control using Javascript or jQuery I have a CheckBoxList that displays a list of checkboxes using data from a table. While the records in this table is expected to change, the last item is expected to have a text value of Other with an expected value. If the user selects "Other", I want to be able to enable an associated text box where they enter a specified "Other" description. I want to be able to do this on the client using Javascript or jQuery. Since the IDs individual list items are dynamically created is there a way that I can avoid hard coding something like: chkOther = document.getElementbyID("checkListItem12_chkOccupationOther") I don't know jQuery, but I figure that that Library probably provides a nice way to get control using a matching ID mask, for example. Suggestions?
If you can guarantee that your "Other" Check box is always last you can use the last selector. Using the ID of the check box list: $(document).ready(function() { $("#<%=YourCheckBoxList.ClientID%> input:checkbox:last").click(function(){ if(this.checked) { //Enable Text Box Here }else{ //Disable here } }); }); **EDIT:** Updated to remove the unnecessary convert of "this" to a jQuery object as per RobG's Comment.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, asp.net, checklistbox" }
Variable resistor that can handle hundreds of watts? We have some big resistor test loads, like 8 Ω 250 W loads for simulating speakers: !enter image description here Are there also big variable load resistors for testing power supplies? What are they called? If not, what do people use instead?
As MikeJ-UK mentioned, there are rheostats. I personally don't like them for the same reasons what Mike mentions. But there are two more options: 1. Build a a resistor box and use switches to change the load. Or if you're fancy you can use MOSFET's and a MCU to do the job as well. Careful selection of the resistor values could give you a very wide range of resistances with fairly fine control. 2. Buy an "electronic load". Just google the term (in quotes) and you'll come up with a lot of pages. Basically it's the opposite of a benchtop power supply. Most will work in 3 modes: Constant Current, Constant Voltage, and Constant Resistance. My employer has one that's rated for 30 KWatts! Of course they make smaller ones.
stackexchange-electronics
{ "answer_score": 6, "question_score": 3, "tags": "power supply, resistors, switch mode power supply, electronic load" }