INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Editing bootstrap CSS to hide an image I've got an image that is displayed when viewing the website on a computer; however, I want it to be hidden when the site is viewed on a mobile device. I've just used the 'display: none;' CSS but for some reason it's not working. HTML: <div class="col-sm-7 col-sm-offset-1"> <img src="./images/testing.jpg" alt=""> </div> CSS: .col-sm-7 { display:none; } Thank you.
Just add the class `hidden-xs` and/or `hidden-sm`. See the docs for more info
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css" }
Contradiction while taking determinant of a nilpotent matrix Consider a nilpotent matrix $A$ of index of nilpotency $n$ , then $A^n=O$ and $A^{n-1}\neq O$ where $O$ denotes null matrix of same order as of $A$ Now $A^n=O\implies \det(A)^m=0\implies \det(A)=0$ but $A^{n-1}\neq O\implies \det(A)\neq0$ I know I am wrong in the second statement because a matrix not being equal to a null matrix doesn't imply that it has to be necessarily non-singular. Therefore aren't we allowed to take determinant on both sides for the inequation $A\neq O$ ?
The statement $A^{n-1}\neq O\implies \det(A)\neq0$ is wrong. In other words, there can be non-zero matrices with zero determinants. For example, consider the matrix \begin{pmatrix} 1&0\\\ 0&0 \end{pmatrix}
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "matrices" }
Loosen the base swivel of a Delta faucet This Delta faucet is supposed to swivel on the joint (I believe) at the base of the faucet. However the joint seems to be too stiff and it's caused the base of the unit to detach from the counter and now the whole unit swivels. How do I loosen this joint so that it can swivel freely? (Before I tighten the whole unit back on the counter.) ![enter image description here]( ![enter image description here](
You need to remove the pull-out spout and let the hose drop down through the faucet body, remove the lever handle, then unscrew the cap and remove the valve components, then pull directly upwards to remove the spout. The spout glides on two o-rings; you need to get a small tube of plumber's grease and grease the heck out of the o-rings, then reassemble. I could go through the disassembly/reassembly steps in detail but it would be a very lengthy process so maybe just watch an internet video on it.
stackexchange-diy
{ "answer_score": 1, "question_score": 1, "tags": "plumbing, faucet" }
Javascript check for existing object in Array I have some simple objects in an Array. I want to add new objects to the Array only if they are not already in it, based on an object property. var o = {text: 'foo'} var a = [o] var checkExisting = function (list, obj) { list.forEach(function(elem) { if (elem.text === obj) { return true } } } checkExisting(a, 'foo') This doesn't work. I can't figure out why. Any help or alternatives would be great.
Because you can't `return` value from `callback` in `forEach`, you can use `for`, like this var checkExisting = function (list, obj) { for (var i = 0, len = list.length; i < len; i++) { if (list[i].text === obj) { return true; } } }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, arrays" }
using group by clause in subquery in sql I am trying to use group by clause in subquery which is in from clause select userID,count(id) from ( ( select id,max(bidAmount),userID from Bids group by id,bidAmount ) group by userID ); but this gives error > Error: near "group": syntax error Is it possible to use group by clause in subquery in from clause in sql?
Check your (), they are not at right places. Should be something more like this: select w.userID,count(w.id) from (select id,max(bidAmount),userID from Bids group by id, userID) w group by w.userID
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 10, "tags": "sql" }
Odd Cygwin netstat output 20:38:41 [setevoy@setevoy-main ~] $ netstat -anp I have clear installtion of **Cygwin** on my **Win7** x64 desktop, but `netstat` returns something very-very odd... What it can be? Can it be caused by **Windows** _Ru_ localization? Or something else? Same output with any options. All other utils works normally. $ which netstat /cygdrive/c/Windows/system32/netstat
Make sure that you are picking the correct `netstat` for your platform. `which netstat` will give you path where it is executing it from.
stackexchange-unix
{ "answer_score": 1, "question_score": 0, "tags": "windows, cygwin" }
Salesperson misquoted price. Do I have to pay back the difference? **Background** I purchased something from a local store. The salesperson made a mistake and quoted me a lower price than what should have been. I made a down payment since they didn't have what I want at that moment. A week later I paid the remaining and got the goods I asked for. Days later, the same salesperson called me (I left my number with the down payment), saying he under-quoted one of the few items. He asked me (with good attitude) to pay back the difference. I decided to be a good guy and deposited the difference to the store's bank account. I though wonder if I am legally required to pay them back. **Question** In the case that a salesperson made a mistake and gave an underpriced quote to a customer, after the service had been served or the goods had been delivered, and the customer had paid in full, can the salesperson (or the store) legally demand the customer to pay back the difference?
In general, no. When the salesperson quoted the price and you accepted it you were each bound to that price by contract. Consideration under a contract must be sufficient (something of value for something of value) but it doesn't have to be fair: you can be obliged to pay $2 million for a cupcake or sell your Picasso for $1. You were and are under no obligation to pay and could successfully sue for the return of your money. To further clarify, it doesn't matter if the store has or has not provided the goods or services when they discover their error: they are obliged to perform their side of the contract without additional payment. Further, if this was a consumer contract then some sort of consumer protection law almost certainly applies. This would probably make what the store did not only a breach of contract but an offence against the state as well.
stackexchange-law
{ "answer_score": 3, "question_score": 2, "tags": "contract law, commerce, hong kong" }
Dynamically invoking KTRs from one KTR I need to have one KTR which is used to invoke multiple KTRs. That base KTR should be connected to MongoDB and based on the mapping in MONGODB, I need to invoke the specific KTR. Am I supposed to use Sub Transformation mapping? but how will i configure which KTR to be invoked?
we need to have JOB instead of mapped Transformations. Just configure first KTR in your job, whatever is the output of that KTR, set it in a variable (using setVariable) and then configure second KTR. In second KTR, configure Transformation file name as ${VariableName}. It will dynamically invoke the required KTR configured in your first KTR.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "pentaho, kettle" }
In javascript how can we identify whether an object is a Hash or an Array? The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two?
**Modern browsers support the`Array.isArray(obj)` method.** See MDN for documentation and a polyfill. = _original answer from 2008_ = you can use the constuctor property of your output: if(output.constructor == Array){ } else if(output.constructor == Object){ }
stackexchange-stackoverflow
{ "answer_score": 140, "question_score": 87, "tags": "javascript" }
How possible that an memory address also have another memory address ? I have stored the address of a integer variable in a pointer and then store the address of that previous into another pointer.I am not able to understand how it actually works. #include <iostream> using namespace std; #include <stdio.h> int main () { int var; int *ptr; int **pptr; var = 30; /* take the address of var */ ptr = &var; /* take the address of ptr using address of operator & */ pptr = &ptr; /* take the value using pptr */ printf("Value of var = %d\n", var ); printf("Value available at ptr = %d\n", ptr ); printf("Value available at pptr = %d\n", pptr); return 0; }
When you do `&ptr` you get the address of the variable `ptr` is stored. So you have a pointer `pptr` which points at `ptr` which in turn point at `var`. Like this: +------+ +-----+ +-----+ | pptr | --> | ptr | --> | var | +------+ +-----+ +-----+ * * * On a side-note, don't use the `"%d"` format to print pointers. Use `"%p"` instead, and then cast the pointers to `void *`.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c, pointers, pointer to pointer" }
tar extract as a specified user : tar: /home/administrateur/glpi-10.0.3.tar: Cannot open: Permission denied Cannot extract tar archive as `www-data` user, I get a `Cannot open: Permission denied` error : $ mkdir $HOME/tmp $ sudo chown www-data $HOME/tmp $ ll -d $HOME/tmp drwxrwxr-x 2 www-data administrateur 4096 2022-11-10 09:43:14 /home/administrateur/tmp/ $ ll $HOME/glpi-10.0.3.tar -rwxrwxrwx 1 administrateur administrateur 216893440 2022-09-14 14:28:21 glpi-10.0.3.tar* $ sudo -u www-data tar -C $HOME/tmp/ -xf $HOME/glpi-10.0.3.tar tar: /home/administrateur/glpi-10.0.3.tar: Cannot open: Permission denied tar: Error is not recoverable: exiting now $ EDIT0: Thanks to @Sotto-Voce, the answer is confirmed by this command : $ sudo -u www-data test -r $HOME/glpi-10.0.3.tar $ echo $? 1 $ sudo -u www-data test -r /tmp/glpi-10.0.3.tar $ echo $? 0
Just don't extract as www-data. As you see, that user has no access to the place you want to extract into, so the operation fails. Instead of trying to extract as a specific user, either extract directly into wherever you want to finally store this (presumably it is not supposed to live in `~/tmp`) or extract as your regular user and then chown the files: $ tar -C "$HOME"/tmp/ -xf "$HOME"/glpi-10.0.3.tar $ sudo -R chown www-data "$HOME"/tmp/
stackexchange-unix
{ "answer_score": 2, "question_score": 0, "tags": "sudo, tar" }
Exception on try? I have this problem which I really cannot understand. I am getting info from a WebClient which misbehaves and returns an empty response. This is another issue which I hope to solve soon, but the real problem is the following. Here is my code: private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error != null) { //... } Stream stm; try { stm = e.Result; } catch (Exception ex) { // debug output return; } WebClient senderWC = (WebClient)sender; DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MapData)); What I get is an exception at the try block. That is, the debugger stops with the arrow pointing to the try line, and highlights the opening braces. Why is that? See shot: screen shot
OUCH!!!! Stupid me! After reading it again and again, I noticed that I was throwing that myself! Visible in the screenshot: if (e.Error != null) { visualControl.debug.Text += e.Error.Message; throw e.Error.InnerException; // <-- this!! Handle it better, or just return... }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio 2008, silverlight" }
<script> tags keep getting stripped out on save by super admin in Joomla 1.6 I have already loaded the jQuery into head section via template manger. I know it is loading properly because it's loading a `.php` page and image into an element.. $("#divid").load("thefolder/thepage.php"); // - works great. The problem is that inside of the articles there's an issue when saving... It keeps stripping out the script tags. From my research I see there were past problems with this and Joomla. It seems it got fixed with newer releases by having the filters. But what about 1.6? I think I have disabled all the text editors and text filters for every user and group! And still, when I save under super admin with no text editor it saves and reloads the page with no script tags! `div` tags save ok though.
You could go directly to your database and edit the article contents within the fields there. Find jos_content and change the "introtext" and "fulltext" fields.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "jquery, mysql, ajax, joomla" }
How do I automatically truncate a growing buffer? I want to run IPython in emacs for all the emacsy goodness I get, but I'm having a problem getting the buffer to automatically truncate (it gets slow quickly printing large dataframes and such). It would also be nice to have my `run on save` test runners in emacs, but for that I would need the window to be automatically cropped at say 1000 lines. How do I do that?
You need to add the function `comint-truncate-buffer` to the hook `comint-output-filter-functions`, like so: (add-hook 'comint-output-filter-functions #'comint-truncate-buffer) By default, the buffer will be truncated at 1024 lines. To change it to 1000 you will need to change the variable `comint-buffer-maximum-size`, like so: (setq comint-buffer-maximum-size 1000) This should work for all major modes that derive from `comint-mode`.
stackexchange-emacs
{ "answer_score": 4, "question_score": 3, "tags": "buffers, window, ipython" }
Why are some of my CQWPs coming back blank for Visitors? I have a page with approx twenty CQWPs on them, all coming from the same library. It looks fine to me (Admin) but for the Visitor permission group, some boxes are coming up blank - no error message, just nothing! The header is still there and there is no error message. I've checked the library documents and there are no permission problems, and when I recreate one of the blank CQWPs (new web part with the same search parameters and display settings) the Visitor is still unable to see them. This does not appear to be a problem with web parts not set up with these settings. I'm at a loss! Grateful for any help. ![Image of web parts showing 'blank' web parts as well as correctly showing webparts](
So I thought I'd come back and update you all since it is a very silly thing - I was selecting a bunch of documents and using the 'check in' box in the ribbon to do a sort of 'mass check in' but guess what! It only checks in, it doesn't 'publish as major version', so it wasn't pulling through to the CQWP for Visitors as it was a minor version, which they can't see. So that's what was wrong! Stick like six forks in me, I am done.
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 1, "tags": "content query web part" }
How to link with a WebDAV application in Unity? In Ubuntu 10.10 Maverick, I could go to the Places menu and click "COnnect to Server" to run a WebDAV server for my NextApp WebSharing Android application. But in Unity, I'm not sure how I achieve the same thing. I tried "Shared Folders" but it says I'm missing plugins. (I uninstalled Evolution and everything related to it, if that helps.)
Start Nautilus, in the menue go to: File-> Connect to server
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 3, "tags": "11.04, sharing, webdav" }
problems when computers outside the network connect to my localhost I'm trying to let others access the website that I have made. A point of sale system to be exact. Is it really normal for people outside the network to see broken links? I'm using apache as a server. Installed through wampserver. How do I fix this problem? Basically everything is working when I'm just the one who is testing the site. Please comment if you need more details. Thanks **update** They can access my localhost using my ip address. They can see the site, but when they click to further links they report an object not found error. I don't know why since I don't see anything like that when I'm the one who is accessing it from localhost itself. <
`localhost` is a "magic" hostname that always refers to "this computer". Specifically, it's the standard hostname given to the loopback network interface. * * * If your site includes links that point to `localhost`, then a user of the site will end up trying to connect to thier own computer. All URLs should be relative if possible (eg, no hostname. So `/images/logo.png` and _not_ ` This eliminates the problem, because without a hostname it will use whichever one was already used. But, if you _have_ to make URLs absolute, then the hostname _cannot_ be `localhost`. It should be either your domain name or external IP address.
stackexchange-superuser
{ "answer_score": 3, "question_score": 0, "tags": "apache http server, ip, wamp, htaccess" }
SQL Server General Pivoting I have this SQL table called **Comments** with 2 columns: NCC_CLTID and NCC_CTYPE The table has the following information NCC_CLTID NCC_CTYPE TEST1 A TEST1 A TEST1 C TEST1 E TEST1 E TEST1 E TEST1 E TEST2 A TEST2 B TEST2 B TEST2 C I want a pivot table that looks like the following: NCC_CLTID TYPE1 TYPE2 TYPE3 TYPE4 TYPE5 TYPE6 TYPE7 TYPE8 ... TYPE20 TEST1 A A C E E E E NULL NULL TEST2 A B B C NULL NULL NULL NULL NULL How can I achieve this? I can't see a way to make this work for some reason
Assuming you have known or maximum number of `TYPE`s, you can use row_number() to determine the column **Example** Select * From ( Select [NCC_CLTID] ,[NCC_CTYPE] ,Item = concat('Type',row_number() over (partition by [NCC_CLTID] order by [NCC_CTYPE]) ) from YourTable ) src Pivot (max([NCC_CTYPE]) for Item in ([Type1],[Type2],[Type3],[Type4],[Type5], [Type6],[Type7],[Type8],[Type9],[Type10], [Type11],[Type12],[Type13],[Type14],[Type15], [Type16],[Type17],[Type18],[Type19],[Type20] ) ) pvt **Results** ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql server, sql server 2012, pivot" }
Function to read in multiple delimited text files Using this answer, I have created a function that should read in all the text datasets in a directory: read.delims = function(dir, sep = "\t"){ # Make a list of all data frames in the "data" folder list.data = list.files(dir, pattern = "*.(txt|TXT|csv|CSV)") # Read them in for (i in 1:length(list.data)) { assign(list.data[i], read.delim(paste(dir, list.data[i], sep = "/"), sep = sep)) } } However, even though there are .txt and .csv files in the specified directory, no R objects get created (I'm guessing this happens because I'm using the `read.delim` within a function). How to correct this?
You can add the parameter `envir` in your assignment, like this : read.delims = function(dir, sep = "\t"){ # Make a list of all data frames in the "data" folder list.data = list.files(dir, pattern = "*.(txt|TXT|csv|CSV)") # Read them in for (i in 1:length(list.data)) { assign(list.data[i], read.delim(paste(dir, list.data[i], sep = "/"), sep = sep), envir=.GlobalEnv) } } Doing this, your object will be created in the global environment and not just in the function environment
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "r, function, csv" }
Tooltip alignment How can I change the CSS so, that the tooltip shows up from right to left? Exactly the opposite of now. < Thank you!
write like this : .tooltip span.info { display:none; position: absolute; white-space:nowrap; border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0,0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); font-family: Calibri, Tahoma, Geneva, sans-serif; margin-left: 0; z-index: 1; top:20px; right:0; } check this <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "html, css, tooltip, alignment" }
is it possible to use multiple groups with cvpartition in matlab? thank you in advance for the input. I am using cvpartition to produce sets that I will use for training and validation on some data. In particular I'm using c = cvpartition(a,'kfold',5) where a is a single group. I would like to be able to generate training and testing sets using two groups, say a and b, rather than just a. In other words I'm looking for something like this c = cvpartition([a b],'kfold',5) %I haven't tried this; I would like to know ahead of time if this will work Is this possible to do using cvpartition? If not is there another way that I could easily do this without hard coding a solution?
I was able to find a solution on my own. Albeit not really my desired solution. In my case a and b are integers so I divided a by 10 then added it to b to get a.b. I then used this as my grouping variable. In other words, I created a combined variable that encodes information from a and b, is one to one given a and b, and allows me to use cvpartition to the desired affect.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "matlab, machine learning, cross validation" }
Async requests in Unity I've been unable to make async requests in Unity 4.6 C#. I have been trying out the WebAsync class from < but don't know how to get the response data (I'm expecting a json string) from the result. Answer on that would be appreciated, or another way to do this without the use of WebAsync would be ok too.
Do you really need this process in another thread ? If it's not critical, you can use Unity WWW class: < It is still asynchronous if used in coroutine (with added bonus of being much simpler and you can use Unity API - not available in other threads). void Start(){ StartCoroutine(AskServerSomething()); } IEnumerator AskServerSomething() { WWW www = new WWW(" yield return www; if(www.error == null){ print("success: " + www.text); } else { print("something wrong: " + www.text); } }
stackexchange-stackoverflow
{ "answer_score": -3, "question_score": 0, "tags": "c#, rest, asynchronous, unity3d" }
Which is more proper javascript syntax? if (//some condition) { //some code } else { //other code } or if (//some condition) { //some code } else { //other code }
I think the first one isn't good, and I have the same feelings about the second one
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript, syntax" }
? icon after file names in Xcode In Xcode, sometimes there is a `?`, an `A`, or an `M` in a box to the right of the name of a file. What are the meanings of these icons? Will they have some influence on how the project compiles and runs on the simulator or device?
These are version control status labels. M means the file is modified, A means it has been added, and ? means your version control system doesn't know about it yet.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "iphone, xcode" }
Is there any downside to using __weak in non-ARC iOS Objective-C code? I'm writing iOS Objective-C code sans ARC. I prefer __weak MyClass *myWeakIVar; to, e.g. MyClass *myWeakIvar; // weak Not only does it read better to me, but if I ever use this code on a garbage-collected platform, etc., I get the benefits of the __weak directive. Are there any downsides to this? Put another way, is it presently equivalent (again, w/o ARC) to a noop on iOS?
According to this thread, `__weak` does nothing on iOS if ARC is disabled.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "objective c, iphone, ios" }
PayPal adaptive payments response I'm using the paypal adaptive SDK on github, for a simple 1 recipient payment, so I'm using the simple pay file. < I'm able to make a payment, I've entered all the details correctly and that's fine, but I'm just wondering where I get the response so I Know the payment was successful and I can process the order? Currently it just goes to the return URL, but where does the payment success date come from? And also, if you could tell me how to send data like the order and user ID across that would be great too! Thanks.
You can not check if payment was successful via success form, it doesnt recieve any payment information. Instead you should use IPN It will contact your server in a secure way and inform you on payment event. You can periodically pull your server on IPN message recieved for client via AJAX, to show inform what payment was processed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, paypal" }
When one need to use archives.php page Why do I need this page in my wordpress theme? What url can cause wordpress to use archives.php? If I delete this page from my theme, what will happen? Thanks in advance for any specific reply.
Nothing will happen if your theme is properly structured. Basically all needed files in your theme are `style.css, functions.php and index.php`. You can do all your logic in index.php, but оne of the main advantages of WordPress is template hierarchy Template Hierarchy, part of which is `archive.php` WordPress searches down through the template hierarchy until it finds a matching template file. So you can catch this query at any point in this hierarchy and be more flexible in your theme. Another hierarchy useful resource
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "wordpress, archive" }
How to export variables from a file? I have a `tmp.txt` file containing variables to be exported, for example: a=123 b="hello world" c="one more variable" How can I export all these variables using the `export` command, so that they can later be used by child processes?
source tmp.txt export a b c ./child ... * * * Judging by your other question, you don't want to hardcode the variable names: source tmp.txt export $(cut -d= -f1 tmp.txt) test it: $ source tmp.txt $ echo "$a $b $c" 123 hello world one more variable $ perl -E 'say "@ENV{qw(a b c)}"' $ export $(cut -d= -f1 tmp.txt) $ perl -E 'say "@ENV{qw(a b c)}"' 123 hello world one more variable
stackexchange-unix
{ "answer_score": 127, "question_score": 191, "tags": "bash" }
How can I split this string? I have this string: a = "hy what are you doing [Zoho Reports] will you like? [Zoho Books] reply" and I want to split it so the result is like this: hy what are you doing [Zoho Reports] will you like? [Zoho Books] reply How can I loop that string to achieve those results? I'm currently doing this: a.split("") but it splits up `"[Zoho Reports]"` into `"[Zoho"` and `"Reports]"`, which I don't want.
Not very pretty, but gets the job done: a.scan(/(\S+)|(\[.+?\])/).map(&:compact).flatten Later I noticed that the groups I used were not necessary at all and without them the solution could be simplified to: a.scan(/\S+|\[.+?\]/)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "ruby" }
PHP array with MySQL data I have to send the list of all the users through JSON to javascript. The problem is that I don't know the function to store all the data in one variables. This is my code: $sql = "SELECT * FROM ___ WHERE __ = ___ "; $result = mysqli_query($conn, $sql); while( /* from here I don't know which function should be inserted */) $json = json_encode('something'); echo $json;
It looks like your code is vulnerable to SQL injection. I need to point it out that if you have variable input (which I assume you do in WHERE clause) you need to bind the input via prepared statements. $sql = "SELECT * FROM yourTable WHERE someColumn = ? "; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $someVariable); $stmt->execute(); $result = $stmt->get_result(); // Now fetch it into an array $arrayOfRows = $result->fetch_all(MYSQLI_ASSOC); // echo out JSON echo json_encode($arrayOfRows); There is no need for any loop, especially not `while` loop. Just fetch all the records into a multidimensional array.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -3, "tags": "php, mysql, arrays, json" }
How to show multiple columns from objects in a datagridview using BindingSource? I have an object that I would like to show in a datagridview. The object (a movement) has a name, a weight and then some Location objects. The Locations each have a name and a value. What I want to be able to do is for each movement to show the name, weight, location1.name, location1.value, location2.name, location2.value each in their own column of the DGV. I've managed to override the toString method for Location but that only gives me 1 column per Location, I really want to be able to have two. Is there any way to do this? I'm currently using a BindingSource like this BindingSource movementSource = new BindingSource(); movementsSource.DataSource = aircraft.movements; MovementDataGridView.DataSource = movementsSource; If it makes any difference movements is a `List<Movement>` Thanks!
What I do is create a wrapper class like this: class MovementView { private Movement movement; public MovementView(Movement m) { movement = m; } public string Name { get { return movement.Name; } } // etc.. public string Location1Name { get { return movement.Locations[0].Name; } } // etc.. } Then bind the grid to a `List<MovementView>` instead: movementsSource.DataSource = aircraft.movements .Select(t => new MovementView(t)) .ToList();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net, winforms" }
ASP.NET MVC TDD with LINQ and SQL database I am trying to start a new MVC project with tests and I thought the best way to go would have 2 databases. 1 for testing against and 1 for when I run the app and use it (also test really as it's not production yet). For the test database I was thinking of putting create table scripts and fill data scripts within the test setup method and then deleting all this in the tear down method. I am going to be using Linq to SQL though and I don't think that will allow me to do this? Will I have to just go the ADO route if I want to do it this way? Or should I just use a mock object and store data as an array or something?. Any tips on best practices? How did Jeff go about doing this for StackOveflow?
I checked out the link from tvanfosson and RikMigrations and after playing about with them I prefer the mocking datacontext method best. I realised I don't need to create tables and drop them all the time. After a little more research I found Stephen Walther's article < which to me seems easier and more reliable. So I am going with this implementation. Thanks for the help.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "sql, asp.net mvc, linq, tdd" }
Custom taxonomy as HTML class I have a custom taxonomy that needs a different colour applied to each term inside. I figured I could grab the slug of the taxonomy and put it in a class. Unfortunately I've been defeated with every try. I've tried a few things with get terms to no avail. Sample of what I'd like <div class="<?php echo $myCustomClass; ?>">the custom taxonomy</div>
First you would need to get the custom taxomomy and loop through every term applying the slug of the term as the class. <?php // get the tags from your custom taxonomy, in this case it's 'skills' $tags = get_terms('skills'); // print out the start of the list, putting an ID on it to make styling it easier echo '<ul id="taxonomy-list-skills">'; // loop through each tag as a list item foreach($tags as $tag) { echo '<li class="'.$tag->slug.'">'.$tag->name.'</li>'; } // close the list echo '</ul>'; ?>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wordpress, wordpress theming" }
JS/jQuery Accessing iframe elements cross domain (but the js file is the same domain) I have a page (different domain) with an external js file that lives on the same domain as an iframe that is also on the page... can this js file access contents in this iframe since they are sitting on the same domain? Or is that still not possible? Thanks!
It does not matter what domain the JS files are on, only the domain of the web pages / frames. Here's an MDN reference on the same-origin policy for more detailed info.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, iframe" }
jQuery selectors (select only target, without descendants) I want to bind an event only to "pages" in jQuery. The problem is that the code is executed not only for "pages", but for all descendants when `addClass` is used. I want to trigger the event only when `addClass` is used for "pages" divs. How can I do that? // (function( func ) { $.fn.addClass = function() { // replace the existing function on $.fn func.apply( this, arguments ); // invoke the original function this.trigger('eventAddClass'); // trigger the custom event return this; // retain jQuery chainability } })($.fn.addClass); // pass the original function as an argument $(document).on( "eventAddClass", 'div[data-role="page"]', function(event) { //code - do some stuff });
You can this. This is event bubbling. read this~ < $(document).on( "eventAddClass", 'div[data-role="page"]', function(event) { if(event.target !== event.currentTarget) return; // your custom code });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "jquery, jquery mobile, jquery selectors" }
Forcing macOS Sierra L2TP client to use specific interface I've got a WiFi (en0) and Ethernet (en8) connection on my machine. Each interface is on a separate network and en0 has priority over en8. The gateway for en0 is `192.168.100.1` and for en8 it is `172.20.10.1` There are services I need to access that are only available on the en0 network, and the VPN is only available via en2 network. I want to be able to force the macOS Sierra L2TP client to use en8. I have successfully added a static route to route the IP address that I want to connect to, to the gateway of en2 and have verified by running `trace get <vpn address>` However the connection still fails and when I look at the logs in `/var/ppp/ppp.log` it looks like the L2TP client is still trying to go through the en0 gateway: `Wed Mar 22 13:53:10 2017 : l2tp_get_router_address 192.168.100.1 from dict 1` Routing Table below: ![routing table](
Having two default gateways in macOS will result in: the gateway of the interface with the higher priority will be the default one and the other one is disregarded. To get the order enter in Terminal: `networksetup -listnetworkserviceorder`. So remove the default gateway of interface en8 and either add a custom route to the VPN server: sudo route add -host <VPN-server-ip-address> -interface en8 or sudo route add -host <VPN-server-ip-address> -link <MAC-of-en8> or to the network (here the example network: 10.0.0.0/16) sudo route -n add -net 10.0.0.0/16 172.20.10.1 * * * Depending on the network environment of the VPN-server a second inverted route pointing to your local 172.20.10.0/28 network has to be added there.
stackexchange-apple
{ "answer_score": 1, "question_score": 2, "tags": "network, macos, vpn" }
Event handling with WPF I just started learning WPF and C#. I'm trying to listen to global events on my WPF application. It has to run during the entire time the program is running. On a console application, I would run the logic in the Main() function. However, Main() is generated during compile time in a WPF application. Where do I put the event handlers in a WPF application?
Not sure what you mean by Global events in this context, but what I usually do is this : public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Loaded += MainWindow_Loaded; } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { //do stuff here } } This is the MainWindow.xaml.cs class that is generated in every WPF template in Visual Studio.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, wpf, event handling" }
ERROR H10 al desplegar una app nodejs en heroku hola estoy tratando de subir una app nodejs a heroku pero al desplegarla me sale el error H10, tengo el script Start en el package.json y el puerto bien app.set('port', process.env.PORT || 3000); app.listen(app.get('port'), () => { console.log('server start in port ' + app.get('port')); }); mi package.json "scripts": { "start": "node src/app.js", "nodemon": "nodemon src/app.js" }, ![Error en al consol](
Bueno me puse a investigar el log de heroku me di cuenta que estaba pidiendo un modulo de mi proyecto que no existia el cual es "../model/user", y el modulo correcto era "../model/User". No sabia que heroku se fijaba en las mayusculas pero bueno todos los dias se aprende algo nuevo.
stackexchange-es_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "nodejs, heroku" }
How do I use a block as an expression in ruby I essentially want to know what's the most idiomatic way to do this: @var ||= lambda { #some expression here to generate @var }.call
You can use a multi-line block to achieve this kind of memoization. @result ||= begin # The return value in here will be assigned to @result. end This syntax can be broken into two methods. def result @result ||= generate_result end def generate_result # Do the heavy lifting here end _Edit_ : These stackoverflow answers might help, too.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby" }
Recursion value default change I want to make sure 'rep' isn't made 0 at the beginning of each recursion. At the current point it is defaulted to starting at 0, but I want it to save the value of rep+=1. Is there an easy fix? def printPattern(n,k,rep =0): 'prints a pattern of stars' if n == k: print ('{}{}'.format(' '*rep,'*'*n)) elif n%2 == 0: rep+=1 print ('{}{}'.format(' '*rep,'*'*n)) printPattern(n+1,k) else: rep+=1 print ('{}*'.format(' '*rep)) printPattern(n+1,k)
You can start by actually passing rep in your recursive call printPattern(n+1,k, rep) def printPattern(n,k,rep =0): 'prints a pattern of stars' if n == k: print ('{}{}'.format(' '*rep,'*'*n)) elif n%2 == 0: rep+=1 print ('{}{}'.format(' '*rep,'*'*n)) printPattern(n+1,k, rep) else: rep+=1 print ('{}*'.format(' '*rep)) printPattern(n+1,k, rep)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, recursion, default" }
Looking for C# Google Safe Browsing LOOKUP API Client Is there any client or a way to use the existing google API client to consume the Google Safe Browsing Lookup API service?
I'm not aware of any pre-built API library for the Google Safe Browsing Lookup API service, but RestSharp (< would help you consume the API.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, rest" }
Check remote file size through fetched link in Ruby I was wondering if there was a way to check on the size of files you have a link to? I have extracted the path to an image (with mechanize) from a site and want to put a condition on it that turns true or false depending on the file size. page = Mechanize.new.get( image = page.search('//img[@id="img1"]/@src').text Now, what I want to do is checking for the file size of `image`. For a local file I could do something like `File.size` to get its size in bytes. Is there any way to check the size of `image`?
I think the Mechanize#head method will work: image_size = Mechanize.new.head( image_url )["content-length"].to_i HTTP `HEAD` requests are a lesser known cousin of HTTP `GET`, where the server is expected to respond with the same headers as if performing the GET request, but does not include the body. It is used often in web caching. More on HTTP HEAD Example taken from Mobile Phones/eBay (requested by Arup Rakshit) start_url = ' crawler = Mechanize.new page = crawler.get( start_url ).parser image_url = page.search('//img/@src').first.text image_size = crawler.head( image_url )["content-length"].to_i => 4244
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "ruby on rails, ruby, mechanize, ruby 2.0" }
Is there a tool like phpMyAdmin which can be configured to access just a single database? Is there a tool like phpMyAdmin which can be configured to access only a single MySQL database in a server? I cannot use phpMyAdmin because it allows access to all databases. A view that can allow a user to create/delete/insert/update tables should do. I remember using a software similar to this but dont remember what it was. It would also be great if its in PHP.
You can create a MySQL user with permissions to access only a single database, and then use that account to log into phpMyAdmin.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 2, "tags": "php, mysql, database, web applications, phpmyadmin" }
Adding an @ symbol before a string in C# Within a console application, several parameters are passed. One of which is a file path. This works fine, except when the path contains spaces. The workaround for having spaces within a file name is to have an `@` symbol before, such as `@"folder f/file.exe"` How can I add the `@` symbol to the `args[4]` parameter like so? boot = new Main(args[2], args[3], args[4], (args.Length == 5) ? "" : args[5], args[args.Length - 1].Equals("-r")); I have tried the following but it did not work for me. boot = new Main(args[2], args[3], @"" + args[4], (args.Length == 5) ? "" : args[5], args[args.Length - 1].Equals("-r"));
If you are passing agrument at runtime use quotes to "close" its value within: `C:\your_console_application "arg_1_value" "arg 2 value"` this will be exctracted inside appliaction as: args[0] -> arg_1_value args[1] -> arg 2 value
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, file, path, symbols" }
Comparing two strings using > (greater than sign) in Ruby? I came across a piece of code in a project I'm working on that looks kind of scary. It's supposed to be displaying a +/- delta between two numbers, but it's using a `>` to compare strings of numbers instead of numbers. I'm assuming that the code is working as expected at the moment, so I'm just trying to understand how Ruby is comparing these strings in this case. Here's an example with the variables replaced: if '55.59(100)' > '56.46(101)' delta = '+' else delta = '-' end
`String` includes the `Comparable` module, which defines `<`, `>`, `>=`, etc, based on the base class's compare (`<=>`) method. So if string a comes alphabetically prior to string b, `a <=> b` returns `-1`, and `<` returns `true`. The same `<=>` method is used for sorting strings, so you can imagine that in a sorted array of strings, each string is 'less than' its neighbor to the right.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "ruby, string, compare" }
Creative workaround for granting edit rights to individual jobs for a group? We have two developers that say they can not function without full rights to a few jobs on our database server. They both want rights to the same jobs. Given that it seems that MS doesn't seem to be budging on granting rights to windows groups, I was wondering if anyone had a creative workaround? I can't let them have the system wide agent roles. < I'm about to create a user and tell these two to log in to a shared account if they want to run/edit their jobs - but then there is no accountability. Anyone have a creative solution I have missed? Thanks :)
In the past to solve this I've created a web based app to allow users to change jobs. The app connected via a sysadmin login, but only allowed the user to edit/start/stop the jobs that they had access to via the app. Another option would be to go the single login route, but have auditing enabled for that login specifically and make sure that the auditing tracks the computer name as well as the login. That way if someone does something stupid you've got an audit trail and it'll tie back to their computer. Group's can't be used to own jobs as the job runs under the context of the job owner. There does need to be a better security model for jobs however.
stackexchange-dba
{ "answer_score": 3, "question_score": 4, "tags": "sql server, security, jobs" }
Android Test Automation tools I need a tool to automate testing of my android application. Specially I want to cover the test cases below: * send 10 sms * make a photo * make 10 calls It's even more like a script, which will allow me to record actions. Any hint?
You should take a look at Monkeyrunner I'm pretty sure it's exactly what you are looking for.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 5, "tags": "android, testing, automated tests" }
How to suppress the single quote character in an echo command? If I execute this command directly from CLI, I don't have any problem: ~ # apt autoremove 1>$- 2>$- ~ # But if I call it from a script I have some errors: Here is the script: #!/bin/bash -x NOVERBOSE='1>$- 2>$-' apt autoremove $(echo ${NOVERBOSE}) And here is the output: ~ # /bin/bash -x test2.sh + NOVERBOSE='1>$- 2>$-' ++ echo '1>$-' '2>$-' + apt autoremove '1>$-' '2>$-' Reading package lists ... Done Building the dependency tree Reading status information ... Done E: Unable to find package 1> $ E: Unable to find a package matching the regular expression "1> $" E: Unable to find package 2> $ E: Unable to find a package matching the regular expression "2> $" I don't understand why echo add some singles quotes around each part of the variable.
`NOVERBOSE` should be a flag that indicates the _desire_ to suppress output, not the syntax to do so. You then test the value and redirect output (or not) as appropriate. if [[ $NOVERBOSE = [Yy]* ]]; then # e.g., y, Y, yes, Yes, etc apt autoremove > /dev/null 2> /dev/null else apt autoremove fi If you don't like running `apt` "twice" like this, you can redirect to `/dev/stdout` and `/dev/stderr` explicitly as a no-op redirection. if [[ $NOVERBOSE = [Yy]* ]]; then out=/dev/null err=/dev/null else out=/dev/stdout err=/dev/stderr fi apt autoremove > "$out" 2> "$err"
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "bash" }
Do I need to manually roll back a transaction if not committing changes given some conditions? Example: Using transaction, and only committing if a given condition is satisfied. using (var transaction = context.Database.BeginTransaction()) // ... if (modelState.IsValid) { transaction.Commit(); } } does it need to be: using (var transaction = context.Database.BeginTransaction()) // ... if (modelState.IsValid) { transaction.Commit(); } else { transaction.Rollback(); } } or there is no need for the `else` part. What happens if I don't specify? Any good guidelines?
You don't need to call Rollback manually because you are using the using statement. It is not necessary to explicitly call `Rollback`. The transaction will be rolled-back if `Commit()` has not been called. `DbContextTransaction.Dispose` method will be called in the end of the using block. And it will automatically rollback the transaction if the transaction is not successfully committed
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, entity framework, transactions" }
R: group by a data set, with condition that all values in a particular column in the group match some requirement Got a data set like: A B a x a y b z b z c x c z Now I would like to group by A, with values in B in each group contains 'x' or 'y' only. e.g only 'c' would be chosen. Any simple function for this solution? Please help
We can select groups where `all` the values are either `"x"` or `"y"`. In base R, we can use `ave` with `subset` unique(subset(df, ave(B %in% c('x', 'y'), A, FUN = all), select = A)) # A #1 a #8 d Or with `dplyr` : library(dplyr) df %>% group_by(A) %>% filter(all(B %in% c('x', 'y'))) %>% distinct(A) **data** df <- data.frame(A = c('a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'), B = c('x', 'x', 'y', 'z', 'z', 'x', 'z', 'x', 'x'))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, group by" }
getElementbyID Search with "With block variable to set" error been racking my brain over the last few days without any success. I get the error "Object variable or With block variable not set", on the "If SignInButton > 0 Then" - how? Someone please explain. Thanks. Sub SearchElement Dim IE As Object Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True IE.navigate "appworld.blackberry.com/isvportal/home.do" Do While IE.readystate <> 4 DoEvents Loop Dim signInButton As Object Set signInButton = IE.document.getelementbyid("ssoLoginFrm_0") If signInButton > 0 Then signInButton.Click Else End Sub. I get "end if without block if"
You have an unterminated `else` clause on this line: If signInButton > 0 Then signInButton.Click Else ' Else what?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "vba, loops, search, getelementbyid" }
what is the time complexity of T(n)= 3T(n/2) + n^2? I tried using recursive tree method. and got a geometric series. That follows : kn^2(1+ (3/2) +(3/2)^2 +...+(3/2)^b) The sum = a(r^m -1)/r-1. b = log n. Then what to do I got confused.
Have you heard of the Master's Theorem)? Your example is a relatively simple subcase (no logarithms). The result is: T = Theta(n^2)
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -2, "tags": "recursion, time complexity" }
onload from external js file I'm writing a js script that people will add to their web site by adding a single line of code to the header or end of the body part of their HTML. My question is how to do the onload right on the external js file. Will the code below work? Can't it possibly run after the onload of the document and miss the onload event? function c_onload () { alert ('onload'); } if (window.attachEvent) {window.attachEvent('onload', c_onload);} else if (window.addEventListener) {window.addEventListener('load', c_onload, false);} else {document.addEventListener('load', c_onload, false);} (I can't use Jquery or any other library)
I am afraid that if you can't use jQuery or some other library you need to reproduce a way good deal of their functionality. The reason is that browsers handle the onLoad event differently. I recommend that you download jQuery's code and see how the documentready function is implemented.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, onload" }
Cleaning a MacBook Pro keyboard that's been covered in juice My lovely son spilled apple juice on my laptop keyboard. It works, but it feels like it has grit under the keys and sticks a bit. How do I clean it out? I remember old keyboards could be just banged hard against the desk... I presume thats a bad idea though... It's a macbook pro 15 inch laptop
You can actually remove the keys, clean them and then replace them again. Follow this link to see how it's done: < The problem with liquid damage is that although the laptop may work fine now, if the juice has got onto the Logic Board, it can cause corrosion over time, which will more than likely cause issues. However, I do hope this is not the case! Good luck!
stackexchange-apple
{ "answer_score": 4, "question_score": 5, "tags": "macbook pro, macos" }
Checked Checkbox should be not uncheckable I have some difficulty settings in a game. Because only one option should be active at once i did e.g. for option 'Easy' //Uncheck all other difficulty options if(ui->actionMedium->isChecked()) { ui->actionMedium->setChecked(false); } if(ui->actionHard->isChecked()) { ui->actionHard->setChecked(false); } Now the problem is that if i click on an already checked checkbox the checkbox will uncheck. Ok, thats the normal behaviour of a checkbox, so i added //check if its alreay checked if(ui->actionEasy->isChecked()) { ui->actionEasy->setChecked(true); } but this doent work and i dont understand why. As alternativ i could group radiobuttons, but i would like to unterstand why my code doent work.
If you uncheck the checkbox actionEasy `ui->actionEasy->isChecked() == false` and so your code doesn't check this checkbox.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, qt, qt5" }
Differentiating under the integral sign and $C^1$ class Suppose that $f\in C^1(\mathbb{R}^n; \mathbb{R})$ and $g(x)=\int_{0}^{1}f(x+ty)dt$, where $y \in \mathbb{R}^n$. How to rigorously show that the function $g(x)$ is continuously differentiable? Since the function $f(x+ty)$ is continuously differentiable for both $x \in \mathbb{R}^n$ and $t \in ]0,1[$ that result seems very reasonable, but I don't know what is the true mathematical reason behind that result.
$$\frac{g(x+h)-g(x)}{h}=\int_0^1\frac{f(x+h,ty)-f(x,ty)}{h}\,dt \to\int_0^1\frac{\partial f(x,ty)}{\partial x}\,dt$$as $h\to0$, because $f\in C^1$ implies the integrand converges uniformly. Similarly, since $\partial f/\partial x$ is continuous and hence uniformly continuous on compact sets, uniform convergence now shows that $g'$ is continuous. **Edit:** I've had a request for a reference. In lieu of that, a proof of what's probably the least obvious of the facts used above: > > If $f\in C^1(\mathbb R)$ then $(f(x+h)-f(x))/h\to f'(x)$ uniformly on compact subsets of $\mathbb R$. Proof: Consider $K=[a,b]$. Let $\epsilon>0$. Since $f'$ is continuous on $[a-1,b+1]$ it is uniformly continous there; choose $\delta\in(0,1)$ that "witnesses" this uniform continuity. Now if $x\in[a,b]$ and $0<|h|<\delta$ then MVT shows that $$\left|\frac{f(x+h)-f(x)}{h}-f'(x)\right|=|f'(\xi)-f'(x)|,$$where $|\xi-x|<\delta$. Hence $\xi\in[a-1,b+1]$ and so $|f'(\xi)-f'(x)|<\epsilon$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "calculus, real analysis, analysis, multivariable calculus" }
Mongoose schema. Statics is not a function Why is this code works fine: schema.statics.findByName = function (name) { return this.findOne({ username: name }); }; But when I try this one schema.statics.findByName = (name) => { return this.findOne({ username: name }); }; I get `TypeError: this.findOne is not a function` error when call `User.findByName(username)`
Well, this issue is not related to mongoDB and mongoose. For this, first we need to understand the difference between normal function and arrow functions in JavaScript. The handling of "this" is different in arrow functions compared to regular functions. In short, with arrow functions there are no binding of this. In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions, the this keyword always represents the object that defined the arrow function. They do not have their own this. let user = { name: "Stackoverflow", myArrowFunc:() => { console.log("hello " + this.name); // no 'this' binding here }, myNormalFunc(){ console.log("Welcome to " + this.name); // 'this' binding works here } }; user.myArrowFunc(); // Hello undefined user.myNormalFunc(); // Welcome to Stackoverflow
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, node.js, mongoose" }
UglifyJs unexpected token error I have already used this in my webpack.config.js use: [{ loader: 'babel-loader', options: { presets: ['es2015', 'es2016', 'react'] } }] But still I am getting error at the token **let** which I have used. > I get that uglify doesn't understands ECMAScript-6 Now when i build my webpack with -p, i get the mentioned error, because uglify comes up there. Now, how can i solve this problem as I have already included babel-loader preset es2015 to convert es6 to es5.
As you've said, your current version of the Uglify plugin doesn't support ES6, so you'll need to upgrade. You have a few options: 1. Upgrade to Webpack 4, which includes the new uglify plugin by default 2. If you need to stay on v3 for whatever reason, you can follow the instructions on the docs here to install the new uglify plugin and use it manually.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, reactjs, webpack, ecmascript 6, uglifyjs" }
Error Error trying to diff '[object Object]'. Only arrays and iterables are allowed project.component.ts ngOnInit() { this.pro.getAll().subscribe( respose => { console.log(respose); this.projects = respose; }, () => console.log('error') ); } projectservice.ts getAll():Observable<Project[]>{ return this.http.get<Project[]>(this.link); } project.component.html <ul *ngFor="let p of projects"> <li>{{p.name}}</li> </ul> by console ERROR Error: "Error trying to diff '[object Object]'. Only arrays and iterables are allowed" Angular 7 View_ProjectComponent_0 ProjectComponent.html:47 Angular 23 RxJS 5 Angular 9
can you show what is in the projects variable after the response? Also, if your HTML is using it since the page starts, make sure the var is initialised as [] and not as NULL.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "angular, typescript" }
Pycurl PUT request to JIRA REST API waiting on 100 continue I am trying to change the assignee in JIRA using pycurl. My code is waiting on ****HTTP/1.1 100 Continue****. What am I doing wrong? Thanks for your help. I have attached a snippet of my code below. Also I do not want to use the JIRA Python Library. def assign(self, key, name): data = json.dumps({"fields":{"assignee":{"name":name}}}) c= pycurl.Curl() c.setopt(pycurl.VERBOSE, 1) c.setopt(pycurl.URL, " key ) c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']) c.setopt(pycurl.USERPWD, "****") c.setopt(pycurl.PUT, 1) c.setopt(pycurl.POSTFIELDS,data) c.perform()
Got the code working. def assign(self, key, name): self._startCurl() self.c.setopt(pycurl.URL, " key ) self.c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json']) self.c.setopt(pycurl.USERPWD, "fred:fred") self.c.setopt(pycurl.CUSTOMREQUEST, "PUT") data = json.dumps({"fields":{"assignee":{"name":name}}}) self.c.setopt(pycurl.POSTFIELDS,data) self.c.perform() self.c.close()
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "python, put, pycurl" }
How to check if a NSProgressIndicator is currently animated? `NSProgressIndicator` has methods called `startAnimation:` and `stopAnimation:`, but no method that I can find to check the state (whether it is currently animating or not). How would you do it?
You could just keep a `BOOL` value somewhere in your class that you set to `YES` or `NO` when you start and stop the animation respectively.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 6, "tags": "objective c, cocoa, macos, nsprogressindicator" }
ASP.NET MVC 2 Drop Down List In Place of Master List Grid Instead of a grid with an 'Edit' link in each row, I'd like to use a drop down list and a single 'Edit' button. What's the cleanest way to make that button direct to /Edit/{id}(i.e. the ddl selected value)? Using onclick with window.location is way too ugly, super ugly if I have to account for the url base being < or < since it's on the Index view.
You can use any kind of form presentation, you just have to make sure the name of the value you're submitting matches the type and name what the controller is expecting. For example on the page: <select id="userList" name="userList"> <option value=1>My Name</option> <option value=2>Your Name</option> </select> and then the controller that the form is talking to should look something like: public ActionResult Edit(int userList){...... then whatever option was selected will pass its value to the controller, as long as the names match and the form's action is the correct controller action
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "asp.net mvc, c# 3.0" }
Adafruit motor hat python3 Iv written a script that uses the adafruit motor hat library to control motors when it recives 433MHz ex transmitted codes! Very short range at the moment however this is the best way for my project! The problem is the 433MHz rx/tx library is python3 and won't work on python2 And the adafruit_motor_hat_library is pyrhon2 and wont work on pyrhon3? As I need both of these to work in the same scrip how can I go about this? Also if I try and run from command line it won't work, (if I python3.scrip.py it brings up error with adafruit motor hat, if I python.script.py it brings up error on 433MHz? If anybody needs my full scrip I can copy and past it here but as the problem doesn't seem to be with the actual scrip it seemed pretty pointless! But if you need it I can provide it
To save time, I would convert the **smaller of the two libraries** you mention to the other version. If they're about the same size, I'd convert the 2.x library to 3. The motor hat library is only ~350 lines of code, much of which will not change in conversion to 3.x. Would be a good self-teaching exercise...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python, python 2.7, python 3.x" }
What does "I can get behind that :)" mean when you suggest someone to compromise on an alternative option? "How about we compromise and ... ? ;)" Answer: "I can get behind that :)"
To get behind something is to support it. It is a metaphor that comes from the notion of being physically behind something in order to prop it up. It doesn't specifically need to refer to a compromise. You can get behind any idea that is proposed. > He found an investor who was willing to get behind his startup company. See also the related terms backup (n) or back up(v). > I can back up that idea. > I can back that up with sources. > He provided the needed backup for the plan.
stackexchange-english
{ "answer_score": 9, "question_score": 5, "tags": "idioms, idiomatic" }
UISlider error : Property 'value' not found on object of type '__strong id' .h file: @property (strong, nonatomic) IBOutlet UISlider *sliderr; @property (strong, nonatomic) IBOutlet UILabel *lbl2; .m file: - (IBAction)slidersact:(id)sender { self.lbl2.text = [NSString stringWithFormat:@"%.0f", sender.value]; [error with ^^] } - (void)viewDidLoad { [super viewDidLoad]; self.sliderr.minimumValue = 0.0f; self.sliderr.maximumValue = 100.0f; self.lbl2.text = @"0"; } Error: > Property 'value' not found on object of type '__strong id'
id is any object , you need to identify your object using your control name as like `- (IBAction)slidersact:(UISlider *)sender` instead of `- (IBAction)slidersact:(id)sender` - (IBAction)slidersact:(UISlider *)sender { self.lbl2.text = [NSString stringWithFormat:@"%.0f", sender.value]; }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, objective c, uislider" }
Kettle PDI Concat column values I have a PDI (Kettle) **transformation** that execute an SQL script, the output of scripts is a column looks like: > val1 > > val2 > > val3 > > val4 > > "more values"... I need write this on a only one Excel cell like this: > val1 val2 val3 val4 "more values"... How i can do this? I tried "row denormaliser" and "row flattener" but dont work (i dont know why)
The flattener is an option, but you have problems because you do not know the number of new fields and the seperator. But there is a "trick" to solve your problem: You can do so by following these steps: 1. Add a constant after your input, name: test, type: string, value: a 2. Group by the new field test, aggregate your field with the values with "Concatenate strings separated by" and set a space as seperator. The output is: val1 val2 val3 ....
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "concatenation, kettle" }
Mac Terminal opt + left/right key doesn't skip words, gives [D or [C I have read How to skip words in OS X terminal? and while `esc`+`b` and `f` work, `option` `->` and `<-` will output these annoying [D and [C I have `Use Option as Meta key` ticked and `⌥←` is set to \033b and \033f for right arrow. On macOS Sierra, this always used to work, but seems shortly after upgrading to Sierra that this has happened, not sure if it's related though, as my other computer also on Sierra works fine.
Nevermind, just noticed that I still was on the public beta group, and there was another update to 10.12.1 beta, and after installing this update my issue was fixed.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "macos, keyboard shortcuts, terminal" }
std::vector.data(): использование в ifstream Как использовать vector.data() в ifstream? std::ifstream file(fileAdrress, std::ios::in | std::ios::binary); std::vector<unsigned char> block; Так? file.read(reinterpret_cast<char*>(block.data()), allocateSize); Или как?
Все правильно, но есть тонкости: std::ifstream file(fileAdrress, std::ios::in | std::ios::binary); std::vector<unsigned char> block; block.resize(allocateSize); // Важно! data() не аллоцирует память. file.read(reinterpret_cast<char*>(block.data()), allocateSize ); if(!file) // EOF! прочитали только часть блока. block.resize( file.gcount() ); Если смущает cast, то, смените хранимый в vector тип: std::vector<char> block; ... file.read( block.data(), block.size() ); ...
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, vector, c++14, ifstream" }
Difference between получится and удаётся My question is about two ways of saying "manage to do": > у меня получится and > мне удаётся Can anyone clarify what's the difference between these two? Thank you!
The version _у меня получается_ ( _получится_ in future tense) is typically about **ability** and **skills** (sometimes, about a _sсheduled opportunity_ ) while _мне удаётся_ is more about **effort** and **luck** in getting a desired result. > У меня получается превосходная уха. > > Я раньше не делала этот салат, но у меня явно получается. > > Пытаюсь сделать стойку на голове, но у меня не получается. > > У меня не получится приехать на Рождество из-за контрактных обязательств. > > Мне не удалось с первого раза поступить в университет. > > Иногда мне удаётся поймать крупного лосося (или выбить 50 очков при стрельбе и т. п.). > > При всём его коварстве, ему не удалось нас перехитрить.
stackexchange-russian
{ "answer_score": 4, "question_score": 1, "tags": "выбор слова" }
How can i remove a js file from all browsers others than IE7 How can I remove a javascript file using javascript when the page loads, only let the script run for IE7. The script should not run on chrome, opera, firefox . Thanks in advance.
You can use a **conditional comment** : <!--[if IE 7]> <script src="your/javascript/ie7only/file.js"></script> <![endif]--> You can place this code anywhere where the ordinary `<script>` tag would go, and only IE7 will process it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript" }
Rspec showing wrong version number I'm running a Rails 2.3.4 app under ruby 1.8.7 and rvm with a custom gemset. In trying to get rspec up and running, I've tried several times to uninstall rspec 2 and install rspec and rspec-rails version 1.3.4. However, when I run `rspec -v` I get 2.10.0 regardless of what I do. Finally I got this error message: You are running rspec-2, but it seems as though rspec-1 has been loaded as well. This is likely due to a statement like this somewhere in the specs: require 'spec' Please locate that statement, remove it, and try again. So it looks like 2.10.0 is actually still loaded. Even if I do a `gem uninstall rspec` rspec is still loaded. What's going on?
You should use `spec` (the RSpec 1 executable) instead of `rspec`, as explained in this answer.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby on rails, ruby, rspec" }
Floating point arithemtics bigger or equal I would like to know, if floating point numbers in c# can give incorrect results regarding to bigger or equal. static bool foo() { Random r = new Random(); int i = r.Next(int.MinValue, int.MaxValue), j = r.Next(int.MinValue, int.MaxValue), k = r.Next(int.MinValue, int.MaxValue), l = r.Next(int.MinValue, int.MaxValue); BigInteger b1 = new BigInteger(i) * j, b2 = new BigInteger(k) * l; double d1 = (double)i * j, d2 = (double)k * l; return (b1 >= b2 && d1 >= d2) || (b1 <= b2 && d1 <= d2); } More specifically, Can `foo` ever return false?
I want to rephrase your question. Assume **a** and **b** as two integer which **a >= b**. and **da** is double representation of **a** and **db** is double representation of **b**. Is it possible that **da < db**? The answer is no. if **da < db** then **db** is a double representation of **a** with lower error than **da** which is not possible due to IEEE-754 standard. So the answer to your question is also **NO** and `foo` always returns true.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, floating point, precision, biginteger, floating accuracy" }
Render a file in a specific view mode Which is the right way to render a file in a custom view mode? I'm using Media, 7.2 branch, I've custom view modes and I want to print in a tpl a file (based on fid) in the view mode "header_image".
You'll want to use the file_view_file() function provided by the File entity module. The function has three parameters: a file object, the name of a view mode (or an array of custom display settings) and optionally a language code. If you only have a file ID then you can do a file_load on the ID to get a full file object to pass to the function. Note that file_view_file() returns a array as expected by drupal_render() so, depending on how you are incorporating the file into your template, you may have to render the returned array using render().
stackexchange-drupal
{ "answer_score": 4, "question_score": 0, "tags": "7, files, media" }
Bash Scripting: terminal and multiple other actions Let's say I'm accessing the terminal and performing an ssh command from a bash script. I'd also like to, after I've opened the ssh, perform a few more things like: 1. cd /srv/django 2. python manage.py shell 3. execfile 'home/usr/myscript.py' My script file so far: #!/bin/bash ssh server "python /srv/django/manage.py shell" execfile 'home/usr/myscript.py' How could I go about performing this through the script?
`ssh` accepts a command for the remote system at the end of its command line, for example: xterm -e ssh servercomp cd /srv/django \; python manage.py shell
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bash, python 2.7, terminal, server, ubuntu 14.04" }
Update Subquery Question, with foreign key I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it. Part of my schema: Products Table: ProductName (key) TemplateName TemplateID ... I've added TemplateID, but it has no data in it yet and is nullable. Templates Table: TemplateID (key) TemplateName ... I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table. Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008
You can do it with a simple UPDATE query UPDATE Products SET Products.TemplateID = Templates.TemplateID FROM Templates WHERE Templates.TemplateName = Products.TemplateName You do not need to specify the Products table in the FROM clause, nor a JOIN clause. Just specify the Templates table in the FROM clause. You can use the tablename you use in the UPDATE clause in the WHERE clause, to correlate recordds from both tables.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, stored procedures, foreign keys, subquery" }
where to check out the screen detached command line application crash log on Ubuntu So, I was running some application with the following command line after SSHing into my server, and after then detached the window by ctrl+a ctrl+d: SCREEN /bin/bash -c php index.php -whatever > /logs/inst1_20151020.log Then I encountered some system disfunction complaint, so I SSHed into the server, and found my command line application exited abnormally by using the following command line: ps -aux | grep php So, I'd checked the /var/log/ folder, and didn't find any useful information anywhere. I was trying to figure out what is the cause for this abnormal crash, where can I find the crash log? Here is my detailed web server information: lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 14.04.2 LTS Release: 14.04 Codename: trusty
There is some missing detail: there is no `SCREEN` executable as such. The executable is lowercase `screen` (though it forks and names one process `"SCREEN"`). But assuming that the command was meant as screen /bin/bash -c php index.php -whatever > /logs/inst1_20151020.log then the log-file would be in the directory `/logs`, and contain only the output from _starting_ the bash command (since the `>` operator is run _before_ running bash). More likely than not, _that_ file is empty.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "linux, ubuntu, command line, crash, gnu screen" }
Find indices of vector elements in a list I have this toy character vector: a = c("a","b","c","d","e","d,e","f") in which some elements are concatenated with a comma (e.g. "d,e") and a list that contains the unique elements of that vector, where in case of comma concatenated elements I do not keep their individual components. So this is the list: l = list("a","b","c","d,e","f") I am looking for an efficient way to obtain the indices of the elements of `a` in the `l` list. For elements of `a` that are represented by the comma concatenated elements in `l` it should return the indices of the these comma concatenated elements in `l`. So the output of this function would be: c(1,2,3,4,4,4,5) As you can see it returns index 4 for `a` elements: "d", "e", and "d,e"
You could use a strategy with factors. First, find the index for each element in your list with l <- list("a","b","c","d,e","f") idxtr <- Map(function(x) unique(c(x, strsplit(x, ",")[[1]])), unlist(l)) This build a list for each item in `l` along with all possible matches for each element. Then we take the vector `a` and create a factor with those levels, and then reassign based on the list we just build a <- c("a","b","c","d","e","d,e","f") a <- factor(a, levels=unlist(idxtr)); levels(a) <- idxtr as.numeric(a) # [1] 1 2 3 4 4 4 5 finally, to get the index, we use as.numeric on the factor
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "r, list, vector" }
Change date to Universal Time Format changes my date wrongly I can't get error I am trying to simply change the date format from the datatable to universal time format but it formats it wrongly as if I have date for August 7 it changed it to August 8 after formatting it to universal date time. My code for formatting date is, DateVar[runs] = DateTime.Parse(Convert.ToString(output.Tables[0].Rows[runs][0])).ToUniversalTime().ToString(); Don't get in to code its correct and its a part of loop so "run" is loop and output is data set having one table I have first data in table is "Sunday, August 07, 2011 10:52 PM" and it was converted to "8/8/2011 5:52:00 AM" after implementing universal time format. Hopes for your suggestions
If I run `ToUniversalTime()` from `Greenwich` it will give same time but if i do it while I live some where else it will get an offset date time object of `+ or - hours` depending on position.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c#, asp.net, time, format" }
How to get the number of element in a root json elment I'm trying to get the number of elements in each node of a Json. For example in this case: { "tickets": { "use": "Valida", "useagain": "Valida di nuovo", "usetitle": "Convalida biglietto", "price": "Prezzo" }, "fares": { "nofarestopurchase": "Non è possibile acquistare biglietti per la tratta indicata", "purchasedcongratulations": "Congratulazioni", "farepurchased": "Hai acquistato il tuo biglietto. Lo puoi trovare nella sezione", "mytickets": "I miei biglietti", "fareguestcard": "Hai ottenuto il tuo biglietto. Lo puoi trovare nella sezione" }, "quantity": { "title": "Seleziona il numero di persone:" } } > Ticket contains 4 voices, it contains 4 fares and quantity 1. How do I get in a dynamic way the nodes and the number of elements inside them in javascript?
You can use `Object.keys()` on an object to get an array of its keys; then, use the array's `length` property to find the number of keys in the array. So, if your JSON structure is `yourJSON`, you can do: var ticketsNum = Object.keys(yourJSON.tickets).length; // 4 var faresNum = Object.keys(yourJSON.fares).length; // 4 var quantityNum = Object.keys(yourJSON.quantity).length; // 1 For nested data, like you have here, you could easily write a function that will count the key/value pairs of each of the "top-level" keys: function countKeys (obj) { var count = {}; Object.keys(obj).forEach(function (key) { count[key] = Object.keys(obj[key]).length; }); return count; } var nums = countKeys(yourJSON); // nums = { tickets: 4, fares: 4, quantity: 1 }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, json" }
Can every two points be connected by a simple curve? Let $X$ be a path-connected subset of $\mathbb{R}^2$. For $x,y\in X$, $x\neq y$, does there necessarily exist a simple curve connecting $x,y$? In other words, is there an injective continuous map $\gamma:[0,1]\to X$ such that $\gamma(0)=x$, $\gamma(1)=y$? I could neither prove this nor find any counterexample. It is easy when $\gamma$ has finitely many self-intersections. But is there any result for the general case?
Wikipedia has the answer if you connect the dots. You are asking whether a subset of $\mathbb{R}^2$ that is path-connected is als arc-connected. If you use the induced topology from $\mathbb{R}^2$ any subspace will be Hausdorff and for Hausdorff spaces path-connected and arc-connected are equivalent. So the answer is yes.
stackexchange-math
{ "answer_score": 5, "question_score": 6, "tags": "general topology" }
non convex optimization Hi there, In my studies I come up with this nonconvex optimization problem argmin |Ax|_2+lamda*|x|_1 subject to x'x=1 where cost function is nonsmooth but convex and the constrant in nonconvex. I tries subgradient projection method for convex constraints but the global solution is not my desired solution. My question is that I should solve this problem hurestically or there is a reliable method for this nonconvex optimization problem?
You can have a look of these papers 1\. Jonathan H. Manton, Optimization algorithms exploiting unitary constraints. 2\. Zaiwen Zai and Wotao Yin, A feasible method for optimization with orthogonality constraints. Wish these studies can help you.
stackexchange-mathoverflow_net_7z
{ "answer_score": 1, "question_score": 1, "tags": "convexity, global optimization" }
How to pass arguments to add_action() I declared an action for a single event in Wordpress which accepts an array as an argument: $asins = array(); //I had to declare this since I'm getting a notice of undefined variable if I don't add_action('z_purge_products_cache', array($this, 'purge_products_cache', $asins)); I also tried this one, but it doesn't perform the action either: add_action('z_purge_products_cache', array($this, 'purge_products_cache')); Then I schedule it: wp_schedule_single_event(time() + 20, 'z_purge_products_cache', $asins_r); Then here's the function that will be called once wp cron executes the action: public function purge_products_cache($asins){ //send email here } Any ideas?
The parameter needs to be passed to the callback function in the wp_schedule_single_event function, not the add_action function. Try this: add_action('z_purge_products_cache', array($this, 'purge_products_cache')); Then schedule the event, putting the parameter in an array: wp_schedule_single_event(time() + 20, 'z_purge_products_cache', array($asins_r)); Your `purge_products_cache` function will be called with parameter `$asins_r`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "hooks, actions" }
Does banning from answers in one Stack Exchange community affect all the other Stack Exchange communities? I started using Stack Exchange not long ago. Does banning from answers in one Stack Exchange community affect all the other Stack Exchange communities?
No, it does not. Reputation, flag, review and quality bans are per site. So if you're quality banned on Stack Overflow you might still be able to post on other sites with different topics: Your cooking concerns can go on Seasoned Advice, your dual boot concerns Super User, to name a few. Your practical programming concerns need to stay at bay. Don't make it a habit to hit the bans on all sites you participate in. The bans are there to prevent that content with a similar or lower quality level enter the system. Ignoring the warnings from the system that posts need to be improved can lead to account suspension and if there is nothing worth keeping, even account deletion is an option.
stackexchange-meta_stackoverflow
{ "answer_score": 11, "question_score": 4, "tags": "support, post ban" }
If $p$ is a prime number in $Z$, how do you show $\langle p^n \rangle$ is a primary ideal in $Z$ Suppose $ab \in \langle p^n \rangle = I$. How do you show either $a \in I$ or $b^m\in I$. It has been some time since I've studied this and would appreciate if someone can help me recall how the usual argument goes. Edit: I think you have to write $I = \langle p \rangle ^n$. Then use that fact that a prime ideal is primary.
The statement $ab\in \langle p^n\rangle$ means that $p^n$ divides $ab$. So $p|ab$. So if $p \nmid a$, then $p$ must divide $b$, i.e. $b^n \in \langle p^n\rangle$. So $\langle p^n\rangle$ is primary!
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "ring theory" }
Why would i install bower with NPM? I'm failing to understand something, I've started learning AngularJS, and there is a option to install it trough bower. Then i went and read what is this bower thingy, and **it** said that this is a package manager. But the installation of bower (in the tutorial at least) is trough NPM, which is node's package manager. So... Why would a package manager that is installed with node will be used to install AngularJS? unless i want to use both of them - what's the point?
npm is much more well suited for server side javascript package management. Bower is written specifically to serve the brower's javascript package management needs. For example, npm allows for nested js and nested versions, bower makes the entire dependency tree into flat siblings. That said bower is powered by nodejs, so it makes sense that npm would be the method for getting access to bower. The idea is that you use both.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "angularjs, npm, bower" }
Using multiple links style on the same label Is it possible to use different links style on the same label using TTTAtributedLabel? For example for: "one two" I do want "one" to be link with underline and blue color and "two" to be a link with color green and no underline.
Simply set the attributes for text at the ranges of those links.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios" }
Is there a shorter way to access a property in an array? `$jj_post` is the array output debug via `print_r()`. This variable is an array of objects: Array ( [0] => stdClass Object ( [ID] => 2571 ) ) I access the object property, ID, via code like this: $jj_post_id = $jj_post[0]; $jj_ID = $jj_post_id->ID; So, is there a shorter way, cause this is the only thing I know and I feel the code little bit too long?
Well if you are sure $jj_post is always going to be an array, and that it will always contain an stdClass object, then you should access like so: $jj_ID = $jj_post[0]->ID; But it is not always so sometimes. You may not always know the contents of a variable so you need to do some checking to verify that you access areas that are safe and available. How long the code is shouldn't be an issue if it performs the job well. In my opinion, you have two alternatives: $jj_ID = @$jj_post[0]->ID; This ensures that the runtime errors are silently handled, and not thrown to the standard output. Another way would be to check absolutely for presence of each type: $jj_ID = ""; if(is_array($jj_post)) { $jj_post_id = $jj_post[0]; if(!empty($jj_post_id)) { $jj_ID = $jj_post_id->ID; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, arrays, object" }
Where did my reviews go? Just a while ago, I was reviewing posts of new users and answers, I previously reviewed 100 posts, now i reviewed 3 posts and SO was showing I reviewed only 9 posts, then after few minutes it jumped back to hundred, now i review one post more and total reviews are 101. My question is where did those 3 reviews go?
There are six different review queues, each with a separate review counter per reviewer. You have mostly been reviewing in the "First Posts" queue (~100 reviews), but you have also done a few reviews in the "Late Answers" queue.
stackexchange-meta_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "bug" }
Remove dot and parentheses from the URL in rewrite rule I have the a rewrite rule where I am trying to remove any dots and parentheses from the URL and I managed to get get to the point where I can do one or the other but just can't seem to combine both. How would I write the rule so that if any url has a dot or parentheses, they get removed? Thanks. RewriteEngine On RewriteCond %{REQUEST_URI} [\(\)\.]+ RewriteRule ^(.*)[\(]+([^\)]*)[\)]+(.*)$ /$1$2$3 [L,R=301]
Try: RewriteRule ^(.*)().$ /$1$2 [E=DOT:Y,DPI] RewriteCond %{ENV:DOT} Y RewriteRule ^([^().]+)$ /$1 [L,R=301] This uses an environment variable as a way to know when to redirect. Any number of parentheses and dots will get removed and when they're all done, the URL gets redirected.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "regex, apache, .htaccess, mod rewrite" }
Need advice: Sending information from web Server to Windows Phone 7 In my app I have a news section, and I want to update the news on a website and then be updated on the phone. As I have not much information around this, I am asking what are my options in making a communication path from the web server to the WP7? What are the types of tools I can use to make this? Note: I am prefairing to use ASP.NET as I have experience with it. What else do I need also? Thanks,
What you're looking for is Push Notifications. Your ASP.NET application can send a push notification to the phone (via Microsoft's service), and your phone application can react by going and getting the updated news. There are some good tutorial links in the answers to this SO question: How to start with Windows Phone 7 Push Notification
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "asp.net, web services, web applications, windows phone 7" }
Create unique order number in sequence in java? I need to generate a unique order number in sequence for each request. I need to make sure even after JVM restart it should be unique(i mean it should not match to any number before JVM crash) Best I could think of using database sequence which will give me a unique number in sequence. Is there any alternative to database sequence in java?
The only way to guarantee uniqueness is to persist the state of the "unique number generator" so that even if you restart the JVM or if you start more than one JVM, a previously used number won't be picked. The easiest way is to delegate the unqieu number generation to a database. Alternatively you could generate the numbers sequentially and store the last number in a file (but due to potential data race you need to properly lock the file). If occasional (but low probability) collision is ok you can use UUID (UUIDs typically use timestamps so it is possible that the same ID be picked twice if two JVMs don't have their clocks synchronized).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java" }
Вывод нужного фрагмента в зависимости от введенных пользователем данных Есть EditText, в которое мы должны ввести число, а после, в зависимости от числа, мы должны вывести тот или иной фрагмнет. Но как это сделать я не знаю, никогда с этим не сталкивался. Еще должна идти проверка, которая исключает возможность ввода букв. Надеюсь, кто знает как это реализовать.
получаете число и дальше с помощью операторов условного перехода `switch-case` либо `if` вставляете нужный фрагмент . Насчет валидации ввода , можно использовать только числовую клавиатуру , задав ее в свойствах `EditText` , но это не защит от всех ошибок ввода , например , пользователь может ввести не целое число , лучшим будет валидатор на основе regexp
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java, android" }
Design / Implementation Patterns for Embedded Systems **Are there any good sources on design and/or implementation patterns for embedded systems out there?** Books or good web-resources. Topic could be: * Reflections on the typical way to separate register addresses from driver implementation. * Or the practice of using/building a Hardware Abstraction Layer, and how to do achieve the most benefit from that. * Building the same code base for multiple hardware revisions/platforms. * Prioritising ISRs and separating them into a time-critical part and a to be performed when time allows part. * Unit testing or even test driven development for embedded systems? I guess what I am asking for is something along the lines of GoF, but focused specifically on embedded software development. Thanks
I haven't read it yet, but Bruce Powel Douglass has a new book titled "Design Patterns for Embedded Systems in C". A description of the book states: > The author carefully takes into account the special concerns found in designing and developing embedded applications specifically concurrency, communication, speed, and memory usage. Looks like topics also include hardware access, state machines, debouncing, and resource management.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "design patterns, tdd, embedded" }
HR tag renders white pixel In IE8 and mozilla 3.5 theres an white pixel to the right. How can i get rid of that? Seting background-color changes nothing. neither does width. hr { border-top: 1px solid #111; border-bottom: 1px solid #444; } This is how it looks right now !enter image description here
Adding this to the CSS fixes it (I also noticed a white pixel on the left side, though smaller than the right): border-left: 0; border-right: 0;
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "html, css" }
No doctype in an include with html/php I have a PHP include that contains both HTML and PHP code and is included on another page that already has the `<!doctype html>` tag. The HTML validator (w3.org) tells me it has an error when validating the include, because my include file doesn't contain this tag, but since the include is used on pages where doctype is declared, is it really necessary to declare it in the include? Example: include.php <div> <p> Hello <?php echo "world!"; ?></p> </div> * * * index.php <!doctype html> <html> <head></head> <body> <?php include ("include.php"); ?> </body> </html> > Error: The document type could not be determined, because the document had no correct DOCTYPE declaration. (include.php)
Your problem is that you are trying to validate `include.php` as if it was an HTML document. It isn't, it is a fragment of HTML (and shouldn't have a Doctype declaration of its own). If you want to validate it it independently of the pages that include it, create a minimal wrapper HTML document and include it in that, then validate the wrapper document.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, html, include, doctype" }
dynamic or pre calculate data a bit new to programming and had a general question that I just thought of. Say, I have a database with a bunch of stock information and one column with price and another with earnings. To get the price/earning ratio, would it be better to calculate it everyday or to calculate it on demand? I think performance wise, it'd be quicker to read only but I'm wondering if for math type functions its worth the batch job to pre-calculate it(is it even noticeable?). So how do the professionals do it? have the application process the data for them or have it already available in the database?
The professionals use a variety of methods. It all depends on what you're going for. Do the new real ratios need to be displayed _immediately_? How often is the core data changing? Ideally you would only calculate the ratio any time the price or earning changes, but this takes extra development, and it's probably not worth it if you don't have a substantial amount of activity on the site. On the other hand, if you're receiving hundreds of visits every minute, you're definitely going to want to cache whatever you're calculating, as the time required to re-display a cached result is much less that recreating the result (in most scenarios). However, as a general rule of thumb, don't get stuck trying to optimize something you haven't anticipated any performance issues with.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql" }
Do I really need a Microsoft account in order to access my Windows Phone? I notice that many Windows Phone manual mention that user need to create a Microsoft Account in order to access their Windows Phone. Is it true? Can't I skip the process of creating the Windows Phone Microsoft account to a later stage?
You can skip it during initial setup and add it later. Skipping this step will limit access to some resources e.g. you can't use the marketplace to install applications. From the MS page: ( _highlighting_ a few key items) > ## Microsoft account > > A Microsoft account (formerly Windows Live ID) lets you do all kinds of things on your phone. Once you sign in, you can: > > * _Get apps_ , games, music, and videos from the Store > * Play Xbox games with friends and get your Xbox gamerscore and avatar on your phone > * Use Xbox Music > * Get your Twitter or LinkedIn feeds on your People Hub > * _Find, ring, lock, or erase a lost phone_ > * Create and restore phone backups > * Get personalized suggestions in Local Scout, Music + Videos, and the Store > * Chat using Messenger > * Sync documents with SkyDrive > * Automatically _sync your contacts_ and calendar to Hotmail or Outlook.com >
stackexchange-windowsphone
{ "answer_score": 7, "question_score": 5, "tags": "microsoft account" }
Make 2D particle system in Unity SO I saw a tutorial online how to make a particle system, and I made it. Only thing is, I want to use it for a 2D Menu. So when I add the particles in front of the canvas, they don't show up in 2D. How do I make particles that will show up on a 2D menu?
You can try positioning your `Canvas` in World Space, then moving it behind the particle system. This will allow the `Canvas` to be positioned like all the other objects in your scene, and no longer be constrained to the camera. Here's a guide from Unity on how to do it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "unity3d, game physics, particles" }
python script stuck on reading from stdin For some reason a script that always worked is now failing :( I investigated and trimmed down to something minimal, still not working: cat a.py: import sys for row in sys.stdin.readlines(): print("hey") print(row) Testing: >> cat b.csv a,b,c 1,2,3 >> cat b.csv | python a.py // hangs for ever, if I Ctrl+C: for row in sys.stdin.readlines(): KeyboardInterrupt Any idea what could be going on? Thanks!
After investigation, it looks like it has to do with the aliases I use. ![see commands]( Because I have different libraries for python2 and 3 I had pythonpath2=/usr/local/lib/python2.7/site-packages pythonpath3=~/Library/Python/3.6/lib/python/site-packages:/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages alias p="unset PYTHONPATH; export PYTHONPATH=${pythonpath3}; python3.7" alias p2="unset PYTHONPATH; export PYTHONPATH=${pythonpath2}; echo $PYTHONPATH; python" So I guess before piping in the terminal would pipe into the last command of the alias and a change made it pipe into the first command of the alias (unset) which made it ineffective
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 5, "tags": "python, python 3.x" }
How can my argument be used to create a matlab file? I am writing a function that converts a 2d python array into a matlab file. Here is my code so far... def save_array(arr,fname): import scipy.io import numpy out_dict={} out_dict[fname]=arr scipy.io.savemat(fname.mat,out_dict)` I want fname to be a string, but I am not sure how I can get the savemat part to work.
import scipy.io import numpy as np def save_array(arr, arrname, fname): """ Save an array to a .mat file Inputs: arr: ndarray to save arrname: name to save the array as (string) fname: .mat filename (string) """ out_dict={arrname: arr} scipy.io.savemat(fname,out_dict) save_array(np.array([1,2,3]), 'arr', 'test.mat') Might be worth doing a python tutorial or two. This is very basic stuff!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }