qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
13,769,762 | Our UX asks for a button to start multi-choice mode. this would do the same thing as long-pressing on an item, but would have nothing selected initially.
What I'm seeing in the code is that I cannot enter multi-choice mode mode unless I have something selected, and if I unselect that item, multi-choice mode exits (contextual action bar closes).
I've also tried this in other apps (gmail), and it works the same way.
Is there a way to be in multi-select mode, with no items selected? | 2012/12/07 | [
"https://Stackoverflow.com/questions/13769762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337455/"
] | It's very hacky, but I've done this by having an item selected, but making it look like it's not selected, by making the background temporarily transparent. When an item is then selected by the user, the secretly-selected item is deselected and the background restored to normal. Or, if it's the secretly-selected item which is selected (thus deselecting it), I reselect it, then set a boolean to stop it happening again.
I also had to use a counter in onItemCheckedStateChanged, as I was changing the checked state of the secret item from within that callback, resulting in a loop.
Probably not an ideal solution for all cases, but I don't think there's another way to do it at the moment, since [AbsListView can't easily be extended.](https://stackoverflow.com/questions/9637759/is-it-possible-to-extend-abslistview-to-make-new-listview-implementations)
Edit: if the screen orientation changes while the selected state of the selected item is hidden, it will suddenly be shown as being selected, so you have to make sure to save the fact that it should be hidden, and restore it after the listview is recreated. I had to use the View post() method to ensure the restoration happened after the listview had finished redrawing all its child items after the configuration change.
Edit: another potential issue is if the user tries to carry out an action while there are supposedly no items selected. As far as the application knows there *is* an item selected so it will carry out the action on that item, unless you make sure it doesn't. |
71,164,473 | does anyone have an example of how to remove the records from the table before starting or after finishing the tests?
My tests are working perfectly fine and all that remains is to automatically remove the records in the table. If anyone has an example link I would be very happy. | 2022/02/17 | [
"https://Stackoverflow.com/questions/71164473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18223187/"
] | You set the console log inside the printNumbers function.
Since the state update is async, you'd have to put the console.log inside the useEffect to be notified after an update. Something similar to:
```
useEffect(()=>{
console.log(numbers);
},[numbers,aNumber])
const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);
const printNumbers = ()=>{
setNumbers({...numbers, number2:aNumber});
}
``` |
62,287,390 | I am working on a web application at the moment that has a an api at the top level domain (mydomain.com) and an SPA at subdomain (spa.mydomain.com). In the SPA I have added,
`axios.defaults.withCredentials = true`
To login in I run the following code,
```
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/login', {email: this.email, password: this.password}).then(response => {
this.$router.push({ name: 'Account' });
});
});
```
The get request responds with a 204 as expected and the post request to login responds successfully too, at this point I get redirected and another GET is sent to /api/users/me at this point the server responds with a 401 unauthorized response.
I would have assumed that seen as though I can login everything would be working as expected but sadly not, the key bits of my `.env` file from my api are below to see if I am missing anything obvious.
`SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=.mydomain.com
SANCTUM_STATEFUL_DOMAINS=spa.mydomain.com`
My request headers look like this,
`Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Cookie: XSRF-TOKEN=eyJpdiI6InZDRTAvenNlRGhwdVNzY2p5VUFQeFE9PSIsInZhbHVlIjoiVzBLT0wyNTI2Vk5la3hiQ1M1TXpRU2pRQ3pXeGk1Nkc1eW5QN0F5ZjNFUmdIVmlaWGNqdXZVcU9UYUNVTzhXbiIsIm1hYyI6IjJmMmIyMjc4MzNkODA4ZDdlZjRhZTJhM2RlMTQ5NDg1MWM2MjdhMzdkMTFjZGNiMzdkMDM3YjNjNzM1ZmY5NjAifQ%3D%3D; at_home_club_session=eyJpdiI6ImxLYjlRNHplcGh1d2RVSEtnakxJNmc9PSIsInZhbHVlIjoiWnBjN0xheWlaNDdDUWZnZGxMUzlsM0VzbjZaZVdUSTBZL0R1WXRTTGp5emY0S2NodGZNN25hQmF1ajYzZzU3MiIsIm1hYyI6ImNlMWRmNWJhYmE1ODU3MzM1Y2Q4ZDI0MDIzNTU1OWQ4MDE3MGRiNTJjY2NjNmFmZDU5YzhjZTM4NGJlOGU5ZTkifQ%3D%3D; XSRF-TOKEN=eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ%3D%3D; at_home_club_session=eyJpdiI6IjZxWXZSYjdGWXU5SHBKSFFRdGQycWc9PSIsInZhbHVlIjoiU3RyTDdoNGJBUW93ck9CTmFjVFpjRTRxMVVwQzZmcjJJTXJUNFU0UUZVcnkzcWdBbzZxWjNvTWZrZmFuMXBrbSIsIm1hYyI6IjFkOTFiNDg5YmZjYmE0NGZiZDg3ZGY5ZDQyMDg2MGZjNzFlMmI0OTA1OGY2MzdkMmFmOGI0ZTlkOTE4ZDM0NWUifQ%3D%3D; XLtgHBp79G2IlVzFPoHViq4wcAV1TMveovlNr1V4=eyJpdiI6ImZiRThmNUpBb3N0Z21MVHJRMVIvRFE9PSIsInZhbHVlIjoiVDV5S2tDOTFNcElqc1NINVpsdi9Ibk04cFVSekkvSytvY01YUDFIbENhZkV3VnVTaHpOTjlwUjROVnFlMk96SWgwUlByZFU3MlA0YVhTelFDaEVTdndkQnczUFZ3bXJlVHpUTkZwb3Z2d1Z1VUI1STJkeG1ZMm13N0h3S282V2l3MmlvUmFrQXY4SXFFaHcrNjBucktJcmRmSk81UUtFcUFlOCtNaUZHelJpRmxkY2gyZVFOWWRUWTdqZ2NFYi85WlVBeFJ2bm5xU05IU3F1aE0ybXlzUnltRUh6eG1qZklaVW9GSDRsU3RMWmRrL242WjJ5VFZVa3dDTWtIN051SThUa0FjZDFsSXp6SmNSTWFWTDl5dk5IczFKcEpSWS9qZUZiMGVENTdKcjVrTlBITWRjV2dUY1RmcElNL0FUSzQxS0JGZFBzUWVha3ZIOVh6YWpTZnNZa202bHB1akQvakVHWTRZU1Z1WWFZZmxIcDN2bDZrek9JRHkybE01b3BlTWErYmhKK2xQN0FmTzhZS3M3bTBHUVJaSzhIdzBGWlc4Vjd1QVJCSFovZz0iLCJtYWMiOiI2ZWZlYWIwYzhlZjMyZjlkNTI0ZWJmYjFhMzExYTIxZTkyNDM1ODM3ODg1YjlmM2ZiOTVhMTMwYTAwYjk4NjhiIn0%3D
Host: mydomain.com
Origin: http://spa.mydomain.com
Referer: http://spa.mydomain.info/account
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
X-XSRF-TOKEN: eyJpdiI6ImhadVF0eHlEY3l4RWtnZk45MmVxZ2c9PSIsInZhbHVlIjoiRCs4QkNMRjBodzJKaFIvRVQwZUZlM3BzYmlJMGp0Y0E5RXdHdkYrblVzSzNPQTJZbE42ZlhlYllmWlg2a0ltMSIsIm1hYyI6IjA1NWU0ZjFiNDFjN2VkNjNiMzJiNjFlNTFiMjBmNWE3MzA4Yzk1YmJiNzdmZGUyZmZhNjcwYmQxZTYxYTBmY2QifQ==`
and my cors,
```
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
```
Everything works perfectly on localhost. | 2020/06/09 | [
"https://Stackoverflow.com/questions/62287390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57872/"
] | Turns out when our Azure DevOps instance was first set up, all our users set up Microsoft accounts with their company emails. Later when we finally stood up Azure AD but before we connected it to DevOps we added a new project and set the permissions for a few existing employees. For some reason the user permissions on the new DevOps project were listed as "aaduser" type instead of the standard "user" type (ms account) that all the users in other projects in DevOps had. In other words duplicate UPNs but different accounts (but sort of the same). What's weird is that DevOps managed to find the Azure AD user account before we even connected the two together services together.
We removed the offending users with the standard "user" type and re-added them so they were now all listed as "aaduser." We were then able to connect Azure AD. To be clear, this was all done on the DevOps side and had nothing to do with AD.
Not sure why it was finding Azure AD users when we weren't even connected to it yet. |
31,079,002 | I have a solution with a C# project of 'library' and a project 'JavaScript' after that compiled it generates a .winmd file being taken to another project. But this project is built on x86 and I need to compile for x64, to run the application in order x64 get the following error:
```
'WWAHost.exe' (Script): Loaded 'Script Code (MSAppHost/2.0)'.
Unhandled exception at line 25, column 13 in ms-appx://2c341884-5957-41b1-bb32-10e13dd434ba/js/default.js
0x8007000b - JavaScript runtime error: An attempt was made to load a program with an incorrect format.
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance()
WinRT information: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
at System.Runtime.InteropServices.WindowsRuntime.ManagedActivationFactory.ActivateInstance()
The program '[5776] WWAHost.exe' has exited with code -1 (0xffffffff).
``` | 2015/06/26 | [
"https://Stackoverflow.com/questions/31079002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It looks like you were making calls with no Access Token at all, to data that's publicly visible on Facebook.com
v1.0 of Facebook's Graph API was deprecated in April 2014 and scheduled for removal after 2015-04-30 - one of the changes between v1.0 and v2.0 was that in v2.0 all calls require an Access Token - the deprecation of v1.0 was phased and one of the last things to be removed was the ability to make tokenless calls - it's possible that's why you didn't notice this until recently
More info on the changelog here: <https://developers.facebook.com/docs/apps/changelog#v2_0> - under "Changes from v1.0 to v2.0"
You'll need to rewrite your app to make its API calls using an access token from a user who can see the content you're trying to create, or (possibly) using your app's access token (and given you had no token at all, you may also need to create an app ID for that purpose) |
334,167 | I am late game Alien Crossfire, attacking with gravitons aremed with [string disruptor](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#String_Disruptor).
Unfortunately, the others have gotten wise and are building everything [AAA](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Special_Ability#AAA_Tracking). In a way, that's good, as it is expensive, and diverts their resources.
However, I can no longer "one hit kill", and am losing gravitons.
Should I replace the weapons with [Psi attack](https://strategywiki.org/wiki/Sid_Meier%27s_Alpha_Centauri/Weapon#Psi_Attack)? | 2018/06/24 | [
"https://gaming.stackexchange.com/questions/334167",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/92813/"
] | Psi attack/defense is orthogonal to conventional weapons. Its result depends on *Morale* levels of attacking/defending units.
If an attacker/defender is a *Mind Worm*, they have their own class, plus both faction's *Planet (Green)* scores/attitudes largely affect the outcome of the fight.
**Answer:** see what's your faction's Morale and/or Green score.
You may also trick the system by changing your *Government/Economy* type before the attack. Say, if you possess some *Mind Worms* and you are planning to give them a victorious ride, switch to *Green* several turns before the planned invasion. Or to *Fundamentalist + Power* if you are planning Psi attacks with conventional units.
---
Personally, I *love* Green because if you are lucky enough, you can capture native life forms, making a considerable amount of your units Mind Worms **(Independent)** which means it requires no support from a home base, still performing as police in "at least one unit defending each Base" paradigm. |
43,377,941 | **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? | 2017/04/12 | [
"https://Stackoverflow.com/questions/43377941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5634399/"
] | 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.
>
>
> |
62,380,246 | 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? | 2020/06/15 | [
"https://Stackoverflow.com/questions/62380246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6009213/"
] | 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. |
12,881 | 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;
}
}
``` | 2015/06/24 | [
"https://arduino.stackexchange.com/questions/12881",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/10817/"
] | 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;
``` |
64,999,490 | 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
``` | 2020/11/25 | [
"https://Stackoverflow.com/questions/64999490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14704128/"
] | 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.
>
>
> |
21,657,910 | 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. | 2014/02/09 | [
"https://Stackoverflow.com/questions/21657910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999172/"
] | 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;
}
``` |
2,274,695 | 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? | 2010/02/16 | [
"https://Stackoverflow.com/questions/2274695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/188740/"
] | 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. |
1,806,990 | 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! | 2009/11/27 | [
"https://Stackoverflow.com/questions/1806990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215094/"
] | Please also check the version of scrapy. The latest version uses "name" instead of "domain\_name" attribute to uniquely identify a spider. |
20,931,619 | 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? | 2014/01/05 | [
"https://Stackoverflow.com/questions/20931619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1033305/"
] | 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. |
32,580,318 | Please help me for How to convert data from {"rOjbectId":["abc","def",ghi","ghikk"]} to "["abc", "def", "ghi", "ghikk"] using ajax | 2015/09/15 | [
"https://Stackoverflow.com/questions/32580318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003128/"
] | 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). |
9,458,253 | 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. | 2012/02/26 | [
"https://Stackoverflow.com/questions/9458253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/866333/"
] | 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. |
34,211,201 | 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? | 2015/12/10 | [
"https://Stackoverflow.com/questions/34211201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2893712/"
] | 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. |
38,921,847 | 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
``` | 2016/08/12 | [
"https://Stackoverflow.com/questions/38921847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5140582/"
] | `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
``` |
39,707 | I have a 2006 Vespa LX 150 that starts up and idles perfectly but, when giving it any gas at all, it starts to stall and it is not delivering enough power to move forward. I let it idle for a good 5-10 minutes and kept trying but to no avail.
It has never acted strangely like this at all (never anything weird with the drive mechanics). I drove it two days ago and it was perfect but it may be worth noting that it was in the rain. However, I've done that several times and there was never an issue.
What could be wrong here? | 2016/12/12 | [
"https://mechanics.stackexchange.com/questions/39707",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/9501/"
] | 1. Try replacing your Air-filter, if you haven't done during your last service check-up
2. Also check your Spark Plug for carbon soot and clean if necessary |
13,540,903 | 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. | 2012/11/24 | [
"https://Stackoverflow.com/questions/13540903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437039/"
] | Try this:
```
textView.setText(textToBeSet.toUpperCase());
``` |
6,126,126 | 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. | 2011/05/25 | [
"https://Stackoverflow.com/questions/6126126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/533907/"
] | 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
}
}
``` |
14,847,913 | I try to implement the zoom in/out by spread/pinch gesture and the drag and drop functions on a Relative Layout.
This is the code of my OnPinchListener to handle the zoom effect.
The **mainView** is the RelativeLayout defined in the layout xml file.
I implement the touch listener in the **fakeview** which should be in front of all view. The touch event will change the **mainview** according to the code.
**I want to ask if it is possible to get the actual left, top, width and height after the scale?** It always return 0,0 for left and top, and the original width and height after zoom.
Thanks very much!
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/zoomable_relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
>
<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/background" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
</RelativeLayout>
</RelativeLayout>
public class MainActivity extends Activity {
//ZoomableRelativeLayout mainView = null;
RelativeLayout mainView = null;
RelativeLayout rl = null;
public static final String TAG = "ZoomText."
+ MainActivity.class.getSimpleName();
private int offset_x;
private int offset_y;
private boolean dragMutex = false;
RelativeLayout fakeView = null;
float width = 0, height = 0;
private OnTouchListener listener = new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent event) {
// Log.e(TAG, event + "");
// Log.e(TAG, "Pointer Count = "+event.getPointerCount());
Log.e(TAG,
event.getX() + "," + event.getY() + "|" + mainView.getX()
+ "(" + mainView.getWidth() + "),"
+ mainView.getY() + "(" + mainView.getHeight()
+ ")");
if (event.getX() >= mainView.getLeft()
&& event.getX() <= mainView.getLeft() + mainView.getWidth()
&& event.getY() >= mainView.getTop()
&& event.getY() <=mainView.getTop() + mainView.getHeight())
if (event.getPointerCount() > 1) {
return scaleGestureDetector.onTouchEvent(event);
} else {
return llListener.onTouch(arg0, event);
}
return false;
}
};
private ScaleGestureDetector scaleGestureDetector;
private OnTouchListener llListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
// Log.d(TAG, event + ",LL");
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
offset_x = (int) event.getX();
offset_y = (int) event.getY();
// Log.e(TAG, offset_x + "," + offset_y);
dragMutex = true;
return true;
case MotionEvent.ACTION_MOVE:
// Log.e(TAG, "Finger down");
int x = (int) event.getX() - offset_x;
int y = (int) event.getY() - offset_y;
Log.e(TAG, event.getX() + "," + event.getY());
float _x = mainView.getX();
float _y = mainView.getY();
mainView.setX(_x + x);
mainView.setY(_y + y);
offset_x = (int) event.getX();
offset_y = (int) event.getY();
return true;
case MotionEvent.ACTION_UP:
dragMutex = false;
return true;
}
return false;
}
};
private OnDragListener dragListener = new View.OnDragListener() {
@Override
public boolean onDrag(View arg0, DragEvent arg1) {
Log.e(TAG, "DRAG Listener = " + arg1);
return false;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView = (RelativeLayout) findViewById(R.id.zoomable_relative_layout);
// mainView.setOnTouchListener(new OnPinchListener());
// mainView.setOnTouchListener(listener);
scaleGestureDetector = new ScaleGestureDetector(this,
new OnPinchListener());
rl = (RelativeLayout) findViewById(R.id.linear_layout);
mainView.setOnDragListener(dragListener);
// mainView.setOnTouchListener(llListener);
fakeView = (RelativeLayout) findViewById(R.id.relative_layout);
fakeView.setOnTouchListener(listener);
}
class OnPinchListener extends SimpleOnScaleGestureListener {
float startingSpan;
float endSpan;
float startFocusX;
float startFocusY;
public boolean onScaleBegin(ScaleGestureDetector detector) {
startingSpan = detector.getCurrentSpan();
startFocusX = detector.getFocusX();
startFocusY = detector.getFocusY();
return true;
}
public boolean onScale(ScaleGestureDetector detector) {
// mainView.scale(detector.getCurrentSpan() / startingSpan,
// startFocusX, startFocusY);
// if(width==0)
// width = mainView.getWidth();
// if(height==0)
// height = mainView.getHeight();
mainView.setPivotX(startFocusX);
mainView.setPivotY(startFocusY);
mainView.setScaleX(detector.getCurrentSpan() / startingSpan);
mainView.setScaleY(detector.getCurrentSpan() / startingSpan);
// LayoutParams para = mainView.getLayoutParams();
// width*=detector.getCurrentSpan() / startingSpan;
// height*=detector.getCurrentSpan() / startingSpan;
// para.width = (int)width;
// para.height = (int)height;
// mainView.setLayoutParams(para);
return true;
}
public void onScaleEnd(ScaleGestureDetector detector) {
//mainView.restore();
mainView.invalidate();
Log.e(TAG, mainView.getLeft()+","+mainView.getRight());
}
}
}
``` | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067294/"
] | you need to get the transformation matrix and use that to transform your original points.
so something like this (after you do the scaling):
```
Matrix m = view.getMatrix(); //gives you the transform matrix
m.mapPoints(newPoints, oldPoints); //transform the original points.
``` |
3,851,022 | $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! | 2020/10/04 | [
"https://math.stackexchange.com/questions/3851022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/832188/"
] | 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$. |
68,767,520 | 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();
},
};
``` | 2021/08/13 | [
"https://Stackoverflow.com/questions/68767520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15076973/"
] | probably your page is refreshed, try to use preventDefault to prevent the refresh
```
$('#submit').click(function(event){
//your code here
event.preventDefault();
}
``` |
40,306,717 | First of all i am new to Angular 2 and i am trying to setup new project where i want user to login and if login is successful (which is always in my case) then user should be rerouted to another component.
Here is my code:
<https://github.com/tsingh38/Angular2Demo>
I am also struck with compilation error here
>
> zone.js:355Unhandled Promise rejection: Template parse errors:
> 'navigation' is not a known element:
> 1. If 'navigation' is an Angular component, then verify that it is part of this module.
> 2. If 'navigation' is a Web Component then add "CUSTOM\_ELEMENTS\_SCHEMA" to the '@NgModule.schemas' of this component
> to suppress this message. (" [ERROR
> ->]
>
>
> "): SiteComponent@5:0 ; Zone: ; Task: Promise.then ; Value:
> Error: Template parse errors:(…) Error: Template parse errors:
> 'navigation' is not a known element:
> 1. If 'navigation' is an Angular component, then verify that it is part of this module.
> 2. If 'navigation' is a Web Component then add "CUSTOM\_ELEMENTS\_SCHEMA" to the '@NgModule.schemas' of this component
> to suppress this message. (" [ERROR
> ->]
>
>
>
And please suggest me, is this the standard way of defining the flow ?
Thanks | 2016/10/28 | [
"https://Stackoverflow.com/questions/40306717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5160771/"
] | Use `Trim`: (*and also in this case consider changing to the query syntax, IMO more readable when it comes to joins*)
```
var fidn = from post in repository.users
join meta in repository.usersLG on post.pcod equals meta.pcod
where post.fam_v.Trim() == "Johny"
select new Final {
mcod = post.mcod,
pcod = post.pcod,
c_ogrn = post.c_ogrn,
fam_v = post.fam_v,
im_v = post.im_v,
ot_v = post.ot_v,
idGK = meta.idGK
};
```
*Aslo have a look at [C# naming conventions](https://msdn.microsoft.com/en-us/library/ms229002(v=vs.110).aspx) for the names of the properties in the `Final` object* |
238,163 | 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 | 2021/01/13 | [
"https://mathematica.stackexchange.com/questions/238163",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/403/"
] | [`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
>
>
> |
29,922,241 | Here is my Database: `bott_no_mgmt_data`
```
random_no ; company_id ; bottle_no ; date ; returned ; returned_to_stock ; username
30201 ; MY COMP ; 1 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30202 ; MY COMP ; 2 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30205 ; MY COMP ; 5 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30208 ; MY COMP ; 8 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30209 ; MY COMP ; 9 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30210 ; MY COMP ; 10 ; 2015-04-28 ; 10 ; NULL ; ANDREW
30211 ; MY COMP ; 1 ; 2015-04-29 ; 20 ; NULL ; ANDREW
30212 ; MY COMP ; 2 ; 2015-04-29 ; 20 ; NULL ; ANDREW
30213 ; MY COMP ; 9 ; 2015-04-29 ; 30 ; NULL ; ANDREW
30214 ; MY COMP ; 10 ; 2015-04-29 ; 30 ; NULL ; ANDREW
```
I have successfully pulled all the entire unique rows from `bott_no_mgmt_data` where the field `random_no` is highest and `bottle_no` is unique with the following code:
```
select yt.*
from bott_no_mgmt_data yt<br>
inner join(select bottle_no, max(random_no) random_no
from bott_no_mgmt_data
WHERE username = 'ANDREW'
group by bottle_no) ss on yt.bottle_no = ss.bottle_no
and yt.random_no = ss.random_no
where returned < 15 and date > '2015-04-01'
```
So for example one of the rows it returns will be
```
30214;MY COMP;10;2015-04-29;30;NULL;ANDREW
```
and NOT
```
30210;MY COMP;10;2015-04-28;10;NULL;ANDREW
```
because while their bottleno's are the same the former's random\_no is higher.
My Problem:
I now wish to compare each returned rows 'bottleno' with another table 'sample' which simply contains field 'bottleno' with a list of bottle numbers. I wish to compare them and only return those that match. I assume we would then 'LEFT JOIN' the results above with database 'sample' as below:
```
select yt.* from bott_no_mgmt_data yt<br>
inner join(select bottle_no, max(random_no) random_no
from bott_no_mgmt_data WHERE username = 'ANDREW'
group by bottle_no) ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no
where returned < 15 and date > '2015-04-01'
LEFT JOIN sample ON sample.bottleno = yt.bottle_no
```
The extra left join gives me an error
>
> 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN sample ON sample.bottleno = yt.bottleno WHERE sample.bottleno IS NULL ' at line 7
>
>
> | 2015/04/28 | [
"https://Stackoverflow.com/questions/29922241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4842148/"
] | All joins should be written before Where clause as Daan mentions:
```
select yt.* from bott_no_mgmt_data yt
inner join(
select bottle_no, max(random_no) random_no
from bott_no_mgmt_data
WHERE username = 'ANDREW' group by bottle_no
)
ss on yt.bottle_no = ss.bottle_no and yt.random_no = ss.random_no
LEFT JOIN sample ON sample.bottleno = yt.bottle_no
where returned < 15 and date > '2015-04-01'
``` |
17,435,721 | 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? | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710802/"
] | 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. |
35,029,058 | 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 | 2016/01/27 | [
"https://Stackoverflow.com/questions/35029058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4089992/"
] | 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());
});
``` |
28,808,099 | I am writing a script which will pick the last created file for the given process instance.
The command I use in my script is
```
CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT/console/*${INSTANCE}*" | tail -1`
```
but while the script is getting executed, the above command changes to
```
ls -1 '....../console/*ABP*'
```
because of the single quotes, `*` is not being treated as a wildcard character and it is giving output like:
```
ls -1 $ABP_AJTUH_ROOT/console/*${INSTANCE}* | tail -1
+ ls -1 '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*'
+ tail -1
ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory
+ CONSOLE_FILE=''
```
---
it is working on command line after removing ' from the command but not working while using in script as mentioned above
```
tc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l '/tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*'
ls: /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*: No such file or directory
devtc1@gircap01!DEV:devtc1/Users/RB/AIMOS_CLEANUP_CANSUB> ls -l /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/*UHMF_RT_1085*
-rw-r--r-- 1 devtc1 aimsys 72622 Feb 17 20:55 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_205519.log
-rw-r--r-- 1 devtc1 aimsys 177039 Feb 17 21:02 /tcusers1/dev/aimsys/devtc1/var/dev/projs/ajtuh/console/ADJ1UHMINFUL_UHMF_RT_1085_console_20150217_210203.log
``` | 2015/03/02 | [
"https://Stackoverflow.com/questions/28808099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4623068/"
] | You cannot use double quotes around the wildcard, because that turns the asterisks into literal characters.
```
CONSOLE_FILE=`ls -1 "$ABP_AJTUH_ROOT"/console/*"$INSTANCE"* | tail -1`
```
should work, but see the caveats against <http://mywiki.wooledge.org/ParsingLs> and generally <http://mywiki.wooledge.org/BashPitfalls> |
60,744,543 | 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
``` | 2020/03/18 | [
"https://Stackoverflow.com/questions/60744543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10871734/"
] | 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"
``` |
5,803,170 | I have encountered a problem when trying to select data from a table in MySQL in Java by a text column that is in utf-8. The interesting thing is that with code in Python it works well, in Java it doesn't.
The table looks as follows:
```
CREATE TABLE `x` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `text` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
```
The query looks like this:
```
SELECT * FROM x WHERE text = 'ěščřž'"
```
The Java code that doesn't work as exptected is the following:
```
public class test {
public static void main(String [] args) {
java.sql.Connection conn = null;
System.out.println("SQL Test");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://127.0.0.1/x?user=root&password=root&characterSet=utf8&useUnicode=true&characterEncoding=utf-8&characterSetResults=utf8");
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
System.out.println("Connection established");
try {
java.sql.Statement s = conn.createStatement();
java.sql.ResultSet r = s.executeQuery("SELECT * FROM x WHERE text = 'ěščřž'");
while(r.next()) {
System.out.println (
r.getString("id") + " " +
r.getString("text")
);
}
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}
```
The Python code is:
```
# encoding: utf8
import MySQLdb
conn = MySQLdb.connect (host = "127.0.0.1",
port = 3307,
user = "root",
passwd = "root",
db = "x")
cursor = conn.cursor ()
cursor.execute ("SELECT * FROM x where text = 'ěščřž'")
row = cursor.fetchone ()
print row
cursor.close ()
conn.close ()
```
Both are stored on the filesystem in utf8 encoding (checked with hexedit). I have tried different versions of mysql-connector (currently using 5.1.15). Mysqld is 5.1.54.
Mysqld log for the Java code and Python code respectively:
```
110427 12:45:07 1 Connect root@localhost on x
110427 12:45:08 1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SHOW VARIABLES WHERE Variable_name ='language' OR Variable_name = 'net_write_timeout' OR Variable_name = 'interactive_timeout' OR Variable_name = 'wait_timeout' OR Variable_name = 'character_set_client' OR Variable_name = 'character_set_connection' OR Variable_name = 'character_set' OR Variable_name = 'character_set_server' OR Variable_name = 'tx_isolation' OR Variable_name = 'transaction_isolation' OR Variable_name = 'character_set_results' OR Variable_name = 'timezone' OR Variable_name = 'time_zone' OR Variable_name = 'system_time_zone' OR Variable_name = 'lower_case_table_names' OR Variable_name = 'max_allowed_packet' OR Variable_name = 'net_buffer_length' OR Variable_name = 'sql_mode' OR Variable_name = 'query_cache_type' OR Variable_name = 'query_cache_size' OR Variable_name = 'init_connect'
1 Query /* mysql-connector-java-5.1.15 ( Revision: ${bzr.revision-id} ) */SELECT @@session.auto_increment_increment
1 Query SHOW COLLATION
1 Query SET autocommit=1
1 Query SET sql_mode='STRICT_TRANS_TABLES'
1 Query SELECT * FROM x WHERE text = 'ěščřž'
110427 12:45:22 2 Connect root@localhost on x
2 Query set autocommit=0
2 Query SELECT * FROM x where text = 'ěščřž'
2 Quit
```
Does anybody have any suggestions what might be the cause why the Python code works and why the Java code does not? (by not working I mean not finding the desired data -- the connection works fine)
Many thanks. | 2011/04/27 | [
"https://Stackoverflow.com/questions/5803170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429274/"
] | Okay, my bad. The database was wrongly built. It was built through the mysql client that by default is latin1 so in the database the data were encoded by utf8 twice.
The problem and the major difference between the two source codes is in that the Python code doesn't set the default charset (therefore it is latin1) whereas the Java code does (therefore it is utf8). So it was coincidence of many factors that made me think that something peculiar is actually going on.
Thanks for your responses anyway. |
24,220,365 | 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? | 2014/06/14 | [
"https://Stackoverflow.com/questions/24220365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298622/"
] | 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. |
3,398,839 | 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. | 2019/10/18 | [
"https://math.stackexchange.com/questions/3398839",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/209695/"
] | 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. |
32,969,687 | 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. | 2015/10/06 | [
"https://Stackoverflow.com/questions/32969687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3622730/"
] | 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). |
62,440,916 | 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
``` | 2020/06/18 | [
"https://Stackoverflow.com/questions/62440916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4048592/"
] | 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. |
37,455,599 | 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? | 2016/05/26 | [
"https://Stackoverflow.com/questions/37455599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5367540/"
] | 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. |
2,315,242 | 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. | 2010/02/23 | [
"https://Stackoverflow.com/questions/2315242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266159/"
] | 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. |
7,710,639 | 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. | 2011/10/10 | [
"https://Stackoverflow.com/questions/7710639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/817455/"
] | 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))$
``` |
24,444,188 | 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>
``` | 2014/06/27 | [
"https://Stackoverflow.com/questions/24444188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771301/"
] | 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")** |
47,331,969 | I'm trying to merge informations in two different data frames, but problem begins with uneven dimensions and trying to use not the column index but the information in the column. merge function in R or join's (dplyr) don't work with my data.
I have to dataframes (One is subset of the others with updated info in the last column):
`df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"))`
```
Name val Case
1 A 1 NA
2 B 2 1
3 C 3 NA
4 D 1 NA
5 E 2 1
6 F 3 NA
7 G 1 1
8 H 2 NA
9 I 3 NA
```
Some rows in the `Case` column in `df1` have to be changed with the info in the `df2` below:
`df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1")`
```
Name val Case
1 A 1 1
2 D 2 1
3 H 3 1
```
So there's nothing important in the `val` column, however I added it into the examples since I want to indicate that I have more columns than two and also my real data is way bigger than the examples.
Basically, I want to change specific rows by checking the information in the first columns (in this case, they're unique letters) and in the end I still want to have `df1` as a final data frame.
for a better explanation, I want to see something like this:
```
Name val Case
1 A 1 1
2 B 2 1
3 C 3 NA
4 D 1 1
5 E 2 1
6 F 3 NA
7 G 1 1
8 H 2 1
9 I 3 NA
```
Note changed information for `A`,`D` and `H`.
Thanks. | 2017/11/16 | [
"https://Stackoverflow.com/questions/47331969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8609239/"
] | `%in%` from base-r is there to rescue.
```
df1=data.frame(Name = print(LETTERS[1:9]), val = seq(1:3), Case = c("NA","1","NA","NA","1","NA","1","NA","NA"), stringsAsFactors = F)
df2 = data.frame(Name = c("A","D","H"), val = seq(1:3), Case = "1", stringsAsFactors = F)
df1$Case <- ifelse(df1$Name %in% df2$Name, df2$Case[df2$Name %in% df1$Name], df1$Case)
df1
Output:
> df1
Name val Case
1 A 1 1
2 B 2 1
3 C 3 NA
4 D 1 1
5 E 2 1
6 F 3 NA
7 G 1 1
8 H 2 1
9 I 3 NA
``` |
5,669,878 | 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? | 2011/04/14 | [
"https://Stackoverflow.com/questions/5669878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484488/"
] | Instead of asking what is standard practice, since that's often unclear and subjective, you might try looking to the module itself for guidance. In general, using the `with` keyword as another user suggested is a great idea, but in this specific circumstance it may not give you quite the functionality you expect.
As of version 1.2.5 of the module, `MySQLdb.Connection` implements the [context manager protocol](http://docs.python.org/2/library/stdtypes.html#context-manager-types) with the following code ([github](https://github.com/farcepest/MySQLdb1/blob/2204283605e8c450223965eda8d8f357d5fe4c90/MySQLdb/connections.py)):
```
def __enter__(self):
if self.get_autocommit():
self.query("BEGIN")
return self.cursor()
def __exit__(self, exc, value, tb):
if exc:
self.rollback()
else:
self.commit()
```
There are several existing Q&A about `with` already, or you can read [Understanding Python's "with" statement](http://effbot.org/zone/python-with-statement.htm), but essentially what happens is that `__enter__` executes at the start of the `with` block, and `__exit__` executes upon leaving the `with` block. You can use the optional syntax `with EXPR as VAR` to bind the object returned by `__enter__` to a name if you intend to reference that object later. So, given the above implementation, here's a simple way to query your database:
```
connection = MySQLdb.connect(...)
with connection as cursor: # connection.__enter__ executes at this line
cursor.execute('select 1;')
result = cursor.fetchall() # connection.__exit__ executes after this line
print result # prints "((1L,),)"
```
The question now is, what are the states of the connection and the cursor after exiting the `with` block? The `__exit__` method shown above calls only `self.rollback()` or `self.commit()`, and neither of those methods go on to call the `close()` method. The cursor itself has no `__exit__` method defined – and wouldn't matter if it did, because `with` is only managing the connection. Therefore, both the connection and the cursor remain open after exiting the `with` block. This is easily confirmed by adding the following code to the above example:
```
try:
cursor.execute('select 1;')
print 'cursor is open;',
except MySQLdb.ProgrammingError:
print 'cursor is closed;',
if connection.open:
print 'connection is open'
else:
print 'connection is closed'
```
You should see the output "cursor is open; connection is open" printed to stdout.
>
> I believe you need to close the cursor before committing the connection.
>
>
>
Why? The [MySQL C API](https://dev.mysql.com/doc/refman/5.6/en/c-api-function-overview.html), which is the basis for `MySQLdb`, does not implement any cursor object, as implied in the module documentation: ["MySQL does not support cursors; however, cursors are easily emulated."](http://mysql-python.sourceforge.net/MySQLdb.html#connection-objects) Indeed, the `MySQLdb.cursors.BaseCursor` class inherits directly from `object` and imposes no such restriction on cursors with regard to commit/rollback. An Oracle developer [had this to say](http://forums.mysql.com/read.php?50,578823,578941#msg-578941):
>
> cnx.commit() before cur.close() sounds most logical to me. Maybe you
> can go by the rule: "Close the cursor if you do not need it anymore."
> Thus commit() before closing the cursor. In the end, for
> Connector/Python, it does not make much difference, but or other
> databases it might.
>
>
>
I expect that's as close as you're going to get to "standard practice" on this subject.
>
> 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?
>
>
>
I very much doubt it, and in trying to do so, you may introduce additional human error. Better to decide on a convention and stick with it.
>
> Is there a lot of overhead for getting new cursors, or is it just not a big deal?
>
>
>
The overhead is negligible, and doesn't touch the database server at all; it's entirely within the implementation of MySQLdb. You can [look at `BaseCursor.__init__` on github](https://github.com/farcepest/MySQLdb1/blob/master/MySQLdb/cursors.py) if you're really curious to know what's happening when you create a new cursor.
Going back to earlier when we were discussing `with`, perhaps now you can understand why the `MySQLdb.Connection` class `__enter__` and `__exit__` methods give you a brand new cursor object in every `with` block and don't bother keeping track of it or closing it at the end of the block. It's fairly lightweight and exists purely for your convenience.
If it's really that important to you to micromanage the cursor object, you can use [contextlib.closing](http://docs.python.org/2/library/contextlib.html#contextlib.closing) to make up for the fact that the cursor object has no defined `__exit__` method. For that matter, you can also use it to force the connection object to close itself upon exiting a `with` block. This should output "my\_curs is closed; my\_conn is closed":
```
from contextlib import closing
import MySQLdb
with closing(MySQLdb.connect(...)) as my_conn:
with closing(my_conn.cursor()) as my_curs:
my_curs.execute('select 1;')
result = my_curs.fetchall()
try:
my_curs.execute('select 1;')
print 'my_curs is open;',
except MySQLdb.ProgrammingError:
print 'my_curs is closed;',
if my_conn.open:
print 'my_conn is open'
else:
print 'my_conn is closed'
```
Note that `with closing(arg_obj)` will not call the argument object's `__enter__` and `__exit__` methods; it will *only* call the argument object's `close` method at the end of the `with` block. (To see this in action, simply define a class `Foo` with `__enter__`, `__exit__`, and `close` methods containing simple `print` statements, and compare what happens when you do `with Foo(): pass` to what happens when you do `with closing(Foo()): pass`.) This has two significant implications:
First, if autocommit mode is enabled, MySQLdb will `BEGIN` an explicit transaction on the server when you use `with connection` and commit or rollback the transaction at the end of the block. These are default behaviors of MySQLdb, intended to protect you from MySQL's default behavior of immediately committing any and all DML statements. MySQLdb assumes that when you use a context manager, you want a transaction, and uses the explicit `BEGIN` to bypass the autocommit setting on the server. If you're used to using `with connection`, you might think autocommit is disabled when actually it was only being bypassed. You might get an unpleasant surprise if you add `closing` to your code and lose transactional integrity; you won't be able to rollback changes, you may start seeing concurrency bugs and it may not be immediately obvious why.
Second, `with closing(MySQLdb.connect(user, pass)) as VAR` binds the *connection object* to `VAR`, in contrast to `with MySQLdb.connect(user, pass) as VAR`, which binds *a new cursor object* to `VAR`. In the latter case you would have no direct access to the connection object! Instead, you would have to use the cursor's `connection` attribute, which provides proxy access to the original connection. When the cursor is closed, its `connection` attribute is set to `None`. This results in an abandoned connection that will stick around until one of the following happens:
* All references to the cursor are removed
* The cursor goes out of scope
* The connection times out
* The connection is closed manually via server administration tools
You can test this by monitoring open connections (in Workbench or by [using `SHOW PROCESSLIST`](http://dev.mysql.com/doc/refman/5.6/en/show-processlist.html)) while executing the following lines one by one:
```
with MySQLdb.connect(...) as my_curs:
pass
my_curs.close()
my_curs.connection # None
my_curs.connection.close() # throws AttributeError, but connection still open
del my_curs # connection will close here
``` |
56,148,199 | 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. | 2019/05/15 | [
"https://Stackoverflow.com/questions/56148199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2828594/"
] | 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) |
199,883 | 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. | 2019/06/06 | [
"https://mathematica.stackexchange.com/questions/199883",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/41975/"
] | 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}]
``` |
61,989,976 | I am trying to perform JWT auth in spring boot and the request are getting stuck in redirect loop.
**JWTAuthenticationProvider**
```
@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Autowired
private JwtUtil jwtUtil;
@Override
public boolean supports(Class<?> authentication) {
return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
String token = jwtAuthenticationToken.getToken();
JwtParsedUser parsedUser = jwtUtil.parseToken(token);
if (parsedUser == null) {
throw new JwtException("JWT token is not valid");
}
UserDetails user = User.withUsername(parsedUser.getUserName()).password("temp_password").authorities(parsedUser.getRole()).build();
return user;
}
```
**JwtAuthenticationFilter**
```
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
super("/**");
this.setAuthenticationManager(authenticationManager);
}
@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
return true;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
throw new JwtException("No JWT token found in request headers");
}
String authToken = header.substring(7);
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
return getAuthenticationManager().authenticate(authRequest);
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
}
```
**SecurityConfiguration**
```
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationProvider jwtAuthenticationProvider;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(jwtAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/secured-resource-1/**", "/secured-resource-2/**")
.hasRole("ADMIN").antMatchers("/secured-resource-2/**").hasRole("ADMIN").and().formLogin()
.successHandler(new AuthenticationSuccessHandler()).and().httpBasic().and().exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler()).authenticationEntryPoint(getBasicAuthEntryPoint())
.and()
.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()),
FilterSecurityInterceptor.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
}
```
**MainController**
```
@RestController
public class MainController {
@Autowired
private JwtUtil jwtUtil;
@GetMapping("/secured-resource-1")
public String securedResource1() {
return "Secured resource1";
}
}
```
When I hit the endpoint with the valid JWT token, the code goes in a loop from Filter to provider class and ends in Error:
```
Exceeded maxRedirects. Probably stuck in a redirect loop http://localhost:8000/ error.
```
Debug logs shows the following error:
```
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendError() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
```
Any suggestions what am I missing here.
Thanks in advance. | 2020/05/24 | [
"https://Stackoverflow.com/questions/61989976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4457734/"
] | I believe the the reason for this is because you have not actually set the `AuthenticationSuccessHandler` for the bean `JwtAuthenticationFilter`, since it is not actually set it will keep looping around super and chain and later when the error needs to be sent since response is already written in `super()` `chain.doFilter` will fail because once the response is written it cannot be again written hence the error `call sendError() after the response has been committed`.
To correct this in your SecurityConfiguration before setting this
```
.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()),
FilterSecurityInterceptor.class)
```
Instantiate the filter and set it's success manager like so
```
JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager()),FilterSecurityInterceptor.class);
jwtAuthenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
```
Now use the above variable to set the filter.
This is a great reference project: <https://gitlab.com/palmapps/jwt-spring-security-demo/-/tree/master/>. |
4,177,291 | 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? | 2010/11/14 | [
"https://Stackoverflow.com/questions/4177291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264419/"
] | 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
``` |
44,169,413 | [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
``` | 2017/05/24 | [
"https://Stackoverflow.com/questions/44169413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6484371/"
] | 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? |
29,130,635 | 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. | 2015/03/18 | [
"https://Stackoverflow.com/questions/29130635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2668777/"
] | 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. |
25,677,031 | 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? | 2014/09/05 | [
"https://Stackoverflow.com/questions/25677031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2615384/"
] | 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"
``` |
3,829,150 | 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? | 2010/09/30 | [
"https://Stackoverflow.com/questions/3829150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383759/"
] | 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. |
66,233,268 | 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. | 2021/02/16 | [
"https://Stackoverflow.com/questions/66233268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2518602/"
] | 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]
``` |
6,677,308 | 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. | 2011/07/13 | [
"https://Stackoverflow.com/questions/6677308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/768789/"
] | 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. |
24,010 | UPDATE
Have included an image. As you can see, LED is ON when base is floating. This is a 2N222A transistor.
![enter image description here](https://i.stack.imgur.com/0x1RH.jpg)
![enter image description here](https://i.stack.imgur.com/C2V28.jpg)
---
Playing with an NPN bipolar transistor. The Collector is connected to the positive terminal of a 9V battery through a 1k Ohm resistor, and the Emitter is connected to the ground through an LED. The Base is not connected to anything.
The LED seems to be dim in the above case. When I connect the Base to the positive terminal, the LED is much brighter. That makes sense as current through the base Base amplifies the current.
My questions is: **should any current flow through the emitter if the base is not connected to anything? I.e. Shouldn't the LED be completely off?**
I have a similar question for NPN Unijunction transistors (understand that nomenclature changes from CBE to AGC)? | 2011/12/21 | [
"https://electronics.stackexchange.com/questions/24010",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/4336/"
] | Okay, looking at the picture I think you may have the transistor the wrong way round.
Try turning it round.
See this picture for reference:
![enter image description here](https://i.stack.imgur.com/tDQzJ.png)
As you can see the collector is on the right with the flat part facing you, so you have the collector connected to the LED in your circuit (if the 2N2222A part you are using has the same pinout)
I got the picture from [here](http://www.fairchildsemi.com/ds/PN/PN2222A.pdf).
**EDIT** - It's actually a 2N222A, but the above advice still goes as the pinout appears to be the same from the picture posted.
As Russell mentions the more standard way is to connect the LED to the collector, but your circuit should work if set up correctly. |
23,238,724 | 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? | 2014/04/23 | [
"https://Stackoverflow.com/questions/23238724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505055/"
] | 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)
``` |
74,081,278 | 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? | 2022/10/15 | [
"https://Stackoverflow.com/questions/74081278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17378883/"
] | 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]
``` |
25,207,910 | 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? | 2014/08/08 | [
"https://Stackoverflow.com/questions/25207910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3923011/"
] | 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. ;) |
54,405,329 | I'm new to QT and I've watched some tutorials about how to create a widget app. In most of them, I had to modify label text using:
```
ui->label->setText("smthg");
```
I've tried the same thing with QTextEdit and can't seem have access to it.
Tried `ui->help_plz`, says **"no member named "textEdit" in UI::MainWindow".**
How can I access QTextEdit and copy text from it?
Code:
main window.ui:
```
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>550</width>
<height>368</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralWidget">
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>140</x>
<y>210</y>
<width>114</width>
<height>32</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
</widget>
<widget class="QLabel" name="succ">
<property name="geometry">
<rect>
<x>200</x>
<y>100</y>
<width>59</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>TextLabel</string>
</property>
</widget>
<widget class="QLineEdit" name="help_plz">
<property name="geometry">
<rect>
<x>230</x>
<y>60</y>
<width>113</width>
<height>21</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>550</width>
<height>22</height>
</rect>
</property>
</widget>
<widget class="QToolBar" name="mainToolBar">
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<widget class="QStatusBar" name="statusBar"/>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>
```
main.cpp:
```
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
```
mainwidow.cpp
```
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextEdit>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
ui->succ->setText("yeah");
ui->help_plz //no member named "help_plz" in UI::MainWindow
}
```
main.h:
```
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
``` | 2019/01/28 | [
"https://Stackoverflow.com/questions/54405329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10935201/"
] | It says `no member named "textEdit" in UI::MainWindow` because there isn't anything called `textEdit` in your `.ui` file (you can search it yourself to confirm it). You cannot access UI elements that are not there. Add a line edit to your ui file. |
18,392,750 | 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? | 2013/08/23 | [
"https://Stackoverflow.com/questions/18392750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2556050/"
] | 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. |
4,882,465 | I am quite a noob when it comes to deploying a Django project. I'd like to know what are the various methods to deploy Django project and which one is the most preferred. | 2011/02/03 | [
"https://Stackoverflow.com/questions/4882465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277848/"
] | Use the Nginx/Apache/mod-wsgi and you can't go wrong.
If you prefer a simple alternative, just use Apache.
There is a very good deployment document: <http://lethain.com/entry/2009/feb/13/the-django-and-ubuntu-intrepid-almanac/> |
23,898,432 | I have this source of a single file that is successfully compiled in C:
```
#include <stdio.h>
int a;
unsigned char b = 'A';
extern int alpha;
int main() {
extern unsigned char b;
double a = 3.4;
{
extern a;
printf("%d %d\n", b, a+1);
}
return 0;
}
```
After running it, the output is
>
> 65 1
>
>
>
Could anybody please tell me why the extern a statement will capture the global value instead of the **double** local one and why the **printf** statement print the global value instead of the local one?
Also, I have noticed that if I change the statement on line 3 from
```
int a;
```
to
```
int a2;
```
I will get an error from the **extern a;** statement. Why does not a just use the assignment **double a=3.4;** ? It's not like it is bound to be int. | 2014/05/27 | [
"https://Stackoverflow.com/questions/23898432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2565010/"
] | The problem is here:
```
System.out.println("Average of column 1:" + (myTable [0][0] + myTable [0][1] + myTable [0][2] + myTable [0][3] + myTable [0][4]) / 4 );
```
You're accessing to `myTable[0][4]`, when `myTable` is defined as `int[5][4]`. Fix this and your code will work.
```
System.out.println("Average of column 1:" + (myTable [0][0] + myTable [0][1] + myTable [0][2] + myTable [0][3]) / 4 );
```
---
A biggest problem here is your design. You should use a `for` loop to set the values in your `myTable` instead of using 20 variables (!). Here's an example:
```
int[][] myTable = new int[5][4];
for (int i = 0; i < myTable.length; i++) {
for (int j = 0; j < myTable[i].length; j++) {
System.out.println("Type a number:");
myTable[i][j] = Integer.parseInt(mVHS.readLine());
}
}
``` |
2,884,715 | I am currently investigating the specific square number $a^n+1$ and whether it can become a square. I know that $a^n+1$ cannot be a square if n is even because then I can write n=2x, and so $(a^n)^2$+1 is always smaller than $(a^n+1)^2$.
But what about odd powers of n? Can they allow $a^n+1$ to become a square? Or a more general case, can $a^n+1$ ever be a square number? | 2018/08/16 | [
"https://math.stackexchange.com/questions/2884715",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/449771/"
] | To answer the question in the title:
The next square after $n^2$ is $(n+1)^2=n^2+2n+1 > n^2+1$ if $n>0$.
Therefore, $n^2+1$ is never a square, unless $n=0$. |
4,623,475 | The MySQL Stored Procedure was:
```
BEGIN
set @sql=_sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
set _ires=LAST_INSERT_ID();
END$$
```
I tried to convert it to:
```
BEGIN
EXECUTE _sql;
SELECT INTO _ires CURRVAL('table_seq');
RETURN;
END;
```
I get the error:
```
SQL error:
ERROR: relation "table_seq" does not exist
LINE 1: SELECT CURRVAL('table_seq')
^
QUERY: SELECT CURRVAL('table_seq')
CONTEXT: PL/pgSQL function "myexecins" line 4 at SQL statement
In statement:
SELECT myexecins('SELECT * FROM tblbilldate WHERE billid = 2')
```
The query used is for testing purposes only. I believe this function is used to get the row id of the inserted or created row from the query. Any Suggestions? | 2011/01/07 | [
"https://Stackoverflow.com/questions/4623475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563296/"
] | You can add an option 'expression' to the configuration. Normally it gets a "$user" as argument. So you can do something like:
```
array('allow',
'actions'=>array('index','update', 'create', 'delete'),
'expression'=> '$user->isAdmin',
),
```
Note that I haven't tested this but I think it will work.
Take a look [here](http://www.yiiframework.com/doc/api/1.1/CAccessControlFilter) for the rest. |
3,988,620 | This should be straight foreward, but I simply can't figure it out(!)
I have a UIView 'filled with' a UIScrollView. Inside the scrollView I wan't to have a UITableView.
I have hooked up both the scrollView and the tableView with IBOutlet's in IB and set the ViewController to be the delegate and datasource of the tableView.
What else do I need to do ? Or what shouldn't I have done? | 2010/10/21 | [
"https://Stackoverflow.com/questions/3988620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463808/"
] | Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
```
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
```
This is easier to extend, and easier to read if it gets any more complex. |
4,084,790 | AFAIK GHC is the most common compiler today, but I also see, that some other ompilers are available too. Is GHC really the best choice for all purposes or may I use something else instead? For instance, I read that some compiler (forgot the name) does better on optimizations, but doesn't implements all extensions. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4084790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417501/"
] | GHC is by far the most widely used Haskell compiler, and it offers the most features. There are other options, though, which sometimes have some benefits over GHC. These are some of the more popular alternatives:
[Hugs](http://www.haskell.org/hugs/) - Hugs is an interpreter (I don't think it includes a compiler) which is fast and efficient. It's also known for producing more easily understood error messages than GHC.
[JHC](http://repetae.net/computer/jhc/) - A whole-program compiler. JHC can produce very efficient code, but it's not feature-complete yet (this is probably what you're thinking of). Note that it's not always faster than GHC, only sometimes. I haven't used JHC much because it doesn't implement multi-parameter type classes, which I use heavily. I've heard that the source code is extremely clear and readable, making this a good compiler to hack on. JHC is also more convenient for cross-compiling and usually produces smaller binaries.
[UHC](http://www.cs.uu.nl/wiki/UHC) - The Utrecht Haskell Compiler is near feature-complete (I think the only thing missing is n+k patterns) for Haskell98. It implements many of GHC's most popular extensions and some original extensions as well. According to the documentation code isn't necessarily well-optimized yet. This is also a good compiler to hack on.
In short, if you want efficient code and cutting-edge features, GHC is your best bet. JHC is worth trying if you don't need MPTC's or some other features. UHC's extensions may be compelling in some cases, but I wouldn't count on it for fast code yet. |
3,551 | I have a chunk of text I need to paste into Illustrator. No matter what I do, I can't resize the text area without scaling the text. I want to resize the area and have the text wrap (font size to remain the same).
How can I do this? I'm using CS5.1 | 2011/09/06 | [
"https://graphicdesign.stackexchange.com/questions/3551",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2357/"
] | Select your `Type` tool. Instead of clicking on your canvas, click and drag to draw a box. Put whatever copy you want inside the type box and when you resize the box it will reflow the text instead of changing the font.
You can also link multiple type boxes together to flow text across multiple points on your artboard. Create type objects wherever you want text to be. Add all your copy to the first box. Assuming it overflows, there will be a ![+](https://i.stack.imgur.com/FpE3v.png) symbol in the bottom-right corner of the type box. Click this ![+](https://i.stack.imgur.com/FpE3v.png) symbol and then click the next type box where you want text to flow. Illustrator will flow text through as many type boxes as you link together. |
21,816,154 | I have a question about if a animation ends that it will like `gotoAndStop()` to another frame
```
if (bird.hitTestObject(pipe1)) {
bird.gotoAndStop(3); //frame 3 = animation
}
```
after it ends it will need to go the Game Over frame (frame 3) and I use the `Flash Timeline` not `.as` thanks! | 2014/02/16 | [
"https://Stackoverflow.com/questions/21816154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3316757/"
] | Java does not provide a convenient way to list the "files" in a "directory", when that directory is backed by a JAR file on the classpath (see [How do I list the files inside a JAR file?](https://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) for some work-arounds). I believe this is because the general case where a "directory" exists in multiple .jar files and classpath directories is really complicated (the system would have to present a union of entries across multiple sources and deal with overlaps).
Because Java/Android do not have clean support this, neither does Libgdx (searching the classpath is what "internal" Libgdx files map to).
I think the easiest way to work-around this is to build a list of levels into a text file, then open that and use it as a list of file names. So, something like:
```
// XXX More pseudo code in Java than actual code ... (this is untested)
fileList = Gdx.files.internal("levels.txt");
String files[] = fileList.readString().split("\\n");
for (String filename: files) {
FileHandle fh = Gdx.files.internal("levels/" + filename);
...
}
```
Ideally you'd set something up that builds this text file when the JAR file is built. (That's a separate SO question I don't know the answer to ...)
As an aside, your work-around that uses `ApplicationType.Desktop` is leveraging the fact that in addition to the .jar file, there is a real directory on the classpath that you can open. That directory doesn't exist on the Android device (it actually only exists on the desktop when running under your build environment). |
3,197,405 | I got the following crash logs after my app crashes:
```
0 libobjc.A.dylib 0x000034f4 objc_msgSend + 20
1 UIKit 0x000a9248 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 644
2 UIKit 0x000a8eac -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 44
3 UIKit 0x0006f480 -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1300
4 UIKit 0x0006ce40 -[UITableView layoutSubviews] + 200
5 UIKit 0x00014ab0 -[UIView(CALayerDelegate) _layoutSublayersOfLayer:] + 32
6 CoreFoundation 0x000285ba -[NSObject(NSObject) performSelector:withObject:] + 18
7 QuartzCore 0x0000a61c -[CALayer layoutSublayers] + 176
8 QuartzCore 0x0000a2a4 CALayerLayoutIfNeeded + 192
9 QuartzCore 0x00009bb0 CA::Context::commit_transaction(CA::Transaction*) + 256
10 QuartzCore 0x000097d8 CA::Transaction::commit() + 276
11 QuartzCore 0x000119d8 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 80
12 CoreFoundation 0x00074244 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 12
13 CoreFoundation 0x00075d9e __CFRunLoopDoObservers + 494
14 CoreFoundation 0x000772f6 __CFRunLoopRun + 934
15 CoreFoundation 0x0001e0bc CFRunLoopRunSpecific + 220
16 CoreFoundation 0x0001dfca CFRunLoopRunInMode + 54
17 GraphicsServices 0x00003f88 GSEventRunModal + 188
18 UIKit 0x00007b40 -[UIApplication _run] + 564
19 UIKit 0x00005fb8 UIApplicationMain + 964
20 my_app 0x0000291e main (main.m:14)
21 my_app 0x000028c8 start + 32
```
or, another times:
```
0 libobjc.A.dylib 0x00003508 objc_msgSend + 40
1 CoreFoundation 0x00027348 -[NSObject(NSObject) performSelector:withObject:withObject:] + 20
2 UIKit 0x00009ae4 -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] + 276
3 UIKit 0x00009b04 -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] + 308
4 UIKit 0x00009b04 -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] + 308
5 UIKit 0x00009b04 -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] + 308
6 UIKit 0x00009b04 -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:withObject:copySublayers:] + 308
7 UIKit 0x000099bc -[UIView(Hierarchy) _makeSubtreePerformSelector:withObject:] + 28
8 UIKit 0x000095d4 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 448
9 UIKit 0x00009400 -[UIView(Hierarchy) addSubview:] + 28
10 UIKit 0x0009b788 +[UIViewControllerWrapperView wrapperViewForView:frame:] + 328
11 UIKit 0x0009e42c -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 140
12 UIKit 0x0009e38c -[UITabBarController transitionFromViewController:toViewController:] + 32
13 UIKit 0x0009d9d0 -[UITabBarController _setSelectedViewController:] + 248
14 UIKit 0x0009d8c8 -[UITabBarController setSelectedViewController:] + 12
15 UIKit 0x000b8e54 -[UITabBarController _tabBarItemClicked:] + 308
16 CoreFoundation 0x00027348 -[NSObject(NSObject) performSelector:withObject:withObject:] + 20
17 UIKit 0x0008408c -[UIApplication sendAction:to:from:forEvent:] + 128
18 UIKit 0x00083ff4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
19 UIKit 0x000b8c7c -[UITabBar _sendAction:withEvent:] + 416
20 CoreFoundation 0x00027348 -[NSObject(NSObject) performSelector:withObject:withObject:] + 20
21 UIKit 0x0008408c -[UIApplication sendAction:to:from:forEvent:] + 128
22 UIKit 0x00083ff4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
23 UIKit 0x00083fbc -[UIControl sendAction:to:forEvent:] + 44
24 UIKit 0x00083c0c -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 528
25 UIKit 0x000b8acc -[UIControl sendActionsForControlEvents:] + 16
26 UIKit 0x000b890c -[UITabBar(Static) _buttonUp:] + 108
27 CoreFoundation 0x00027348 -[NSObject(NSObject) performSelector:withObject:withObject:] + 20
28 UIKit 0x0008408c -[UIApplication sendAction:to:from:forEvent:] + 128
29 UIKit 0x00083ff4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
30 UIKit 0x00083fbc -[UIControl sendAction:to:forEvent:] + 44
31 UIKit 0x00083c0c -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 528
32 UIKit 0x00084484 -[UIControl touchesEnded:withEvent:] + 452
33 UIKit 0x000824e4 -[UIWindow _sendTouchesForEvent:] + 580
34 UIKit 0x00081b18 -[UIWindow sendEvent:] + 388
35 UIKit 0x0007c034 -[UIApplication sendEvent:] + 444
36 UIKit 0x0007b7e8 _UIApplicationHandleEvent + 6704
37 GraphicsServices 0x00004edc PurpleEventCallback + 1024
38 CoreFoundation 0x000742ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 22
39 CoreFoundation 0x000761d6 __CFRunLoopDoSource1 + 158
40 CoreFoundation 0x0007718e __CFRunLoopRun + 574
41 CoreFoundation 0x0001e0bc CFRunLoopRunSpecific + 220
42 CoreFoundation 0x0001dfca CFRunLoopRunInMode + 54
43 GraphicsServices 0x00003f88 GSEventRunModal + 188
44 UIKit 0x00007b40 -[UIApplication _run] + 564
45 UIKit 0x00005fb8 UIApplicationMain + 964
46 my_app 0x00002ba2 main (main.m:14)
47 my_app 0x00002b4c start + 32
```
What's wrong there? I mean - my app is at the bottom of the stack trace in the main-method... I checked for memory leaks - nothing...
Thanks for any help! | 2010/07/07 | [
"https://Stackoverflow.com/questions/3197405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27404/"
] | My best guess would be that something isn't linking correctly in one of you .xib views. Another common cause of this is an object being called upon that's already been released from memory. Try tracing this with `NSZombieEnabled` |
22,953,075 | I am using jQuery mobile 1.4.2. I need to shift the search icon from left to right and how can I avoid the clear button appearing.
```
<div data-role=page">
<form method="post">
<input name="search" id="search" value="" placeholder="Buscar" type="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Buscar'">
</form>
</div>
``` | 2014/04/09 | [
"https://Stackoverflow.com/questions/22953075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3350169/"
] | The constructor is `new Rect(left,top,width,height)`
Any fewer arguments will result in those many fields not being set. eg. `new Rect(1,2,3)` will return a Rect object with no height
Screenshot here : <http://puu.sh/81KSa/e225064bec.png> |
33,958,674 | In the repository class of WebApi project there is the method `GetSingleIncluding()` that returns an entity with indluded objects that were passed as parameters.
```
private readonly EFDbContext _context;
private IDbSet<T> _entities;
private IDbSet<T> Entities
{
get
{
_entities = _entities ?? _context.Set<T>();
return _entities;
}
}
public T GetSingleIncluding(int id, params Expression<Func<T, object>>[] includeProperties)
{
var query = Entities.Where(x => x.ID == id);
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.First();
}
```
I have an action in a controller
```
public HttpResponseMessage GetFull(int id, string entities)
```
I use it as:
```
var entitiy = Repository.GetSingleIncluding(id, x => x.Person);
```
here I pass explicitly a parameter `x => x.Persons`
Is there any way to pass this parameters by url request? E.g I will pass all objects (that can be include for the current entity) as string in the url
```
http://localhost/api/House/1/Person,Address,...
```
and the controller will be pass these params to the `GetSingleIncluding()` method:
```
Repository.GetSingleIncluding(id, x => x.Person, y => y.Address);
```
House entity
```
public class House : BaseEntity
{
public int PersonID { get; set; }
public int HouseID { get; set; }
public int AddressID { get; set; }
...
public virtual Person Person { get; set; }
public virtual Address Address { get; set; }
}
``` | 2015/11/27 | [
"https://Stackoverflow.com/questions/33958674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4275342/"
] | With the information we have so far, I think you need a query with a PIVOT:
```
SELECT P.VehicleNo, V.DriverConsoleVersion, P.[1] AS [Device1SwVersion], P.[2] AS [Device1SwVersion], P.[3] AS [Device1SwVersion]
FROM (
SELECT VehicleNo, [1], [2], [3]
FROM (
SELECT VehicleNo, DevicePosition, DeviceSwVersion
FROM @DeviceInfo
) as d
PIVOT (
MAX(DeviceSwVersion)
FOR DevicePosition IN ([1], [2], [3])
) PIV
) P
LEFT JOIN @DeviceInfo V
ON V.VehicleNo = P.VehicleNo AND V.DevicePosition = 1;
```
You can create a view with such a query.
The first subquery get 4 column for Device 1 to 3 for each vehicle.
It then LEFT JOIN it with the SwVersion table in order to get the Console version associated with Device 1.
**Output:**
```
VehicleNo DriverConsoleVersion Device1SwVersion Device1SwVersion Device1SwVersion
102 1.34 8.01 NULL 8.00
305 1.34 8.01 8.00 8.00
312 1.33 8.00 8.00 8.00
414 NULL NULL 8.01 8.00
```
**Your data:**
```
Declare @DeviceInfo TABLE([DeviceSerial] int, [VehicleNo] int, [DevicePosition] int, [DeviceSwVersion] varchar(10), [DriverConsoleVersion] varchar(10));
INSERT INTO @DeviceInfo([DeviceSerial], [VehicleNo], [DevicePosition], [DeviceSwVersion], [DriverConsoleVersion])
VALUES
(1040, 305, 3, '8.00', '0'),
(1044, 305, 2, '8.00', '0'),
(1063, 305, 1, '8.01', '1.34'),
(1071, 312, 2, '8.00', '0'),
(1075, 312, 1, '8.00', '1.33'),
(1078, 312, 3, '8.00', '0'),
(1099, 414, 3, '8.00', '0'),
(1106, 414, 2, '8.01', '0'),
(1113, 102, 1, '8.01', '1.34'),
(1126, 102, 3, '8.00', '0')
;
``` |
70,504,314 | I have some code which captures a key.
Now i have in event.code the real key-name and in event.key i get the key-char.
To make an example: I press SHIFT and J, so i get:
*event.code: SHIFT KEYJ*
*event.key: J*
So, i get in event.key the "interpreted key" from shift J. But now i need to convert the native key to a char. So i am looking for a solution to get from "KEYJ" to a char, that means "j". How can this be done? I have not found anything about this. | 2021/12/28 | [
"https://Stackoverflow.com/questions/70504314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17779252/"
] | Solution was the H2 version.
We upgraded also H2 to 2.0 but that version is not compatible with Spring Batch 4.3.4.
Downgrade to H2 version 1.4.200 solved the issue. |
11,240,180 | I want to run a .exe file (or) any application from pen drive on insert in to pc. I dont want to use Autorun.inf file, as all anti virus software's blocks it. I have used portable application launcher also, that also using autorun only. so once again anti virus software blocks it. Is there any alternative option, such that .exe file from pen drive should start automatically on pen drive insert? | 2012/06/28 | [
"https://Stackoverflow.com/questions/11240180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487797/"
] | Anti-virus programs block autorun.inf on the solely purpose not to allow some .exe-s to start automatically on pen drive insert. So, basically, what you're asking is impossible. |
1,712,401 | Here is what I have so far:
Let $\varepsilon > 0$ be given
We want for all $n >N$, $|1/n! - 0|< \varepsilon$
We know $1/n <ε$ and $1/n! ≤ 1/n < ε$.
I don't know how to solve for $n$, given $1/n!$. And this is where I get stuck in my proof, I cannot solve for $n$, and therefore cannot pick $N > \cdots$. | 2016/03/25 | [
"https://math.stackexchange.com/questions/1712401",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/325725/"
] | Since $0 < \frac{1}{n!} < \frac{1}{n}$, by the squeeze theorem...
Without squeeze theorem: Let $\epsilon > 0$. Define $N = \epsilon^{-1}$. Then if $n > N$, $$\left|\frac{1}{n!}\right| = \frac{1}{n!} < \frac{1}{n} < \frac{1}{N} = \epsilon$$ |
5,637,808 | I got my first android phone since two week
And I'm starting my first real App.
My phone is a LG Optimus 2X and one of the missing thing is a
notification led for when there is a missed call, sms, email ect ...
So I'm wondering what's the best way to do this.
For know I've a broatcastreceiver for incoming sms, and the I call a
service that will light the phone buttons (don't bother about this
part, it's working).
But seems that this method will workin only for sms, phone calls, not
emails.
So know I'm thinking to used Listeners instead for everything, but
this mean having a service running nonstop. Not sure it's the best
way ...
I hope I'm clear, and that my ennglish is not too bad.
Thx in advance | 2011/04/12 | [
"https://Stackoverflow.com/questions/5637808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704403/"
] | ```
UIBarButtonItem *addButton =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(myCallback:)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
``` |
151,322 | Recently, I read a lot of good articles about how to do good encapsulation. And when I say "good encapsulation", I am not talking about hiding private fields with public properties; I am talking about preventing users of your API from doing wrong things.
Here are two good articles about this subject:
<http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx>
<http://lostechies.com/derickbailey/2011/03/28/encapsulation-youre-doing-it-wrong/>
At my job, the majority of our applications are not destined for other programmers but rather for the customers.
About 80% of the application code is at the top of the structure (Not used by other code). For this reason, there is probably no chance ever that this code will be used by other application.
An example of encapsulation that prevents users from doing wrong things with your API is returning an IEnumerable instead of IList when you don't want to give the ability to the user to add or remove items in the list.
My question is: When can encapsulation be considered simply OOP purism, keeping in mind that each hour of programming is charged to the customer?
I want to create code that is maintainable and easy to read and use, but when I am not building a public API (to be used by other programmers), where can we draw the line between perfect code and not so perfect code? | 2012/06/02 | [
"https://softwareengineering.stackexchange.com/questions/151322",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/44035/"
] | Answer: When you have your interface complete, then automatically you are done with encapsulation. It does not matter if implemenation or consumption part is incomplete, you are done since interface is accepted as final.
**Proper development tools should reduce cost more than tools cost themself.**
You suggest that if encapsulation or whatever property is not relevant to market offer, if customer does not care then the property has no value. Correct. And customer cares nearly about no internal property of code.
So why this and other measurable properties of code exist ? Why deveoper should care ? I think the reason is money as well: any labor intensive and costly work in software development will call for a cure. Encapsulation is targeted not at the customer but at user of library. You saying you do not have external users, but for your own code you yourself are the user number 1.
* If you introduce risk of errors into daily use, then you **increase the cost of development**.
* If you spend on reducing the risk, you will **increase the cost of development**.
Market and evolution keep forcing this choice. Choose the least increase.
This is all understood well. But you are asking about this particular feature. It is not the hardest one to maintain. It is definitely cost effective. But be aware about laws of human nature and economy. Tools have their own market. The labeled cost for some can be $0, but there is always hidden cost in terms of time spent on adoption. And this market is flooded with methodologies and practices with negative value. |
14,790,045 | I am trying to insert a new column into a CSV file after existing data. For example, my CSV file currently contains:
```
Heading 1 Heading 2
1
1
0
2
1
0
```
I have a list of integers in format:
```
[1,0,1,2,1,2,1,1]
```
**How can i insert this list into the CSV file under 'Header 2'?**
So far all i have been able to achieve is adding the new list of integers underneath the current data, for example:
```
Heading 1 Heading 2
1
1
0
2
1
0
1
0
1
2
1
2
1
1
```
Using the code:
```
#Open CSV file
with open('C:\Data.csv','wb') as g:
#New writer
gw = csv.writer(g)
#Add headings
gw.writerow(["Heading 1","Heading 2"])
#Write First list of data to heading 1 (orgList)
gw.writerows([orgList[item]] for item in column)
#For each value in new integer list, add row to CSV
for val in newList:
gw.writerow([val])
``` | 2013/02/09 | [
"https://Stackoverflow.com/questions/14790045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987845/"
] | I guess this question is already kind of old but I came across the same problem.
Its not any "best practice" solution but here is what I do.
In `twig` you can use this `{{ path('yourRouteName') }}` thing in a perfect way. So in my `twig` file I have a structure like that:
```
...
<a href="{{ path('myRoute') }}"> //results in e.g http://localhost/app_dev.php/myRoute
<div id="clickMe">Click</div>
</a>
```
Now if someone clicks the div, I do the following in my `.js file`:
```
$('#clickMe').on('click', function(event) {
event.preventDefault(); //prevents the default a href behaviour
var url = $(this).closest('a').attr('href');
$.ajax({
url: url,
method: 'POST',
success: function(data) {
console.log('GENIUS!');
}
});
});
```
I know that this is not a solution for every situation where you want to trigger an Ajax request but I just leave this here and perhaps somebody thinks it's useful :) |
24,923,412 | I am attempting to use Tkinter for the first time on my computer, and I am getting the error in the title, "NameError: name 'Tk' is not defined", citing the "line root = Tk()". I have not been able to get Tkinter to work in any form. I am currently on a macbook pro using python 2.7.5. I have tried re-downloading python multiple times but it is still not working.
Anyone have any ideas as to why it isn't working? Any more information needed from me?
Thanks in advance
```
#!/usr/bin/python
from Tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
``` | 2014/07/24 | [
"https://Stackoverflow.com/questions/24923412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3871003/"
] | You have some other module that is taking the name "Tkinter", shadowing the one you actually want. Rename or remove it.
```
import Tkinter
print Tkinter.__file__
``` |
280,990 | I have a list:
```
\begin{enumerate}[label={[\Roman*]},ref={[\Roman*]}]
\item\label{item1} The first item.
\end{enumerate}
```
What I want to achieve is this:
In the most instances, I want to refer to the items of the list by the format specified above (that is: `\ref{item1}` should in general produce "[I]"). However, in a few particular instances, I want to refer to the items by a custom reference formatting (more specifically, without the square brackets, by "1" instead of "[1]"), but I want still that the numbering is automatic (otherwise, I could use, for example `\hyperref[item1]{1}` to refer). Therefore, I would like to, for example, define a new command `\nobracketsref` such that `\nobracketsref{item1}` should produces "1".
How this could be achieved? I would appreciate any help.
PS. In the situation there is one twist that may affect the solution: I have two `.tex` files so that the list is in one file (the list document) and I am referring to its items from the other file (the main document).
This is done in a usual way by involving in the preamble of the main document:
```
\usepackage{xr-hyper}
\usepackage{hyperref}
\externaldocument{the_list_document.tex}
``` | 2015/12/01 | [
"https://tex.stackexchange.com/questions/280990",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/93296/"
] | Define `ref=` to use a macro, instead of the explicit brackets; such a macro can be redefined to do nothing when the brackets are not wanted.
```
\documentclass{article}
\usepackage{enumitem,xparse}
\usepackage[colorlinks]{hyperref}
\makeatletter
\NewDocumentCommand{\nobracketref}{sm}{%
\begingroup\let\bracketref\@firstofone
\IfBooleanTF{#1}{\ref*{#2}}{\ref{#2}}%
\endgroup
}
\makeatother
\NewDocumentCommand{\bracketref}{m}{[#1]}
\begin{document}
\begin{enumerate}[label={[\Roman*]},ref={\bracketref{\Roman*}}]
\item\label{item1} The first item.
\end{enumerate}
With brackets: \ref{item1} (link)
With brackets: \ref*{item1} (no link)
Without brackets: \nobracketref{item1} (link)
Without brackets: \nobracketref*{item1} (no link)
\end{document}
```
I don't think `xr-hyper` is much of a concern here.
[![enter image description here](https://i.stack.imgur.com/W0rtE.png)](https://i.stack.imgur.com/W0rtE.png) |
1,556,700 | there is a page ($9\times 9$) how many different rectangles can you draw with odd area?
rectangles are different if they are different on size and place.
for example if a rectangle is $15$ squares, its area is odd.
if a rectangle is $12$ squares, its area is even.
I have no idea how to approach this question so I can't give my answer.
Thanks! | 2015/12/02 | [
"https://math.stackexchange.com/questions/1556700",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/295268/"
] | If the area has to be odd, the length and breadth both have to be odd. Hence, we count the number of rectangles by first choosing a row and a column ($10 \cdot 10$ ways to do this), and then choosing another row and column which are at an odd distance from the chosen one ($5 \cdot 5$ ways to do this). But we have counted each rectangle four times -- by the first row/column and then again by the second row/column -- so we divide by 4 to get our final answer: $1/4 \cdot 10 \cdot 10 \cdot 5 \cdot 5 = 625$. |
31,633,191 | What is the best way of removing element from a list by either a comparison to the second list or a list of indices.
```
val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
val toDropFromMylist = List(Cat, Cat, Dog)
```
Which the indices accordance with myList are:
```
val indices = List(2, 7, 0)
```
The end result expected to be as below:
```
newList = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Any idea? | 2015/07/26 | [
"https://Stackoverflow.com/questions/31633191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79147/"
] | Using `toDropFromMylist` is actually the simplest.
```
scala> myList diff toDropFromMylist
res0: List[String] = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
``` |
233,158 | I am working on a web api and I am curios about the `HTTP SEARCH` verb and how you should use it.
My first approach was, well you could use it surely for a search. But asp.net WebApi doesn't support the `SEARCH` verb.
My question is basically, should I use `SEARCH` or is it not important?
PS: I found the `SEARCH` verb in fiddler2 from telerik. | 2014/03/21 | [
"https://softwareengineering.stackexchange.com/questions/233158",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/82918/"
] | The HTTP protocol is defined by RFC documents. RFC2616 defines HTTP/1.1 the current release.
SEARCH is not documented as a verb in this document. |
3,639,718 | I recreated a Select box and its dropdown function using this:
```
$(".selectBox").click(function(e) {
if (!$("#dropDown").css("display") || $("#dropDown").css("display") == "none")
$("#dropDown").slideDown();
else
$("#dropDown").slideUp();
e.preventDefault();
});
```
The only problem is that if you click away from the box, the dropdown stays. I'd like it to mimic a regular dropdown and close when you click away, so I thought I could do a 'body' click:
```
$('body').click(function(){
if ($("#dropdown").css("display") || $("#dropdown").css("display") != "none")
$("#dropdown").slideUp();
});
```
But now, when you click the Select box, the dropdown slides down and right back up. Any ideas what I'm doing wrong? Thanks very much in advance... | 2010/09/03 | [
"https://Stackoverflow.com/questions/3639718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324529/"
] | You also need to stop a click from *inside* the `#dropdown` from bubbling back up to `body`, like this:
```
$(".selectBox, #dropdown").click(function(e) {
e.stopPropagation();
});
```
We're using [`event.stopPropagation()`](http://api.jquery.com/event.stopPropagation/) it stops the click from bubbling up, causing the [`.slideUp()`](http://api.jquery.com/slideUp/). Also your other 2 event handlers can be simplified with [`:visible`](http://api.jquery.com/visible-selector/) or [`.slideToggle()`](http://api.jquery.com/slideToggle/), like this overall:
```
$(".selectBox").click(function(e) {
$("#dropDown").slideToggle();
return false; //also prevents bubbling
});
$("#dropdown").click(function(e) {
e.stopPropagation();
});
$(document).click(function(){
$("#dropdown:visible").slideUp();
});
``` |
28,429,768 | Lets say I have a `ItemsControl`which is used to render buttons for a list of viewModels
```
<ItemsControl ItemsSource="{Binding PageViewModelTypes}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
CommandParameter="{Binding }" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
```
The `PageViewModelTypes`are the view models which are available (For example `OtherViewModel`). For each of the types there is a `DataTemplate` setup with the according views.
```
<dx:DXWindow.Resources>
<DataTemplate DataType="{x:Type generalDataViewModel:GeneralViewModel}">
<generalDataViewModel:GeneralView />
</DataTemplate>
<DataTemplate DataType="{x:Type other:OtherViewModel}">
<other:OtherView />
</DataTemplate>
</dx:DXWindow.Resources>
```
Is there any way of replacing the `PageViewModelTypes` with the corresponding template types for the `ItemsControl` within the view? | 2015/02/10 | [
"https://Stackoverflow.com/questions/28429768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/931051/"
] | Bind the button content to the item content and your templates will be resolved to the actual types:
```
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding}"
CommandParameter="{Binding }" />
</DataTemplate>
</ItemsControl.ItemTemplate>
``` |
39,070,614 | Here is a program about the Fibonacci sequence. Each time the code branches off again you are calling the fibonacci function from within itself two times.
```
def fibonacci(number)
if number < 2
number
else
fibonacci(number - 1) + fibonacci(number - 2)
end
end
puts fibonacci(6)
```
The only thing I understand is that it adds the number from the previous number. This program was taken from my assignment. It says, "If you take all of those ones and zeros and add them together, you'll get the same answer you get when you run the code."
[![enter image description here](https://i.stack.imgur.com/JoZlf.jpg)](https://i.stack.imgur.com/JoZlf.jpg)
I really tried my best to understand how this code works but I failed. Can anyone out there who is so kind and explain to me in layman's term or in a way a dummy would understand what's happening on this code? | 2016/08/22 | [
"https://Stackoverflow.com/questions/39070614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is just the direct 1:1 translation (with a simple twist) of the standard mathematical definition of the Fibonacci Function:
```
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-2) + Fib(n-1)
```
Translated to Ruby, this becomes:
```
def fib(n)
return 0 if n.zero?
return 1 if n == 1
fib(n-2) + fib(n-1)
end
```
It's easy to see that the first two cases can be combined: if n is 0, the result is 0, if n is 1, the result is 1. That's the same as saying if n is 0 or 1, the result is the same as n. And "n is 0 or 1" is the same as "n is less than 2":
```
def fib(n)
return n if n < 2
fib(n-2) + fib(n-1)
end
```
There's nothing special about this, it's the exact translation of the recursive definition of the mathematical Fibonacci function. |
20,506,847 | How can I retrieve all keys in a Hash in Ruby, also the nested ones. Duplicates should be ignored, e.g.
```
{ a: 3, b: { b: 2, b: { c: 5 } } }.soberize
=> [:a, :b, :c]
```
What would be the fastest implementation? | 2013/12/10 | [
"https://Stackoverflow.com/questions/20506847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642429/"
] | Simple recursive solution:
```
def recursive_keys(data)
data.keys + data.values.map{|value| recursive_keys(value) if value.is_a?(Hash) }
end
def all_keys(data)
recursive_keys(data).flatten.compact.uniq
end
```
Usage:
```
all_keys({ a: 3, b: { b: 2, b: { c: 5 } } })
=> [:a, :b, :c]
``` |
11,602,072 | I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification.
```
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
```
I have created a text file to work on, the text reads:
```
so this is where you have been
```
After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter:
```
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
```
But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned. | 2012/07/22 | [
"https://Stackoverflow.com/questions/11602072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1259395/"
] | At this point:
```
if(c == ' ')
{
if(inspace == 0) // <-- here
```
If inspace is equal to 1, it will not execute the if body, it will jump to:
```
if(c != ' ') {
```
And as long as c == ' ' above will be false, so it will skip the if body and jump to:
```
while((c = getchar()) != EOF) {
```
And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space:
```
if(c != ' ')
{
inspace = 0;
putchar(c);
```
inspace is zeroed, and character is printed. |
172,847 | I am new to CartoDB/Leaflet. Here's my fiddle...
<http://jsfiddle.net/zippyferguson/fLkqgf4q/1/>
If you click the play button, I want it to load data to the map year by year from 1966 to 2015 from a CartoDB query. But, with each iteration, the map is cleared of data, and then the next year data appears. I am looking to load the next year data and remove the previous year data underneath in the previous layer, without the clearing of everything on the map. If you comment out this line in the fiddle, you will kind of see what I am looking for.
```
removeAllLayersExcept(layer);
```
...this function is an attempt to remove all layers on the map except the one just loaded.
But, with removeAllLayersExcept(layer) commented out, that just keeps putting more layers on the map. I don't understand why it clears the whole map each iteration. | 2015/12/07 | [
"https://gis.stackexchange.com/questions/172847",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/62913/"
] | You correctly remove previous layer(s) only once the data for the new layer is received, but not its tiles (images). That is why your map appears empty for a short time.
You could first attach your `removeAllLayersExcept` callback to the [`"load"` event](http://leafletjs.com/reference.html#tilelayer-load) of your new Tile Layer.
>
> Fired when the tile layer loaded all visible tiles.
>
>
>
Then you would also leave a short timeout before actually removing other layer(s), because the new tiles will appear with a little delay and transition, even if they are correctly loaded already.
```js
cartodb.createLayer(map, layerSource)
.addTo(map)
.done(function(layer) {
//removeAllLayersExcept(layer);
layer.once("load", function () { // Remove only once the new tile layer has downloaded all tiles in view port.
removeAllLayersExcept(layer);
});
setTimeout(updateMap, 1000);
})
.error(function(err) {
console.log("error: " + err);
});
function removeAllLayersExcept(new_layer) {
console.log('new_layer._leaflet_id:' + new_layer._leaflet_id);
var layer_index = 0;
map.eachLayer(function(layer) {
if (layer_index > 0 && layer._leaflet_id != new_layer._leaflet_id) {
console.log('layer removed:' + layer._leaflet_id);
//map.removeLayer(layer);
setTimeout(function () { // give a little time before removing previous tile layer because new one will appear with some transition.
map.removeLayer(layer);
}, 500);
}
layer_index++;
});
}
```
Demo: <http://jsfiddle.net/fLkqgf4q/5/>
Note: you may also need to harden your `removeAllLayersExcept` function to cover the case where a more recent Tile Layer is loaded *before* a previous one (due to some back connectivity or whatever). Otherwise the previous layer will make the new one being removed from map. But then you also need to handle the case when the user manually drags the cursor backwards. |
284,563 | I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress.
Now I want to know if there is any way to redirect URLs as mentioned below.
Current (In Blogger):
```
http://www.example.com/2017/10/seba-online-form-fill-up-2018.html
```
After (In WordPress):
```
http://www.example.com/seba-online-form-fill-up-2018.html
```
That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs. | 2017/11/01 | [
"https://wordpress.stackexchange.com/questions/284563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`:
```
RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L]
```
This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`.
The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`.
Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.) |
36,739,985 | Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop. | 2016/04/20 | [
"https://Stackoverflow.com/questions/36739985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6027397/"
] | I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
```
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
```
Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is
```
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
``` |
12,765,480 | Are there any major overhead differences between using a `UNIQUE` constraint on two columns and simply having one column that contains the concatenation of the two column values/GUID and using an index on that? For example, instead of using `|John|Smith|` (two different columns) as the unique constraint, would it be more efficient to add an extra column that holds `JohnSmith` or a random GUID? | 2012/10/07 | [
"https://Stackoverflow.com/questions/12765480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369784/"
] | I would go with adding those two columns and define a unique constraint on them as they seem to have business relevance and a GUID doesn't seem to be suitable. Also, the motivation to NOT combine them is to avoid any `SUBSTRING` operations at a later point to process them separately. |
22,105,306 | So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
``` | 2014/02/28 | [
"https://Stackoverflow.com/questions/22105306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355076/"
] | You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*:
```
vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
vertices.append((x, y))
```
You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred. |
7,233,392 | Is there any way I can authenticate a Facebook user without requiring them to connect in the front end? I'm trying to report the number of "likes" for an alcohol-gated page and will need to access the information with an over-21 access token, but do not want to have to log in every time I access the data.
Or is there a way to generate an access token that doesn't expire?
I'm really not that much of an expert with facebook, so any alternatives to these ideas would be greatly appreciated. | 2011/08/29 | [
"https://Stackoverflow.com/questions/7233392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402606/"
] | When you're requesting the access token you're going to use to check the Page, request the `offline_access` extended permission and the token won't expire when you/the user logs out. |
23,673,577 | I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly.
```
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c(a);
```
This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves? | 2014/05/15 | [
"https://Stackoverflow.com/questions/23673577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3639950/"
] | A `shared_ptr` expects to *own* the pointed-at object.
What you've done is to create *two* separate smart pointers, each of which thinks it has exclusive ownership of the underlying `int`. They don't know about each other's existence, they don't talk to each other. Therefore, when they go out of scope, both pointers delete the underlying resource, with the obvious result.
When you create a `shared_ptr`, it creates a sort of "management object" which is responsible for the resource's lifetime. When you *copy* a `shared_ptr`, both copies reference the same management object. The management object keeps track of how many `shared_ptr` instances are pointing at this resource. An `int*` by itself has no such "management object", so copying it does not keep track of references.
Here's a minimal rewrite of your code:
```
// incidentally, "make_shared" is the best way to do this, but I'll leave your
// original code intact for now.
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c = b;
```
Now, they both reference the same underlying management object. As each `shared_ptr` is destroyed, the number of references on the `int*` is reduced and when the last reference goes ther object is deleted. |
230,264 | I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible? | 2014/02/25 | [
"https://softwareengineering.stackexchange.com/questions/230264",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/121236/"
] | In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information.
An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system.
In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this.
Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web. |
286,606 | In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.
Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?
Thanks! | 2008/11/13 | [
"https://Stackoverflow.com/questions/286606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] | You don't need to.
Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control.
The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus. |
844,323 | If $\cos{(A-B)}=\frac{3}{5}$ and $\sin{(A+B)}=\frac{12}{13}$, then find $\cos{(2B)}$.
Correct answer = 63/65.
I tried all identities I know but I have no idea how to proceed. | 2014/06/23 | [
"https://math.stackexchange.com/questions/844323",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/159625/"
] | Every $B(4,k)$ admits a graceful labeling.
We prove this by induction on $k$.
Our induction hypothesis is: every $B(4,k)$ admits a graceful labeling where the vertex of degree 1 has label 0.
For $k=1$ we cyclically assign the labels $1,4,3,5$ to the vertices of the cycle.
Then add one pending edge to the vertex with label $5$ and give the last vertex label 0.
It is trivially verified that this defines a graceful labeling.
For the induction step: take a $B(4,k)$ with a graceful labeling where the vertex of degree 1 has label 0.
Now prolong the path with one more edge and give the new vertex label $k+5$.
We now have a graceful labeling of $B(4,k+1)$.
Finally invert that labeling (i.e. replace each label $x$ by $k+5-x$ and we end up with a graceful
labeling of $B(4,k+1)$ with $0$ on the vertex of degree 1.
Note that this procedure generalizes to all $B(n,k)$, where $C\_n$ is graceful. |
51,548,884 | ```
try:
folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True).decode().split()[0])
print('\t\tTotal download progress (MB):\t' + str(folderSizeInMB), end = '\r')
except Exception as e:
print('\t\tDownloading' + '.'*(loopCount - gv.parallelDownloads + 3), end = '\r')
```
I have this code in my script because for some reason my unix decided to not find 'du' command. It throws an error `/bin/sh: du: command not found`.
My hope with this code was that even though my program runs into this error, it will just display the message in the `except` block and move-along. However, it prints the error before displaying the message in the `except` block. Why is it doing so? Is there a way for me to suppress the error message displayed by the `try` block?
Thanks.
EDIT:
I rewrote the code after receiving the answer like shown below and it works. I had to rewrite only one line:
```
folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True, stederr=subprocess.DEVNULL).decode().split()[0])
``` | 2018/07/26 | [
"https://Stackoverflow.com/questions/51548884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868465/"
] | The error is being shown by the shell, printing to stderr. Because you’re not redirecting its stderr, it just goes straight through to your own program’s stderr, which goes to your terminal.
If you don’t want this—or any other shell features—then the simplest solution is to just not use the shell. Pass a list of arguments instead of a command line, and get rid of that `shell=True`, and the error will become a normal Python exception that you can handle with the code you already have.
If you just use the shell for some reason, you will need to redirect its stderr. You can pass `stderr=subprocess.STDOUT` to make it merge in with the stdout that you’re already capturing, or `subprocess.DEVNULL` to ignore it. The `subprocess` module docs explain all of the options nicely, so read them, decide which behavior you want, and do that. |
81,247 | I work with reconstructing fossil skeletons of human ancestors. Bones are usually incomplete and I need to assemble whole virtual bones from laser scans of different fossil parts of the bone I have scanned. How can I efficiently delete parts I don't need so that I can assemble whole virtual bones? I know it's easy to delete by bisecting, but that's not enough for what I need [![enter image description here](https://i.stack.imgur.com/zYOwO.jpg)](https://i.stack.imgur.com/zYOwO.jpg)Does this image help explain what I wantto do? | 2017/06/12 | [
"https://blender.stackexchange.com/questions/81247",
"https://blender.stackexchange.com",
"https://blender.stackexchange.com/users/40161/"
] | Hope this helps:
You can try centering the mesh in an axis (X or Y most commonly) and then use `numpad 1` or `numpad 3` to get an isometric view of the mesh along that axis. (Depending on your blender config, you might need to also press `numpad 5`)
Then you can press `z` and `tab` to go into wireframe mode and edit mode respectively.
Once there, you can select whatever vertices are not needed (To select vertices you can use the hotkey `ctrl`+`shift`+`tab` and select vertices in the popup menu) and delete them. Then press `tab` again to go back to object mode and add a mirror modifier to mirror the whole "correct" side of the mesh along the axis you need. Fiddle around with the merge and clipping options to get whatever desired effect you were looking for. |
6,527,788 | In Objective C I want to create a simple application that posts a string to a php file using ASIHTTPRequest.
I have no need for an interface and am finding it hard to find any example code. Does anyone know where I can find code, or can anyone give me an example of such code? | 2011/06/29 | [
"https://Stackoverflow.com/questions/6527788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559142/"
] | The ASIHTTPRequest documentation covers this. Specifically, [Sending a form POST with ASIFormDataRequest](http://allseeing-i.com/ASIHTTPRequest/How-to-use#sending_a_form_post_with_ASIFormDataRequest). |
451,792 | I am using Survival Analysis to analyse a data set, but i'm having a bit of trouble.
The data consists of everyone who has/has not been terminated from employment within a 4 year period. The aim of the analysis is to uncover the median time to termination.
The data includes 400 people who has experienced the event and 2275 people who have not.
Looking at the raw data, 150 people have remained employed between 30-48 years.
The remaining 2525 people have been employed for less than 30 years.
The average time spent working in the organisation is 4 years.
However, the median time to survival using survival analysis is 40 years.
I'm very familiar with the organisation and this median time to leaving is counter intuitive. Am I missing something?
My code is below
You will see, I start by calculating the length of time from when they began working in the organisation and when they leave (variable name is 'yrs'). If they have not been terminated, today's date is used as they are still employed in the organisation (perhaps this is where i'm going wrong?).
Then I create a survival curve using 'yrs' and 'termid', where termid is an indicator variable, indicating if the observation has been terminated or not.
The median survival time of 40 years is then returned
Is there an issue with my code? Or is it expected that so few observations could carry this much weight in a Survival Analysis.
```
#find survival time #calculating the number of days between last follow up date and date of starting in the organisation
leaversanalysis = leaversanalysis %>%
mutate(
yrs =
as.numeric(
difftime(Term.Date,
Date.Joined.Organisation,
units = "days")) / 365.25
)
#Indicator variable for termination is 'termid'
#Kaplan Meier estimator for any termination (termination =1, no termination =0)
a <- Surv(leaversanalysis$yrs, leaversanalysis$termid)
#Create survival curve
surv_curvleave <- survfit(Surv(yrs, termid) ~ 1 , data = leaversanalysis)
surv_curvleave
``` | 2020/02/28 | [
"https://stats.stackexchange.com/questions/451792",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/237783/"
] | Median survival here is the time at which 50% of your participants would still be non-terminated.
The lower the risk (hazard) of an event (in your case being "terminated"), the longer it will take to get to the point where 50% of participants have had that event.
An example:
simulate data similar to yours:
```
set.seed(129)
yrs1 <- round(rbeta(n=2225, shape1 = 1.3, shape2 = 8)*48,1)
yrs2 <- runif(450, min=0, max=48)
yrs <- c(yrs1,yrs2)
termid <- sample(x = c(rep(1, each = 400), rep(0,each=2275)), size = 2675)
data <- data.frame(yrs,termid)
sum(yrs>30) # 167 people employed over 30 yrs
hist(yrs, breaks = 20)
```
[![enter image description here](https://i.stack.imgur.com/zcjOW.png)](https://i.stack.imgur.com/zcjOW.png)
Your code is fine. The survival plot below should reveal why the "median survival" is what it is.
```
fit <- survfit(Surv(yrs,termid) ~1, data = data)
plot(fit, xlab = "years", ylab = "probability of not being terminated")
abline(h=0.5); abline(v=43.3)
fit
```
[![Survival plot](https://i.stack.imgur.com/UOE0C.png)](https://i.stack.imgur.com/UOE0C.png)
```
Call: survfit(formula = Surv(yrs, termid) ~ 1, data = data)
n events median 0.95LCL 0.95UCL
2675.0 400.0 43.3 40.1 46.2
```
The reported median survival here is 43.3 years.
You have said "this median time to leaving is counter intuitive". What you are studying is the median time to being terminated. If people are **leaving** for other reasons, then using these methods, they are censored, and so do not affect the position of the survival curve. |
69,224 | I have this metric:
$$ds^2=-dt^2+e^tdx^2$$
and I want to find the equation of motion (of x). for that i thought I have two options:
1. using E.L. with the Lagrangian: $L=-\dot t ^2+e^t\dot x ^2 $.
2. using the fact that for a photon $ds^2=0$ to get: $0=-dt^2+e^tdx^2$ and then:
$dt=\pm e^{t/2} dx$.
The problem is that (1) gives me $x=ae^{-t}+b$ and (2) gives me $x=ae^{-t/2} +b$. | 2013/06/26 | [
"https://physics.stackexchange.com/questions/69224",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/26299/"
] | If your solution is not a null geodesic then it is wrong for a massless particle.
The reason you go astray is that Lagrangian you give in (1) is incorrect for massless particles. The general action for a particle (massive or massless) is:
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \left( \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 + \frac{m^2}{\sigma(\xi)}\right), $$
where $\xi$ is an arbitrary worldline parameter and $\sigma(\xi)$ an auxiliary variable that must be eliminated by its equation of motion. Also note the notation
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2\equiv \pm g\_{\mu\nu} \frac{\mathrm{d}X^\mu}{\mathrm{d}\xi}\frac{\mathrm{d}X^\nu}{\mathrm{d}\xi}, $$
modulo your metric sign convention (I haven't checked which one is right for your convention). Check that for $m\neq 0$ this action reduces to the usual action for a massive particle. For the massless case however, you get
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2. $$
The equation of motion for $\sigma$ gives the constraint
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 = 0, $$
for a null geodesic. This is necessary and consistent for massless particles, as you know.
The equation of motion for $X^\mu$ is (**EDIT**: Oops, I forgot a term here. Note that $g\_{\mu\nu}$ depends on $X$ so a term involving $\partial\_\rho g\_{\mu\nu}$ comes into the variation. Try working it out for yourself. I'll fix the following equations up later):
$$ \frac{\mathrm{d}}{\mathrm{d}\xi}\left(\sigma g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\xi}\right)=0, $$
but you can change the parameter $\xi\to\lambda$ so that $\sigma \frac{\mathrm{d}}{\mathrm{d}\xi} = \frac{\mathrm{d}}{\mathrm{d}\lambda}$, so the equation of motion simplifies to
$$ \frac{\mathrm{d}}{\mathrm{d}\lambda}\left(g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\lambda}\right)=0, $$
which you should be able to solve to get something satisfying the null constraint. |
72,924,818 | I've been trying for a long time to write the results to my file, but since it's a multithreaded task, the files are written in a mixed way
The task that adds the file is in the get\_url function
And this fonction is launched via pool.submit(get\_url,line)
```
import requests
from concurrent.futures import ThreadPoolExecutor
import fileinput
from bs4 import BeautifulSoup
import traceback
import threading
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
count_requests = 0
host_error = 0
def get_url(url):
try:
global count_requests
result_request = requests.get(url, verify=False)
soup = BeautifulSoup(result_request.text, 'html.parser')
with open('outfile.txt', 'a', encoding="utf-8") as f:
f.write(soup.title.get_text())
count_requests = count_requests + 1
except:
global host_error
host_error = host_error + 1
with ThreadPoolExecutor(max_workers=100) as pool:
for line in fileinput.input(['urls.txt']):
pool.submit(get_url,line)
print(str("requests success : ") + str(count_requests) + str(" | requests error ") + str(host_error), end='\r')
```
This is what the output looks like :
google.com - Google
w3schools.com - W3Schools Online Web Tutorials | 2022/07/09 | [
"https://Stackoverflow.com/questions/72924818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19518180/"
] | You can use [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool) and `pool.imap_unordered` to receive processed results and write it to the file. That way the results are written only inside main thread and won't be interleaved. For example:
```py
import requests
import multiprocessing
from bs4 import BeautifulSoup
def get_url(url):
# do your processing here:
soup = BeautifulSoup(requests.get(url).content, "html.parser")
return soup.title.text
if __name__ == "__main__":
# read urls from file or other source:
urls = ["http://google.com", "http://yahoo.com"]
with multiprocessing.Pool() as p, open("result.txt", "a") as f_out:
for result in p.imap_unordered(get_url, urls):
print(result, file=f_out)
``` |