prompt
stringlengths
48
2.37k
chosen
stringlengths
7
4.28k
rejected
stringlengths
11
4.44k
Question: **Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this? Answer:
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
From the author himself (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper (<https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf>). > > > So you can't directly apply new data points. However, you can fit a multivariate regression model between your data and the embedded dimensions. The author recognizes that it's a limitation of the method and suggests this way to get around it.
Question: **Goal**: I aim to use t-SNE (t-distributed Stochastic Neighbor Embedding) in R for dimensionality reduction of my training data (with *N* observations and *K* variables, where *K>>N*) and subsequently aim to come up with the t-SNE representation for my test data. **Example**: Suppose I aim to reduce the K variables to *D=2* dimensions (often, *D=2* or *D=3* for t-SNE). There are two R packages: `Rtsne` and `tsne`, while I use the former here. ``` # load packages library(Rtsne) # Generate Training Data: random standard normal matrix with J=400 variables and N=100 observations x.train <- matrix(nrom(n=40000, mean=0, sd=1), nrow=100, ncol=400) # Generate Test Data: random standard normal vector with N=1 observation for J=400 variables x.test <- rnorm(n=400, mean=0, sd=1) # perform t-SNE set.seed(1) fit.tsne <- Rtsne(X=x.train, dims=2) ``` where the command `fit.tsne$Y` will return the (100x2)-dimensional object containing the t-SNE representation of the data; can also be plotted via `plot(fit.tsne$Y)`. **Problem**: Now, what I am looking for is a function that returns a prediction `pred` of dimension (1x2) for my test data based on the trained t-SNE model. Something like, ``` # The function I am looking for (but doesn't exist yet): pred <- predict(object=fit.tsne, newdata=x.test) ``` (How) Is this possible? Can you help me out with this? Answer:
This the mail answer from the author (Jesse Krijthe) of the Rtsne package: > > Thank you for the very specific question. I had an earlier request for > this and it is noted as an open issue on GitHub > (<https://github.com/jkrijthe/Rtsne/issues/6>). The main reason I am > hesitant to implement something like this is that, in a sense, there > is no 'natural' way explain what a prediction means in terms of tsne. > To me, tsne is a way to visualize a distance matrix. As such, a new > sample would lead to a new distance matrix and hence a new > visualization. So, my current thinking is that the only sensible way > would be to rerun the tsne procedure on the train and test set > combined. > > > Having said that, other people do think it makes sense to define > predictions, for instance by keeping the train objects fixed in the > map and finding good locations for the test objects (as was suggested > in the issue). An approach I would personally prefer over this would > be something like parametric tsne, which Laurens van der Maaten (the > author of the tsne paper) explored a paper. However, this would best > be implemented using something else than my package, because the > parametric model is likely most effective if it is selected by the > user. > > > So my suggestion would be to 1) refit the mapping using all data or 2) > see if you can find an implementation of parametric tsne, the only one > I know of would be Laurens's Matlab implementation. > > > Sorry I can not be of more help. If you come up with any other/better > solutions, please let me know. > > >
t-SNE does not really work this way: The following is an expert from the t-SNE author's website (<https://lvdmaaten.github.io/tsne/>): > > Once I have a t-SNE map, how can I embed incoming test points in that > map? > > > t-SNE learns a non-parametric mapping, which means that it does not > learn an explicit function that maps data from the input space to the > map. Therefore, it is not possible to embed test points in an existing > map (although you could re-run t-SNE on the full dataset). A potential > approach to deal with this would be to train a multivariate regressor > to predict the map location from the input data. Alternatively, you > could also make such a regressor minimize the t-SNE loss directly, > which is what I did in this paper. > > > You may be interested in his paper: <https://lvdmaaten.github.io/publications/papers/AISTATS_2009.pdf> This website in addition to being really cool offers a wealth of info about t-SNE: <http://distill.pub/2016/misread-tsne/> On Kaggle I have also seen people do things like this which may also be of intrest: <https://www.kaggle.com/cherzy/d/dalpozz/creditcardfraud/visualization-on-a-2d-map-with-t-sne>
Question: As the title says is there a way to programmatically render (into a DOM element) a component in angular? For example, in React I can use `ReactDOM.render` to turn a component into a DOM element. I am wondering if it's possible to something similar in Angular? Answer:
At first you'll need to have a template in your HTML file at the position where you'll want to place the dynamically loaded component. ```html <ng-template #placeholder></ng-template> ``` In the component you can inject the `DynamicFactoryResolver` inside the constructor. Once you'll execute the `loadComponent()` function, the `DynamicComponent` will be visible in the template. `DynamicComponent` can be whatever component you would like to display. ```js import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent { @ViewChild('placeholder', {read: ViewContainerRef}) private viewRef: ViewContainerRef; constructor(private cfr: ComponentFactoryResolver) {} loadComponent() { this.viewRef.clear(); const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent); const componentRef = this.viewRef.createComponent(componentFactory); } } ``` Here is a [Stackblitz](https://stackblitz.com/edit/angular-ivy-dynamic-components?file=src%2Fapp%2Fapp.component.ts). What the `loadComponent` function does is: 1. It clears the host 2. It creates a so called factory object of your component. (`resolveComponentFactory`) 3. It creates an instance of your factory object and inserts it in the host reference (`createComponent`) 4. You can use the `componentRef` to, for example, modify public properties or trigger public functions of that components instance.
If you want to render the angular component into a Dom element which is not compiled by angular, Then we can't obtain a ViewContainerRef. Then you can use Angular cdk portal and portal host concepts to achieve this. Create portal host with any DOMElememt, injector, applicationRef, componentFactoryResolver. Create portal with the component class. And attach the portal to host. <https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c>
Question: No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ``` Answer:
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
The error is due to wrong expectations on operators precedence: ++ and -> have the same precedence, so they are evaluated left to right. See <http://en.cppreference.com/w/c/language/operator_precedence> . Overall, the lack of parenthesis makes the readability poor. The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period. Then read the value and decide if it's high or low. But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling. Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.
Question: No matter how I rearrange this, the increment compare always returns false.... I have even taken it out of the if, and put it in its own if: ``` int buttonFSM(button *ptrButton) { int i; i = digitalRead(ptrButton->pin); switch(ptrButton->buttonState) { case SW_UP: if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; return SW_UP; case SW_DOWN: if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up { ptrButton->buttonState = SW_UP; ptrButton->debounceTics = 0; return SW_TRANS_DU; } ptrButton->debounceTics = 0; return SW_DOWN; } } ``` Answer:
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC\_TICS is set to, but I'm assuming it's > 1. ptrButton->debounceTics will never be greater than 1 because you always: ``` ptrButton->debounceTics = 0; ```
```C++ if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down { ptrButton->buttonState = SW_DOWN; ptrButton->debounceTics = 0; return SW_TRANS_UD; } ptrButton->debounceTics = 0; ``` I'm going to agree with user3877595 but explain why, as his/her answer got a downvote. `DBNC_TICS` has to be > 1, right? Otherwise what is the point? We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero. If `DBNC_TICS` is == 1 then this is always true: ```C++ ++ptrButton->debounceTics == DBNC_TICS ``` Therefore that test is useless. If `DBNC_TICS` > 1 then it will not execute the "if" block and execute this instead: ```C++ ptrButton->debounceTics = 0; ``` So `ptrButton->debounceTics` is back to zero, and we are back to square 1. Therefore the test will always be false. > > No matter how I rearrange this, the increment compare always returns false.... > > > As stated in the question.
Question: Hi I'm learning right now how to upload images to database, but I'm getting this error/notice. ``` </select> <input type="text" name="nama" class="input-control" placeholder="Nama Produk" required> <input type="text" name="harga" class="input-control" placeholder="Harga Produk" required> <input type="file" name="img" class="input-control" required> <textarea class="input-control" name="deskripsi" placeholder="Desrkipsi"></textarea> <select class="input-control" name="status"> <option value="">--Pilih--</option> <option value="1">Aktif</option> <option value="0">Tidak Aktif</option> </select> <input type="submit" name="submit" value="Submit" class="btn-login"> </form> <?php if(isset($_POST['submit'])){ $kategori = $_POST['kategori']; $nama = $_POST['nama']; $harga = $_POST['harga']; $deskripsi = $_POST['deskripsi']; $status = $_POST['status']; $filename = $_FILES['img']['name']; $tmp_name = $_FILES['img']['tmp_name']; } ``` the error output ``` Notice: Undefined index: img in C:\xampp\htdocs\pa_web\tambah_produk.php on line 66 ``` Answer:
You need to add `enctype="multipart/form-data"` to your form <https://www.php.net/manual/en/features.file-upload.post-method.php> > > **Note:** > Be sure your file upload form has attribute > enctype="multipart/form-data" otherwise the file upload will not work. > > >
When you want to submit file from form you should put "enctype="multipart/form-data". ``` <form "enctype="multipart/form-data" ...> </form> ``` Do you put it?
Question: Can we change the color of the text based on the color of the background image? I have a background image which i have appended it to body. When you reload the page every time the background image gets changed. But i have my menus which are positioned on the image having text color as black. If the background image is black, menus wont be visible. Any solutions for my problem? Thanks in advance. Answer:
use switch case to handle ``` switch(backgroundimage){ case "black.jpg": document.body.color = "white"; break; case "white.jpg": document.body.color = "black"; break; case "green.jpg": document.body.color = "gray"; break; } ```
If you know what will be the image that will be loaded you can create a dictionary with the image name and the css class that will be appended to the text for it. then on page load attach the class to the body classes. If you dont know the image that will be loaded there are some solutions but they are not complete. look at this [answer](https://stackoverflow.com/a/2541680/395890)
Question: My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > > * weird construction. Delete 'new' > > > We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique? Answer:
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
Your code is just similar to the less weird construct ``` function Foo () { var inner = 'some value'; this.foo = 'blah'; ... }; var someObj = new Foo; ```
Question: My colleague has been using "new function()" with a lower case "f" to define new objects in JavaScript. It seems to work well in all major browsers and it also seems to be fairly effective at hiding private variables. Here's an example: ``` var someObj = new function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }; ``` As soon as "this" is used, it becomes a public property of someObj. So someObj.foo, someObj.get\_inner() and someObj.set\_inner() are all available publicly. In addition, set\_inner() and get\_inner() are privileged methods, so they have access to "inner" through closures. However, I haven't seen any reference to this technique anywhere. Even Douglas Crockford's JSLint complains about it: > > * weird construction. Delete 'new' > > > We're using this technique in production and it seems to be working well, but I'm a bit anxious about it because it's not documented anywhere. Does anyone know if this is a valid technique? Answer:
I've seen that technique before, it's valid, you are using a function expression as if it were a [Constructor Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function). But IMHO, you can achieve the same with an auto-invoking function expression, I don't really see the point of using the `new` operator in that way: ``` var someObj = (function () { var instance = {}, inner = 'some value'; instance.foo = 'blah'; instance.get_inner = function () { return inner; }; instance.set_inner = function (s) { inner = s; }; return instance; })(); ``` The purpose of the `new` operator is to create new object instances, setting up the `[[Prototype]]` internal property, you can see how this is made by the [`[Construct]`](http://bclary.com/2004/11/07/#a-13.2.2) internal property. The above code will produce an equivalent result.
To clarify some aspects and make Douglas Crockford's JSLint not to complain about your code here are some examples of instantiation: ```javascript 1. o = new Object(); // normal call of a constructor 2. o = new Object; // accepted call of a constructor 3. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; })(); // normal call of a constructor 4. var someObj = new (function () { var inner = 'some value'; this.foo = 'blah'; this.get_inner = function () { return inner; }; this.set_inner = function (s) { inner = s; }; }); // accepted call of a constructor ``` In example 3. expression in (...) as value is a function/constructor. It looks like this: new (function (){...})(). So if we omit ending brackets as in example 2, the expression is still a valid constructor call and looks like example 4. Douglas Crockford's JSLint "thinks" you wanted to assign the function to someObj, not its instance. And after all it's just an warning, not an error.
Question: Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help! Answer:
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
Have you included the spider in `SPIDER_MODULES` list in your scrapy\_settings.py? It's not written in the tutorial anywhere that you should to this, but you do have to.
Question: Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help! Answer:
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
I believe you have syntax errors there. The `name = hxs...` will not work because you don't get defined before the `hxs` object. Try running `python yourproject/spiders/domain.py` to get syntax errors.
Question: Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help! Answer:
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
These two lines look like they're causing trouble: ``` u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) ``` * Only one rule will be followed each time the script is run. Consider creating a rule for each URL. * You haven't created a `parse_item` callback, which means that the rule does nothing. The only callback you've defined is `parse`, which changes the default behaviour of the spider. Also, here are some things that will be worth looking into. * `CrawlSpider` doesn't like having its default `parse` method overloaded. Search for `parse_start_url` in the documentation or the docstrings. You'll see that this is the preferred way to override the default `parse` method for your starting URLs. * `NuSpider.hxs` is called before it's defined.
Question: Since nothing so far is working I started a new project with ``` python scrapy-ctl.py startproject Nu ``` I followed the tutorial exactly, and created the folders, and a new spider ``` from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from Nu.items import NuItem from urls import u class NuSpider(CrawlSpider): domain_name = "wcase" start_urls = ['http://www.whitecase.com/aabbas/'] names = hxs.select('//td[@class="altRow"][1]/a/@href').re('/.a\w+') u = names.pop() rules = (Rule(SgmlLinkExtractor(allow=(u, )), callback='parse_item'),) def parse(self, response): self.log('Hi, this is an item page! %s' % response.url) hxs = HtmlXPathSelector(response) item = Item() item['school'] = hxs.select('//td[@class="mainColumnTDa"]').re('(?<=(JD,\s))(.*?)(\d+)') return item SPIDER = NuSpider() ``` and when I run ``` C:\Python26\Scripts\Nu>python scrapy-ctl.py crawl wcase ``` I get ``` [Nu] ERROR: Could not find spider for domain: wcase ``` The other spiders at least are recognized by Scrapy, this one is not. What am I doing wrong? Thanks for your help! Answer:
Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider.
You are overriding the `parse` method, instead of implementing a new `parse_item` method.
Question: I got nearly 10 functions in class having similar pattern like following function ``` SQLiteDatabase database = this.getWritableDatabase(); try { //Some different code , all other code(try,catch,finally) is same in all functions } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` I want to remove that common code from all functions (try ,catch , finally) and move it to a single place How can I achieve this? Answer:
There are a number of frameworks out there that drastically simplify database interaction that you can use, but if you want to do things on your own, and are interested in the Java way to do things like this, here's the idea: Make your "executor" like so: ``` public class Executor { public static void runOperation(Operation operation) { SQLiteDatabase database = this.getWritableDatabase(); try { operation.run(database); } catch (SQLiteException e) { Log.e(operation.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` Now each of the 10 things you want to do will be operations: ``` public interface Operation { void run(SQLiteDatabase database) throws SQLiteException; } ``` Here is what a particular operation would look like: ``` Operation increaseSalary = new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // .... write the new increased salary to the database } }; ``` And you run it with: ``` . . Executor.runOperation(increaseSalary); . . ``` You can also make the implementation of the interface an anonymous inner class, but that may make it a little less readable. ``` . . Executor.runOperation(new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { // put the increase salary database-code in here } }); . . ``` You can look through a list of classic Design Patterns to find out which one this is.
**To expand further on [Ray Toal's original answer](https://stackoverflow.com/a/20931708/1134080),** it is worth noting that using anonymous inner class will help avoid creating a separate class file for each operation. So the original class with 10 or so functions can remain the same way, except being refactored to use the `Executor` pattern. Also, when using the `Executor` pattern, you have to take care of the usage of `this` in the original code. Assume the original functions are as follows: ``` public boolean operation1() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 1 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } public boolean operation2() { SQLiteDatabase database = this.getWritableDatabase(); try { //Code for Operation 2 return true; } catch (SQLiteException e) { Log.e(this.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } ``` With the `Executor` class defined as follows: ``` public class Executor { public static boolean runOperation(SQLiteOpenHelper helper, Operation operation) { SQLiteDatabase database = helper.getWritableDatabase(); try { operation.run(database); return true; } catch (SQLiteException e) { Log.e(helper.getClass().getName(), e.getMessage()); return false; } finally { database.close(); } } } ``` And the `Operation` interface defined as follows: ``` public interface Operation { public void run(SQLiteDatabase database) throws SQLiteException; } ``` The original functions can now be rewritten as follows: ``` public boolean operation1() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 1 } }); } public boolean operation2() { return Executor.runOperation(this, new Operation() { public void run(SQLiteDatabase database) throws SQLiteException { //Code for Operation 2 } }); } ``` *This expansion also corrects mistakes Ray has overlooked in his original answer.*
Question: Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax Answer:
You can load a placeholder image, but then you must *load* that image (when you're already loading another image). If you load something like a spinner via a `GET` request, that should be ok since you can set cache headers from the server so the browser does not actually make any additional requests for that loading image. A way that Pinterest gets around this is by loading a solid color and the title of each of their posts in the post boxes while the images are loading, but now we're getting into a design discussion. There are multiple ways to skin a cat. Regarding loading several images, you have to understand a couple considerations: 1. The time it takes to fetch and download an image. 2. The time it takes to decode this image. 3. The maximum number of concurrent sockets you may have open on a page. If you don't have a ton of images that need to be loaded up front, consideration 3 is typically not a problem since you can *optimistically* load images under the fold, but if you have 100s of images on the page that need to be loaded quickly for a good user experience, then you may need to find a better solution. Why? Because you're incurring 100s of additional round trips to your server just load each image which makes up a small portion of the total loading spectrum (the spectrum being 100s of images). Not only that, but you're getting choked by the browser limitation of having X number of concurrent requests to fetch these images. If you have many small images, you may want to go with an approach similar to what [Dropbox describes here](https://blogs.dropbox.com/tech/2014/01/retrieving-thumbnails/). The basic gist is that you make one giant request for multiple thumbnails and then get a chunked encoding response back. That means that each packet on the response will contain the payload of each thumbnail. Usually this means that you're getting back the base64-encoded version of the payload, which means that, although you are reducing the number of round trips to your server to potentially just one, you will have a greater amount of data to transfer to the client (browser) since the string representation of the payload will be larger than the binary representation. Another issue is that you can no longer safely cache this request on the browser without using something like [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API). You also incur a decode cost when you set the background image of each `img` tag to a base64 string since the browser now must convert the string to binary and then have the `img` tag decode that as whatever file format it is (instead of skipping the `base64`->`binary` step altogether when you request an image and get a binary response back).
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
Question: Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax Answer:
I found a good solution on GitHub. Just use the **CSS** code below: ```css img[src=""], img:not([src]) { visibility: hidden; } ``` Link: <https://github.com/wp-media/rocket-lazy-load/issues/60>
you can use placeholder image, which is very light weight and use that in place of each image. same time while loading page, you can load all the images in hidden div. then on document ready you can replace all the images with jQuery. e.g. HTML ---- ``` <img src="tiny_placeholder_image" alt="" data-src="original_image_src"/> <!-- upto N images --> <!-- images are loading in background --> <div style="display:none"> <img src="original_image_src" alt=""/> <!-- upto N images --> </div> ``` JavaScript ---------- ``` (function($){ // Now replace all data-src with src in images. })(jQuery); ```
Question: Perhaps I am worrying over nothing. I desire for data members to closely follow the RAII idiom. How can I initialise a protected pointer member in an abstract base class to null? I know it should be null, but wouldn't it be nicer to ensure that is universally understood? Putting initialization code outside of the initializer list has the potential to not be run. Thinking in terms of the assembly operations to allocate this pointer onto the stack, couldn't they be interrupted in much the same way (as the c'tor body) in multithreading environments or is stack expansion guaranteed to be atomic? If the destructor is guaranteed to run then might not the stack expansion have such a guarantee even if the processor doesn't perform it atomically? How did such a simple question get so expansive? Thanks. If I could avoid the std:: library that would be great, I am in a minimilist environment. Answer:
I have had this problem in the past - and fixed it. The images you're displaying are much too large. I love using html or css to resize my images (because who wants to do it manually), but the fact remains that most browsers will hiccup when moving them around. I'm not sure why. With the exception of Opera, which usually sacrifices resolution and turns websites into garbage. Resize the largest images, and see if that helps.
Performance in JavaScript is slow, as you're going through many layers of abstraction to get any work done, and many manipulations with objects on the screen are happening in the background. Performance cannot be guaranteed from system to system. You'll find that with all jQuery animation, you will get a higher "frame rate" (not the right term here, but I can't think of a better one) on faster machines and better-performing browsers (such as Chrome) than you will on slower machines. If you are curious what all happens in the background when you set a scroll position, or other property, use one of the many tools for profiling your code. Google Chrome comes with one built-in, and for Firefox, you can use Firebug to give you some insight. See also this question: [What is the best way to profile javascript execution?](https://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution)
Question: I have a Python script that uploads a Database file to my website every 5 minutes. My website lets the user query the Database using PHP. If a user tries to run a query while the database is being uploaded, they will get an error message > > PHP Warning: SQLite3::prepare(): Unable to prepare statement: 11, database disk image is malformed in XXX on line 127 > > > where line 127 is just the `prepare` function ``` $result = $db->prepare("SELECT * FROM table WHERE page_url_match = :pageurlmatch"); ``` Is there a way to test for this and retry the users request once the database is done uploading? Answer:
First of all there is a weird thing with your implementation: you use a parameter `n` that you never use, but simply keep passing and you never modify. Secondly the second recursive call is incorrect: ``` else: m = y*power(y, x//2, n) #Print statement only used as check print(x, m) return m*m ``` If you do the math, you will see that you return: *(y yx//2)2=y2\*(x//2+1)* (mind the `//` instead of `/`) which is thus one *y* too much. In order to do this correctly, you should thus rewrite it as: ``` else: m = power(y, x//2, n) #Print statement only used as check print(x, m) return y*m*m ``` (so removing the `y*` from the `m` part and add it to the `return` statement, such that it is not squared). Doing this will make your implementation at least semantically sound. But it will not solve the performance/memory aspect. Your [comment](https://stackoverflow.com/questions/34211198/using-recursion-to-calculate-powers-of-large-digit-numbers#comment56167183_34211198) makes it clear that you want to do a modulo on the result, so this is probably *Project Euler*? The strategy is to make use of the fact that modulo is closed under multiplication. In other words the following holds: *(a b) mod c = ((a mod c) \* (b mod c)) mod c* You can use this in your program to prevent generating **huge numbers** and thus work with small numbers that require little computational effort to run. Another optimization is that you can simply use the square in your argument. So a faster implementation is something like: ``` def power(y, x, n): if x == 0: #base case return 1 elif (x%2==0): #x even return power((y*y)%n,x//2,n)%n else: #x odd return (y*power((y*y)%n,x//2,n))%n ``` If we do a small test with this function, we see that the two results are identical for small numbers (where the `pow()` can be processed in reasonable time/memory): `(12347**2742)%1009` returns `787L` and `power(12347,2742,1009)` `787`, so they generate the same result (of course this is no *proof*), that both are equivalent, it's just a short test that filters out obvious mistakes.
here is my approach accornding to the c version of this problem it works with both positives and negatives exposents: ``` def power(a,b): """this function will raise a to the power b but recursivelly""" #first of all we need to verify the input if isinstance(a,(int,float)) and isinstance(b,int): if a==0: #to gain time return 0 if b==0: return 1 if b >0: if (b%2==0): #this will reduce time by 2 when number are even and it just calculate the power of one part and then multiply if b==2: return a*a else: return power(power(a,b/2),2) else: #the main case when the number is odd return a * power(a, b- 1) elif not b >0: #this is for negatives exposents return 1./float(power(a,-b)) else: raise TypeError('Argument must be interfer or float') ```
Question: I want to remove the card from the `@hand` array if it has the same rank as the given input. I'm looping through the entire array, why doesn't it get rid of the last card? Any help is greatly appreciated! Output: ``` 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Clubs 3 of Spades ------------ 2 of Clubs 2 of Spades 2 of Hearts 2 of Diamonds 3 of Spades ``` Code: ``` deck = Deck.new hand = Hand.new(deck.deal, deck.deal, deck.deal, deck.deal, deck.deal, deck.deal) puts hand.to_s hand.remove_cards("3") puts "------------" puts hand.to_s ``` Hand class: ``` class Hand def initialize(*cards) @hand = cards end def remove_cards(value) @hand.each_with_index do |hand_card, i| if hand_card.rank == value @hand.delete_at(i) end end end def to_s output = "" @hand.each do |card| output += card.to_s + "\n" end return output end end ``` Card class: ``` class Card attr_reader :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def to_s "#{@rank} of #{@suit}" end end ``` Answer:
`remove_cards(value)` has an issue: one should not `delete` during iteration. The correct way would be to [`Array#reject!`](http://ruby-doc.org/core-2.3.1/Array.html#method-i-reject-21) cards from a hand: ``` def remove_cards(value) @hands.reject! { |hand_card| hand_card.rank == value } end ```
Your issue is in this line ``` @hands.each_with_index do |hand_card, i| ``` You have an instance variable `@hand`, not `@hands`
Question: TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing. Answer:
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
What about oldskool `strtoupper()`?
Question: TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing. Answer:
What about oldskool `strtoupper()`?
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
Question: TextView.setAllCaps() started as of API 14. What is its equivalent for older APIs (e.g. 13 and lowers)? I cannot find such method on lower APIs. Is maybe setTransformationMethod() responsible for this on older APIs? If yes, how should I use it? `TextView.setTransformationMethod(new TransformationMethod() {...` is a bit confusing. Answer:
Try this: ``` textView.setText(textToBeSet.toUpperCase()); ```
Bottom line is that `toUpperCase()` is the solution. I can't object that. If you prefer doing the `setAllCaps()` with `TransformationMethod`, take a look at my [answer](https://stackoverflow.com/a/24025691/557179).
Question: If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense. Answer:
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
Question: If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense. Answer:
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
Question: If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense. Answer:
Members of the SubClass will not be able to access the DoSomething from BaseClass without explicitly indicating the class name. So it is effectively "hidden" to members of SubClass, but still accessible. For example: ``` public class SubClass : BaseClass { public static void DoSomething() { } public static void DoSomethingElse() { DoSomething(); // Calls SubClass BaseClass.DoSomething(); // Calls BaseClass } } ```
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
Question: If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense. Answer:
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
It's just a warning. The compiler just wants to make sure you intentionally used the same method name.
Question: If you declare an inheritance hierarchy where both the parent and child class have a static method of the same name and parameters\*, Visual Studio will raise warning [CS0108](http://msdn.microsoft.com/en-us/library/3s8070fc.aspx): Example: ``` public class BaseClass { public static void DoSomething() { } } public class SubClass : BaseClass { public static void DoSomething() { } } ``` `: warning CS0108: 'SubClass.DoSomething()' hides inherited member 'BaseClass.DoSomething()'. Use the new keyword if hiding was intended.` Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name: ``` BaseClass.DoSomething(); SubClass.DoSomething(); ``` or, unqualified in the class itself. In either case, there is no ambiguity as to which method is being called (i.e., no 'hiding'). \*Interestingly enough, the methods can differ by return type and still generate the same warning. However, if the method parameter types differ, the warning is not generated. Please note that I am not trying to create an argument for or discuss static inheritance or any other such nonsense. Answer:
> > Why is this considered method hiding? Neither method is involved in the inheritance hierarchy and can only be invoked by using the class name. > > > That is not true. You can call DoSomething from any inherited class name: ``` public Class A { public static void C() {...} } public Class B: A { } B.C() // Valid call! ``` That is why you are hiding C() if you declare the method with the same signature in B. Hope this helps.
Visual Studio, and Philippe, are saying it's a warning so your code will compile and run. However, 'CodeNaked' nicely demonstrates why it is hidden. This code compiles without throwing errors or warnings. Thanks to 'CodeNaked' ``` public class BaseClass { public virtual void DoSomething() { } } public class SubClass : BaseClass { public override void DoSomething() { } public void DoSomethingElse() { DoSomething(); // Calls SubClass base.DoSomething(); // Calls BaseClass } } ``` EDIT: With Travis's code I can do the following: BaseClass.DoSomething(); SubClass.DoSomething(); And it works fine. Thing is though you might wonder why SubClass is inheriting from BaseClass and both are implementing the same static methods. Actually that's not true, both classes are implementing methods that could be completely different but have the same name. That could be potential confusing.
Question: $A^{2}-2A=\begin{bmatrix} 5 & -6 \\ -4 & 2 \end{bmatrix}$ Can someone help me solve this? I've been trying to solve it for a while, but no matter what I try, the only information that I manage to get about A is that if $A=\begin{bmatrix} a & b \\ c & d \end{bmatrix}$ then $c=\frac{2b}{3}$. Any help would be appreciated, thanks! Answer:
Denote by $I$ the identity matrix. Then, completing squares you can write $$A^2 - 2A = A^2 -2IA + I^2 -I^2 = (A-I)^2 -I^2.$$ Hence, your equation is equivalent to $$(A-I)^2 = X + I$$ since $I^2 = I$. Denote by $Y=X+I$ the new matrix (which is known). You want to find $B$ such that $B^2=Y.$ Here, I recommend to diagonalize $Y$, i.e. find $U$ and diagonal $D$ such that $$Y=UDU^{-1}.$$ Thus, $$B= Y^{1/2} = UD^{1/2}U^{-1}.$$ See [this link](https://en.wikipedia.org/wiki/Square_root_of_a_matrix#By_diagonalization) for more information. Once you have found $B$, $A$ is given by $$A=B+I.$$ Remember that you may have more than one square root of the matrix $Y$.
$\newcommand{\Tr}{\mathrm{Tr}\,}$ Let $Y=A-I$, $X=B+I$, $B$ for the rhs matrix. Then $\Tr X = 9$, $\det X=-6$, and we need to solve $$Y^2=X$$ for $Y$. Write $\alpha=\Tr Y$, $\beta = \det Y$. Then $$Y^2-\alpha Y + \beta I=0$$ or $$\alpha Y = \beta I + X$$ so that finding allowed values of $\alpha$, $\beta$ solves the problem. Take the trace and determinant of both sides of $Y^2=X$. Then $$\begin{align} \alpha^2 - 2\beta &= \Tr X = 9 \\ \beta^2 &= \det X = -6 \end{align}$$ which means that $$\begin{align} \alpha A &= (\alpha+\beta +1)I + B \\ \alpha^2 & = 9 +2\beta \\ \beta^2 &= -6\text{.} \end{align}$$ Note that there are four solutions.
Question: I have a discord bot that gets info from an API. The current issue I'm having is actually getting the information to be sent when the command is run. ``` const axios = require('axios'); axios.get('https://mcapi.us/server/status?ip=asean.my.to') .then(response => { console.log(response.data); }); module.exports = { name: 'serverstatus', description: 'USes an API to grab server status ', execute(message, args) { message.channel.send(); }, }; ``` Answer:
probably your page is refreshed, try to use preventDefault to prevent the refresh ``` $('#submit').click(function(event){ //your code here event.preventDefault(); } ```
You have a button with type `"submit"`. ```html <input type="submit" id="submit" value="Save"> ``` As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL. As [Sterko](https://stackoverflow.com/users/13474687/sterko) stated, you could use a event-handler to prevent the submission of your form due to the submit button.
Question: I have Echo's buried in code all over my notebook, I'd like a flag to turn them all on or off globally. * Sure `Unprotect[Echo];Echo=Identity` would disable them, but then you can't re-enable them * A solution that works for all the various types of Echos (EchoName, EchoEvaluation, ...) would be nice * `QuietEcho` doesn't work because I'd have to write it add it around every blob of code Answer:
[`Echo`](http://reference.wolfram.com/language/ref/Echo) has an autoload, so you need to make sure the symbol is autoloaded before you modify its values: ``` DisableEcho[] := (Unprotect[Echo]; Echo; Echo = #&; Protect[Echo];) EnableEcho[] := (Unprotect[Echo]; Echo=.; Protect[Echo];) ``` Test: ``` DisableEcho[] Echo[3] EnableEcho[] Echo[3, "EchoLabel"] ``` > > 3 > > > > > EchoLabel 3 > > > > > 3 > > >
I would recommend using `QuietEcho` rather than redefining `Echo`: ``` In[62]:= $Pre = QuietEcho; In[63]:= Echo[3] Out[63]= 3 ``` This has the added benefit of disabling printing for all `Echo` functions, not just `Echo`.
Question: I have a project with multiple modules say "Application A" and "Application B" modules (these are separate module with its own pom file but are not related to each other). In the dev cycle, each of these modules have its own feature branch. Say, ``` Application A --- Master \ - Feature 1 Application B --- Master \ - Feature 1 ``` Say Application A is independent and has its own release cycle/version. Application B uses Application A as a jar. And is defined in its pom dependency. Now, both teams are working on a feature branch say "Feature 1". What is the best way to setup Jenkins build such that, Build job for Application B is able to use the latest jar from "Feature 1" branch of Application A. Given Feature 1 is not allowed to deploy its artifacts to maven repository. Somehow I want the jar from Application A's Feature 1 branch to be supplied as the correct dependency for Application B? Answer:
You can do this with a before update trigger. You would use such a trigger to assign the value of `offer_nr` based on the historical values. The key code would be: ``` new.offer_nr = (select coalesce(1+max(offer_nr), 1) from offers o where o.company_id = new.company_id ) ``` You might also want to have `before update` and `after delete` triggers, if you want to keep the values in order. Another alternative is to assign the values when you query. You would generally do this using a variable to hold and increment the count.
Don't make it this way. Have autoincremented company ids as well as independent order ids. That's how it works. There is no such thing like "number" in database. Numbers appears only at the time of select.
Question: HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array Answer:
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
Question: HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array Answer:
The declaration array syntax is in correct.Please check the below code ``` var val1=[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
Question: HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array Answer:
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
You can try the following **HTML** ``` <select class="form-control min-select" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` **JQUERY** ``` var values = []; $("select.min-select").each(function(i, sel){ var selectedVal = $(sel).val(); values.push(selectedVal); }); ``` Is min\_select[] a multiple choice select?
Question: HTML CODE ``` <select class="form-control" name="min_select[]"> <option value="15">15</option> <option value="30">30</option> </select> ``` JQuery Code ``` var val1[]; $('select[name="min_select[]"] option:selected').each(function() { val1.push($(this).val()); }); ``` when i run this code I get empty val array Answer:
This will also work ``` var val1= $("select[name=\'min_select[]\']").map(function() { return $(this).val(); }).toArray(); ```
To get the selected value, whether it is multiselect or single select, use jQuery [`.val()`](http://api.jquery.com/val/) method. If it is a multiselect, it will return an array of the selected values. See [jsfiddle for demo](https://jsfiddle.net/txk25c4c/). Check console log
Question: I'm trying to get the Download Folder to show on my file explorer. However on Android 9, when I use the getexternalstoragedirectory() method is showing self and emulated directories only and if I press "emulated" I cannot see more folders, it shows an empty folder. So this is how I'm getting the path, it's working fine in other Android versions but Android 9. Any guide would be appreciated ``` val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath ``` Answer:
This is because [dictionaries](https://docs.julialang.org/en/v1/base/collections/#Dictionaries-1) in Julia (`Dict`) are not ordered: each dictionary maintains a *set* of keys. The order in which one gets keys when one iterates on this set is not defined, and can vary as one inserts new entries. There are two things that one can do to ensure that one iterates on dictionary entries in a specific order. The first method is to get the set of keys (using [`keys`](https://docs.julialang.org/en/v1/base/collections/#Base.keys)) and sort it yourself, as has been proposed in another answer: ``` julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> for key in sort!(collect(keys(fruits))) val = fruits[key] println("$key => $val") end Apples => 8 Mangoes => 5 Pomegranates => 4 ``` That being said, if the order of keys is important, one might want to reflect that fact in the type system by using an *ordered* dictionary ([OrderedDict](https://juliacollections.github.io/OrderedCollections.jl/latest/ordered_containers.html#OrderedDicts-and-OrderedSets-1)), which is a data structure in which the order of entries is meaningful. More precisely, an `OrderedDict` preserves the order in which its entries have been inserted. One can either create an `OrderedDict` from scratch, taking care of inserting keys in order, and the order will be preserved. Or one can create an `OrderedDict` from an existing `Dict` simply using `sort`, which will sort entries in ascending order of their key: ``` julia> using OrderedCollections julia> fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); julia> ordered_fruits = sort(fruits) OrderedDict{String,Int64} with 3 entries: "Apples" => 8 "Mangoes" => 5 "Pomegranates" => 4 julia> keys(ordered_fruits) Base.KeySet for a OrderedDict{String,Int64} with 3 entries. Keys: "Apples" "Mangoes" "Pomegranates" ```
Try this: ``` fruits = Dict("Mangoes" => 5, "Pomegranates" => 4, "Apples" => 8); for key in sort(collect(keys(fruits))) println("$key => $(fruits[key])") end ``` It gives this result: ``` Apples => 8 Mangoes => 5 Pomegranates => 4 ```
Question: I have this SQL server instance which is shared by several client-processes. I want queries to finish taking as little time as possible. Say a call needs to read 1k to 10k records from this shared Sql Server. My natural choice would be to use ExecuteReaderAsync to take advantage of async benefits such as reusing threads. I started wondering whether async will pose some overhead since execution might stop and resume for every call to ExecuteReaderAsync. That being true, seems that overall time for query to complete would be longer if compared to a implementation that uses ExecuteReader. Does that make (any) sense? Answer:
Whether you use sync or async to call SQL Server makes no difference for the work that SQL Server does and for the CPU-bound work that ADO.NET does to serialize and deserialize request and response. So no matter what you chose the difference will be small. Using async is not about saving CPU time. It is about saving memory (less thread stacks) and about having a nice programming model in UI apps. In fact async never saves CPU time as far as I'm aware. It adds overhead. If you want to save CPU time use a synchronous approach. On the server using async in low-concurrency workloads adds no value whatsoever. It adds development time and CPU cost.
The difference between the async approach and the sync approach is that the async call will cause the compiler to generate a state machine, whereas the sync call will simply block while the work agains't the database is being done. IRL, the best way to choose is to benchmark both approaches. As usr said, usually those differrences are neglectable compared to the time the query takes to execute. Async will shine brighter in places where it may save resources such as allocating a new thread There are many posts about async performance: 1. [*Async await performance*](https://stackoverflow.com/questions/23871806/async-await-performance) 2. [*The zen of async: best practices for best performance*](http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-829T) 3. [*Async Performance: Understanding the Costs of Async and Await*](http://msdn.microsoft.com/en-us/magazine/hh456402.aspx)
Question: I'm trying to prove this by induction, but something doesn't add up. I see a solution given [here](https://www.algebra.com/algebra/homework/word/misc/Miscellaneous_Word_Problems.faq.question.29292.html), but it is actually proving that the expression is **greater** than $2\sqrt{n}$. I'd appreciate some insight. Answer:
Base step: 1<2. Inductive step: $$\sum\_{j=1}^{n+1}\frac1{\sqrt{j}} < 2\sqrt{n}+\frac1{\sqrt{n+1}}$$ So if we prove $$2\sqrt{n}+\frac1{\sqrt{n+1}}<2\sqrt{n+1}$$ we are done. Indeed, that holds true: just square the left hand side sides to get $$4n+2\frac{\sqrt{n}}{\sqrt{n+1}}+\frac1{n+1}<4n+3<4n+4$$ which is the square of the right end side. Errata: I forgot the double product in the square. The proof must be amended as follows: $$2\sqrt{n}<2\sqrt{n+1}-\frac1{\sqrt{n+1}}$$ since by squaring it we get $$4n<4n+4-4+\frac1{n+1}$$ which is trivially true.
Note that $$ 2\sqrt{n+1}-2\sqrt n=2\cdot\frac{(\sqrt{n+1}-\sqrt{n})(\sqrt{n+1}+\sqrt{n})}{\sqrt{n+1}+\sqrt{n}}=2\cdot \frac{(n+1)-n}{\sqrt{n+1}+\sqrt{n}}<\frac 2{\sqrt n+\sqrt n}$$
Question: I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes. Answer:
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
Question: I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes. Answer:
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
Question: I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes. Answer:
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
Just an idea, can you save result of that query into temp table ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension INTO #TempEmployee FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` And after that just do the update of #TempEmployee?
Question: I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes. Answer:
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
If you just want to create a unique random 5 digit number for those `empExtension` column values are null, then **Query** ``` ;with cte as ( select rn = row_number() over ( order by empId ),* from employeeDetails ) select t1.empId,t2.deptName, case when t1.empExtension is null then t1.rn + (convert(numeric(5,0),rand() * 20000) + 10000) else t1.empExtension end as empExtension from cte t1 left join employeeDepartment t2 on t1.empId = t2.empId; ``` [**SQL Fiddle**](http://www.sqlfiddle.com/#!3/29acb/1)
Question: I have a scenario where I need to auto generate the value of a column if it is null. Ex: `employeeDetails`: ``` empName empId empExtension A 101 null B 102 987 C 103 986 D 104 null E 105 null ``` `employeeDepartment`: ``` deptName empId HR 101 ADMIN 102 IT 103 IT 104 IT 105 ``` Query ``` SELECT empdt.empId, empdprt.deptName, empdt.empExtension FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Output: ``` empId deptName empExtension 101 HR null 102 ADMIN 987 103 IT 986 104 IT null 105 IT null ``` Now my question is I want to insert some dummy value which replaces null and auto-increments starting from a 5 digit INT number Expected output: ``` empId deptName empExtension 101 HR 12345 102 ADMIN 987 103 IT 986 104 IT 12346 105 IT 12347 ``` Constraints : I cannot change existing tables structure or any column's datatypes. Answer:
You should be able to do that with a CTE to grab [ROW\_NUMBER](https://msdn.microsoft.com/en-us/library/ms186734.aspx), and then [COALESCE](https://msdn.microsoft.com/en-us/library/ms190349.aspx) to only use that number where the value is NULL: ``` WITH cte AS( SELECT empId, empExtension, ROW_NUMBER() OVER(ORDER BY empExtension, empId) rn FROM employeeDetails ) SELECT cte.empId, deptName, COALESCE(empExtension, rn + 12344) empExtension FROM cte LEFT JOIN employeeDepartment ON cte.empID = employeeDepartment.empID ORDER BY cte.empId ``` Here's an [SQLFiddle](http://sqlfiddle.com/#!3/142d1/5).
``` declare @rand int = (rand()* 12345); SELECT empdt.empId, empdprt.deptName, isnull(empdt.empExtension,row_number() over(order by empdt.empId)+@rand) FROM employeeDetails empdt LEFT JOIN employeeDepartment empdprt ON empdt.empId = empdprt.empId ``` Incase the empExtension, get the row\_number + a random number.
Question: I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ``` Answer:
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
Question: I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ``` Answer:
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
Question: I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ``` Answer:
No, there isn't. Unless you consider this a one liner: ``` for x in range(6): print(x) ``` but there's no reason to do that.
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
Question: I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ``` Answer:
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
For your specific case to print a range of 6: ```py print(*range(6), sep='\n') ``` This is not a for loop however @Boris is correct.
Question: I'm brand new to python 3 & my google searches have been unproductive. Is there a way to write this: ``` for x in range(10): print(x) ``` as this: ``` print(x) for x in range(10) ``` I do not want to return a list as the `arr = [x for x in X]` list comprehension syntax does. EDIT: I'm not actually in that specific case involving `print()`, I'm interested in a generic pythonic syntactical construction for ``` method(element) for element in list ``` Answer:
Looks like you are looking for something like `map`. If the function you are calling returns `None`, then it won't be too expensive. Map will return an iterator, so you are just trying to consume it. One way is: ```py list(map(print, range(6))) ``` Or using a zero length deque if you don't want the actual list elements stored. ```py from collections import deque deque(map(print, range(6)), maxlen=0) ```
What you are looking for is a generator expression that returns a generator object. ```py print(i for i in range(10)) #<generator object <genexpr> at 0x7f3a5baacdb0> ``` To see the values ```py print(*(i for i in range(10))) # 0 1 2 3 4 5 6 7 8 9 ``` Pros: * Extremely Memory Efficient. * Lazy Evaluation - generates next element only on demand. Cons: * Can be iterated over till the stop iteration is hit, after that one cannot reiterate it. * Cannot be indexed like a list. Hope this helps!
Question: When I run my project on my iphone or in the simulator it works fine. When I try to run it on an ipad I get the below error: *file was built for arm64 which is not the architecture being linked (armv7)* The devices it set to Universal. Does anybody have an idea about what else I should check? Answer:
Just in case somebody has the same problem as me. Some of my target projects had different iOS Deployment target and that is why the linking failed. After moving them all to the same the problem was solved.
I should have added armv6 for iPad 2. Done that and it works now
Question: I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs. Answer:
If you are choosing to use the Membership API for your site, then this [link](http://www.asp.net/(S(pdfrohu0ajmwt445fanvj2r3))/learn/security/tutorial-08-cs.aspx) has information regarding how to add extra information to a user. I was faced with the same scenario recently and ended up ditching the membership functionality and rolled my own db solution in tandem with the DotNetOpenAuth library.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.
Question: I'm just starting a new project on ASP.NET MVC and this will be the first project actually using this technology. As I created my new project with Visual Studio 2010, it created to my sql server a bunch of tables with "aspnet\_" prefix. Part of them deal with the built-in user accounts and permission support. Now, I want to keep some specific information about my users. My question is "Is it a good practice changing the structure of this aspnet\_ tables, to meet my needs about user account's information?". And as i suppose the answer is "No." (Why exactly?), I intend to create my own "Users" table. What is a good approach to connect the records from aspnet\_Users table and my own custom Users table. I want the relationship to be 1:1 and the design in the database to be as transparent as possible in my c# code (I'm using linq to sql if it is important). Also, I don't want to replicate the usernames and passwords from the aspnet\_ tables to my table and maintain the data. I'm considering using a view to join them. Is this a good idea? Thanks in advance! EDIT: From the answer, I see that I may not be clear enough, what I want. The question is not IF to use the default asp.net provider, but how to adopt it, to my needs. Answer:
I would create [custom membership provider](http://www.15seconds.com/issue/050216.htm) and omit those `aspnet_x` tables completely. I've seen what happens when one `join`s these tables and custom ones with nhibernate mappings - pure nightmare.
Using the membership system in asp.net has its advantages and drawbacks. It's easy to start, because you don't have to worry about validation, user registration, resetting passwords. (Be careful if you plan to modify the table structures, you will have to change them in the views/store procedures generated **However there are drawbacks to using Membership** You will have to maintain 2 separated systems, because the Membership API has restrictions, for example, you cannot perform operations inside a transaction with the membership api. (Unless you use TransactionScope i think, but you don't have other choices). A valid alternative would be to implement your own security validation routines, and using FormsAuthentication. This way you will have total control over your users tables, and remove dependency to the membership API.
Question: I am modifying a regex validator control. The regex at the moment looks like this: ``` (\d*\,?\d{2}?){1}$ ``` As I can understand it allows for a number with 2 decimal places. I need to modify it like this: * The number must range from 0 - 1.000.000. (Zero to one million). * The number may or may not have 2 decimals. * The value can not be negative. * Comma (`,`) is the decimal separator. * Should not allow any thousand separators. Answer:
Try this regex: ``` ^(((0|[1-9]\d{0,5})(\,\d{2})?)|(1000000(\,00)?))$ ``` It accepts numbers like: `"4", "4,23", "123456", "1000000", "1000000,00"`, but don't accepts: `",23", "4,7", "1000001", "4,234", "1000000,55"`. If you want accept only numbers with exactly two decimals, use this regex: ``` ^(((0|[1-9]\d{0,5})\,\d{2})|(1000000\,00))$ ```
What about this one ``` ^(?:\d{1,6}(?:\,\d{2})?|1000000)$ ``` See it [here on Regexr](http://regexr.com?2ut4u) It accepts between 1 and 6 digits and an optional fraction with 2 digits OR "1000000". And it allows the number to start with zeros! (001 would be accepted) `^` anchors the regex to the start of the string `$` anchors the regex to the end of the string `(?:)` is a non capturing group
Question: I am modifying a regex validator control. The regex at the moment looks like this: ``` (\d*\,?\d{2}?){1}$ ``` As I can understand it allows for a number with 2 decimal places. I need to modify it like this: * The number must range from 0 - 1.000.000. (Zero to one million). * The number may or may not have 2 decimals. * The value can not be negative. * Comma (`,`) is the decimal separator. * Should not allow any thousand separators. Answer:
Try this regex: ``` ^(((0|[1-9]\d{0,5})(\,\d{2})?)|(1000000(\,00)?))$ ``` It accepts numbers like: `"4", "4,23", "123456", "1000000", "1000000,00"`, but don't accepts: `",23", "4,7", "1000001", "4,234", "1000000,55"`. If you want accept only numbers with exactly two decimals, use this regex: ``` ^(((0|[1-9]\d{0,5})\,\d{2})|(1000000\,00))$ ```
``` ^(([0-9]|([1-9][0-9]{1,5}))(\.[0-9]{1,2})?)|1000000$ ```
Question: can someone please tell me what is going wrong? I am trying to create a basic login page and that opens only when a correct password is written ``` <html> <head> <script> function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } var x=document.forms["myForm"]["fname2"].value; if (x==null || x=="") { alert("password must be filled out"); return false; } } function isValid(myNorm){ var password = myNorm.value; if (password == "hello_me") { return true; } else {alert('Wrong Password') return false; } } </script> </head> <body> <form name="myForm" action="helloworld.html" onsubmit="return !!(validateForm()& isValid())" method="post"> Login ID: <input type="text" name="fname"> <br /> <br> Password: <input type="password" name="fname2" > <br /> <br /> <br /> <input type="submit" value="Submit"> <input type="Reset" value="clear"> </form> </body> </html> ``` Answer:
try this ``` BufferedWriter writer = new BufferedWriter(new FileWriter("result.txt")); for (String element : misspelledWords) { writer.write(element); writer.newLine(); } ``` Adding line separator at the end (like "\n") should work on most OS,but to be on safer side you should use **System.getProperty("line.separator")**
Open your file in append mode like this `FileWriter(String fileName, boolean append)` when you want to make an object of class `FileWrite` in constructor. ``` File file = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects\\addNewLinetoTxtFile\\src\\addnewlinetotxtfile\\a.txt"); try (Writer newLine = new BufferedWriter(new FileWriter(file, true));) { newLine.write("New Line!"); newLine.write(System.getProperty( "line.separator" )); } catch (IOException e) { } ``` Note: > > "**line.separator**" is a Sequence used by operating system to separate lines > in text files > > > source: <http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html>
Question: I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal? Answer:
I think you'll be better off trying to use one cursor for all of your executions, and close it at the end of your code. It's easier to work with, and it might have efficiency benefits as well (don't quote me on that one). ``` conn = MySQLdb.connect("host","user","pass","database") cursor = conn.cursor() cursor.execute("somestuff") results = cursor.fetchall() ..do stuff with results cursor.execute("someotherstuff") results2 = cursor.fetchall() ..do stuff with results2 cursor.close() ``` The point is that you can store the results of a cursor's execution in another variable, thereby freeing your cursor to make a second execution. You run into problems this way only if you're using fetchone(), and need to make a second cursor execution before you've iterated through all results from the first query. Otherwise, I'd say just close your cursors as soon as you're done getting all of the data out of them. That way you don't have to worry about tying up loose ends later in your code.
I suggest to do it like php and mysql. Start i at the beginning of your code before printing of the first data. So if you get a connect error you can display a `50x`(Don't remember what internal error is) error message. And keep it open for the whole session and close it when you know you wont need it anymore.
Question: I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal? Answer:
It's better to rewrite it using 'with' keyword. 'With' will take care about closing cursor (it's important because it's unmanaged resource) automatically. The benefit is it will close cursor in case of exception too. ``` from contextlib import closing import MySQLdb ''' At the beginning you open a DB connection. Particular moment when you open connection depends from your approach: - it can be inside the same function where you work with cursors - in the class constructor - etc ''' db = MySQLdb.connect("host", "user", "pass", "database") with closing(db.cursor()) as cur: cur.execute("somestuff") results = cur.fetchall() # do stuff with results cur.execute("insert operation") # call commit if you do INSERT, UPDATE or DELETE operations db.commit() cur.execute("someotherstuff") results2 = cur.fetchone() # do stuff with results2 # at some point when you decided that you do not need # the open connection anymore you close it db.close() ```
I suggest to do it like php and mysql. Start i at the beginning of your code before printing of the first data. So if you get a connect error you can display a `50x`(Don't remember what internal error is) error message. And keep it open for the whole session and close it when you know you wont need it anymore.
Question: I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe you need to close the cursor before committing the connection. Is there any significant advantage to finding sets of transactions that don't require intermediate commits so that you don't have to get new cursors for each transaction? Is there a lot of overhead for getting new cursors, or is it just not a big deal? Answer:
It's better to rewrite it using 'with' keyword. 'With' will take care about closing cursor (it's important because it's unmanaged resource) automatically. The benefit is it will close cursor in case of exception too. ``` from contextlib import closing import MySQLdb ''' At the beginning you open a DB connection. Particular moment when you open connection depends from your approach: - it can be inside the same function where you work with cursors - in the class constructor - etc ''' db = MySQLdb.connect("host", "user", "pass", "database") with closing(db.cursor()) as cur: cur.execute("somestuff") results = cur.fetchall() # do stuff with results cur.execute("insert operation") # call commit if you do INSERT, UPDATE or DELETE operations db.commit() cur.execute("someotherstuff") results2 = cur.fetchone() # do stuff with results2 # at some point when you decided that you do not need # the open connection anymore you close it db.close() ```
I think you'll be better off trying to use one cursor for all of your executions, and close it at the end of your code. It's easier to work with, and it might have efficiency benefits as well (don't quote me on that one). ``` conn = MySQLdb.connect("host","user","pass","database") cursor = conn.cursor() cursor.execute("somestuff") results = cursor.fetchall() ..do stuff with results cursor.execute("someotherstuff") results2 = cursor.fetchall() ..do stuff with results2 cursor.close() ``` The point is that you can store the results of a cursor's execution in another variable, thereby freeing your cursor to make a second execution. You run into problems this way only if you're using fetchone(), and need to make a second cursor execution before you've iterated through all results from the first query. Otherwise, I'd say just close your cursors as soon as you're done getting all of the data out of them. That way you don't have to worry about tying up loose ends later in your code.
Question: I am new to the Ruby on Rails ecosystem so might question might be really trivial. I have set up an Active Storage on one of my model ```rb class Sedcard < ApplicationRecord has_many_attached :photos end ``` And I simply want to seed data with `Faker` in it like so: ```rb require 'faker' Sedcard.destroy_all 20.times do |_i| sedcard = Sedcard.create!( showname: Faker::Name.female_first_name, description: Faker::Lorem.paragraph(10), phone: Faker::PhoneNumber.cell_phone, birthdate: Faker::Date.birthday(18, 40), gender: Sedcard.genders[:female], is_active: Faker::Boolean.boolean ) index = Faker::Number.unique.between(1, 99) image = open("https://randomuser.me/api/portraits/women/#{index}.jpg") sedcard.photos.attach(io: image, filename: "avatar#{index}.jpg", content_type: 'image/png') end ``` The problem is that some of these records end up with multiple photos attached to them, could be 5 or 10. Most records are seeded well, they have only one photo associated, but the ones with multiple photos all follow the same pattern, they are all seeded with the exact same images. Answer:
I found the problem myself. I was using UUID as my model's primary key which is not natively compatible with ActiveStorage. Thus, I more or less followed the instructions [here](https://www.wrburgess.com/posts/2018-02-03-1.html)
You need to purge the attachments. Try adding this snippet before destroyingthe `Sedcard`'s ``` Sedcard.all.each{ |s| s.photos.purge } ``` Ref: <https://edgeguides.rubyonrails.org/active_storage_overview.html#removing-files>
Question: Say I have an expansion of terms containing functions `y[j,t]` and its derivatives, indexed by `j` with the index beginning at 0 whose independent variable are `t`, like so: `Expr = y[0,t]^2 + D[y[0,t],t]*y[0,t] + y[0,t]*y[1,t] + y[0,t]*D[y[1,t],t] + (y[1,t])^2*y[0,t] +` ... etc. Now I wish to define new functions indexed by `i`, call them `A[i]`, that collect all terms from the expression above such that the sum of the indices of the factors in each term sums to `i`. In the above case for the terms shown we would have for example `A[0] = y[0,t]^2 + D[y[0,t],t]*y[0,t]` `A[1] = y[0,t]*y[1,t] + y[0,t]*D[y[1,t],t]` `A[2] = (y[1,t])^2*y[0,t]` How can I get mathematica to assign these terms to these new functions automatically for all `i`? Note: If there is a better way to be indexing functions also feel free to suggest. Answer:
Since [`Show`](http://reference.wolfram.com/language/ref/Show) uses the [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) setting from the first plot, you can just set your plot range when defining the first plot: ``` p1=LogLogPlot[ RO, {t,0.00001,0.05}, PlotRange -> {{10^-5, 10^-4}, All}, PlotStyle->{Purple} ]; Show[p1, p2] ``` or you can use a dummy plot with the desired plot range: ``` p0 = LogLogPlot[None, {t, 10^-5, 10^-4}]; Show[p0, p1, p2] ``` If you really want to set the [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) using a [`Show`](http://reference.wolfram.com/language/ref/Show) option, than you need to realize that the [`Graphics`](http://reference.wolfram.com/language/ref/Graphics) objects produced by `p1` and `p2` don't know that "Log" scaling functions were used. So, you need to adjust the desired [`PlotRange`](http://reference.wolfram.com/language/ref/PlotRange) accordingly: ``` Show[p1, p2, PlotRange -> {Log @ {10^-5, 10^-4}, All}] ```
Your syntax is incorrect, it should be ``` Show[{p1,p2},PlotRange->{{x_min,x_max},{y_min,y_max}}] ``` If you want all in y, you can do: ``` Show[{p1,p2},PlotRange->{{10^(-5),10^(-4)},All}] ```
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
Use [`SimpleDateFormat`](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy [`Date`](http://download.oracle.com/javase/6/docs/api/java/util/Date.html) and use another one to format the parsed `Date` to a string in another pattern. ``` String string1 = "Mon Sep 14 15:24:40 UTC 2009"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1); String string2 = new SimpleDateFormat("d/M/yyyy").format(date); System.out.println(string2); // 14/9/2009 ```
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
You can use SimpleDateFormat class to convert the string you have to a date object. The date format can be given in the constructor. The format method converts the string to a date object. After getting the date object, you can format it in the way you want.
One liner in java 8 and above. ``` String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy")); ```
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
Use [`SimpleDateFormat`](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy [`Date`](http://download.oracle.com/javase/6/docs/api/java/util/Date.html) and use another one to format the parsed `Date` to a string in another pattern. ``` String string1 = "Mon Sep 14 15:24:40 UTC 2009"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1); String string2 = new SimpleDateFormat("d/M/yyyy").format(date); System.out.println(string2); // 14/9/2009 ```
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
One liner in java 8 and above. ``` String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy")); ```
``` Date d = new Date("Mon Sep 14 15:24:40 UTC 2009"); SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy"); String s = new String(f.format(d)); ```
Question: I have the following string: ``` Mon Sep 14 15:24:40 UTC 2009 ``` I need to format it into a string like this: ``` 14/9/2009 ``` How do I do it in Java? Answer:
Use [`SimpleDateFormat`](http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) (click the javadoc link to see patterns) to parse the string in one pattern to a fullworthy [`Date`](http://download.oracle.com/javase/6/docs/api/java/util/Date.html) and use another one to format the parsed `Date` to a string in another pattern. ``` String string1 = "Mon Sep 14 15:24:40 UTC 2009"; Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1); String string2 = new SimpleDateFormat("d/M/yyyy").format(date); System.out.println(string2); // 14/9/2009 ```
One liner in java 8 and above. ``` String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy")); ```
Question: [Error Message Picture](https://i.stack.imgur.com/kkbkN.png) I basically followed the instructions from the below link EXACTLY and I'm getting this damn error? I have no idea what I'm supposed to do, wtf? Do I need to create some kind of persisted method?? There were several other questions like this and after reading ALL of them they were not helpful at ALL. Please help. <https://github.com/zquestz/omniauth-google-oauth2> Omniauths Controller ``` class OmniauthCallbacksController < Devise::OmniauthCallbacksController def google_oauth2 # You need to implement the method below in your model (e.g. app/models/user.rb) @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" sign_in_and_redirect @user, :event => :authentication else session["devise.google_data"] = request.env["omniauth.auth"].except(:extra) #Removing extra as it can overflow some session stores redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n") end end end ``` User model code snippet ``` def self.from_omniauth(access_token) data = access_token.info user = User.where(:email => data["email"]).first # Uncomment the section below if you want users to be created if they don't exist # unless user # user = User.create(name: data["name"], # email: data["email"], # password: Devise.friendly_token[0,20] # ) # end user end ``` Answer:
Changed the bottom portion to: ``` def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.name = auth.info.name # assuming the user model has a name end end ``` ran rails g migration AddOmniauthToUsers provider:string uid:string Then it went to Successfully authenticated from Google account. So I believe it works now. I think maybe the issue was I needed to add the provider and uid to the user database model?
The persisted? method is checking whether or not the user exists thereby returning nil value if no such record exists and your user model is not creating new ones. So by uncommenting the code from the example to this: ``` def self.from_omniauth(access_token) data = access_token.info user = User.where(:email => data["email"]).first # creates a new user if user email does not exist. unless user user = User.create(name: data["name"], email: data["email"], password: Devise.friendly_token[0,20] ) end user end ``` Should solve the problem of checking to see if the user exists or creating a new user.
Question: I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks. Answer:
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
I think the session items are client sided. You can create a query to count the open connections (hence you're working with a MySQL database.) Another option is to use external software (I use the tawk.to helpchat, which shows the amount of users visiting a page in realtime). You could maybe use that, making the supportchat invisible, and only putting it on paging which are accesible for loggedin users. OR Execute an update query which adds/substracts from a column in your database (using the onStart and OnEnd hooks).
Question: I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks. Answer:
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
That is the problem that you cannot do it using *Session[]* variables. You need to be using a database (or a central data source to store the total number of active users). For example, you can see in your application, when the application starts there is no `Application["UsersOnline"]` variable, you create it at the very instance. That is why, each time the application is started, the variable is initialized with a *new value*; always *1*. You can create a separate table for your application, and inside it you can then create a column to contain *OnlineUsers* value. Which can be then incremented each time the app start event is triggered. ``` public void Session_OnStart() { Application.Lock(); Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; // At this position, execute an SQL command to update the value Application.UnLock(); } ``` Otherwise, for every user the session variable would have a new value, and you would not be able to accomplish this. Session variables were never designed for such purpose, you can access the variables, but you cannot rely on them for such a task. You can get more guidance about SQL commands in .NET framework, from MSDN's [SqlClient namespace library](https://msdn.microsoft.com/en-us/library/system.data.sqlclient%28v=vs.110%29.aspx).
Question: I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks. Answer:
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Perhaps I am missing something, but why not something like this: ``` public void Session_OnStart() { Application.Lock(); if (Application["UsersOnline"] == null ) { Application["UsersOnline"] = 0 } Application["UsersOnline"] = (int)Application["UsersOnline"] + 1; Application.UnLock(); ``` }
Question: I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks. Answer:
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Maybe I'm missing something, but is there a reason you don't just want to use something like Google Analytics? Unless you're looking for more queryable data, in which case I'd suggest what others have; store the login count to a data store. Just keep in mind you also have to have something to decrement that counter when the user either logs out or their session times out.
Question: I read [this](https://stackoverflow.com/questions/5842903/block-tridiagonal-matrix-python), but I wasn't able to create a (N^2 x N^2) - matrix **A** with (N x N) - *matrices* **I** on the lower and upper side-diagonal and **T** on the diagonal. I tried this ``` def prep_matrix(N): I_N = np.identity(N) NV = zeros(N*N - 1) # now I want NV[0]=NV[1]=...=NV[N-1]:=I_N ``` but I have no idea how to fill NV with my matrices. What can I do? I found a lot on how to create tridiagonal matrices with scalars, but not with matrix blocks. Answer:
Dirty, hacky, inefficient, solution (assumes use of forms authentication): ``` public void Global_BeginRequest(object sender, EventArgs e) { if( Context.User != null && !String.IsNullOrWhiteSpace(Context.User.Identity.Name) && Context.Session != null && Context.Session["IAMTRACKED"] == null ) { Context.Session["IAMTRACKED"] = new object(); Application.Lock(); Application["UsersLoggedIn"] = Application["UsersLoggedIn"] + 1; Application.UnLock(); } } ``` At a high level, this works by, on every request, checking if the user is logged in and, if so, tags the user as logged in and increments the login. This assumes users cannot log out (if they can, you can add a similar test for users who are logged out and tracked). This is a horrible way to solve your problem, but it's a working proto-type which demonstrates that your problem is solvable. Note that this understates logins substantially after an application recycle; logins are much longer term than sessions.
Try this. It may help you. ``` void Application_Start(object sender, EventArgs e) { Application["cnt"] = 0; Application["onlineusers"] = 0; // Code that runs on application startup } void Session_Start(object sender, EventArgs e) { Application.Lock(); Application["cnt"] = (int)Application["cnt"] + 1; if(Session["username"] != null) { Application["onlineusers"] = (int)Application["onlineusers"] + 1; } else { Application["onlineusers"] = (int)Application["onlineusers"] - 1; } Application.UnLock(); // Code that runs when a new session is started } ``` now you can display the number of users(Without Loggedin): ``` <%=Application["cnt"].ToString()%> ``` and number of online users: ``` <%=Application["onlineusers"].ToString()%> ```
Question: I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way? Answer:
If using Rails 4.2, you can set the placeholder attribute to true: ``` = f.text_field :first_name, placeholder: true ``` and specify the placeholder text in the locale file like this: ``` en: helpers: placeholder: user: first_name: "Your name" ```
You can view the source on render at <http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label> to see how Rails does it. It probably doesn't get a lot better than you have, but you could probably swipe some of Rail's logic and stick it in a helper, if you have a lot of them to do. Alternatively, you may consider using a custom form builder to remove some of the repetition in your whole form, not just placeholders.
Question: I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way? Answer:
With Rails >= 4.2, you can set the placeholder attribute to true `= f.text_field :first_name, placeholder: true` and in your local file (e.g. en.yml): ``` ru: activerecord: attributes: user: first_name: Your name ``` otherwise (Rails >= 3.0) I think you can write something like this: ``` = f.text_field :attr, placeholder: "#{I18n.t 'activerecord.attributes.user.first_name'}" ```
You can view the source on render at <http://rubydoc.info/docs/rails/ActionView/Helpers/Tags/Label> to see how Rails does it. It probably doesn't get a lot better than you have, but you could probably swipe some of Rail's logic and stick it in a helper, if you have a lot of them to do. Alternatively, you may consider using a custom form builder to remove some of the repetition in your whole form, not just placeholders.
Question: I want Rails to automatically translate placeholder text like it does with form labels. How can I do this? Form labels are translated automatically like this: ``` = f.text_field :first_name ``` This helper uses the locale file: ``` en: active_model: models: user: attributes: first_name: Your name ``` Which outputs this HTML ``` <label for="first_name">Your name</label> ``` How can I make it so the placeholder is translated? Do I have to type the full scope like this: ``` = f.text_field :first_name, placeholder: t('.first_name', scope: 'active_model.models.user.attributes.first_name') ``` Is there are easier way? Answer:
If using Rails 4.2, you can set the placeholder attribute to true: ``` = f.text_field :first_name, placeholder: true ``` and specify the placeholder text in the locale file like this: ``` en: helpers: placeholder: user: first_name: "Your name" ```
With Rails >= 4.2, you can set the placeholder attribute to true `= f.text_field :first_name, placeholder: true` and in your local file (e.g. en.yml): ``` ru: activerecord: attributes: user: first_name: Your name ``` otherwise (Rails >= 3.0) I think you can write something like this: ``` = f.text_field :attr, placeholder: "#{I18n.t 'activerecord.attributes.user.first_name'}" ```
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
You can open the background page's console if you click on the "background.html" link in the extensions list. To access the background page that corresponds to your extensions open `Settings / Extensions` or open a new tab and enter `chrome://extensions`. You will see something like this screenshot. ![Chrome extensions dialogue](https://i.stack.imgur.com/Xulbx.png) Under your extension click on the link `background page`. This opens a new window. For the **[context menu sample](https://developer.chrome.com/extensions/samples#context-menus-sample)** the window has the title: `_generated_background_page.html`.
To answer your question directly, when you call `console.log("something")` from the background, this message is logged, to the background page's console. To view it, you may go to `chrome://extensions/` and click on that `inspect view` under your extension. When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
The simplest solution would be to add the following code on the top of the file. And than you can use all full [Chrome console api](https://developers.google.com/chrome-developer-tools/docs/console-api) as you would normally. ``` console = chrome.extension.getBackgroundPage().console; // for instance, console.assert(1!=1) will return assertion error // console.log("msg") ==> prints msg // etc ```
In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around: You can access other extension pages (i.e. options page, popup page) from *within the background page/script* with the `chrome.extension.getViews()` call. As described [here](https://developer.chrome.com/extensions/background_pages). ``` // overwrite the console object with the right one. var optionsPage = ( chrome.extension.getViews() && (chrome.extension.getViews().length > 1) ) ? chrome.extension.getViews()[1] : null; // safety precaution. if (optionsPage) { var console = optionsPage.console; } ```
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
You can still use console.log(), but it gets logged into a separate console. In order to view it - right click on the extension icon and select "Inspect popup".
To view console while debugging your chrome extension, you should use the `chrome.extension.getBackgroundPage();` API, after that you can use `console.log()` as usual: ``` chrome.extension.getBackgroundPage().console.log('Testing'); ``` This is good when you use multiple time, so for that you create custom function: ``` const console = { log: (info) => chrome.extension.getBackgroundPage().console.log(info), }; console.log("foo"); ``` you only use `console.log('learnin')` everywhere
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
Curently with Manifest 3 and service worker, you just need to go to `Extensions Page / Details` and just click `Inspect Views / Service Worker`.
To view console while debugging your chrome extension, you should use the `chrome.extension.getBackgroundPage();` API, after that you can use `console.log()` as usual: ``` chrome.extension.getBackgroundPage().console.log('Testing'); ``` This is good when you use multiple time, so for that you create custom function: ``` const console = { log: (info) => chrome.extension.getBackgroundPage().console.log(info), }; console.log("foo"); ``` you only use `console.log('learnin')` everywhere
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
``` const log = chrome.extension.getBackgroundPage().console.log; log('something') ``` Open log: * Open: chrome://extensions/ * Details > Background page
Curently with Manifest 3 and service worker, you just need to go to `Extensions Page / Details` and just click `Inspect Views / Service Worker`.
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
You can open the background page's console if you click on the "background.html" link in the extensions list. To access the background page that corresponds to your extensions open `Settings / Extensions` or open a new tab and enter `chrome://extensions`. You will see something like this screenshot. ![Chrome extensions dialogue](https://i.stack.imgur.com/Xulbx.png) Under your extension click on the link `background page`. This opens a new window. For the **[context menu sample](https://developer.chrome.com/extensions/samples#context-menus-sample)** the window has the title: `_generated_background_page.html`.
You can still use console.log(), but it gets logged into a separate console. In order to view it - right click on the extension icon and select "Inspect popup".
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
Any *extension page* (except [content scripts](http://developer.chrome.com/extensions/content_scripts.html)) has direct access to the background page via [`chrome.extension.getBackgroundPage()`](http://developer.chrome.com/extensions/extension.html#method-getBackgroundPage). That means, within the [popup page](http://developer.chrome.com/extensions/browserAction.html), you can just do: ``` chrome.extension.getBackgroundPage().console.log('foo'); ``` To make it easier to use: ``` var bkg = chrome.extension.getBackgroundPage(); bkg.console.log('foo'); ``` Now if you want to do the same within [content scripts](http://developer.chrome.com/extensions/content_scripts.html) you have to use [Message Passing](http://developer.chrome.com/extensions/messaging.html) to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the [Message Passing](http://developer.chrome.com/extensions/messaging.html) page for you to check out. Hope that clears everything.
To get a console log from a background page you need to write the following code snippet in your background page background.js - ``` chrome.extension.getBackgroundPage().console.log('hello'); ``` Then load the extension and inspect its background page to see the console log. Go ahead!!
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
The simplest solution would be to add the following code on the top of the file. And than you can use all full [Chrome console api](https://developers.google.com/chrome-developer-tools/docs/console-api) as you would normally. ``` console = chrome.extension.getBackgroundPage().console; // for instance, console.assert(1!=1) will return assertion error // console.log("msg") ==> prints msg // etc ```
`chrome.extension.getBackgroundPage()` I get `null` and accrouding [documentation](https://developer.chrome.com/docs/extensions/mv3/mv3-migration-checklist/), > > Background pages are replaced by service workers in MV3. > > > * Replace `background.page` or `background.scripts` with `background.service_worker` in manifest.json. Note that the service\_worker field takes a string, not an array of strings. > > > manifest.json ```json { "manifest_version": 3, "name": "", "version": "", "background": { "service_worker": "background.js" } } ``` anyway, I don't know how to use `getBackgroundPage`, but I found another solution as below, Solution -------- use the [chrome.scripting.executeScript](https://developer.chrome.com/docs/extensions/reference/scripting/#runtime-functions) So you can inject any script or file. You can directly click inspect (F12) and can debug the function. for example ```js chrome.commands.onCommand.addListener((cmdName) => { switch (cmdName) { case "show-alert": chrome.storage.sync.set({msg: cmdName}) // You can not get the context on the function, so using the Storage API to help you. // https://developer.chrome.com/docs/extensions/reference/storage/ chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{ chrome.scripting.executeScript({ target: {tabId: tab.id}, function: () => { chrome.storage.sync.get(['msg'], ({msg})=> { console.log(`${msg}`) alert(`Command: ${msg}`) }) } }) }) break default: alert(`Unknown Command: ${cmdName}`) } }) ``` I create an [open-source](https://github.com/CarsonSlovoka/chrome/tree/f9d37b5/tutorials/extensions/console-alert) for you reference.
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
``` const log = chrome.extension.getBackgroundPage().console.log; log('something') ``` Open log: * Open: chrome://extensions/ * Details > Background page
In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around: You can access other extension pages (i.e. options page, popup page) from *within the background page/script* with the `chrome.extension.getViews()` call. As described [here](https://developer.chrome.com/extensions/background_pages). ``` // overwrite the console object with the right one. var optionsPage = ( chrome.extension.getViews() && (chrome.extension.getViews().length > 1) ) ? chrome.extension.getViews()[1] : null; // safety precaution. if (optionsPage) { var console = optionsPage.console; } ```
Question: If I call `console.log('something');` from the popup page, or any script included off that it works fine. However as the background page is not directly run off the popup page it is not included in the console. Is there a way that I can get `console.log()`'s in the background page to show up in the console for the popup page? is there any way to, from the background page call a function in the popup page? Answer:
Try this, if you want to log to the active page's console: ``` chrome.tabs.executeScript({ code: 'console.log("addd")' }); ```
To view console while debugging your chrome extension, you should use the `chrome.extension.getBackgroundPage();` API, after that you can use `console.log()` as usual: ``` chrome.extension.getBackgroundPage().console.log('Testing'); ``` This is good when you use multiple time, so for that you create custom function: ``` const console = { log: (info) => chrome.extension.getBackgroundPage().console.log(info), }; console.log("foo"); ``` you only use `console.log('learnin')` everywhere
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
In steps. First we do a rolling `diff` on your index, anything that is greater than 1 we code as True, we then apply a `cumsum` to create a new group per sequence. ``` 45 0 46 0 47 0 51 1 52 1 ``` --- Next, we use the `groupby` method with the new sequences to create your nested list inside a list comprehension Setup. ------ ``` df = pd.DataFrame([1,2,3,4,5],columns=['A'],index=[45,46, 47, 51, 52]) A 45 1 46 2 47 3 51 4 52 5 ``` --- ``` df['grp'] = df.assign(idx=df.index)['idx'].diff().fillna(1).ne(1).cumsum() idx = [i.index.tolist() for _,i in df.groupby('grp')] [[45, 46, 47], [51, 52]] ```
The issue is with this line ``` sequences[seq] = [index] ``` You are trying to assign the list an index which is not created. Instead do this. ``` sequences.append([index]) ```
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
You can use this: ``` s_index=df.index.to_series() l = s_index.groupby(s_index.diff().ne(1).cumsum()).agg(list).to_numpy() ``` Output: ``` l[0] [45, 46, 47] ``` and ``` l[1] [51, 52] ```
The issue is with this line ``` sequences[seq] = [index] ``` You are trying to assign the list an index which is not created. Instead do this. ``` sequences.append([index]) ```
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
The issue is with this line ``` sequences[seq] = [index] ``` You are trying to assign the list an index which is not created. Instead do this. ``` sequences.append([index]) ```
I use the diff to find when the index value diff changes greater than 1. I iterate the tuples and access by index their values. ``` index=[45,46,47,51,52] price=[3909.0,3908.75,3908.50,3907.75,3907.5] count=[8,8,8,8,8] df=pd.DataFrame({'index':index,'price':price,'count':count}) df['diff']=df['index'].diff().fillna(0) print(df) result_list=[[]] seq=0 for row in df.itertuples(): index=row[1] diff=row[4] if diff<=1: result_list[seq].append(index) else: seq+=1 result_list.insert(1,[index]) print(result_list) output: [[45, 46, 47], [51, 52]] ```
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
You can use this: ``` s_index=df.index.to_series() l = s_index.groupby(s_index.diff().ne(1).cumsum()).agg(list).to_numpy() ``` Output: ``` l[0] [45, 46, 47] ``` and ``` l[1] [51, 52] ```
In steps. First we do a rolling `diff` on your index, anything that is greater than 1 we code as True, we then apply a `cumsum` to create a new group per sequence. ``` 45 0 46 0 47 0 51 1 52 1 ``` --- Next, we use the `groupby` method with the new sequences to create your nested list inside a list comprehension Setup. ------ ``` df = pd.DataFrame([1,2,3,4,5],columns=['A'],index=[45,46, 47, 51, 52]) A 45 1 46 2 47 3 51 4 52 5 ``` --- ``` df['grp'] = df.assign(idx=df.index)['idx'].diff().fillna(1).ne(1).cumsum() idx = [i.index.tolist() for _,i in df.groupby('grp')] [[45, 46, 47], [51, 52]] ```
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
In steps. First we do a rolling `diff` on your index, anything that is greater than 1 we code as True, we then apply a `cumsum` to create a new group per sequence. ``` 45 0 46 0 47 0 51 1 52 1 ``` --- Next, we use the `groupby` method with the new sequences to create your nested list inside a list comprehension Setup. ------ ``` df = pd.DataFrame([1,2,3,4,5],columns=['A'],index=[45,46, 47, 51, 52]) A 45 1 46 2 47 3 51 4 52 5 ``` --- ``` df['grp'] = df.assign(idx=df.index)['idx'].diff().fillna(1).ne(1).cumsum() idx = [i.index.tolist() for _,i in df.groupby('grp')] [[45, 46, 47], [51, 52]] ```
I use the diff to find when the index value diff changes greater than 1. I iterate the tuples and access by index their values. ``` index=[45,46,47,51,52] price=[3909.0,3908.75,3908.50,3907.75,3907.5] count=[8,8,8,8,8] df=pd.DataFrame({'index':index,'price':price,'count':count}) df['diff']=df['index'].diff().fillna(0) print(df) result_list=[[]] seq=0 for row in df.itertuples(): index=row[1] diff=row[4] if diff<=1: result_list[seq].append(index) else: seq+=1 result_list.insert(1,[index]) print(result_list) output: [[45, 46, 47], [51, 52]] ```
Question: I am working on a project where we frequently work with a list of usernames. We also have a function to take a username and return a dataframe with that user's data. E.g. ``` users = c("bob", "john", "michael") get_data_for_user = function(user) { data.frame(user=user, data=sample(10)) } ``` We often: 1. Iterate over each element of `users` 2. Call `get_data_for_user` to get their data 3. `rbind` the results into a single dataerame I am currently doing this in a purely imperative way: ``` ret = get_data_for_user(users[1]) for (i in 2:length(users)) { ret = rbind(ret, get_data_for_user(users[i])) } ``` This works, but my impression is that all the cool kids are now using libraries like `purrr` to do this in a single line. I am fairly new to `purrr`, and the closest I can see is using `map_df` to convert the vector of usernames to a vector of dataframes. I.e. ``` dfs = map_df(users, get_data_for_user) ``` That is, it seems like I would still be on the hook for writing a loop to do the `rbind`. I'd like to clarify whether my solution (which works) is currently considered best practice in R / amongst users of the tidyverse. Thanks. Answer:
You can use this: ``` s_index=df.index.to_series() l = s_index.groupby(s_index.diff().ne(1).cumsum()).agg(list).to_numpy() ``` Output: ``` l[0] [45, 46, 47] ``` and ``` l[1] [51, 52] ```
I use the diff to find when the index value diff changes greater than 1. I iterate the tuples and access by index their values. ``` index=[45,46,47,51,52] price=[3909.0,3908.75,3908.50,3907.75,3907.5] count=[8,8,8,8,8] df=pd.DataFrame({'index':index,'price':price,'count':count}) df['diff']=df['index'].diff().fillna(0) print(df) result_list=[[]] seq=0 for row in df.itertuples(): index=row[1] diff=row[4] if diff<=1: result_list[seq].append(index) else: seq+=1 result_list.insert(1,[index]) print(result_list) output: [[45, 46, 47], [51, 52]] ```
Question: I'm using jQuery Treeview. Is there's a way to populate a children node in a specific parent on onclick event? Please give me some advise or simple sample code to do this. Answer:
You can trigger the change event yourself in the `inputvalue` function: ``` function inputvalue(){ $("#inputid").val("bla").change(); } ``` Also notice the correction of your syntax... in jQuery, `val` is a function that takes a string as a parameter. You can't assign to it as you are doing. Here is an [example fiddle](http://jsfiddle.net/sm4cD/) showing the above in action.
Your function has an error. Try this: ``` function inputvalue(){ $("#inputid").val()="bla" } ``` EDIT My function is also wrong as pointed in comments. The correct is: Using pure javascript ``` function inputvalue(){ document.getElementById("inputid").value ="bla"; } ``` Using jQuery ``` function inputvalue(){ $("#inputid").val("bla"); } ```
Question: I have a layout as follows for mobile .. ``` +------------------------+ | (col-md-6) Div 1 | +------------------------+ | (col-md-6) Div 2 | +------------------------+ | (col-md-6) Div 3 | +------------------------+ | (col-md-6) Div 4 | +------------------------+ | (col-md-6) Div 5 | +------------------------+ | (col-md-6) Div 6 | +------------------------+ | (col-md-6) Div 7 | +------------------------+ ``` When the screen widens or goes on tablet the layout changes as expected to ... ``` +------------------------+------------------------+ | (col-md-6) Div 1 | (col-md-6) Div 2 | +------------------------+------------------------+ | (col-md-6) Div 3 | (col-md-6) Div 4 | +------------------------+------------------------+ | (col-md-6) Div 5 | (col-md-6) Div 6 | +------------------------+------------------------+ | (col-md-6) Div 7 | +------------------------+ ``` But I would like the layout to look like .. ``` +------------------------+------------------------+ | (col-md-6) Div 1 | (col-md-6) Div 5 | +------------------------+------------------------+ | (col-md-6) Div 2 | (col-md-6) Div 6 | +------------------------+------------------------+ | (col-md-6) Div 3 | (col-md-6) Div 7 | +------------------------+------------------------+ | (col-md-6) Div 4 | +------------------------+ ``` Is this possible? Answer:
The problem is not linked to data.frame, but simply that you cannot have in the same vector objects of class numeric and objects of class character. It is NOT possible. The person who started the project before you should not have used the string "Error" to indicate a missing data. Instead, you should use NA : ``` x=c(1,2) y=c("Error","Error") c(x,y) # Here the result is coerced as character automatically by R. There is no way to avoid that. ``` Instead you should use ``` c(x,NA) # NA is accepted in a vector of numeric ``` **Note:** you should think a data.frame as a list of vectors which are the columns of the data.frame. Hence if you have 2 columns, *each column is an independent vector* and hence it is possible to have different class per column: ``` x <- c(1,2) y <- c("Error","Error") df=data.frame(x=x,y=y,stringsAsFactors=FALSE) class(df$x) class(df$y) ``` Now if you try to transpose the data.frame, of course the new column vectors will become c(1,"Error") and c(2,"Error") that will be coerced as character as we have seen before. ``` t(df) ```
You could do this: ``` x <- 1 y <- c("Error","Error") df <- data.frame(c(list(), x, y), stringsAsFactors = FALSE) > str(df) 'data.frame': 1 obs. of 3 variables: $ X1 : num 1 $ X.Error. : chr "Error" $ X.Error..1: chr "Error" ``` You just have to set proper column names.
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
As mentioned in the comment, `True/False` values are also the instances of `int` in Python, so you can add one more condition to check if the value is not an instance of `bool`: ```py >>> lst = [True, 19, 19.5, False] >>> [x for x in lst if isinstance(x, int) and not isinstance(x, bool)] [19] ```
`bool` is a subclass of `int`, therefore `True` is an instance of `int`. * `False` equal to `0` * `True` equal to `1` you can use another check or `if type(i) is int`
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
As mentioned in the comment, `True/False` values are also the instances of `int` in Python, so you can add one more condition to check if the value is not an instance of `bool`: ```py >>> lst = [True, 19, 19.5, False] >>> [x for x in lst if isinstance(x, int) and not isinstance(x, bool)] [19] ```
Use `type` comparison instead: ``` _list = [i for i in _list if type(i) is int] ``` Side note: avoid using `list` as the variable name since it's the Python builtin name for the [`list`](https://docs.python.org/3/library/stdtypes.html#list) type.
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
As mentioned in the comment, `True/False` values are also the instances of `int` in Python, so you can add one more condition to check if the value is not an instance of `bool`: ```py >>> lst = [True, 19, 19.5, False] >>> [x for x in lst if isinstance(x, int) and not isinstance(x, bool)] [19] ```
You could try using a conditional statement within your code that checks for isinstance(i, int) and only appends i to the list if that condition is True.
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
Use `type` comparison instead: ``` _list = [i for i in _list if type(i) is int] ``` Side note: avoid using `list` as the variable name since it's the Python builtin name for the [`list`](https://docs.python.org/3/library/stdtypes.html#list) type.
`bool` is a subclass of `int`, therefore `True` is an instance of `int`. * `False` equal to `0` * `True` equal to `1` you can use another check or `if type(i) is int`
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
`bool` is a subclass of `int`, therefore `True` is an instance of `int`. * `False` equal to `0` * `True` equal to `1` you can use another check or `if type(i) is int`
You could try using a conditional statement within your code that checks for isinstance(i, int) and only appends i to the list if that condition is True.
Question: I have a dataframe which looks like this: ``` val "ID: abc\nName: John\nLast name: Johnson\nAge: 27" "ID: igb1\nName: Mike\nLast name: Jackson\nPosition: CEO\nAge: 42" ... ``` I would like to extract Name, Position and Age from those values and turn them into separate columns to get dataframe which looks like this: ``` Name Position Age John NaN 27 Mike CEO 42 ``` How could I do that? Answer:
Use `type` comparison instead: ``` _list = [i for i in _list if type(i) is int] ``` Side note: avoid using `list` as the variable name since it's the Python builtin name for the [`list`](https://docs.python.org/3/library/stdtypes.html#list) type.
You could try using a conditional statement within your code that checks for isinstance(i, int) and only appends i to the list if that condition is True.
Question: I'm adding a new model to rails\_admin. The list page displays datetime fields correctly, even without any configuration. But the detail (show) page for a given object does not display datetimes. How do I configure rails\_admin to show datetime fields on the show page? Model file: alert\_recording.rb: ``` class AlertRecording < ActiveRecord::Base attr_accessible :user_id, :admin_id, :message, :sent_at, :acknowledged_at, :created_at, :updated_at end ``` Rails\_admin initializer file: ``` ... config.included_models = [ AlertRecording ] ... config.model AlertRecording do field :sent_at, :datetime field :acknowledged_at, :datetime field :message field :user field :admin field :created_at, :datetime field :updated_at, :datetime list do; end show do; end end ``` What's the correct way to configure the datetime fields so I see them on the show view? Answer:
These fields are hidden by default as you can see here: <https://github.com/sferik/rails_admin/blob/ead1775c48754d6a99c25e4d74494a60aee9b4d1/lib/rails_admin/config.rb#L277> You can overwrite this setting on your config initializer, just open the file `config/initializers/rails_admin.rb` and add this line to it: `config.default_hidden_fields = []` or something like this: `config.default_hidden_fields = [:id, :my_super_top_secret_field]` That way you doesn't need to do a config to every model in your app ;) **BUT!!!** This will show these fields in *edit* action, so it's a good idea to hide id, created\_at and updated\_at in this case. To do this you can assign a hash on this setting, like so: ``` config.default_hidden_fields = { show: [], edit: [:id, :created_at, :updated_at] } ``` And *voilà*, you have what you want. ;)
What you have in there for `sent_at` and `acknowledged_at` should work. Make sure the records you are trying to "show" have dates present for these fields. For `created_at` and `updated_at`, try [this](https://github.com/sferik/rails_admin/issues/994): ``` config.model AlertRecording do field :created_at configure :created_at do show end field :updated_at, :datetime configure :updated_at do show end end ```
Question: Trying to work out where I have screwed up with trying to create a count down timer which displays seconds and milliseconds. The idea is the timer displays the count down time to an NSString which updates a UILable. The code I currently have is ``` -(void)timerRun { if (self.timerPageView.startCountdown) { NSLog(@"%i",self.timerPageView.xtime); self.timerPageView.sec = self.timerPageView.sec - 1; seconds = (self.timerPageView.sec % 60) % 60 ; milliseconds = (self.timerPageView.sec % 60) % 1000; NSString *timerOutput = [NSString stringWithFormat:@"%i:%i", seconds, milliseconds]; self.timerPageView.timerText.text = timerOutput; if (self.timerPageView.resetTimer == YES) { [self setTimer]; } } else { } } -(void)setTimer{ if (self.timerPageView.xtime == 0) { self.timerPageView.xtime = 60000; } self.timerPageView.sec = self.timerPageView.xtime; self.timerPageView.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerRun) userInfo:Nil repeats:YES]; self.timerPageView.resetTimer = NO; } int seconds; int milliseconds; int minutes; } ``` Anyone got any ideas what I am doing wrong? Answer:
You have a timer that will execute roughly 100 times per second (interval of 0.01). You decrement a value by `1` each time. Therefore, your `self.timerPageView.sec` variable appears to be hundredths of a second. To get the number of seconds, you need to divide this value by 100. To get the number of milliseconds, you need to multiply by 10 then modulo by 1000. ``` seconds = self.timerPageView.sec / 100; milliseconds = (self.timerPageView.sec * 10) % 1000; ``` Update: Also note that your timer is highly inaccurate. The timer will not repeat EXACTLY every hundredth of a second. It may only run 80 times per second or some other inexact rate. A better approach would be to get the current time at the start. Then inside your `timerRun` method you get the current time again. Subtract the two numbers. This will give the actual elapsed time. Use this instead of decrementing a value each loop.
These calculations look pretty suspect: ``` seconds = (self.timerPageView.sec % 60) % 60 ; milliseconds = (self.timerPageView.sec % 60) % 1000; ``` You are using int type calculations (pretty sketchy in their implementation) on a float value for seconds. ``` NSUInteger seconds = (NSUInteger)(self.timerPageView.sec * 100); //convert to an int NSUInteger milliseconds = (NSUInteger) ((self.timerPageView.sec - seconds)* 1000.); ```