qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | ```
git push origin <local-branch-name>:<remote-branch-name>
```
Substitute for `<local-branch-name>` and `<remote-branch-name>`. They may be same or different, as you wish. | As you have set up the remotes already, the command is just
```
git push origin branch-name
```
on the first push.
Afterward, using `git push origin` would push all branches with the matching name on remote. |
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | As you have set up the remotes already, the command is just
```
git push origin branch-name
```
on the first push.
Afterward, using `git push origin` would push all branches with the matching name on remote. | if you need to pull any branch code from remotely to locally
```
$git pull origin branch_name
```
while if you need to push code to your branch
**you need to check is your code successfully save
you can check by**
```
$git status
```
than
```
$git add -A
```
**after this make commit to your branch**
```
$git commit -m "this is initial change"
```
than(Last)
**push your code to your branch by:**
```
$git push origin branch_name
``` |
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | ```
git push origin <local-branch-name>:<remote-branch-name>
```
Substitute for `<local-branch-name>` and `<remote-branch-name>`. They may be same or different, as you wish. | Make sure that your remote URL is using SSH syntax and not just Git protocol syntax. If you run,
```
git remote show origin
```
the URL printed should look something like,
```
git@github.com:yourname/projectname.git
```
You need the URL too to look like that if you want to be able to push. If you are just a public user (without write access) the URL will look like,
```
git://github.com/yourname/projectname.git
```
If yours looks like the latter then you can manually edit it in your projects `.git/config` file. |
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | Make sure that your remote URL is using SSH syntax and not just Git protocol syntax. If you run,
```
git remote show origin
```
the URL printed should look something like,
```
git@github.com:yourname/projectname.git
```
You need the URL too to look like that if you want to be able to push. If you are just a public user (without write access) the URL will look like,
```
git://github.com/yourname/projectname.git
```
If yours looks like the latter then you can manually edit it in your projects `.git/config` file. | if you need to pull any branch code from remotely to locally
```
$git pull origin branch_name
```
while if you need to push code to your branch
**you need to check is your code successfully save
you can check by**
```
$git status
```
than
```
$git add -A
```
**after this make commit to your branch**
```
$git commit -m "this is initial change"
```
than(Last)
**push your code to your branch by:**
```
$git push origin branch_name
``` |
1,072,261 | I have a local repository I'm working on and its remote is hosted on GitHub. I recently created a branch and started working on it, making several commits and now wish to push the branch to GitHub and be able to pull it to another cloned repository. How do I do this? | 2009/07/02 | [
"https://Stackoverflow.com/questions/1072261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27025/"
] | ```
git push origin <local-branch-name>:<remote-branch-name>
```
Substitute for `<local-branch-name>` and `<remote-branch-name>`. They may be same or different, as you wish. | if you need to pull any branch code from remotely to locally
```
$git pull origin branch_name
```
while if you need to push code to your branch
**you need to check is your code successfully save
you can check by**
```
$git status
```
than
```
$git add -A
```
**after this make commit to your branch**
```
$git commit -m "this is initial change"
```
than(Last)
**push your code to your branch by:**
```
$git push origin branch_name
``` |
43,434,195 | I am trying write a bash file to find a string in a .txt file using shell script and want to replace same with new string.
The string pattern which I am trying find `{{asdf}}` and I want to replace it with `ghjk` from command line arg.
I tried with the following bash file:
```
ptr="\{\{(.*?)\}\}"
username="$1"
password="$2"
sed 's/$ptr/${username}/g' new.txt
sed 's/$ptr/${password}/g' sec.txt
```
but it's not working. | 2017/04/16 | [
"https://Stackoverflow.com/questions/43434195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7873502/"
] | You need double codes before the vars will be replaced by their values.
With a `+` telling at least once, you can use
```
ptr="{{.\+}}"
sed "s/$ptr/${username}/g" usertemplate.txt > new.txt
```
Using `sed` for the password will be a challenge in view of the special characters (don't tell others, my password is `/\\[.*&{7z`).
You can try something like
```
ptr="{{.\+}}"
username='/\\[.*&{7z'
escapedname=$(sed 's/[&=\/|]/\\&/g' <<< "$username")
sed "s/$ptr/${escapedname}/g" usertemplate.txt
```
Edit: I first tried to escape most characters, but that was to hard for me.
I changed it into a minimal version. I hope this one is better. | Just use awk:
```
username="$1" awk '
{
gsub(/}}/,"\n")
delete a
if ( match($0,/{{[^\n]+\n/) ) {
a[1] = substr($0,1,RSTART-1)
a[2] = ENVIRON["username"]
a[3] = substr($0,RSTART+RLENGTH)
}
else {
a[1] = $0
}
gsub(/\n/,"}}",a[1])
gsub(/\n/,"}}",a[3])
print a[1] a[2] a[3]
}
' new.txt
```
The above will work for any value of `username` and will not fail if/when `{{foo}` (just one `}`) appears in the input. Repeat for password. It's important to set the shell variable `username` on the awk command line exactly as shown so it's available to awk via the ENVIRON array without needing to export it. |
43,434,195 | I am trying write a bash file to find a string in a .txt file using shell script and want to replace same with new string.
The string pattern which I am trying find `{{asdf}}` and I want to replace it with `ghjk` from command line arg.
I tried with the following bash file:
```
ptr="\{\{(.*?)\}\}"
username="$1"
password="$2"
sed 's/$ptr/${username}/g' new.txt
sed 's/$ptr/${password}/g' sec.txt
```
but it's not working. | 2017/04/16 | [
"https://Stackoverflow.com/questions/43434195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7873502/"
] | one thing you should note is that `''` single quotes have special meaning in shell programming. Single quotes negates a variable i.e they don't allow you to access the content of the variable but just the name of the variable.
What you need to do , is to remove the single quotes `'s/$ptr/${username}/g'` and wrap with with double quotes i.e `"s/$ptr/${username}/g"`.
Better still if you wish to use single quotes, you should use here strings just as [walter](https://stackoverflow.com/users/3220113/walter-a) specified. Here strings can be done with `<<<`. If you decide to use here strings, the logic of the code will change totally. | Just use awk:
```
username="$1" awk '
{
gsub(/}}/,"\n")
delete a
if ( match($0,/{{[^\n]+\n/) ) {
a[1] = substr($0,1,RSTART-1)
a[2] = ENVIRON["username"]
a[3] = substr($0,RSTART+RLENGTH)
}
else {
a[1] = $0
}
gsub(/\n/,"}}",a[1])
gsub(/\n/,"}}",a[3])
print a[1] a[2] a[3]
}
' new.txt
```
The above will work for any value of `username` and will not fail if/when `{{foo}` (just one `}`) appears in the input. Repeat for password. It's important to set the shell variable `username` on the awk command line exactly as shown so it's available to awk via the ENVIRON array without needing to export it. |
37,299,630 | I am using APi The access to this api is done with hash key that we need to send to the api but we don't really know how to implement.
I found <https://www.npmjs.com/package/crypto-js> but i dont know how to integrate angular 2
also i found <https://www.npmjs.com/package/angular-md5> but i dont know how to import using angular 2 typscript | 2016/05/18 | [
"https://Stackoverflow.com/questions/37299630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6246988/"
] | For angular 2 use
```
npm install ts-md5 --save
```
then import it into component, service or wherever you want
```
import {Md5} from 'ts-md5/dist/md5';
```
When you are using **systemJS** is neccessary set map and package paths.
```
map: {
'ts-md5': 'src/js/ts-md5',
},
packages: {
'ts-md5': {main: '/md5.js'},
}
```
This is the example from one of my project where I copy neccessary libraries to separate file structure. | You can get a md5.ts file here:
<https://github.com/ManvendraSK/angular2-quickstart/blob/master/app/md5.ts>
import it in your component/service:
```
import {md5} from './md5'; //make sure it points to the folder where the md5.ts file is
```
then you can use it in your component/service:
```
let e = md5(this.email);
``` |
71,473,962 | I know this is probably really basic and there is an easy answer, but I'm not sure how to make two functions call each other. Function A calls Function B on a condition or two, and function B calls function A on a condition or two. Example:
```
def functionA():
if something is true:
functionB()
if something isn't true:
something is false
def functionB():
if something is false:
functionA()
```
I am pretty bad at python, so if you answer my question please give me an example or two. I know that I am supposed to put the function before it is called, but I'm not sure how to make it work with two functions. Thanks. | 2022/03/14 | [
"https://Stackoverflow.com/questions/71473962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13812746/"
] | #### What you've already written will "work".
This isn't C; you can *define* a function that calls a function that doesn't yet exist, so as long as you don't *call* such a function until the dependencies exist. As long as neither `functionA` nor `functionB` is called until both are defined, this "works".
The reason I'm quoting "works" is because as written, this will immediately die with a `RecursionError` (the condition for calling each other is the same, so they'd recurse until they hit Python's limit, which you can check by
calling `sys.getrecursionlimit()`). But they would be calling each other as requested, you just need to trigger the first one to be called (e.g. by adding a plain `functionA()` or `functionB()` call after you've defined both of them). | I think one of the most common way to call a function into another function is use callback. It mean you call a function that will call another function you gave it as a parameter.
Here is an example :
```
def sum_numbers(a, b, callback):
res = a + b
callback(res)
def print_result(res):
print(res)
sum_numbers(1, 8, print_result)
```
Output :
```
9
```
Here the first function calculate the sum and the second just print the result. But for sure you can do a lot of things more interesting with that. |
44,978,196 | I've a data frame that looks like the following
```
x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})
```
What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in `0` for the `val` column. So the desired output is
```
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-03 a 0
3 2016-01-04 a 0
4 2016-01-05 a 0
5 2016-01-06 a 0
6 2016-01-01 b 0
7 2016-01-02 b 0
8 2016-01-03 b 0
9 2016-01-04 b 0
10 2016-01-05 b 2
11 2016-01-06 b 1
```
I've tried the solution mentioned [here](https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe) and [here](https://stackoverflow.com/questions/27241795/fill-missing-dates-by-group-in-pandas) but they aren't what I'm after.
Any pointers much appreciated. | 2017/07/07 | [
"https://Stackoverflow.com/questions/44978196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210178/"
] | Initial Dataframe:
```
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-05 b 2
3 2016-01-06 b 1
```
First, convert the dates to datetime:
```
x['dt'] = pd.to_datetime(x['dt'])
```
Then, generate the dates and unique users:
```
dates = x.set_index('dt').resample('D').asfreq().index
>> DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
'2016-01-05', '2016-01-06'],
dtype='datetime64[ns]', name='dt', freq='D')
users = x['user'].unique()
>> array(['a', 'b'], dtype=object)
```
This will allow you to create a MultiIndex:
```
idx = pd.MultiIndex.from_product((dates, users), names=['dt', 'user'])
>> MultiIndex(levels=[[2016-01-01 00:00:00, 2016-01-02 00:00:00, 2016-01-03 00:00:00, 2016-01-04 00:00:00, 2016-01-05 00:00:00, 2016-01-06 00:00:00], ['a', 'b']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]],
names=['dt', 'user'])
```
You can use that to reindex your DataFrame:
```
x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index()
Out:
dt user val
0 2016-01-01 a 1
1 2016-01-01 b 0
2 2016-01-02 a 33
3 2016-01-02 b 0
4 2016-01-03 a 0
5 2016-01-03 b 0
6 2016-01-04 a 0
7 2016-01-04 b 0
8 2016-01-05 a 0
9 2016-01-05 b 2
10 2016-01-06 a 0
11 2016-01-06 b 1
```
which then can be sorted by users:
```
x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index().sort_values(by='user')
Out:
dt user val
0 2016-01-01 a 1
2 2016-01-02 a 33
4 2016-01-03 a 0
6 2016-01-04 a 0
8 2016-01-05 a 0
10 2016-01-06 a 0
1 2016-01-01 b 0
3 2016-01-02 b 0
5 2016-01-03 b 0
7 2016-01-04 b 0
9 2016-01-05 b 2
11 2016-01-06 b 1
``` | As @ayhan suggests
```
x.dt = pd.to_datetime(x.dt)
```
One-liner using mostly @ayhan's ideas while incorporating `stack`/`unstack` and `fill_value`
```
x.set_index(
['dt', 'user']
).unstack(
fill_value=0
).asfreq(
'D', fill_value=0
).stack().sort_index(level=1).reset_index()
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-03 a 0
3 2016-01-04 a 0
4 2016-01-05 a 0
5 2016-01-06 a 0
6 2016-01-01 b 0
7 2016-01-02 b 0
8 2016-01-03 b 0
9 2016-01-04 b 0
10 2016-01-05 b 2
11 2016-01-06 b 1
``` |
44,978,196 | I've a data frame that looks like the following
```
x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})
```
What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in `0` for the `val` column. So the desired output is
```
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-03 a 0
3 2016-01-04 a 0
4 2016-01-05 a 0
5 2016-01-06 a 0
6 2016-01-01 b 0
7 2016-01-02 b 0
8 2016-01-03 b 0
9 2016-01-04 b 0
10 2016-01-05 b 2
11 2016-01-06 b 1
```
I've tried the solution mentioned [here](https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe) and [here](https://stackoverflow.com/questions/27241795/fill-missing-dates-by-group-in-pandas) but they aren't what I'm after.
Any pointers much appreciated. | 2017/07/07 | [
"https://Stackoverflow.com/questions/44978196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210178/"
] | Initial Dataframe:
```
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-05 b 2
3 2016-01-06 b 1
```
First, convert the dates to datetime:
```
x['dt'] = pd.to_datetime(x['dt'])
```
Then, generate the dates and unique users:
```
dates = x.set_index('dt').resample('D').asfreq().index
>> DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
'2016-01-05', '2016-01-06'],
dtype='datetime64[ns]', name='dt', freq='D')
users = x['user'].unique()
>> array(['a', 'b'], dtype=object)
```
This will allow you to create a MultiIndex:
```
idx = pd.MultiIndex.from_product((dates, users), names=['dt', 'user'])
>> MultiIndex(levels=[[2016-01-01 00:00:00, 2016-01-02 00:00:00, 2016-01-03 00:00:00, 2016-01-04 00:00:00, 2016-01-05 00:00:00, 2016-01-06 00:00:00], ['a', 'b']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]],
names=['dt', 'user'])
```
You can use that to reindex your DataFrame:
```
x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index()
Out:
dt user val
0 2016-01-01 a 1
1 2016-01-01 b 0
2 2016-01-02 a 33
3 2016-01-02 b 0
4 2016-01-03 a 0
5 2016-01-03 b 0
6 2016-01-04 a 0
7 2016-01-04 b 0
8 2016-01-05 a 0
9 2016-01-05 b 2
10 2016-01-06 a 0
11 2016-01-06 b 1
```
which then can be sorted by users:
```
x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index().sort_values(by='user')
Out:
dt user val
0 2016-01-01 a 1
2 2016-01-02 a 33
4 2016-01-03 a 0
6 2016-01-04 a 0
8 2016-01-05 a 0
10 2016-01-06 a 0
1 2016-01-01 b 0
3 2016-01-02 b 0
5 2016-01-03 b 0
7 2016-01-04 b 0
9 2016-01-05 b 2
11 2016-01-06 b 1
``` | An old question, with already excellent answers; this is an alternative, using the [complete](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.complete.html#janitor.complete) function from [pyjanitor](https://pyjanitor-devs.github.io/pyjanitor/) that could help with the abstraction when generating explicitly missing rows:
```py
#pip install pyjanitor
import pandas as pd
import janitor as jn
x['dt'] = pd.to_datetime(x['dt'])
# generate complete list of dates
dates = dict(dt = pd.date_range(x.dt.min(), x.dt.max(), freq='1D'))
# build the new dataframe, and fill nulls with 0
x.complete('user', dates, fill_value = 0)
user dt val
0 a 2016-01-01 1
1 a 2016-01-02 33
2 a 2016-01-03 0
3 a 2016-01-04 0
4 a 2016-01-05 0
5 a 2016-01-06 0
6 b 2016-01-01 0
7 b 2016-01-02 0
8 b 2016-01-03 0
9 b 2016-01-04 0
10 b 2016-01-05 2
11 b 2016-01-06 1
``` |
44,978,196 | I've a data frame that looks like the following
```
x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})
```
What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in `0` for the `val` column. So the desired output is
```
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-03 a 0
3 2016-01-04 a 0
4 2016-01-05 a 0
5 2016-01-06 a 0
6 2016-01-01 b 0
7 2016-01-02 b 0
8 2016-01-03 b 0
9 2016-01-04 b 0
10 2016-01-05 b 2
11 2016-01-06 b 1
```
I've tried the solution mentioned [here](https://stackoverflow.com/questions/19324453/add-missing-dates-to-pandas-dataframe) and [here](https://stackoverflow.com/questions/27241795/fill-missing-dates-by-group-in-pandas) but they aren't what I'm after.
Any pointers much appreciated. | 2017/07/07 | [
"https://Stackoverflow.com/questions/44978196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210178/"
] | As @ayhan suggests
```
x.dt = pd.to_datetime(x.dt)
```
One-liner using mostly @ayhan's ideas while incorporating `stack`/`unstack` and `fill_value`
```
x.set_index(
['dt', 'user']
).unstack(
fill_value=0
).asfreq(
'D', fill_value=0
).stack().sort_index(level=1).reset_index()
dt user val
0 2016-01-01 a 1
1 2016-01-02 a 33
2 2016-01-03 a 0
3 2016-01-04 a 0
4 2016-01-05 a 0
5 2016-01-06 a 0
6 2016-01-01 b 0
7 2016-01-02 b 0
8 2016-01-03 b 0
9 2016-01-04 b 0
10 2016-01-05 b 2
11 2016-01-06 b 1
``` | An old question, with already excellent answers; this is an alternative, using the [complete](https://pyjanitor-devs.github.io/pyjanitor/reference/janitor.functions/janitor.complete.html#janitor.complete) function from [pyjanitor](https://pyjanitor-devs.github.io/pyjanitor/) that could help with the abstraction when generating explicitly missing rows:
```py
#pip install pyjanitor
import pandas as pd
import janitor as jn
x['dt'] = pd.to_datetime(x['dt'])
# generate complete list of dates
dates = dict(dt = pd.date_range(x.dt.min(), x.dt.max(), freq='1D'))
# build the new dataframe, and fill nulls with 0
x.complete('user', dates, fill_value = 0)
user dt val
0 a 2016-01-01 1
1 a 2016-01-02 33
2 a 2016-01-03 0
3 a 2016-01-04 0
4 a 2016-01-05 0
5 a 2016-01-06 0
6 b 2016-01-01 0
7 b 2016-01-02 0
8 b 2016-01-03 0
9 b 2016-01-04 0
10 b 2016-01-05 2
11 b 2016-01-06 1
``` |
24,547,252 | I would like to correctly format my help message for my Perl scripts and if possible by using a standard module such as `Pod::Usage`. Unfortunately I do not really like the output format of pod2usage. For instance, with `grep` I get the following help structure:
```
$ grep --help
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c
Regexp selection and interpretation:
-E, --extended-regexp PATTERN is an extended regular expression (ERE)
-F, --fixed-strings PATTERN is a set of newline-separated fixed strings
-G, --basic-regexp PATTERN is a basic regular expression (BRE)
-P, --perl-regexp PATTERN is a Perl regular expression
```
But this is very different with `Pod::Usage` and I get unwanted `\n` and `\t`:
```
$ ./sample.pl --help
Usage:
sample [options] [file ...]
This program will read the given input file(s) and do something useful
with the contents thereof.
Options:
--help
Print a brief help message and exits.
--man
Prints the manual page and exits.
```
I would like to modify the format of my help in the traditional way i.e. without `\n` and without leading `\t`. In fact, I am looking to solution that allows me to write this:
```
__END__
=head1 SYNOPSIS
sample [options] [file ...]
B<This program> will read the given input file(s) and do something
useful with the contents thereof.
=head1 OPTIONS
=item B<-h,--help>
Print a brief help message and exits.
=item B<-v,--version>
Prints the version and exits.
=cut
```
And get this:
```
Usage: sample [options] [file ...]
This program will read the given input file(s) and do something useful
with the contents thereof.
Options:
-h, --help Print a brief help message and exits.
-v, --version Prints the version and exits.
```
Not this:
```
Usage:
sample [options] [file ...]
This program will read the given input file(s) and do something useful
with the contents thereof.
Options:
-h,--help Print a brief help message and exits.
-v,--version Prints the version and exits.
```
Any clue ? | 2014/07/03 | [
"https://Stackoverflow.com/questions/24547252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2612235/"
] | When you use `=item`, you should prefix it with an `=over x` where `x` is how far you want to move over. After you finish your items, you need to use `=back`. If `=over x` is far enough over, the paragraph for that item will print on the same line as the `=item`. I played around and found `=over 20` looks pretty good:
```
use strict;
use warnings;
use Pod::Usage;
pod2usage( -verbose => 1);
=pod
=head1 SYNOPSIS
sample [options] [file ...]
B<This program> will read the given input file(s) and do something
useful with the contents thereof.
=head1 OPTIONS
=over 20
=item B<-h>, B<--help>
Print a brief help message and exits.
=item B<-v>, B<--version>
Prints the version and exits.
=back
=cut
```
This prints out:
```
Usage:
sample [options] [file ...]
This program will read the given input file(s) and do something useful
with the contents thereof.
Options:
-h, --help Print a brief help message and exits.
-v, --version Prints the version and exits.
```
There's not much you can do with the `v, --version` stuff in POD to get it to print in pretty three column format. What you can do is give a bit more space between the `-h` and `--help` like I did above in order to improve readability.
Remember, the important stuff is the data in your POD and not the absolute formatting. Use the formatting to make it easy to read, but don't sweat the details too much.
I highly recommend you use the old standard Man page layout (which `Pod2Usage` assumes). | Two things you can try:
The [-noperldoc option](https://metacpan.org/pod/Pod::Usage#noperldoc) to make it switch to Pod::Text, which is a simpler formatter.
or
[Set a different formatter](https://metacpan.org/pod/Pod::Usage#Formatting-base-class)
`Pod::Text` has several formatting options as well, such as the left margin, indent level, page width which may make it more to your liking. |
17,255,713 | I have various values in a PHP array, that look like below:
```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
```
The first part before the underscore (*news, blog, member*) is dynamic so I would like to get all the matches in a specific section (*news*) followed by the numbers.
Something like below:
```
$section = "news";
$matches = preg_match('$section/[_])GETNUMBER/', $values);
```
This would return 24 and 27, but only where news was before the underscore.
Thanks. | 2013/06/22 | [
"https://Stackoverflow.com/questions/17255713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2497987/"
] | ```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
$section = "news";
foreach($values as $value) {
$matches = preg_match("/{$section}_(\\d+)/", $value, $number);
if ($matches)
echo $number[1], PHP_EOL;
}
``` | ```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
function func($type){
$results = null;
foreach($values as $val){
$curr = explode('_',$val);
if($curr[0]==$type){
$results[] = $curr[1];
}
}
return $results;
}
$News = func('news');
```
Good luck! :P |
17,255,713 | I have various values in a PHP array, that look like below:
```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
```
The first part before the underscore (*news, blog, member*) is dynamic so I would like to get all the matches in a specific section (*news*) followed by the numbers.
Something like below:
```
$section = "news";
$matches = preg_match('$section/[_])GETNUMBER/', $values);
```
This would return 24 and 27, but only where news was before the underscore.
Thanks. | 2013/06/22 | [
"https://Stackoverflow.com/questions/17255713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2497987/"
] | ```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
$section = "news";
foreach($values as $value) {
$matches = preg_match("/{$section}_(\\d+)/", $value, $number);
if ($matches)
echo $number[1], PHP_EOL;
}
``` | Note I added two cases:
```
$values = array ("news_24", "news_81", "blog_56", "member_55", "news_27",
"blognews_99", "news_2012_12");
$section = "news";
preg_match_all("/^{$section}_(\\d+)\$/m", implode("\n", $values), $matches);
print_r($matches[1]);
```
The implode might not be super efficient, but it's less code.
The difference is in the matching & regex.
This solution only outputs
```
Array
(
[0] => 24
[1] => 81
[2] => 27
)
```
While the others also output 2012 and the solution of Mark also 99. |
17,255,713 | I have various values in a PHP array, that look like below:
```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
```
The first part before the underscore (*news, blog, member*) is dynamic so I would like to get all the matches in a specific section (*news*) followed by the numbers.
Something like below:
```
$section = "news";
$matches = preg_match('$section/[_])GETNUMBER/', $values);
```
This would return 24 and 27, but only where news was before the underscore.
Thanks. | 2013/06/22 | [
"https://Stackoverflow.com/questions/17255713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2497987/"
] | ```
$values = array("news_24", "news_81", "blog_56", "member_55", "news_27");
function func($type){
$results = null;
foreach($values as $val){
$curr = explode('_',$val);
if($curr[0]==$type){
$results[] = $curr[1];
}
}
return $results;
}
$News = func('news');
```
Good luck! :P | Note I added two cases:
```
$values = array ("news_24", "news_81", "blog_56", "member_55", "news_27",
"blognews_99", "news_2012_12");
$section = "news";
preg_match_all("/^{$section}_(\\d+)\$/m", implode("\n", $values), $matches);
print_r($matches[1]);
```
The implode might not be super efficient, but it's less code.
The difference is in the matching & regex.
This solution only outputs
```
Array
(
[0] => 24
[1] => 81
[2] => 27
)
```
While the others also output 2012 and the solution of Mark also 99. |
830,198 | I have 2 Server 2012r2 servers running DNS in failover/loadbalance. They both sync fine but I have noticed that they each claim themselves as SOA. It sounds wrong to me, but is this due to the failover?
Thanks,
Travis | 2017/02/02 | [
"https://serverfault.com/questions/830198",
"https://serverfault.com",
"https://serverfault.com/users/292043/"
] | For AD integrated DNS zones, each server hosting a copy of the zone is the SOA for it's copy of the zone.
This is perfectly normal. | It is typical for systems that do not use DNS to replicate to claim themselves as master. This is true for not only Windows (AD Integrated zones) but also bind (ldap-bind) and powerdns (ldap, database, etc).
More on [Windows](https://support.microsoft.com/en-us/help/282826/active-directory-integrated-dns-zone-serial-number-behavior) [Bind](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/6.4_Technical_Notes/bind-dyndb-ldap.html), and [PowerDNS](https://doc.powerdns.com/md/types/#soa)
I've asked this question as well, I expect as more people use APIs with multiple providers, the SOA and Serial # will continue to diverge. |
25,714,197 | I'm interested in printing a double as raw hex. I don't want the mantissa and exponent interpreted.
Is there a print function in Java to accomplish it?
If not, how does one extract raw octets from a double in Java? | 2014/09/07 | [
"https://Stackoverflow.com/questions/25714197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608639/"
] | Use [`Double.doubleToLongBits()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToLongBits(double)) or [`Double.doubleToRawLongBits()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToRawLongBits(double)). | First, get the bits as long, using [Double.doubleToLongBits()](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToLongBits(double) "javadoc") or [Double.doubleToRawLongBits()](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToRawLongBits(double) "javadoc").
However if you would like to print the bits then and if you have Java 8, I would recommend converting your `long` to `String` using the new unsigned API, possibly with base 16 or 2.
```
double number = Math.E;
long bits = Double.doubleToRawLongBits(number);
System.out.println(Long.toUnsignedString(bits, 16)); // 4005bf0a8b145769
``` |
17,035,819 | I have a mysql table
```
Table A
--------------------
item_id category_id
--------------------
1 1
1 2
1 4
2 1
2 3
```
Would like to make an sql query that will select all matches in an array
***example:***
```
given category_ids are 1,4 it should return only item_id 1
given category_ids are 1 it should return item_id 1 and 2
```
Thanks | 2013/06/11 | [
"https://Stackoverflow.com/questions/17035819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2472949/"
] | For categories 1, 4:
```
SELECT item_id, COUNT(*) c
FROM TableA
WHERE category_id IN (1, 4)
GROUP BY item_id
HAVING c = 2
```
For category 1:
```
SELECT item_id, COUNT(*) c
FROM TableA
WHERE category_id IN (1)
GROUP BY item_id
HAVING c = 1
```
I think you should be able to see the pattern -- the `HAVING` clause should match the number of categories.
This assumes that `item_id, category_id` is unique in the table. | given category\_ids are 1,4
---------------------------
SELECT item\_id, category\_id
FROM TableA
WHERE category\_id IN (1, 4)
given category\_ids are 1
-------------------------
SELECT item\_id, category\_id
FROM TableA
WHERE category\_id IN (1) |
38,720,294 | I have around 21 databases on my SQL Server 2012 machine, which should ideally have the same list of tables but they don't.
Assume:
* Database 1 has tables A,B,C,D,E
* Database 2 has tables A,B,C,D,Z
* Database 3 has tables A,B,C,Y,Z
* Database 4 has tables A,B,X,Y,Z
The output of my final query must be a table list like A,B,C,D,E,X,Y,Z
I understand this information can be sourced by joining `sys.tables` of each database, but I am not sure about which join should I use and how.
Any starting point will be appreciated | 2016/08/02 | [
"https://Stackoverflow.com/questions/38720294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955698/"
] | You can use `union`:
```
select d.*
from ((select table_name from db1.information_schema.tables) union
(select table_name from db2.information_schema.tables) union
. . .
(select table_name from db21.information_schema.tables)
) d;
```
Actually, the subquery is not really necessary, but it is handy if you want to do something such as count the number of times that each table appears. | If I understood your question correctly,
You want to list all the tables for all databases
There is avery simple script which will accomplish this task
as floowing:
```
sp_msforeachdb 'select "?" AS db, * from [?].sys.tables'
```
and getting the list of tables only :
```
sp_msforeachdb 'select "?" AS db, name from [?].sys.tables'
```
hope this helps |
38,720,294 | I have around 21 databases on my SQL Server 2012 machine, which should ideally have the same list of tables but they don't.
Assume:
* Database 1 has tables A,B,C,D,E
* Database 2 has tables A,B,C,D,Z
* Database 3 has tables A,B,C,Y,Z
* Database 4 has tables A,B,X,Y,Z
The output of my final query must be a table list like A,B,C,D,E,X,Y,Z
I understand this information can be sourced by joining `sys.tables` of each database, but I am not sure about which join should I use and how.
Any starting point will be appreciated | 2016/08/02 | [
"https://Stackoverflow.com/questions/38720294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955698/"
] | Just for those who stumble upon this in future.
```
SET NOCOUNT ON
DECLARE @AllTables TABLE
(
ServerName NVARCHAR(200)
,DBName NVARCHAR(200)
,SchemaName NVARCHAR(200)
,TableName NVARCHAR(200)
)
DECLARE @SearchSvr NVARCHAR(200)
,@SearchDB NVARCHAR(200)
,@SearchS NVARCHAR(200)
,@SearchTbl NVARCHAR(200)
,@SQL NVARCHAR(4000)
SET @SearchSvr = NULL --Search for Servers, NULL for all Servers
SET @SearchDB = NULL --Search for DB, NULL for all Databases
SET @SearchS = NULL --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL --Search for Tables, NULL for all Tables
SET @SQL = 'SELECT
@@SERVERNAME
,''?''
,s.name
,t.name
FROM [?].sys.tables t
JOIN sys.schemas s on t.schema_id=s.schema_id
WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
'
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables
INSERT INTO @AllTables
(
ServerName
,DBName
,SchemaName
,TableName
)
EXEC sp_MSforeachdb @SQL
SET NOCOUNT OFF
SELECT distinct tablename
FROM @AllTables
``` | You can use `union`:
```
select d.*
from ((select table_name from db1.information_schema.tables) union
(select table_name from db2.information_schema.tables) union
. . .
(select table_name from db21.information_schema.tables)
) d;
```
Actually, the subquery is not really necessary, but it is handy if you want to do something such as count the number of times that each table appears. |
38,720,294 | I have around 21 databases on my SQL Server 2012 machine, which should ideally have the same list of tables but they don't.
Assume:
* Database 1 has tables A,B,C,D,E
* Database 2 has tables A,B,C,D,Z
* Database 3 has tables A,B,C,Y,Z
* Database 4 has tables A,B,X,Y,Z
The output of my final query must be a table list like A,B,C,D,E,X,Y,Z
I understand this information can be sourced by joining `sys.tables` of each database, but I am not sure about which join should I use and how.
Any starting point will be appreciated | 2016/08/02 | [
"https://Stackoverflow.com/questions/38720294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955698/"
] | Just for those who stumble upon this in future.
```
SET NOCOUNT ON
DECLARE @AllTables TABLE
(
ServerName NVARCHAR(200)
,DBName NVARCHAR(200)
,SchemaName NVARCHAR(200)
,TableName NVARCHAR(200)
)
DECLARE @SearchSvr NVARCHAR(200)
,@SearchDB NVARCHAR(200)
,@SearchS NVARCHAR(200)
,@SearchTbl NVARCHAR(200)
,@SQL NVARCHAR(4000)
SET @SearchSvr = NULL --Search for Servers, NULL for all Servers
SET @SearchDB = NULL --Search for DB, NULL for all Databases
SET @SearchS = NULL --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL --Search for Tables, NULL for all Tables
SET @SQL = 'SELECT
@@SERVERNAME
,''?''
,s.name
,t.name
FROM [?].sys.tables t
JOIN sys.schemas s on t.schema_id=s.schema_id
WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
'
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables
INSERT INTO @AllTables
(
ServerName
,DBName
,SchemaName
,TableName
)
EXEC sp_MSforeachdb @SQL
SET NOCOUNT OFF
SELECT distinct tablename
FROM @AllTables
``` | If I understood your question correctly,
You want to list all the tables for all databases
There is avery simple script which will accomplish this task
as floowing:
```
sp_msforeachdb 'select "?" AS db, * from [?].sys.tables'
```
and getting the list of tables only :
```
sp_msforeachdb 'select "?" AS db, name from [?].sys.tables'
```
hope this helps |
2,931,642 | I am trying to simulate a 'HEAD' method using UrlLoader; essentially, I just want to check for the presence of a file without downloading the entire thing. I figured I would just use HttpStatusEvent, but the following code throws an exception (one that I can't wrap in a try/catch block) when you run in debug mode.
```
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()">
<mx:Script>
<![CDATA[
private static const BIG_FILE:String = "http://www.archive.org/download/gspmovvideotestIMG0021mov/IMG_0021.mov";
private var _loader:URLLoader;
private function init():void {
_loader = new URLLoader();
_loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler);
_loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
_loader.load(new URLRequest(BIG_FILE));
}
public function unload():void {
try {
_loader.close();
_loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler);
_loader.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
_loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
}
catch(error:Error) {
status.text = error.message;
}
}
private function errorHandler(event:Event):void {
status.text = "error";
unload();
}
private function statusHandler(event:HTTPStatusEvent):void {
if(event.status.toString().match(/^2/)) {
status.text = "success";
unload();
}
else {
errorHandler(event);
}
}
]]>
</mx:Script>
<mx:Label id="status" />
```
I tried using ProgressEvents instead, but it seems that some 404 pages return content, so the status event will correctly identify if the page exists.
Anyone have any ideas? | 2010/05/28 | [
"https://Stackoverflow.com/questions/2931642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51442/"
] | It's a bug in the URLLoader class, I think.
If you read the error message (at least the one I got, you haven't pasted yorrs!) you will see it:
>
> Error: Error #2029: This URLStream
> object does not have a stream opened
> at flash.net::URLStream/readBytes()
> at flash.net::URLLoader/onComplete()
>
>
>
This gives you some insight on what's happening. The URLLoader class internally uses a [URLStream](http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/net/URLStream.html) object, which provides low-level access to the downloaded data.
The error message indicates that an onComplete handler is being called on URLLoader. The file is big but it's probably cached so it loads rather fast. Now, if you add a listener for both progress and complete events, you'll see the order in which events are fired is this:
* progress
* status
* complete
The [docs](http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html#event:httpStatus) confirm this:
>
> Note that the httpStatus event (if
> any) is sent before (and in addition
> to) any complete or error event.
>
>
>
Now, you can see the problem is that from the status handler you're calling close(). This closes the stream. But apparently (and this is the bug, I think), the onComplete handler in the URLLoader class *does not* check whether the stream is open or not. (From Actionscript there's no way to check this, so you'd have to wrap code in try/catch). You cannot read data from a closed stream, so this is why it blows.
I can see 2 ways to fix this:
1) Defer execution of the function that calls close() (your unload method), so close() is called *after* the URLLoader internal onComplete method is called.
That is, do this:
```
setTimeout(unload,1);
```
instead of this:
```
unload();
```
2) Use a URLStream instead of a URLLoader. The first option strikes me as a bit of a hackish workaround, so I'd go with this last one in your situation. Using a URLStream means more work on your side, generally, but in this case you're not actually interested in reading any data, so it doesn't make much difference. Plus, you'd only have to change two lines in your current code:
This one:
```
private var _loader:URLStream;
```
And this one:
```
_loader = new URLStream();
```
And you're all set. | I have run into a similary issue.
What I discovered to be the problem was this call:
```
_loader.close();
```
The error occurred when I tried to close a file that I had not even opened. So in "try" clause, do a check for if the file is open before you try to close it.
Mike |
5,174,841 | I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
`let "k += 0.025"`
and
`let "$k += 0.025"`
and
`k += 0.025`
and many other variations. Does anyone know how to accomplish this? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381798/"
] | Use integer math and then convert to decimal when needed.
```
#!/bin/bash
k=25
# Start of loop
#
# Increment variable by 0.025 (times 1000).
#
let k="$k+25"
# Get value as fraction (uses bc).
#
v=$(echo "$k/1000"|bc -l)
# End of loop
#
echo $v
```
Save as `t.sh`, then:
```
$ chmod +x t.sh
$ ./t.sh
.05000000000000000000
``` | Bash doesn't handle floating point math whatsoever. You need help from an external tool like [bc](http://en.wikipedia.org/wiki/Bc_programming_language). |
5,174,841 | I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
`let "k += 0.025"`
and
`let "$k += 0.025"`
and
`k += 0.025`
and many other variations. Does anyone know how to accomplish this? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381798/"
] | ```
#!/bin/sh
k=1.00
incl=0.025
k=`echo $k + $incl | bc`
echo $k
``` | Bash doesn't handle floating point math whatsoever. You need help from an external tool like [bc](http://en.wikipedia.org/wiki/Bc_programming_language). |
5,174,841 | I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
`let "k += 0.025"`
and
`let "$k += 0.025"`
and
`k += 0.025`
and many other variations. Does anyone know how to accomplish this? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381798/"
] | You may be working on some giant bash masterpiece that can't be rewritten without a king's ransom.
Alternatively, this problem may be telling you "*write me in **Ruby** or **Python** or **Perl** or **Awk***". | Bash doesn't handle floating point math whatsoever. You need help from an external tool like [bc](http://en.wikipedia.org/wiki/Bc_programming_language). |
5,174,841 | I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
`let "k += 0.025"`
and
`let "$k += 0.025"`
and
`k += 0.025`
and many other variations. Does anyone know how to accomplish this? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381798/"
] | Use integer math and then convert to decimal when needed.
```
#!/bin/bash
k=25
# Start of loop
#
# Increment variable by 0.025 (times 1000).
#
let k="$k+25"
# Get value as fraction (uses bc).
#
v=$(echo "$k/1000"|bc -l)
# End of loop
#
echo $v
```
Save as `t.sh`, then:
```
$ chmod +x t.sh
$ ./t.sh
.05000000000000000000
``` | ```
#!/bin/sh
k=1.00
incl=0.025
k=`echo $k + $incl | bc`
echo $k
``` |
5,174,841 | I wanted to increment a variable, k inside a loop. Each increment is by 0.025. I tried using:
`let "k += 0.025"`
and
`let "$k += 0.025"`
and
`k += 0.025`
and many other variations. Does anyone know how to accomplish this? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5174841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381798/"
] | Use integer math and then convert to decimal when needed.
```
#!/bin/bash
k=25
# Start of loop
#
# Increment variable by 0.025 (times 1000).
#
let k="$k+25"
# Get value as fraction (uses bc).
#
v=$(echo "$k/1000"|bc -l)
# End of loop
#
echo $v
```
Save as `t.sh`, then:
```
$ chmod +x t.sh
$ ./t.sh
.05000000000000000000
``` | You may be working on some giant bash masterpiece that can't be rewritten without a king's ransom.
Alternatively, this problem may be telling you "*write me in **Ruby** or **Python** or **Perl** or **Awk***". |
110,573 | In the IID case, it is known that all order statistics are positively correlated.\* Thus, we know that $$\text{Cov}(X\_{(i)},X\_{(j)}) \geq 0.$$ Is this known in the INID (independent, non-identically distributed) case? If it is not known, how could this be proved? If it does not seem true, what would be a counter-example?
* E.g., see Bickel (1967), "Some contributions to the theory of order statistics" | 2012/10/24 | [
"https://mathoverflow.net/questions/110573",
"https://mathoverflow.net",
"https://mathoverflow.net/users/27304/"
] | You asked for an example with **independent** variables and **negatively correlated** order statistics. I can come close in two ways.
Here is an example with **uncorrelated** variables and **negatively correlated** order statistics.

Suppose the states of the world are the interval (-2,2), with variables
$A = |x|-2$, $B = -1$, $C = +1$, $D = x+1-\text{sign}(x)$. Let $X=\{A,B,C,D\}$. Then $X\_{(2)}$ and $X\_{(3)}$ are negatively correlated.
Discretizing gives **independent** variables and **uncorrelated** order statistics.
Suppose there are four states of the world, and the four variables have values
depending on the states as $A=(0,-2,-2,0), B=(-1,-1,-1,-1), C=(1,1,1,1), D=(0,2,0,2)$. Again let $X=\{A,B,C,D\}$. Then $X\_{(2)}$ and $X\_{(3)}$ are uncorrelated. | If $X\sim N(0,1)$ and $(X\_1,X\_2) = (X,-X)$ the covariance of $(X^{(1)},X^{(2)})=\min(X\_1,X\_2),\max(X\_1,X\_2)$ is negative. |
5,528,295 | I haven't actually came across this situation yet but i will probably have a need for it in the near future. In current frameworks or CMS like joomla I have noticed multiple parameters and values stored in 1 field within a database table. what would be the best way to extract these values as a key => value in an array? so say a field / column has (Joomla example):
```
show_title=1
link_titles=1
show_intro=blah blah blah
show_section=
link_section=
```
and so on ......
how would such break these up in a nice clean way? it also seems the entries have a new line to break apart each parameter. Is it actually possible to explode a /n? | 2011/04/03 | [
"https://Stackoverflow.com/questions/5528295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635925/"
] | The easiest way to make round corners is to use `-moz-border-radius` and `webkit-border-radius`, however these properties are only supported on Mozilla and Webkit browsers.
However what I would do is make a main div with a relative position and then have your corners as absolute, like so:
```
<div style="position:relative">
<div style="position:absolute;top:0;left:0;"></div>
<div style="position:absolute;top:0;right:0;"></div>
<div style="position:absolute;bottom:0;left:0;"></div>
<div style="position:absolute;bottom:0;right:0;"></div>
Div content here
</div>
```
You can adjust the heights and add the background images using background-position.
Also I would put the CSS in a seperate file, I just placed it inline for the purpose of example. | Use jQuery round corner plugin.
<http://jquery.malsup.com/corner/>
It's supported in all browsers including IE. It draws corners in IE using nested divs (no images). It also has native border-radius rounding in browsers that support it (Opera 10.5+, Firefox, Safari, and Chrome). So in those browsers the plugin simply sets a css property instead.
Here's How to use it
--------------------
You need to include the jQuery and the Corner js script before `</body>`. Then write your jQuery like $('div, p').corner('10px'); and place before ''. So your html will look like the below code. Here i'm making round corners for all `div` and `p` tags. If you want to do it for specific id or class then you can do something like `$('#myid').corner();`
```
<body>
<div class="x"></div>
<p class="y"></p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/corner/raw/master/jquery.corner.js?v2.11"></script>
<script>$('div, p').corner();</script>
</body>
```
Check working example at <http://jsfiddle.net/VLPpk/1>
------------------------------------------------------ |
5,528,295 | I haven't actually came across this situation yet but i will probably have a need for it in the near future. In current frameworks or CMS like joomla I have noticed multiple parameters and values stored in 1 field within a database table. what would be the best way to extract these values as a key => value in an array? so say a field / column has (Joomla example):
```
show_title=1
link_titles=1
show_intro=blah blah blah
show_section=
link_section=
```
and so on ......
how would such break these up in a nice clean way? it also seems the entries have a new line to break apart each parameter. Is it actually possible to explode a /n? | 2011/04/03 | [
"https://Stackoverflow.com/questions/5528295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635925/"
] | The easiest way to make round corners is to use `-moz-border-radius` and `webkit-border-radius`, however these properties are only supported on Mozilla and Webkit browsers.
However what I would do is make a main div with a relative position and then have your corners as absolute, like so:
```
<div style="position:relative">
<div style="position:absolute;top:0;left:0;"></div>
<div style="position:absolute;top:0;right:0;"></div>
<div style="position:absolute;bottom:0;left:0;"></div>
<div style="position:absolute;bottom:0;right:0;"></div>
Div content here
</div>
```
You can adjust the heights and add the background images using background-position.
Also I would put the CSS in a seperate file, I just placed it inline for the purpose of example. | I recently answered a similar question and the answer might help if you want a pure CSS method, nesting rather than float may be the answer.
[See this answer for possible solution](https://stackoverflow.com/questions/5474951/css-make-divs-inherit-a-height/5480017#5480017) |
5,528,295 | I haven't actually came across this situation yet but i will probably have a need for it in the near future. In current frameworks or CMS like joomla I have noticed multiple parameters and values stored in 1 field within a database table. what would be the best way to extract these values as a key => value in an array? so say a field / column has (Joomla example):
```
show_title=1
link_titles=1
show_intro=blah blah blah
show_section=
link_section=
```
and so on ......
how would such break these up in a nice clean way? it also seems the entries have a new line to break apart each parameter. Is it actually possible to explode a /n? | 2011/04/03 | [
"https://Stackoverflow.com/questions/5528295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635925/"
] | I recently answered a similar question and the answer might help if you want a pure CSS method, nesting rather than float may be the answer.
[See this answer for possible solution](https://stackoverflow.com/questions/5474951/css-make-divs-inherit-a-height/5480017#5480017) | Use jQuery round corner plugin.
<http://jquery.malsup.com/corner/>
It's supported in all browsers including IE. It draws corners in IE using nested divs (no images). It also has native border-radius rounding in browsers that support it (Opera 10.5+, Firefox, Safari, and Chrome). So in those browsers the plugin simply sets a css property instead.
Here's How to use it
--------------------
You need to include the jQuery and the Corner js script before `</body>`. Then write your jQuery like $('div, p').corner('10px'); and place before ''. So your html will look like the below code. Here i'm making round corners for all `div` and `p` tags. If you want to do it for specific id or class then you can do something like `$('#myid').corner();`
```
<body>
<div class="x"></div>
<p class="y"></p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://github.com/malsup/corner/raw/master/jquery.corner.js?v2.11"></script>
<script>$('div, p').corner();</script>
</body>
```
Check working example at <http://jsfiddle.net/VLPpk/1>
------------------------------------------------------ |
1,965,777 | This seems like a really basic calculus question, which is a tad embarrassing since I'm a graduate student, but what does it mean when a substitution in a definite integral makes the bounds the same? For example, if we have some function of $\sin(x)$:
$$\int\_0^{\pi} f(\sin(x)) \,\mathrm{d}x$$
If we make the substitution $u = \sin(x)$, then $du = \cos(x)\,\mathrm{d}x$, we find
$$\int\_{\sin(0)}^{\sin(\pi)} \frac{f(u)}{\cos(x)} \,\mathrm{d}u
= \int\_0^0 \frac{f(u)}{\sqrt{1-u^2}} \,\mathrm{d}u$$
This would imply that the integral is zero. Is this always the case? For another example (more relevant to the problem I'm actually trying to solve) consider
$$\int\_{-b}^{b} \frac{1}{\sqrt{x^2 + a^2}}\,\mathrm{d}x$$
Clearly this can be solved using a trigonometric substitution to get $2\operatorname{arcsinh}(b)$, but what if I substituted $u = \sqrt{x^2 + a^2}$? Then
$$\mathrm{d}u = \frac{x\,\mathrm{d}x}{\sqrt{x^2 + a^2}} \implies \mathrm{d}x = \frac{u\,\mathrm{d}u}{x} = \frac{u\, \mathrm{d}u}{\sqrt{u^2 - a^2}},$$
so the integral becomes
$$\int\_{\sqrt{b^2 + a^2}}^{\sqrt{b^2 + a^2}}
\frac{1}{\sqrt{u^2 - a^2}}\,\mathrm{d}u$$
This integral seems to be zero, which is not the case for the integral before the substitution. What's going on here? Does this just mean that these substitutions are not valid? | 2016/10/12 | [
"https://math.stackexchange.com/questions/1965777",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/148555/"
] | For the second integral, note that the substitution $u=\sqrt{x^2+a^2}$ implies:
$$
u\ge 0 \quad \mbox{and}\quad x=\pm\sqrt{u^2-a^2}
$$
so:
$$
dx=\frac{udu}{\sqrt{u^2-a^2}} \mbox{for}\quad x \ge 0
$$
$$
dx=\frac{udu}{-\sqrt{u^2-a^2}} \mbox{for}\quad x < 0
$$
and the integral splits in two parts as $\int\_{-b}^0 +\int\_0^b$. This gives the correct result.
We have an analogous situation for the first integral with the substitution
$$
u=\sin x \qquad \cos x=\pm \sqrt{1-u^2}
$$ | The first integral is NOT zero! Let $f$ be the identity function, for example.
In the second integral it is wrong to say that $x=\sqrt{u^2-a^2}$ for all values of $x$. In the first integral, the same: $cos(x)=\sqrt{1-u^2}$ is not true for all values of $x$.
When the substitution is not injective, problems arise when you try to express the integrand in terms of the new variable, as it can be seen from this examples. So always split the integration domain so that there is injectivity in each part. |
29,632,408 | I have billions records in `patients colletion`,
I have no idea how could I filter it with pipeline.
Or this is a limit on mongoDB, we couldn't aggregate with pipeline on large collection ?
I've already add `allowDiskUse=True` option, but it doesn't work too.
How could I get the filtered result by the pipeline ?
How could I simply store the filtered result into another collection ? Thanks
Sample code (I use `pymongo` so the follows are in Python syntax )
==================================================================
```
import datetime
pipeline = [
{"$project": {"birthday":1, "id":1}
},
{
"$match": { "birthday":{"$gte":datetime.datetime(1987, 1, 1, 0, 0)} }
},{"$group": ~~~
}
]
res =db.patients.aggregate(pipeline,allowDiskUse=True)
```
Exception Message
=================
```
OperationFailure: command SON([('aggregate', u'patients'), ('pipeline', [{'$match': {'birthday': {'$gte': datetime.datetime(1987, 1, 1, 0, 0)}}}]), ('allowDiskUse', True)]) on namespace tw_insurance_security_development.$cmd failed: exception: aggregation result exceeds maximum document size (16MB)
```
How | 2015/04/14 | [
"https://Stackoverflow.com/questions/29632408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3675188/"
] | Try this:
```
var selected = $(this).find('option:selected').text()
```
See [Fiddle](http://jsfiddle.net/9mt3ag58/) | Here is code :
```php
echo '<select name="country" id="country" />';
echo '<option value="0" selected>Select Country</option>';
echo '<option value = "'.money_format('%.2n', $row2["price"]).'">'.$row2["monday"].'</option>';
}
echo '</select>
``` |
54,283,616 | I've been reading a introduction to java book *(Core Java SE 9, not that it's important)* and it mentioned that you couldn't write a method that changes an object reference to something else.
The code they've provided as an example of what doesn't work is as follows. My question is what is the alternative to this I could use if I wanted to acomplish the same results.
```
public class EvilManager {
...
public void replaceWithZombie(Employee e) {
e = new Employee("", 0);
}
}
```
sorry I may have screwed up some of the exact nomanclature, I'm newish but I'm trying hard | 2019/01/21 | [
"https://Stackoverflow.com/questions/54283616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7922708/"
] | Do you add `<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />` in AndroidManifest file ?
**UPDATE**:
if you want to save to internal storage, you can use below code:
```
private void storeImage(Bitmap image) {
try {
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName="MI_"+ timeStamp +".jpg";
FileOutputStream fos = openFileOutput(mImageName, MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
```
it will save to data/data/your\_packagename/files | You can use below code to save bitmap to internal storage.It will create dirctory in internal storage `imageDir` , and you have to give the name to save your image i.e `profile.jpg`
```
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
``` |
5,557,219 | I'm experimenting with ways of creating immutable objects. The following builder objects
are quite attractive because they keep the role of the arguments clear. However I would like
to use the compiler to verify that certain fields are set, like with the `Immutable()` constructor invocation. `StrictImmutableBuilder` provides those checks, but is rather noisy. Is there some way to get the same checks but with the form of `LaxImmutableBuilder`? Perhaps using annotations?
```
public class Immutable {
public static void main(String[] args) {
new Immutable("13272873C", 23, false);
// nice but what where those arguments?
new LaxImmutableBuilder() {{
refCode("13272873C");
age(23);
subscribed(false);
}}.build();
// now I know what each value represents
// but what if I forgot to set one?
new StrictImmutableBuilder() {
public String refCode() { return "13272873C"; }
public int age() { return 23; }
public boolean subscribed() { return false; }
}.build();
// now I'm forced to set each field, but now
// we have the extra noise of "return"
// and also "public" if we want to use
// this outside the current package
// is there another way? maybe using annotations?
}
private final String refCode;
private final int age;
private final boolean subscribed;
public String getRefCode() {
return refCode;
}
public int getAge() {
return age;
}
public boolean isSubscribed() {
return subscribed;
}
public Immutable(String a, int b, boolean c) {
this.refCode = a;
this.age = b;
this.subscribed = c;
}
}
abstract class StrictImmutableBuilder {
public abstract String refCode();
public abstract int age();
public abstract boolean subscribed();
public Immutable build() {
return new Immutable(refCode(), age(), subscribed());
}
}
abstract class LaxImmutableBuilder {
private String refCode;
private int age;
private boolean subscribed;
protected void refCode(String refCode) {
this.refCode = refCode;
}
protected void age(int age) {
this.age = age;
}
protected void subscribed(boolean subscribed) {
this.subscribed = subscribed;
}
public Immutable build() {
return new Immutable(refCode, age, subscribed);
}
}
``` | 2011/04/05 | [
"https://Stackoverflow.com/questions/5557219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682006/"
] | Here's the pattern I use:
```
class YourClass {
// these are final
private final int x;
private final int y;
private int a;
private int b;
// finals are passed into the constructor
private YourClass(int x, int y) {
this.x = x;
this.y = y;
}
public static class Builder {
// int x, int y, int a, int b
// whatever's final is passed into constructor
public Builder(int x, int y) {
this.x = x;
this.y = y;
}
// a and b are optional, so have with() methods for these
public Builder withA(int a) {
this.a = a;
return this;
}
public Builder withB(int b) {
this.b = b;
return this;
}
public YourClass build() {
YourClass c = new YourClass (x, y);
c.a = a;
c.b = b;
return c;
}
}
}
``` | there is this trick: Type-safe Builder Pattern
<http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/>
but that's just too crazy. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | I would recommend checking the permissions on `/etc/passwd` and `/etc/group`. If they're not set to 644 (`-rw-r--r--`), then run:
`chmod 644 /etc/passwd; chmod 644 /etc/group` | Check that each and every line in `/etc/passwd` has exactly seven fields. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | I would recommend checking the permissions on `/etc/passwd` and `/etc/group`. If they're not set to 644 (`-rw-r--r--`), then run:
`chmod 644 /etc/passwd; chmod 644 /etc/group` | I know it's right on time, but the reason could be `coreutils` compiled without ACL support. Check it and rebuild the package if needed. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | Notice there is a missing `x`
This is the content of mine on Linux Mint with kernel 3.8.0-35-generic
```
root:x:0:0:root:/root:/bin/zsh
```
The `x` means that the actual password information is being stored in a separate shadow password file, tipically `/etc/shadow`
<https://en.wikipedia.org/wiki/Passwd> | Check that each and every line in `/etc/passwd` has exactly seven fields. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | Notice there is a missing `x`
This is the content of mine on Linux Mint with kernel 3.8.0-35-generic
```
root:x:0:0:root:/root:/bin/zsh
```
The `x` means that the actual password information is being stored in a separate shadow password file, tipically `/etc/shadow`
<https://en.wikipedia.org/wiki/Passwd> | I know it's right on time, but the reason could be `coreutils` compiled without ACL support. Check it and rebuild the package if needed. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | Check that each and every line in `/etc/passwd` has exactly seven fields. | I know it's right on time, but the reason could be `coreutils` compiled without ACL support. Check it and rebuild the package if needed. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | just say my experience
// after check /etc/passwd, /etc/shadow
0. problem
----------
on broken device:
```
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
```
and
```
whoami
whoami: cannot find name for user ID 0
```
on normal device:
```
whoami
root
```
1. research
-----------
try to find the reason:
```
strace whoami 2>&1 | grep -E '/etc|/lib'
...
open("/lib/arm-linux-gnueabi/libnss_compat.so.2", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnsl.so.1", O_RDONLY) = 3
open("/etc/ld.so.cache", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnss_nis.so.2", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnss_files.so.2", O_RDONLY) = 3
open("/etc/passwd", O_RDONLY|O_CLOEXEC) = 3
```
found it need those \*.so:
```
/lib/arm-linux-gnueabi/libnss_compat.so.2
/lib/arm-linux-gnueabi/libnsl.so.1
/lib/arm-linux-gnueabi/libnss_nis.so.2
/lib/arm-linux-gnueabi/libnss_files.so.2
```
//all come from `libc6` package, i work with arm linux device.
2. solution
-----------
i copy them to the broken device, then `whoami` worked right,
and bash prompt `I have no name!@localhost` got fixed. | Check that each and every line in `/etc/passwd` has exactly seven fields. |
63,182 | When I run `whoami` it says:
>
> whoami: cannot find name for user id 0
>
>
>
My `/etc/passwd` file looks like this:
```
root::0:0:root:/root:/bin/bash
``` | 2013/01/31 | [
"https://unix.stackexchange.com/questions/63182",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/30609/"
] | just say my experience
// after check /etc/passwd, /etc/shadow
0. problem
----------
on broken device:
```
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
```
and
```
whoami
whoami: cannot find name for user ID 0
```
on normal device:
```
whoami
root
```
1. research
-----------
try to find the reason:
```
strace whoami 2>&1 | grep -E '/etc|/lib'
...
open("/lib/arm-linux-gnueabi/libnss_compat.so.2", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnsl.so.1", O_RDONLY) = 3
open("/etc/ld.so.cache", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnss_nis.so.2", O_RDONLY) = 3
access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory)
open("/lib/arm-linux-gnueabi/libnss_files.so.2", O_RDONLY) = 3
open("/etc/passwd", O_RDONLY|O_CLOEXEC) = 3
```
found it need those \*.so:
```
/lib/arm-linux-gnueabi/libnss_compat.so.2
/lib/arm-linux-gnueabi/libnsl.so.1
/lib/arm-linux-gnueabi/libnss_nis.so.2
/lib/arm-linux-gnueabi/libnss_files.so.2
```
//all come from `libc6` package, i work with arm linux device.
2. solution
-----------
i copy them to the broken device, then `whoami` worked right,
and bash prompt `I have no name!@localhost` got fixed. | I know it's right on time, but the reason could be `coreutils` compiled without ACL support. Check it and rebuild the package if needed. |
71,704,319 | I'm trying to create a discord bot, specifically the married.
I am using a MongoDB database. Now everything works and is saved, but there is one problem, the data is saved for the second and third rounds, etc.
That is, the checks that I added do not work. I am trying to find data through `const exists = Marry.findOne({ userID: message.author.id });`, everything finds, I checked with console log. But I get text for 100 lines, one of the lines contains `userID: 9573697251580611109`.
But I need to get only numbers `9573697251580611109` and nothing more as I try to validate it just doesn't work. `if (exists == message.author.id) { return message.channel.send("You are already married!"); }`
How can i do this? Help me please!
```
const { Command } = require("discord.js-commando");
const mongoose = require("mongoose");
mongoose.connect('mongodb+srv://admon:admin@cluster0.sobzp.mongodb.net/dbname?retryWrites=true&w=majority');
//create Schema
const marrySchema = new mongoose.Schema({
userID: {
type: mongoose.SchemaTypes.String,
required: true
},
userPartnerID: {
type: mongoose.SchemaTypes.String,
required: true
}
});
const Marry = mongoose.model('Marry', marrySchema);
module.exports = class MarryCommand extends Command {
constructor(client) {
super(client, {
name: "marry",
memberName: "marry",
group: "test",
description: "Marry the mentioned user",
guildOnly: true,
args: [{
key: "userToMarry",
prompt: "Please select the member you wish to marry.",
type: "member",
}, ],
});
}
async run(message, { userToMarry }) {
const exists = await Marry.findOne({ userID: message.author.id });
const married = await Marry.findOne({ userID: userToMarry.id });
if (!userToMarry) {
return message.channel.send("Please try again with a valid user.");
}
if (exists == message.author.id) {
return message.channel.send("You are already married!");
}
if (married == userToMarry.id) {
return message.channel.send("This user is already married!");
}
if (userToMarry.id == message.author.id) {
return message.channel.send("You cannot marry yourself!");
}
if (exists != message.author.id && married != userToMarry.id) {
message.channel.send(
`**Important announcement!**
${message.author} makes a marriage proposal ${userToMarry}
Are you ready to get married?`
)
.then((message) => {
message.react("")
.then(() => message.react(""))
.catch(() => {
//code
});
message.awaitReactions((reaction, user) =>
user.id == userToMarry.id && (reaction.emoji.name == "" || reaction.emoji.name == ""), {
max: 1,
time: 10000,
errors: ["time"]
}
).then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "") {
return message.channel.send("I think **no**...");
}
if (reaction.emoji.name === "") {
const createdExists = new Marry({
userID: message.author.id,
userPartnerID: userToMarry.id
});
createdExists.save().catch(e => console.log(e));
const createdMarried = new Marry({
userID: userToMarry.id,
userPartnerID: message.author.id
});
createdMarried.save().catch(e => console.log(e));
message.channel.send(`${message.author} and ${userToMarry} now married!!`)
.catch(() => {
message.reply(
"No reaction after 10 seconds, operation canceled"
);
});
}
}).catch(() => {});
}).catch(() => {});
}
}
};
```
Now I am getting the full record from the database
```
{"_id":{"$oid":"6245bfbd9f4e545addad1111"},
"userID":"654733308680201312",
"userPartnerID":"5134125460452801324",
"__v":{"$numberInt":"0"}}
```
And I need to get only numbers from userID (654733308680201312) so that I can check | 2022/04/01 | [
"https://Stackoverflow.com/questions/71704319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was facing the same issue.
Root cause was me npm installing `@angular/material-date-fns-adapter` with a different version to the rest of angular/material.
It turns out, date-fns is not possible with my version of material, so I will try to upgrade the website to latest version of material. Wish me luck.
The angular material documentation website lets you select the version. Maybe it's the same for you. | That means that when you are providing an adapter object (or a class) for the DateAdapter interface the D in the interface is manadatory... so you have to define D or say it is 'any' like so:
```
{
provide: DateAdapter<any>,
useClass: DateFnsAdapter,
deps: [MAT_DATE_LOCALE],
},
```
that or `DateAdapter<undefined>` or even `DateAdapter<unknown>`
but the preferred thing would be to have strict typing like: `DateAdapter<MyInterfaceForDateAdapter>` |
15,348,516 | I am using Magical Record to help with core data saving and multi threading.
I kick off a new thread with GCD. In that new thread, I check if an Entity exists; if it does not I want to create a new one and save it.
Will `saveUsingCurrentThreadContextWithBlock^(NSManagedObjectContext *localContext){}` return to the main thread to save if it is called on a non-main thread?
or should i just pass the context to the new thread?
EDIT:
On the main thread, I create a MBProgress indicator and create a new thread:
```
MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.mapView animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
NSLog(@"SEPERATE THREAD | person %@ does not exist, creating", self.user.username);
person = [Person MR_createEntity];
person.name = self.user.username;
person.uid = self.user.UID;
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person) {
NSLog(@"COMPLETION BLOCK | person exists: %@", person.name);
}
}];
}
else {
NSLog(@"SEPERATE THREAD | person %@ does", self.user.username);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
```
(this method of saving is not persistence, I restart the app and I can't find the Person entity):
```
2013-03-12 14:25:44.014 SEPERATE THREAD | person iDealer does not exist, creating
2013-03-12 14:25:44.014 SEPERATE THREAD | thread: <NSThread: 0x84ca720>{name = (null), num = 4}
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Saving <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Parents? 0
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Synchronously? 0
2013-03-12 14:25:44.016 -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x840ec30) Context UNNAMED is about to save. Obtaining permanent IDs for new 1 inserted objects
2013-03-12 14:25:44.132 __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x840ec30) → Finished saving: <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.134 COMPLETION BLOCK | thread: <NSThread: 0x8435f30>{name = (null), num = 1}
2013-03-12 14:25:44.134 COMPLETION BLOCK | person exists: iDealer
``` | 2013/03/11 | [
"https://Stackoverflow.com/questions/15348516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875498/"
] | In the current version of MagicalRecord, yes, the completion block will return to the main thread. However, your method here is incorrect. There are now more explicit variants of the save method:
```
saveOnlySelf:completion:
saveToPersistentStore:completion:
```
Have a look at these methods in the current version. And as a reminder, make sure you only use managed objects from the localContext given to you. That working block can be run in any thread/queue, and you still want to use the proper thread management rules for core data in this case. | Yes, the completion block with execute in the main thread. For example:
```
NSOperationQueue *newQueue = [[NSOperationQueue alloc] init];
[newQueue addOperationWithBlock:^{
[MagicalRecord saveUsingCurrentThreadContextWithBlock:^(NSManagedObjectContext *localContext) {
// save something
} completion:^(BOOL success, NSError *error) {
// this will execute in the main thread
}];
}];
``` |
15,348,516 | I am using Magical Record to help with core data saving and multi threading.
I kick off a new thread with GCD. In that new thread, I check if an Entity exists; if it does not I want to create a new one and save it.
Will `saveUsingCurrentThreadContextWithBlock^(NSManagedObjectContext *localContext){}` return to the main thread to save if it is called on a non-main thread?
or should i just pass the context to the new thread?
EDIT:
On the main thread, I create a MBProgress indicator and create a new thread:
```
MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.mapView animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
NSLog(@"SEPERATE THREAD | person %@ does not exist, creating", self.user.username);
person = [Person MR_createEntity];
person.name = self.user.username;
person.uid = self.user.UID;
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person) {
NSLog(@"COMPLETION BLOCK | person exists: %@", person.name);
}
}];
}
else {
NSLog(@"SEPERATE THREAD | person %@ does", self.user.username);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
```
(this method of saving is not persistence, I restart the app and I can't find the Person entity):
```
2013-03-12 14:25:44.014 SEPERATE THREAD | person iDealer does not exist, creating
2013-03-12 14:25:44.014 SEPERATE THREAD | thread: <NSThread: 0x84ca720>{name = (null), num = 4}
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Saving <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Parents? 0
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Synchronously? 0
2013-03-12 14:25:44.016 -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x840ec30) Context UNNAMED is about to save. Obtaining permanent IDs for new 1 inserted objects
2013-03-12 14:25:44.132 __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x840ec30) → Finished saving: <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.134 COMPLETION BLOCK | thread: <NSThread: 0x8435f30>{name = (null), num = 1}
2013-03-12 14:25:44.134 COMPLETION BLOCK | person exists: iDealer
``` | 2013/03/11 | [
"https://Stackoverflow.com/questions/15348516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875498/"
] | Ok, I got it to work:
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
[MagicalRecord saveUsingCurrentThreadContextWithBlock:^(NSManagedObjectContext *localContext){
Person *localPerson = [Person MR_createInContext:localContext];
localPerson.name = self.user.username;
} completion:^(BOOL success, NSError *error){
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
}];
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
```
This works and save. I am unsure what casademora means by this method is incorrect. I am not able to determine what the difference between using this method to using `saveOnlySelf:completion:` method.
It seems like I was never able to save the context to the persistent store with the `saveOnlySelf`. If I created it with the code in my question, it would get placed in the context. If I did a search for the Person entity, I could find it. But once I terminated the app and restarted, that Person entity would not be there. It felt like I was saving or merging the thread context to the main/default context but that context was not being saved.
EDIT:
After some more playing around with MR, it seems that if any of the `saveOnlySelf` methods are used in a non-main thread, it will merge local context to the default context, but it does not save it to the persistent store. If you check the default context after completion, the new entity is indeed there. But once you terminate the app and re-run it, it isn't there.
To merge the context and save to the store, you need to call one of the `saveToPersistentStoreAndWait` type methods. | Yes, the completion block with execute in the main thread. For example:
```
NSOperationQueue *newQueue = [[NSOperationQueue alloc] init];
[newQueue addOperationWithBlock:^{
[MagicalRecord saveUsingCurrentThreadContextWithBlock:^(NSManagedObjectContext *localContext) {
// save something
} completion:^(BOOL success, NSError *error) {
// this will execute in the main thread
}];
}];
``` |
15,348,516 | I am using Magical Record to help with core data saving and multi threading.
I kick off a new thread with GCD. In that new thread, I check if an Entity exists; if it does not I want to create a new one and save it.
Will `saveUsingCurrentThreadContextWithBlock^(NSManagedObjectContext *localContext){}` return to the main thread to save if it is called on a non-main thread?
or should i just pass the context to the new thread?
EDIT:
On the main thread, I create a MBProgress indicator and create a new thread:
```
MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.mapView animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
NSLog(@"SEPERATE THREAD | person %@ does not exist, creating", self.user.username);
person = [Person MR_createEntity];
person.name = self.user.username;
person.uid = self.user.UID;
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person) {
NSLog(@"COMPLETION BLOCK | person exists: %@", person.name);
}
}];
}
else {
NSLog(@"SEPERATE THREAD | person %@ does", self.user.username);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
```
(this method of saving is not persistence, I restart the app and I can't find the Person entity):
```
2013-03-12 14:25:44.014 SEPERATE THREAD | person iDealer does not exist, creating
2013-03-12 14:25:44.014 SEPERATE THREAD | thread: <NSThread: 0x84ca720>{name = (null), num = 4}
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Saving <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Parents? 0
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Synchronously? 0
2013-03-12 14:25:44.016 -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x840ec30) Context UNNAMED is about to save. Obtaining permanent IDs for new 1 inserted objects
2013-03-12 14:25:44.132 __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x840ec30) → Finished saving: <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.134 COMPLETION BLOCK | thread: <NSThread: 0x8435f30>{name = (null), num = 1}
2013-03-12 14:25:44.134 COMPLETION BLOCK | person exists: iDealer
``` | 2013/03/11 | [
"https://Stackoverflow.com/questions/15348516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/875498/"
] | Ok, I got it to work:
```
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
[MagicalRecord saveUsingCurrentThreadContextWithBlock:^(NSManagedObjectContext *localContext){
Person *localPerson = [Person MR_createInContext:localContext];
localPerson.name = self.user.username;
} completion:^(BOOL success, NSError *error){
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
}];
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
```
This works and save. I am unsure what casademora means by this method is incorrect. I am not able to determine what the difference between using this method to using `saveOnlySelf:completion:` method.
It seems like I was never able to save the context to the persistent store with the `saveOnlySelf`. If I created it with the code in my question, it would get placed in the context. If I did a search for the Person entity, I could find it. But once I terminated the app and restarted, that Person entity would not be there. It felt like I was saving or merging the thread context to the main/default context but that context was not being saved.
EDIT:
After some more playing around with MR, it seems that if any of the `saveOnlySelf` methods are used in a non-main thread, it will merge local context to the default context, but it does not save it to the persistent store. If you check the default context after completion, the new entity is indeed there. But once you terminate the app and re-run it, it isn't there.
To merge the context and save to the store, you need to call one of the `saveToPersistentStoreAndWait` type methods. | In the current version of MagicalRecord, yes, the completion block will return to the main thread. However, your method here is incorrect. There are now more explicit variants of the save method:
```
saveOnlySelf:completion:
saveToPersistentStore:completion:
```
Have a look at these methods in the current version. And as a reminder, make sure you only use managed objects from the localContext given to you. That working block can be run in any thread/queue, and you still want to use the proper thread management rules for core data in this case. |
62,257,197 | GCS Signed Urls enable you to simply make objects available temporarily public by a signed url.
<https://cloud.google.com/storage/docs/access-control/signed-urls>
As I understand it, you need to calculate a signature based on several parameters, and then you get
access to the object without any other security layer.
Unfortunately the documentation is not completely clear if an object gets explicitly activated by the GCS service for that and gets a flag "signature XYZ valid for XX minutes on object ABC" or if GCS serves all files all time, as long as the signature is correct.
If any object can be made available with a proper signature, then all files in GCS are **de facto accessible public**, if the signature gets guessed right (brute force).
Is this right?
Is there any information on the level of security, that protect url-signing?
Is there a way to disable the url-signing?
Do the VPC Service Perimeters apply to signed urls?
*These are some points that I need find out due to compliance evaulations and they are more theoretical questions, than some concrete security doubts I have with this service.*
Thanks for your comments. | 2020/06/08 | [
"https://Stackoverflow.com/questions/62257197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12845385/"
] | >
> Unfortunately the documentation is not completely clear if an object gets explicitly activated by the GCS service for that and gets a flag "signature XYZ valid for XX minutes on object ABC" or if GCS serves all files all time, as long as the signature is correct.
>
>
>
The signed URL contains a timestamp after which the signed URL is no longer valid. The timestamp is part of what the signature signs, which means it can't be changed without invalidating the signature. The signatures themselves are generated entirely on the client with no change in server state.
>
> If any object can be made available with a proper signature, then all files in GCS are de facto accessible public, if the signature gets guessed right (brute force). Is this right?
>
>
>
Yes, this is true. Anyone who knows the name of a service account permitted to read the file, the bucket name, and the object name, and who correctly guesses which of the 2256 possible hashes is correct could indeed view your file. Mind you, 2256 is a fairly large number. If an attacker could make one trillion guesses per nanosecond, we would expect that on average they would discover the correct hash in about 3.6x1044 years, which is about 2.7x1034 times the age of the universe.
>
> Is there any information on the level of security, that protect url-signing?
>
>
>
Certainly. GCS uses GCS uses a common signed URL pattern identical to S3's "AWS Signature Version 4." The exact signing process is described on both service's websites. The signature itself is an HMAC SHA-256, which is a type of SHA-2 hash, a well-studied algorithm whose strengths and weaknesses are widely discussed. <https://en.wikipedia.org/wiki/SHA-2>.
>
> Is there a way to disable the url-signing?
>
>
>
VPC service controls are the simplest way. They can prevent any user outside of your project from accessing the data regardless of credentials.
>
> Do the VPC Service Perimeters apply to signed urls?
>
>
>
Yes, signed URLs would only work from within the configured security perimeter. | Looking at the [library code](https://github.com/googleapis/google-cloud-go/blob/3044f9c9ca84c8baddd2472cce72d0ab73eaa394/storage/storage.go#L551), the signed URLs are created using your service account private key without cooperation from GCP.
Regarding the brute-force, each Signed URL has a [credential attached](https://github.com/googleapis/google-cloud-go/blob/3044f9c9ca84c8baddd2472cce72d0ab73eaa394/storage/storage.go#L253), which is linked to the signer. This signer account needs to have permissions you want the user to have on the object. In case the URL is stolen, it can then be revoked by revoking permissions of the signer (you'll revoke all Signed URLs for that signer tho). To minimize risks, you could create a SA that would have access only to specific objects in the bucket.
To decrease the possibility of brute-force attacks, you can also rotate the Service Account key by creating a new one and deleting the previous.
Regarding the question: **Can Signed URLs be fully disabled?** You could "disable" this feature by not granting project-wide storage permissions to any Service Account for which you have generated a Private Key. |
47,059,537 | I want to use a value stored in the AsyncStorage in another function.
Here's my ValueHandler.js
```
import { AsyncStorage } from 'react-native';
export async function getSavedValue() {
try {
const val = await AsyncStorage.getItem('@MyStore:savedValue');
console.log("#getSavedValue", val);
return val;
} catch (error) {
console.log("#getSavedValue", error);
}
return null;
}
```
I made the above function getSavedValue() to get the value of the savedValue stored in the AsyncStorage.
```
import {getSavedValue} from '../lib/ValueHandler';
import Api from '../lib/Api';
export function fetchData() {
return(dispatch, getState) => {
var params = [
'client_id=1234567890',
];
console.log("#getSavedValue()", getSavedValue());
if(getSavedValue() != null) {
params = [
...params,
'savedValue='+getSavedValue()
];
}
params = params.join('&');
console.log(params);
return Api.get(`/posts/5132?${params}`).then(resp => {
console.log(resp.posts);
dispatch(setFetchedPosts({ post: resp.posts }));
}).catch( (ex) => {
console.log(ex);
});
}
}
```
How do I achieve this? I really wanted a simple method to save a value in the local storage and retrieve it simply when I need to make an API call.
Anyone got any suggestions or solutions to this? | 2017/11/01 | [
"https://Stackoverflow.com/questions/47059537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5115097/"
] | You can use the regular bootsrap class used to build your layout **and drop the collapsing navbar classes**: see <https://getbootstrap.com/docs/4.0/utilities/flex/>
>
> **Flex**
>
>
> Quickly manage the layout, alignment, and sizing of grid columns, navigation, components, and more with a full suite of responsive flexbox utilities. For more complex implementations, custom CSS may be necessary.
>
>
>
example with :`flex-md-row` class (play snippet in fullpage and resize windows to see it toggling row/column. You can try also `flex-lg-row` if you think it turns into column too late.
```html
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"/>
<div class="navbar " id="navbar10">
<ul class="navbar-nav nav-fill w-100 flex-md-row">
<li class="nav-item">
<a class="nav-link" href="#">aaa</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">bbb</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">ccc</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">ddd</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">eee</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">ffff</a>
</li>
</ul>
</div>
</div>
``` | Using CSS *media queries*, you can set specific break-points to change your elements. In this example, if the window is *less than* 480px then we can adjust the width to 100%.
(To see it in action, click run > full page > then resize window)
```css
.navTitle {
width: 20%;
float: left;
background-color: lightGrey;
outline: 1px solid black;
}
@media screen and (max-width: 480px) {
.navTitle {
width: 100%;
}
}
```
```html
<div class="navTitle">
<p>Section 1</p>
</div>
<div class="navTitle">
<p>Section 2</p>
</div>
<div class="navTitle">
<p>Section 3</p>
</div>
<div class="navTitle">
<p>Section 4</p>
</div>
<div class="navTitle">
<p>Section 5</p>
</div>
``` |
60,304,126 | I'm new in developement. I'm using VSCode with One Dark+ theme. I would like to change a meta tag name color from "#E06C75" to "#1b1ff0". I tried modified the settings.json but it didn't work. Please help me to resolve this issue.
To make it clear what is "meta tag name" (maybe I use wrong words), it means something like `<xs:complexType> </xs:complexType>` in XML file or html tag like `<p>`, `<br>` etc...
Here is my settings.json file.
Hope it helps.
Thank you.
```
{
"php.validate.executablePath": "C:/xampp/php/php.exe",
"workbench.sideBar.location": "right",
"workbench.iconTheme": "vscode-icons",
"workbench.colorTheme": "One Dark Pro",
"workbench.colorCustomizations":{
"tokenColors": [
{
"scope": "entity.name.tag",
"settings": {
"foreground": "#1b1ff0"
}
},
{
"scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
"settings": {
"foreground": "#1b1ff0"
}
}
]
}
}
``` | 2020/02/19 | [
"https://Stackoverflow.com/questions/60304126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12073199/"
] | Your syntax is just a little off:
```
"editor.tokenColorCustomizations": { // this is different
"textMateRules": [ // this is different
{
"scope": "entity.name.tag",
"settings": {
"foreground": "#1b1ff0"
}
},
{
"scope": "text.html.laravel-blade source.php.embedded.line.html entity.name.tag.laravel-blade",
"settings": {
"foreground": "#1b1ff0"
}
}
]
}
``` | You can try the [Highlight](https://marketplace.visualstudio.com/items?itemName=fabiospampinato.vscode-highlight) extension to configure the tokens colors. Althought I don't know if this plugin provides a way to says "any token", but since is using Regex I think there is and you should figure it out (maybe something like `<*>*<*>`, not actual Regex code btw but you get the idea) |
54,567,047 | I am building a blog by Laravel. I use `migration:refresh` to adjust the name of one of my table.
After that my login is not working and keep saying
>
> "These credentials do not match our records"
>
>
>
though the login information is correct. Here is my seeds
```
App\User::create([
'name'=> 'name',
'email'=>'name@gmail.com',
'password'=>bcrypt('laravel')
]);
```
I am new in laravel. Any help will be much appreciated.Thanks in advance. | 2019/02/07 | [
"https://Stackoverflow.com/questions/54567047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9452193/"
] | Try changing the the `bcrypt()` to `Hash::make()`
```
use Hash;
App\User::create([
'name'=> 'name',
'email'=>'name@gmail.com',
'password'=> Hash::make('laravel')
]);
```
And run
```
php artisan migrate:fresh
``` | Try this command it works for me
```
php artisan migrate:fresh
php artisan migrate
``` |
43,925,195 | On this page (<http://nate.fm/testing/>) you can see that the text link's bottom border gets pushed down. Can anyone tell me where I can change that in the CSS? | 2017/05/11 | [
"https://Stackoverflow.com/questions/43925195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7024325/"
] | You can set the `<a>` tag to `display: inline-block;` then reduce the `line-height`.
Something like this maybe:
```
.post-content a {
line-height: 15px;
display: inline-block;
}
``` | ```
.post-content a {
/* border-bottom: 3px solid #eee; */
text-decoration: underline;
}
``` |
43,925,195 | On this page (<http://nate.fm/testing/>) you can see that the text link's bottom border gets pushed down. Can anyone tell me where I can change that in the CSS? | 2017/05/11 | [
"https://Stackoverflow.com/questions/43925195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7024325/"
] | You can set the `<a>` tag to `display: inline-block;` then reduce the `line-height`.
Something like this maybe:
```
.post-content a {
line-height: 15px;
display: inline-block;
}
``` | They are using `border-bottom` along with `line-height`, the `line-height` property causes the effect of "pushing" down the border you are mentioning
`.post-content a {
border-bottom: 3px solid #eee;
line-height: 160%;
}` |
644 | Is there any Halacha or Minhag that specifies if red or White wine should be used for the four cups of wine during the Passover seder and does it matter what you use to spill out during the 10 plagues? | 2010/04/01 | [
"https://judaism.stackexchange.com/questions/644",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/17/"
] | Not only it is a Minhag, those who say Yotzros on Shabbos Hagadol say it in there:
>
> יין כי יתאדם למצוה הוא מקדם
>
>
>
Translates as "Wine that is Red for the Mitzvah ahead" Not only that the Rambam says you are not Yotzeh using white wine for kiddush (we do not rule like that) and the [Mishnah Berurah](https://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%AA%D7%A2%D7%91_%D7%99%D7%90) adds Pesach there is another reason to remind us of the of the blood of the Jewish children Pharaoh used to Bathe in. | Dittos to YS. The reason that many Ashkenazim stopped using red wine for the seder is because of the blood libels, but today (unless you live in an Arabic country) this is not a concern and therefore it is preferable to use red wine for the four cups at the seder. |
644 | Is there any Halacha or Minhag that specifies if red or White wine should be used for the four cups of wine during the Passover seder and does it matter what you use to spill out during the 10 plagues? | 2010/04/01 | [
"https://judaism.stackexchange.com/questions/644",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/17/"
] | Not only it is a Minhag, those who say Yotzros on Shabbos Hagadol say it in there:
>
> יין כי יתאדם למצוה הוא מקדם
>
>
>
Translates as "Wine that is Red for the Mitzvah ahead" Not only that the Rambam says you are not Yotzeh using white wine for kiddush (we do not rule like that) and the [Mishnah Berurah](https://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%AA%D7%A2%D7%91_%D7%99%D7%90) adds Pesach there is another reason to remind us of the of the blood of the Jewish children Pharaoh used to Bathe in. | The Rav, Rabbi Joseph Ber Solovetchik, says to have red wine for the first cup [Kiddush], to signify Cherut (≈freedom). |
644 | Is there any Halacha or Minhag that specifies if red or White wine should be used for the four cups of wine during the Passover seder and does it matter what you use to spill out during the 10 plagues? | 2010/04/01 | [
"https://judaism.stackexchange.com/questions/644",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/17/"
] | Dittos to YS. The reason that many Ashkenazim stopped using red wine for the seder is because of the blood libels, but today (unless you live in an Arabic country) this is not a concern and therefore it is preferable to use red wine for the four cups at the seder. | The Rav, Rabbi Joseph Ber Solovetchik, says to have red wine for the first cup [Kiddush], to signify Cherut (≈freedom). |
88,924 | So I have a recessed nook about 64" wide and 30" deep (it fits my washer and dryer side by side, plus a 6" narrow cabinet pull-out). I'm planning to have a (probably quartz) countertop installed.
[](https://i.stack.imgur.com/cjmZ1.png)
I presume attaching some wood to the walls to serve as cleats is going to be needed. What is unclear to me is exactly how substantial those cleats need to be. Naturally, I'll do the thickest wood I can fit without causing fitment problems for the washer/dryer, but it's going to be tight enough that I'd like to know how skinny I can go with the cleats before I start running into problems.
Right now it looks like I have, at most, 3/4" of clearance on either side between the wall and each respective appliance. Can I do 1/2" thick cleats on the sides (maybe thicker against the back wall since I'd have the space)? Are the countertop guys going to show up and laugh at me, or does this sound viable? | 2016/04/18 | [
"https://diy.stackexchange.com/questions/88924",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/6581/"
] | The countertop guys will laugh at you if you want to span quartz over a 5' span. Basically quartz and granite can barely span a dishwasher width - meaning we get buy with not having plywood over the counters. And that is given nothing heavy is stored on it on that section. Given you will have a washer and dryer below it, I would protect it. Since if a washer or dryer was jerked out of position it could nick or crack the slab.
So I would basically frame out the area. Cleat on each side - 2x4, then 3 2x4s going the width with one in the middle. Then a think piece of plywood on top (3/8"). You can then install decorative trim on the front panel and since you used a 2x4, the big box stores will have lots of choices. Total cost is about $25. \*You can also just face it with a nice wood veneer.
When the installers come they can just glue it to the plywood - they don't have to overdo this as a couple of dabs will do. The same principle should be used for the 2x4 framing under. Meaning if you need to move the quartz up or down or where ever later it should just take a few minutes with a putty knife. I am sure there is plumbing in that wall and you don't want a shelf you can never move.
Also a couple of notes here:
* stone hardly ever looks good floating. It would look tacky just stuck on top of cleats. First it isn't thick enough for the floating look and second the underside is hardly ever polished and thinking that would be pretty apparent in its location.
* You could also put some drawers below this but this may take some custom cabinetry. | Quartz weigh's 16-20 lbs per sq. ft. depending if it's 3/4" or 1-1/4". You will be fine with attaching a strip of 3/4" x 2" depth plywood or solid wood strips on all three wall sides and then slide the quartz into place for 1-1/4" (3cm) thickness, all four sides need support for 3/4" (2cm) thickness. I am a professional fabricator of 19 years. |
13,960 | When we do k-fold cross validation, should we just use the classifier that has the highest test accuracy? What is generally the best approach in getting a classifier from cross validation? | 2016/09/13 | [
"https://datascience.stackexchange.com/questions/13960",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/20635/"
] | No. You don't select any of the k classifiers built during k-fold cross-validation. First of all, the purpose of cross-validation is not to come up with a predictive model, but to evaluate how accurately a predictive model will perform in practice. Second of all, for the sake of argument, let's say you were to use k-fold cross-validation with k=10 to find out which one of three different classification algorithms would be the most suitable in solving a given classification problem. In that case, the data is randomly split into k parts of equal size. One of the parts is reserved for testing and the rest k-1 parts will be used for training. The cross-validation process is repeated k (fold) times so that on every iteration different part is used for testing. After running the cross-validation you look at the results from each fold and wonder which classification algorithm (not any of the trained models!) is the most suitable. You don't want to choose the algorithm that has the highest test accuracy on one of the 10 iterations, because maybe it just happened randomly that the test data on that particular iteration contained very easy examples, which then lead to high test accuracy. What you want to do, is to choose the algorithm which produced the best accuracy **averaged over all k folds**. Now that you have chosen the algorithm, you can train it using your whole training data and start making predictions in the wild.
This is beyond the scope of this question, but you should also optimize model's hyperparameters (if any) to get the most out of the selected algorithm. People usually perform hyperparameter optimization using cross-validation. | So let us assume you have training out of which you are using 80% as training and rest 20% as validation data. We can train on the 80% and test on the remaining 20% but it is possible that the 20% we took is not in resemblance with the actual testing data and might perform bad latter. So, in order to prevent this we can use k-fold cross validation.
So let us say you have different models and want to know which performs better with your dataset, k-fold cross validation works great. You can know the validation errors on the k-validation performances and choose the better model based on that. This is generally the purpose for k-fold cross validation.
Coming to just one model and if you are checking with k-fold cross-validation, you can get an approximate of errors of test data, but `when you are actually training it finally, you can use the complete training data`.(Because it is assumed here that the whole data will together perform better than a part of it.It might not be the case sometimes, but this is the general assumption.) |
13,960 | When we do k-fold cross validation, should we just use the classifier that has the highest test accuracy? What is generally the best approach in getting a classifier from cross validation? | 2016/09/13 | [
"https://datascience.stackexchange.com/questions/13960",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/20635/"
] | You do cross-validation when you want to do any of these two things:
* Model Selection
* Error Estimation of a Model
Model selection can come in different scenarios:
* Selecting one algorithm vs others for a particular problem/dataset
* Selecting hyper-parameters of a particular algorithm for a particular problem/dataset
(please notice that if you are both selecting an algorithm - better to call it model - and also doing hyper-parameters search, you need to do Nested Cross Validation . [Is Nested-CV really necessary?](https://stackoverflow.com/questions/31632094/nested-cross-validation-really-necessary))
Cross-validation ensures up to some degree that the error estimate is the closest possible as generalization error for that model (although this is very hard to approximate). When observing the average error among folds you can have a good projection of the expected error for a model built on the full dataset. Also is importance to observe the variance of the prediction, this is, how much the error varies from fold to fold. If the variation is too high (considerably different values) then the model will tend to be unstable. Bootstrapping is the other method providing good approximation in this sense. I suggest to read carefully the section 7 on "Elements of Statistical Learning" Book, freely available at: [ELS-Standford](http://statweb.stanford.edu/~tibs/ElemStatLearn/)
As it has been mentioned before you must not take the built model in none of the folds. Instead, you have to rebuild the model with the full dataset (the one that was split into folds). If you have a separated test set, you can use it to try this final model, obtaining a similar (and must surely higher) error than the one obtained by CV. You should, however, rely on the estimated error given by the CV procedure.
After performing CV with different models (algorithm combination, etc) chose the one that performed better regarding error and its variance among folds. You will need to rebuild the model with the whole dataset. Here comes a common confusion in terms: we commongly refer to model selection, thinking that the model is the ready-to-predict model built on data, but in this case it refers to the combination of algorithm+preprocesing procedures you apply. So, to obtain the actual model you need for making predictions/classification you need to build it using the winner combination on the whole dataset.
Last thing to note is that if you are applying any kind of preprocessing the uses the class information (feature selection, LDA dimensionality reduction, etc) this must be performed in every fold, and not previously on data. This is a critical aspect. Should do the same thing if you are applying preprocessing methods that involve direct information of data (PCA, normalization, standardization, etc). You can, however, apply preprocessing that is not depend from data (deleting a variable following expert opinion, but this is kinda obvious). This video can help you in that direction: [CV the right and the wrong way](https://www.youtube.com/watch?v=S06JpVoNaA0)
Here, a final nice explanation regarding the subject: [CV and model selection](https://stats.stackexchange.com/questions/2306/feature-selection-for-final-model-when-performing-cross-validation-in-machine) | So let us assume you have training out of which you are using 80% as training and rest 20% as validation data. We can train on the 80% and test on the remaining 20% but it is possible that the 20% we took is not in resemblance with the actual testing data and might perform bad latter. So, in order to prevent this we can use k-fold cross validation.
So let us say you have different models and want to know which performs better with your dataset, k-fold cross validation works great. You can know the validation errors on the k-validation performances and choose the better model based on that. This is generally the purpose for k-fold cross validation.
Coming to just one model and if you are checking with k-fold cross-validation, you can get an approximate of errors of test data, but `when you are actually training it finally, you can use the complete training data`.(Because it is assumed here that the whole data will together perform better than a part of it.It might not be the case sometimes, but this is the general assumption.) |
13,960 | When we do k-fold cross validation, should we just use the classifier that has the highest test accuracy? What is generally the best approach in getting a classifier from cross validation? | 2016/09/13 | [
"https://datascience.stackexchange.com/questions/13960",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/20635/"
] | You do cross-validation when you want to do any of these two things:
* Model Selection
* Error Estimation of a Model
Model selection can come in different scenarios:
* Selecting one algorithm vs others for a particular problem/dataset
* Selecting hyper-parameters of a particular algorithm for a particular problem/dataset
(please notice that if you are both selecting an algorithm - better to call it model - and also doing hyper-parameters search, you need to do Nested Cross Validation . [Is Nested-CV really necessary?](https://stackoverflow.com/questions/31632094/nested-cross-validation-really-necessary))
Cross-validation ensures up to some degree that the error estimate is the closest possible as generalization error for that model (although this is very hard to approximate). When observing the average error among folds you can have a good projection of the expected error for a model built on the full dataset. Also is importance to observe the variance of the prediction, this is, how much the error varies from fold to fold. If the variation is too high (considerably different values) then the model will tend to be unstable. Bootstrapping is the other method providing good approximation in this sense. I suggest to read carefully the section 7 on "Elements of Statistical Learning" Book, freely available at: [ELS-Standford](http://statweb.stanford.edu/~tibs/ElemStatLearn/)
As it has been mentioned before you must not take the built model in none of the folds. Instead, you have to rebuild the model with the full dataset (the one that was split into folds). If you have a separated test set, you can use it to try this final model, obtaining a similar (and must surely higher) error than the one obtained by CV. You should, however, rely on the estimated error given by the CV procedure.
After performing CV with different models (algorithm combination, etc) chose the one that performed better regarding error and its variance among folds. You will need to rebuild the model with the whole dataset. Here comes a common confusion in terms: we commongly refer to model selection, thinking that the model is the ready-to-predict model built on data, but in this case it refers to the combination of algorithm+preprocesing procedures you apply. So, to obtain the actual model you need for making predictions/classification you need to build it using the winner combination on the whole dataset.
Last thing to note is that if you are applying any kind of preprocessing the uses the class information (feature selection, LDA dimensionality reduction, etc) this must be performed in every fold, and not previously on data. This is a critical aspect. Should do the same thing if you are applying preprocessing methods that involve direct information of data (PCA, normalization, standardization, etc). You can, however, apply preprocessing that is not depend from data (deleting a variable following expert opinion, but this is kinda obvious). This video can help you in that direction: [CV the right and the wrong way](https://www.youtube.com/watch?v=S06JpVoNaA0)
Here, a final nice explanation regarding the subject: [CV and model selection](https://stats.stackexchange.com/questions/2306/feature-selection-for-final-model-when-performing-cross-validation-in-machine) | No. You don't select any of the k classifiers built during k-fold cross-validation. First of all, the purpose of cross-validation is not to come up with a predictive model, but to evaluate how accurately a predictive model will perform in practice. Second of all, for the sake of argument, let's say you were to use k-fold cross-validation with k=10 to find out which one of three different classification algorithms would be the most suitable in solving a given classification problem. In that case, the data is randomly split into k parts of equal size. One of the parts is reserved for testing and the rest k-1 parts will be used for training. The cross-validation process is repeated k (fold) times so that on every iteration different part is used for testing. After running the cross-validation you look at the results from each fold and wonder which classification algorithm (not any of the trained models!) is the most suitable. You don't want to choose the algorithm that has the highest test accuracy on one of the 10 iterations, because maybe it just happened randomly that the test data on that particular iteration contained very easy examples, which then lead to high test accuracy. What you want to do, is to choose the algorithm which produced the best accuracy **averaged over all k folds**. Now that you have chosen the algorithm, you can train it using your whole training data and start making predictions in the wild.
This is beyond the scope of this question, but you should also optimize model's hyperparameters (if any) to get the most out of the selected algorithm. People usually perform hyperparameter optimization using cross-validation. |
53,608,406 | I'm using DataTables with server-side processing to display tens of thousands rows. I need to filter these data by checkboxes. I was able to make one checkbox which is working fine, but I don't know how to add multiple checkboxes to work together. I found [similar solution](https://stackoverflow.com/questions/8912442/query-mysql-by-checking-multiple-checkboxes-with-automatic-update) here, but my skills doesn't allow me to modify it to my needs:( Here is what I have tried..
My index.php:
```
Statuses:<br>
<input type="checkbox" id="0" onclick="myCheckFunc()" name="statuses">Open<br>
<input type="checkbox" id="1" onclick="myCheckFunc()" name="statuses">Closed<br>
<input type="checkbox" id="2" onclick="myCheckFunc()" name="statuses">Solved<br>
<script>
var idsa = 5;
$('input[name=statuses]').click(function(){
idsa = [];
$('input[name=statuses]:checked').each(function() {
idsa.push($(this).attr('id'));
});
idsa = idsa.join(",");
console.log("idsa fcia: " + idsa);
$('#example').DataTable().ajax.reload();
});
</script>
```
The idsa variable is initially set to 5, which means all statuses(no checkbox checked) then send to server side script with it's format(d) function (this part is working fine). This is how I modify sql query in server side script:
```
if ($_GET['idsa'] == 5){
$idsa = "0,1,2";
} else { if (isset($_GET['idsa'])) {
$idsa = "('" . str_replace(",", "','", $_GET['idsa']) . "')"; }
}
$whereAll = "STATUS IN ($idsa)";
```
EDIT:
Now after click on first of these three checkboxes, the data are filtered correctly (Open tickets with status 0), but uncheck don't bring back the initial state with all data. When I click on other two, the data are filtered, but when I uncheck, the data are fitered byt first filter (Open). When I click two or more checkboxes, I get this error:
>
> An SQL error occurred: SQLSTATE[21000]: Cardinality violation: 1241
> Operand should contain 1 column(s)
>
>
> | 2018/12/04 | [
"https://Stackoverflow.com/questions/53608406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809973/"
] | Ok, here is working code:
```
Status:<br>
<input type="checkbox" id="0" name="statuses">Open<br>
<input type="checkbox" id="1" name="statuses">Closed<br>
<input type="checkbox" id="2" name="statuses">Solved<br>
<script>
var idsa = 5;
$('input[name=statuses]').click(function(){
idsa = [];
$('input[name=statuses]:checked').each(function() {
idsa.push($(this).attr('id'));
});
idsa = idsa.join(",");
console.log("idsa fcia: " + idsa);
if (idsa == '') {
idsa = 5;
}
$('#example').DataTable().ajax.reload();
});
</script>
```
And in the server-side script:
```
if ($_GET['idsa'] == 5){
$idsa = "0,1,2";
} else {
$idsa = $_GET['idsa'];
}
$whereAll = "STATUS IN ($idsa)";
```
The problem was with the server-side part which I grabbed from someone else and there was added another comma. Now it's working fine. Thank you very much for your time. | Try wrapping your `STATUS` column name into backquotes, that seems to be a MySQL keyword |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yup. It's a bit of work though, if you want to use something other than circles or squares :)
See: <http://alistapart.com/article/taminglists>
The article I link to describes doing this by first stripping off the original markup:
```
ul.custom-list {
list-style: none;
margin-left: 0;
padding-left: 1em;
text-indent: -1em;
}
```
Then they add a custom bullet using the "before" pseudo-selector, and injecting content into that:
```
ul.custom-list li:before {
content: "\0BB \020";
}
```
In this case, they're using it to include the "double chevron" symbol. You can look up the symbol code for whatever you want to inject. | Yes you can use
```
list-style
```
style property for that. |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | If you want a simple (and painless) solution for a triangle in your unordered list, then you could use this method. I simply wrote a fiddle where the CSS gives you a UL list with each item marked with a right-pointing triangle instead of a round bullet.
Is this what you were after?
<http://jsfiddle.net/CU5Ry/>
HTML:
```
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>
```
CSS:
```
ul {
list-style: none;
}
ul li:before {
content: "\25BA \0020";
}
``` | Unfortunately there is no triangle available as a standard marker.
A full list of values for `list-style-type` can be found [here](http://www.w3schools.com/cssref/pr_list-style-type.asp). |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yup. It's a bit of work though, if you want to use something other than circles or squares :)
See: <http://alistapart.com/article/taminglists>
The article I link to describes doing this by first stripping off the original markup:
```
ul.custom-list {
list-style: none;
margin-left: 0;
padding-left: 1em;
text-indent: -1em;
}
```
Then they add a custom bullet using the "before" pseudo-selector, and injecting content into that:
```
ul.custom-list li:before {
content: "\0BB \020";
}
```
In this case, they're using it to include the "double chevron" symbol. You can look up the symbol code for whatever you want to inject. | If you want a simple (and painless) solution for a triangle in your unordered list, then you could use this method. I simply wrote a fiddle where the CSS gives you a UL list with each item marked with a right-pointing triangle instead of a round bullet.
Is this what you were after?
<http://jsfiddle.net/CU5Ry/>
HTML:
```
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>
```
CSS:
```
ul {
list-style: none;
}
ul li:before {
content: "\25BA \0020";
}
``` |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | [JSFiddle of triangle bullets](http://jsfiddle.net/2KZja/1/)
Hopefully this is what you mean?
CSS:
```
.ul1 {
margin: 0.75em 0;
padding: 0 1em;
list-style: none;
}
.li1:before {
content: "";
border-color: transparent #111;
border-style: solid;
border-width: 0.35em 0 0.35em 0.45em;
display: block;
height: 0;
width: 0;
left: -1em;
top: 0.9em;
position: relative;
}
``` | If you want a simple (and painless) solution for a triangle in your unordered list, then you could use this method. I simply wrote a fiddle where the CSS gives you a UL list with each item marked with a right-pointing triangle instead of a round bullet.
Is this what you were after?
<http://jsfiddle.net/CU5Ry/>
HTML:
```
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>
```
CSS:
```
ul {
list-style: none;
}
ul li:before {
content: "\25BA \0020";
}
``` |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | [JSFiddle of triangle bullets](http://jsfiddle.net/2KZja/1/)
Hopefully this is what you mean?
CSS:
```
.ul1 {
margin: 0.75em 0;
padding: 0 1em;
list-style: none;
}
.li1:before {
content: "";
border-color: transparent #111;
border-style: solid;
border-width: 0.35em 0 0.35em 0.45em;
display: block;
height: 0;
width: 0;
left: -1em;
top: 0.9em;
position: relative;
}
``` | Yes you can use
```
list-style
```
style property for that. |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yes you can use
```
list-style
```
style property for that. | Unfortunately there is no triangle available as a standard marker.
A full list of values for `list-style-type` can be found [here](http://www.w3schools.com/cssref/pr_list-style-type.asp). |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yup. It's a bit of work though, if you want to use something other than circles or squares :)
See: <http://alistapart.com/article/taminglists>
The article I link to describes doing this by first stripping off the original markup:
```
ul.custom-list {
list-style: none;
margin-left: 0;
padding-left: 1em;
text-indent: -1em;
}
```
Then they add a custom bullet using the "before" pseudo-selector, and injecting content into that:
```
ul.custom-list li:before {
content: "\0BB \020";
}
```
In this case, they're using it to include the "double chevron" symbol. You can look up the symbol code for whatever you want to inject. | Unfortunately there is no triangle available as a standard marker.
A full list of values for `list-style-type` can be found [here](http://www.w3schools.com/cssref/pr_list-style-type.asp). |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yes you can use
```
list-style
```
style property for that. | Yes. Check this out. You can use CSS propriety as discribed here
<http://www.w3schools.com/cssref/playit.asp?filename=playcss_ol_list-style-type&preval=cjk-ideographic> |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | [JSFiddle of triangle bullets](http://jsfiddle.net/2KZja/1/)
Hopefully this is what you mean?
CSS:
```
.ul1 {
margin: 0.75em 0;
padding: 0 1em;
list-style: none;
}
.li1:before {
content: "";
border-color: transparent #111;
border-style: solid;
border-width: 0.35em 0 0.35em 0.45em;
display: block;
height: 0;
width: 0;
left: -1em;
top: 0.9em;
position: relative;
}
``` | Yup. It's a bit of work though, if you want to use something other than circles or squares :)
See: <http://alistapart.com/article/taminglists>
The article I link to describes doing this by first stripping off the original markup:
```
ul.custom-list {
list-style: none;
margin-left: 0;
padding-left: 1em;
text-indent: -1em;
}
```
Then they add a custom bullet using the "before" pseudo-selector, and injecting content into that:
```
ul.custom-list li:before {
content: "\0BB \020";
}
```
In this case, they're using it to include the "double chevron" symbol. You can look up the symbol code for whatever you want to inject. |
18,012,956 | Preferably looking for a triangle to replace the circle. I'd rather not use an image but I would if there was no other way. | 2013/08/02 | [
"https://Stackoverflow.com/questions/18012956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131689/"
] | Yup. It's a bit of work though, if you want to use something other than circles or squares :)
See: <http://alistapart.com/article/taminglists>
The article I link to describes doing this by first stripping off the original markup:
```
ul.custom-list {
list-style: none;
margin-left: 0;
padding-left: 1em;
text-indent: -1em;
}
```
Then they add a custom bullet using the "before" pseudo-selector, and injecting content into that:
```
ul.custom-list li:before {
content: "\0BB \020";
}
```
In this case, they're using it to include the "double chevron" symbol. You can look up the symbol code for whatever you want to inject. | Yes. Check this out. You can use CSS propriety as discribed here
<http://www.w3schools.com/cssref/playit.asp?filename=playcss_ol_list-style-type&preval=cjk-ideographic> |
18,754,376 | I would like to set up CMake to build qresource files when the contents of files referenced in the .qrc file change. For example I have some qml files that are packaged into a qrc file and the qrc needs to be recompiled if the qml files are changed.
I have the following macro to run the resource compiler but it will only rebuild it if the resource file itself changes.
```
MACRO(PYQT5_WRAP_RC outfiles)
FOREACH(it ${ARGN})
GET_FILENAME_COMPONENT(outfile ${it} NAME_WE)
GET_FILENAME_COMPONENT(infile ${it} ABSOLUTE)
SET(outfile ${CMAKE_CURRENT_SOURCE_DIR}/${outfile}_rc.py)
ADD_CUSTOM_TARGET(${it} ALL
DEPENDS ${outfile}
)
ADD_CUSTOM_COMMAND(OUTPUT ${outfile}
COMMAND ${PYRCC5BINARY} ${infile} -o ${outfile}
MAIN_DEPENDENCY ${infile}
)
SET(${outfiles} ${${outfiles}} ${outfile})
ENDFOREACH(it)
ENDMACRO (PYQT5_WRAP_RC)
```
The macro is used like this:
```
PYQT5_WRAP_RC(rc_gen file1.qrc file2.qrc ...)
```
How can I make it so the qrc file gets recompiled if one of files that it refers to changes?
Do I need to do something [convoluted like this](https://stackoverflow.com/questions/16408060/how-to-add-a-dependency-on-a-script-to-a-target-in-cmake)? | 2013/09/12 | [
"https://Stackoverflow.com/questions/18754376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278403/"
] | **This is the snapshot after making changes**:

Remove `float:left;` from
```
<ul class="nav">
```
and add `float:right;` in login and register
```
<li class="login" style="float:right;">
<li class="register.html" style="float:right;">
``` | If you want to shift items to the right, a simple text align should work:
`<li class = "login" style="text-align: right;">`
Or, if you want to use CSS & HTML:
**HTML:** `<li class = "login">`
**CSS:**
```
.login {
text-align: right;
}
``` |
18,754,376 | I would like to set up CMake to build qresource files when the contents of files referenced in the .qrc file change. For example I have some qml files that are packaged into a qrc file and the qrc needs to be recompiled if the qml files are changed.
I have the following macro to run the resource compiler but it will only rebuild it if the resource file itself changes.
```
MACRO(PYQT5_WRAP_RC outfiles)
FOREACH(it ${ARGN})
GET_FILENAME_COMPONENT(outfile ${it} NAME_WE)
GET_FILENAME_COMPONENT(infile ${it} ABSOLUTE)
SET(outfile ${CMAKE_CURRENT_SOURCE_DIR}/${outfile}_rc.py)
ADD_CUSTOM_TARGET(${it} ALL
DEPENDS ${outfile}
)
ADD_CUSTOM_COMMAND(OUTPUT ${outfile}
COMMAND ${PYRCC5BINARY} ${infile} -o ${outfile}
MAIN_DEPENDENCY ${infile}
)
SET(${outfiles} ${${outfiles}} ${outfile})
ENDFOREACH(it)
ENDMACRO (PYQT5_WRAP_RC)
```
The macro is used like this:
```
PYQT5_WRAP_RC(rc_gen file1.qrc file2.qrc ...)
```
How can I make it so the qrc file gets recompiled if one of files that it refers to changes?
Do I need to do something [convoluted like this](https://stackoverflow.com/questions/16408060/how-to-add-a-dependency-on-a-script-to-a-target-in-cmake)? | 2013/09/12 | [
"https://Stackoverflow.com/questions/18754376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278403/"
] | In the context of Bootstrap, all previous answers are wrong. There is specifically `navbar-left` and `navbar-right` to handle just this situation. You should not be trying to float elements left and right on your own, you should be using the provided classes.
The reason you are seeing no space between the elements is that when you apply float to multiple items and they end up next to each other, any margins are ignored when they are floated. The only way to maintain those margins is to put the items in a containing div and float that div, which is why the Bootstrap framework provided `navbar-left` and `navbar-right`.
As you also should have noticed, when floating right on each individual item instead of a containing div, is that you have to define the element in your markup as the first element if you want it to be the far right element; which is obviously unintuitive and should be avoided since someone coming behind you may not understand what is happening.
I know this is 3 years late, but I felt the proper instructions needed to be pointed out. Bootstrap's website has examples of how to structure the navbar:
<http://getbootstrap.com/components/#navbar> | If you want to shift items to the right, a simple text align should work:
`<li class = "login" style="text-align: right;">`
Or, if you want to use CSS & HTML:
**HTML:** `<li class = "login">`
**CSS:**
```
.login {
text-align: right;
}
``` |
18,754,376 | I would like to set up CMake to build qresource files when the contents of files referenced in the .qrc file change. For example I have some qml files that are packaged into a qrc file and the qrc needs to be recompiled if the qml files are changed.
I have the following macro to run the resource compiler but it will only rebuild it if the resource file itself changes.
```
MACRO(PYQT5_WRAP_RC outfiles)
FOREACH(it ${ARGN})
GET_FILENAME_COMPONENT(outfile ${it} NAME_WE)
GET_FILENAME_COMPONENT(infile ${it} ABSOLUTE)
SET(outfile ${CMAKE_CURRENT_SOURCE_DIR}/${outfile}_rc.py)
ADD_CUSTOM_TARGET(${it} ALL
DEPENDS ${outfile}
)
ADD_CUSTOM_COMMAND(OUTPUT ${outfile}
COMMAND ${PYRCC5BINARY} ${infile} -o ${outfile}
MAIN_DEPENDENCY ${infile}
)
SET(${outfiles} ${${outfiles}} ${outfile})
ENDFOREACH(it)
ENDMACRO (PYQT5_WRAP_RC)
```
The macro is used like this:
```
PYQT5_WRAP_RC(rc_gen file1.qrc file2.qrc ...)
```
How can I make it so the qrc file gets recompiled if one of files that it refers to changes?
Do I need to do something [convoluted like this](https://stackoverflow.com/questions/16408060/how-to-add-a-dependency-on-a-script-to-a-target-in-cmake)? | 2013/09/12 | [
"https://Stackoverflow.com/questions/18754376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278403/"
] | **This is the snapshot after making changes**:

Remove `float:left;` from
```
<ul class="nav">
```
and add `float:right;` in login and register
```
<li class="login" style="float:right;">
<li class="register.html" style="float:right;">
``` | In the context of Bootstrap, all previous answers are wrong. There is specifically `navbar-left` and `navbar-right` to handle just this situation. You should not be trying to float elements left and right on your own, you should be using the provided classes.
The reason you are seeing no space between the elements is that when you apply float to multiple items and they end up next to each other, any margins are ignored when they are floated. The only way to maintain those margins is to put the items in a containing div and float that div, which is why the Bootstrap framework provided `navbar-left` and `navbar-right`.
As you also should have noticed, when floating right on each individual item instead of a containing div, is that you have to define the element in your markup as the first element if you want it to be the far right element; which is obviously unintuitive and should be avoided since someone coming behind you may not understand what is happening.
I know this is 3 years late, but I felt the proper instructions needed to be pointed out. Bootstrap's website has examples of how to structure the navbar:
<http://getbootstrap.com/components/#navbar> |
43,854,393 | I have the following dictionaries:
```
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
```
I would like to know if it is possible to get value `42.55` if the value of the key `market` is `apples`.
I was trying something like this:
```
for d in inicio:
if key['market']='apples':
print(d['Valor'])
```
Sorry that I do not include further examples, but I am quite new into dealing with dictionaries and not sure what else to try. | 2017/05/08 | [
"https://Stackoverflow.com/questions/43854393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7836530/"
] | In your example `d` is the dictionary you're looking for:
```
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
```
And use equality operator (`==`) instead of assignment (`=`) | Use this code
```
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
print inicio[1]['Valor']
```
If you have many items with same apples as market then iterate over the list and check if the key equals apples and then the value.
Check this code.
```
for dictionary in inicio:
if dictionary['market'] == 'apples':
print(dictionary['Valor'])
``` |
43,854,393 | I have the following dictionaries:
```
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
```
I would like to know if it is possible to get value `42.55` if the value of the key `market` is `apples`.
I was trying something like this:
```
for d in inicio:
if key['market']='apples':
print(d['Valor'])
```
Sorry that I do not include further examples, but I am quite new into dealing with dictionaries and not sure what else to try. | 2017/05/08 | [
"https://Stackoverflow.com/questions/43854393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7836530/"
] | In your example `d` is the dictionary you're looking for:
```
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
```
And use equality operator (`==`) instead of assignment (`=`) | Your code works. Just replace the "=" with "==" in this line:
```
if d['market'] =='apples':
``` |
43,854,393 | I have the following dictionaries:
```
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
```
I would like to know if it is possible to get value `42.55` if the value of the key `market` is `apples`.
I was trying something like this:
```
for d in inicio:
if key['market']='apples':
print(d['Valor'])
```
Sorry that I do not include further examples, but I am quite new into dealing with dictionaries and not sure what else to try. | 2017/05/08 | [
"https://Stackoverflow.com/questions/43854393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7836530/"
] | In your example `d` is the dictionary you're looking for:
```
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
```
And use equality operator (`==`) instead of assignment (`=`) | if you need the lookup only once then the iterative logic you have provided is alright. One optimization can be applied here -
```
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
break # assuming you only need 1 value
```
However if you need to rerun this logic again, I would suggest you can iterate once and create a mapping of values.
S o eventually the result may become like `{'apples' : 42.55, 'oranges': 104.58}`.
Again assuming there is only one valor for one market.
On the other hand, if there are many valors for each market, you can iterate once and crate a structure like
`{'apples' : [42.55, 99.99], 'oranges': [104.58, 99.22]}`
Hope it helps. |
38,173,722 | I am new in php therefore I cannot figure out how to solve this issue.
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
```
I have a php login system which uses username and password from mysql database table called members. It uses session to see if the user is logged in.
```
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
```
I have another table called booked which stores information like name, id, date, computer no, start date and end date. I have a php code that displays all this information inside a table on the webpage. How would I make sure the system only displays information of a specific user based on their name.
I want to link the value of the session "username" with the value of the row "name" in the table.
for example: if the username saved on the session is "John", I would like the system to display all the information with the name John only.
Below is the full source code for that page:
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title -->
<title> Mycomputer </title>
<!-- css link -->
<link rel="stylesheet" type="text/css" href="booking.css">
</head>
<body>
<!-- headings -->
<h2>You have the following bookings.</h2>
<!-- table -->
<table>
<tr>
<th>ID No</th>
<th>Name</th>
<th>Room</th>
<th>Computer ID</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Action</th>
</tr>
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
``` | 2016/07/03 | [
"https://Stackoverflow.com/questions/38173722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4882481/"
] | In the sql use a `WHERE` clause to get only the filtered rows:
```
$sql = "
SELECT
id, name, room, computer_id, date, start_time, end_time
FROM
booked
WHERE
name = '" . $_SESSION['username'] ."'"
;
$result = mysqli_query($con, $sql);
``` | Use the where clause In sql query like this
```
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked where name='".$username."' ";
$result = mysqli_query($con, $sql);
``` |
38,173,722 | I am new in php therefore I cannot figure out how to solve this issue.
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
```
I have a php login system which uses username and password from mysql database table called members. It uses session to see if the user is logged in.
```
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
```
I have another table called booked which stores information like name, id, date, computer no, start date and end date. I have a php code that displays all this information inside a table on the webpage. How would I make sure the system only displays information of a specific user based on their name.
I want to link the value of the session "username" with the value of the row "name" in the table.
for example: if the username saved on the session is "John", I would like the system to display all the information with the name John only.
Below is the full source code for that page:
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title -->
<title> Mycomputer </title>
<!-- css link -->
<link rel="stylesheet" type="text/css" href="booking.css">
</head>
<body>
<!-- headings -->
<h2>You have the following bookings.</h2>
<!-- table -->
<table>
<tr>
<th>ID No</th>
<th>Name</th>
<th>Room</th>
<th>Computer ID</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Action</th>
</tr>
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
``` | 2016/07/03 | [
"https://Stackoverflow.com/questions/38173722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4882481/"
] | In the sql use a `WHERE` clause to get only the filtered rows:
```
$sql = "
SELECT
id, name, room, computer_id, date, start_time, end_time
FROM
booked
WHERE
name = '" . $_SESSION['username'] ."'"
;
$result = mysqli_query($con, $sql);
``` | Use a `WHERE` clause like this:
```
$sql =
"
SELECT `id`, `name`, `room`, `computer_id`, `date`, `start_time`, `end_time` FROM booked
WHERE
name = '".$username."'
";
$result = mysqli_query($con, $sql);
```
**Note:** Try to `echo` your query to see what exactly is happening. |
38,173,722 | I am new in php therefore I cannot figure out how to solve this issue.
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
```
I have a php login system which uses username and password from mysql database table called members. It uses session to see if the user is logged in.
```
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
```
I have another table called booked which stores information like name, id, date, computer no, start date and end date. I have a php code that displays all this information inside a table on the webpage. How would I make sure the system only displays information of a specific user based on their name.
I want to link the value of the session "username" with the value of the row "name" in the table.
for example: if the username saved on the session is "John", I would like the system to display all the information with the name John only.
Below is the full source code for that page:
```
<?php
// starts a session and checks if the user is logged in
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: index.php');
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- title -->
<title> Mycomputer </title>
<!-- css link -->
<link rel="stylesheet" type="text/css" href="booking.css">
</head>
<body>
<!-- headings -->
<h2>You have the following bookings.</h2>
<!-- table -->
<table>
<tr>
<th>ID No</th>
<th>Name</th>
<th>Room</th>
<th>Computer ID</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Action</th>
</tr>
<?php
include 'booking_connection.php';
$sql = "select id, name, room, computer_id, date, start_time, end_time from booked";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0 ){
while($row = mysqli_fetch_assoc($result)){
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['room']?></td>
<td><?=$row['computer_id']?></td>
<td><?=$row['date']?></td>
<td><?=$row['start_time']?></td>
<td><?=$row['end_time']?></td>
<td>
<a href="delete.php?id=<?=$row['id']?>">CANCEL</a>
</td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
``` | 2016/07/03 | [
"https://Stackoverflow.com/questions/38173722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4882481/"
] | In the sql use a `WHERE` clause to get only the filtered rows:
```
$sql = "
SELECT
id, name, room, computer_id, date, start_time, end_time
FROM
booked
WHERE
name = '" . $_SESSION['username'] ."'"
;
$result = mysqli_query($con, $sql);
``` | >
> *Your best bet is to rethink your approach since you're working with untrusted user data.*
>
>
>
**Creating your Connection object using PDO (pdo\_driver.php):**
```
namespace CompanyName\App\Drivers;
interface DatabaseConnection
{
public function query($statement, array $values = array());
}
class PdoDriver implements DatabaseConnection
{
public function __construct(
$dsn, $user, $pass
) {
try {
parent::__construct($dsn, $user, $pass);
} catch (PDOException $ex) {
die($ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$stmp = parent::Prepare($statement);
return (empty($values)) ? $stmp->execute() : $stmp->execute($values);
}
}
```
**Inside your then file (index.php):**
```
require_once dirname(__FILE__) . '/location/to/file/pdo_driver.php';
$container = array();
// instance our object and establish connection
$container['db'] = new CompanyName\App\Drivers\PdoDriver(
'mysql:host=localhost;dbname=database_name', 'username', 'password'
);
// conditional statement for readabilty
if(!empty($_SESSION['username'])):
// suggest creating a user object and using a unique session key
// rather than a username for the session
$current_user = $_SESSION['username']);
$stmp = $container['db']->query('SELECT id, room, computer_id, date, start_time, end_time FROM booked WHERE name = ?', [$current_user]);
$row = $stmp->fetch(); ?>
<table id=''>
<tr>
<td> <?php echo $row['id']; ?> </td>
<!-- Continue adding these -->
</tr>
</table>
<?php endif; ?>
```
**Why use PDO and what's the advantages of OOP (Object-oriented programming) ?**
PDO is a secure layer which is least depreciated in PHP that uses the basic mysql protocols. Using Object oriented programming allows you to build framework (or an infrastructure) which can then be imported into multiple projects.
I also suggest building some sort of DI software or using prebuilt DI software like Symfony. |
17,563,756 | i got problem with my web.xml. I m getting following error: "element listener-class not allowed here". Anyone knows where could be problem? thx for answers.
my web.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>zkspringcoresec</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/default-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--Spring security-->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Spring security-->
<!--ZK-->
<listener>
<description>Used to cleanup when a session is destroyed</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
<servlet>
<servlet-name>zkLoader</servlet-name>
<servlet-class>
org.zkoss.zk.ui.http.DHtmlLayoutServlet
</servlet-class>
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<servlet>
<description>The asynchronous update engine for ZK</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>org.zkoss.zk.au.http.DHtmlUpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>
<!-- [Optional] Session timeout -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<!-- [Optional] MIME mapping -->
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
<mime-mapping>
<extension>gif</extension>
<mime-type>image/gif</mime-type>
</mime-mapping>
<mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpeg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jpg</extension>
<mime-type>image/jpeg</mime-type>
</mime-mapping>
<mime-mapping>
<extension>js</extension>
<mime-type>text/javascript</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>
<mime-mapping>
<extension>png</extension>
<mime-type>image/png</mime-type>
</mime-mapping>
<mime-mapping>
<extension>txt</extension>
<mime-type>text/plain</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xls</extension>
<mime-type>application/vnd.ms-excel</mime-type>
</mime-mapping>
<mime-mapping>
<extension>xml</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>zul</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<welcome-file-list>
<welcome-file>index.zul</welcome-file>
</welcome-file-list>
</web-app>
```
i am getting eror in this line:
```
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
```
and this:
```
<listener>
<description>Used to cleanup when a session is destroyed</description>
<listener-class>org.zkoss.zk.ui.http.HttpSessionListener</listener-class>
</listener>
``` | 2013/07/10 | [
"https://Stackoverflow.com/questions/17563756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2559447/"
] | ```
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
```
What's the purpose of xmlns:web="http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"? Will it work if you remove it? | version is wrong,change as below
http://java.sun.com/xml/ns/javaee/web-app\_3\_0.xsd" id="WebApp\_ID" version="3.0"> |
65,780,660 | I have solved a [problem to count pairs of values](https://www.hackerrank.com/challenges/sock-merchant/problem) in an inputted array using dictionaries in Python.
Problem Example:
```
Input:
[1,1,2,3,2]
Output:
2 (since there are a pair of 1's and a pair or 2's)
```
Code Snippet:
```
dict = {}
for i in range(len(ar)):
if ar[i] in dict:
dict[ar[i]] += 1
else:
dict[ar[i]] = 1
```
Full Code if interested: <https://pastebin.com/s1LQRQMC>
In the above code, I am using an if statement to check if an array element has been added to the dictionary and adding to it's count if it has. Else, I'm initializing the array element as a key and setting its value as 1.
**My question is if there are any ways in python to simplify the if/else statement that may be cleaner or more acceptable or considering alternate ways using structure of the dictionary.** | 2021/01/18 | [
"https://Stackoverflow.com/questions/65780660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8729177/"
] | As mentioned by @P.J.Meisch, you have done everything correct, but missed defining your field data type to `text`, when you define them as `keyword`, even though you are explicitly telling ElasticSearch to use your custom-analyzer `isbn_search_analyzer`, it will be ignored.
Working example on your sample data when field is defined as `text`.
**Index mapping**
```
{
"settings": {
"analysis": {
"filter": {
"clean_special": {
"type": "pattern_replace",
"pattern": "[^a-zA-Z0-9]",
"replacement": ""
}
},
"analyzer": {
"isbn_search_analyzer": {
"type": "custom",
"tokenizer": "keyword",
"filter": [
"clean_special"
]
}
}
}
},
"mappings": {
"properties": {
"isbn": {
"type": "text",
"analyzer": "isbn_search_analyzer"
},
"ean": {
"type": "text",
"analyzer": "isbn_search_analyzer"
}
}
}
}
```
**Index Sample records**
```
{
"isbn" : "111-3333-444444"
}
{
"isbn" : "111-3333-2222"
}
```
**Search query**
```
{
"query": {
"query_string": {
"fields": [
"isbn",
"ean"
],
"query": "111-3333-444444"
}
}
}
```
**And search response**
```
"hits": [
{
"_index": "65780647",
"_type": "_doc",
"_id": "1",
"_score": 0.6931471,
"_source": {
"isbn": "111-3333-444444"
}
}
]
``` | Elasticsearch does not analyze fields of type `keyword`. You need to set the type to `text`. |
70,175,807 | I'm working on a new application using vaadin-spring-boot-starter 21.0.7 and trying to render training database information in a Grid. I'd like to have the first column in the list be a checkbox for Active/Inactive, but I can't figure out how to get that done. Everything I've seen has been for Vaadin 7 or 8.
Mostly current code is in MainView.java at <https://github.com/gregoryleblanc/ealOperators/tree/vaadin> | 2021/11/30 | [
"https://Stackoverflow.com/questions/70175807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17489131/"
] | You can do it like this for Vaadin 14 and newer. I have no experience with older versions of Vaadin.
```
grid.addComponentColumn(myBean -> {
Checkbox checkbox = new Checkbox();
checkbox.setValue(true); // this you must handle
checkbox.addClickListener(e -> {
// todo
}
return checkbox;
});
```
The lambda may be replaced with a method reference
`grid.addComponentColumn(this::createCheckboxComponent);`
```
private Component createCheckboxComponent(MyBean myBean) {
Checkbox checkbox = new Checkbox();
// code here
return checkbox;
}
``` | I'm using some super old version of vaadin, but I guess the same solution should work in the latest one as well, here's how I usually do it:
* column of type `String`
* column has added `ButtonRenderer` (`column.setRenderer`) renderer with event listener, that allows me to handle user's click action
* value would be a String with FontAwesome font (added custom CSS style `font-family` and configured it at grid with `setCellStyleGenerator`)
* when checked use value `String.valueOf((char) FontAwesome.CHECK_SQUARE_O.getCodepoint())`
* when unchecked use value `String.valueOf((char) FontAwesome.SQUARE_O.getCodepoint())`
There could be easier ways to do it with newer version of vaadin. However, this method should still work. |
1,464 | The problem I solved is a flow-shop scheduling problem with parallel machines.
I solved it with the IBM ILOG CPLEX Optimization framework.
There I used the constraint programming (CP).
The question is now to what kind of field of operations research CP belongs, in particular the described flow-shop problem.
With the definition of some books and websites I thought that it would be part of linear optimization, in particular integer linear optimization.
But I'm not sure because I don't know if my problem can be formulated in a mathematical way, needed for linear optimization.
So can someone help me classify this? | 2019/09/06 | [
"https://or.stackexchange.com/questions/1464",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/1278/"
] | In general, I think Constraint Programming or Constraint Satisfaction Problems have their roots in Computer Science/Artificial Intelligence communities that may or may not overlap to some extent with the Operations Research communities. According to "[Artificial Intelligence, A Modern Approach](http://aima.cs.berkeley.edu/)" by Stuart Russel and Peter Norvig, an early example within computer of a specific constraint satisfaction problem was [Sketchpad](https://en.wikipedia.org/wiki/Sketchpad). That book furthermore notes that the idea that CSP's can be generalized came from a [1974 paper by Ugo Montanari](https://www.sciencedirect.com/science/article/pii/0020025574900085v) in the journal Information Sciences.
Linear programming was developed earlier, mostly by mathematicians, as pure Computer Scientists did not even exist back then. [Wikipedia mentions contributions](https://en.wikipedia.org/wiki/George_Dantzig#Linear_programming) from Kantovorich in 1939, and from Dantzig and Von Neumann in 1947.
Both approaches are quite different. Linear programming basically solves systems of linear equations. With this approach, it is typically difficult to obtain integral solutions, since in general we only know how to solve continuous problems efficiently.
However, it is usually quite efficient to find optimal solutions for such continuous problems, and if we are lucky, those solutions are (close to some) integral solutions.
In Constraint Programming, you can imagine your variables to be nodes in a network with a discrete set of possible values, and the constraints as links between two or more variables/nodes. It performs a "clever" brute force technique: you can pick a constraint, and see if the sets of possible values in the variables affected by the constraint are compatible. For example, if for a variable $x$ we have $\{1,2,3\}$ as possible options, and for variable $y$ we have $\{2,3,4\}$ as possible options, the constraint $x+y\leq 4$ can be used to determine that $y$ can never become $4$, so it can be safely removed from $y$'s set of possible values. It performs guessing (what happens if I assume $x$ should be $2$?), backtracking and repeatedly using constraints to update the possible values of each variable (this is called constraint propagation). It aims to search for a **feasible** solution that satisfies all constraints, not necessarily an optimal one. If it turns out one of the sets of potential values for a variable becomes empty, it is clear you need to backtrack. The advantage of this approach is that you do not need all your constraints to be linear. In fact, as long as a constraint can be efficiently used to prune possible values from the variables it affects, it can get as crazy as you want, and this is why Constraint Programming typically offers greater modeling flexibility compared to linear programming. The downside is, however, that it is very hard to deal with continuous variables in a basic setup.
Note that the IBM ILOG CP Solver has many advanced features that seem to combine ideas from Constraint Programming and Linear Optimization, as it does allow optimization and, I believe, continuous variables. | From a [comment](https://or.stackexchange.com/questions/1464/to-which-area-does-constraint-programming-belong#comment2362_1464):
>
> ... the main question is "how to classify CP within the hierarchy of OR and optimization".
>
>
>
There's a useful graphic on IBM's webpage: "IT Best Kept Secret Is Optimization - [Constraint Programming History](https://www.ibm.com/developerworks/community/blogs/jfp/entry/constraint_programming_history?lang=en)" (Jan 21 2014), by Jean Francois Puget:
>
> Paul Shaw and I were invited by John Poppelaars to give talks at the Back to School seminar of Dutch ORMS society. Part of our presentation was a brief history of constraint programming. We drafted this slide to summarize it:
>
>
> [](https://i.stack.imgur.com/w17wq.png)
>
>
> ... Its abstract is reproduced below, and the slides are available [here](https://www.ibm.com/developerworks/community/wikis/form/api/wiki/de368162-e90b-432c-a4e9-795cc51440dd/page/3603e312-bd20-4280-8011-60bbc26f8280/attachment/1fcb5c85-3641-4dc7-af92-0c9dfbc80c77/media/DutchORCPBackground.pdf) (requires IBMid) [alternative source "[Constraint Programming Background and History - LNMB](http://www.lnmb.nl/conferences/2014/programlnmbconference/Shaw-1.pdf)" (.PDF) 35 pages].
>
>
> **Background and Theory of Constraint Programming**
>
> Jean-François Puget and Paul Shaw
>
>
> This talk will review the principles and the historical roots of constraint programming (CP). Indeed, understanding the history behind this field helps understand the basic principles it is built on. CP can be traced back to a combination of Artificial Intelligence, Combinatorics (graph algorithms), and programming language design. It took two decades to unify these in a comprehensive and versatile framework shared by all modern CP tools and solvers. We'll review this framework and how it is implemented in recent tools. Last we will relate it and contrast it with mathematical programming.
>
>
>
The webpage link contains some additional unrelated (to the question) but interesting information. The blog: "[Optimization Engines Make The Industry Efficient](https://optimiser.com/optimization-engines-make-the-industry-efficient/)" (Aug 28 2018), by Diego explains the earliest history of CP:
>
> In 1997 the Parrot project started with ILOG, Carmen Systems, Lufthansa and Olympic Airways.
>
>
> The objective of the PARROT project is to provide efficient means to address the highly complex and costly problem of airline crew scheduling […] developing on promising results in the combination of Operations Research (OR) techniques and Constraint Programming (CP).
>
>
> ...
>
>
> "I like to describe early Constraint Programming toolkits as “systems that help you write backtracking heuristics”
>
>
> * Prolog (Colmerauer, 1972) was a programming language that included an backtracking mechanism in its core
> * Alice (Laurière) 1976 was a “modern” constraint programming engine where you described your problem with equations and it would find the optimal solution for you
> * CHIP (Dincbas 1988) was an early commercial system based on Prolog
> * ILOG Solver (Puget 1994) was the first successful commercial system in C++ but was harder to use than a MIP engine".
>
>
>
Parrot Project: "[Crew Assignment via Constraint Programming: Integrating Column Generation and Heuristic Tree Search](https://www.researchgate.net/publication/220462132_Crew_Assignment_via_Constraint_Programming_Integrating_Column_Generation_and_Heuristic_Tree_Search)", in Annals of Operations Research 115(1):207-225, September 2002:
>
> "We developed two different algorithms to tackle the large scale optimization problem;of Airline Crew Assignment. The first is an application of the Constraint Programming (CP) based Column Generation Framework. The second approach performs a CP based heuristic tree search. We present how both algorithms can be coupled to overcome their inherent weaknesses by integrating methods from
> Constraint Programming and Operations Research.".
>
>
> |
1,464 | The problem I solved is a flow-shop scheduling problem with parallel machines.
I solved it with the IBM ILOG CPLEX Optimization framework.
There I used the constraint programming (CP).
The question is now to what kind of field of operations research CP belongs, in particular the described flow-shop problem.
With the definition of some books and websites I thought that it would be part of linear optimization, in particular integer linear optimization.
But I'm not sure because I don't know if my problem can be formulated in a mathematical way, needed for linear optimization.
So can someone help me classify this? | 2019/09/06 | [
"https://or.stackexchange.com/questions/1464",
"https://or.stackexchange.com",
"https://or.stackexchange.com/users/1278/"
] | In general, I think Constraint Programming or Constraint Satisfaction Problems have their roots in Computer Science/Artificial Intelligence communities that may or may not overlap to some extent with the Operations Research communities. According to "[Artificial Intelligence, A Modern Approach](http://aima.cs.berkeley.edu/)" by Stuart Russel and Peter Norvig, an early example within computer of a specific constraint satisfaction problem was [Sketchpad](https://en.wikipedia.org/wiki/Sketchpad). That book furthermore notes that the idea that CSP's can be generalized came from a [1974 paper by Ugo Montanari](https://www.sciencedirect.com/science/article/pii/0020025574900085v) in the journal Information Sciences.
Linear programming was developed earlier, mostly by mathematicians, as pure Computer Scientists did not even exist back then. [Wikipedia mentions contributions](https://en.wikipedia.org/wiki/George_Dantzig#Linear_programming) from Kantovorich in 1939, and from Dantzig and Von Neumann in 1947.
Both approaches are quite different. Linear programming basically solves systems of linear equations. With this approach, it is typically difficult to obtain integral solutions, since in general we only know how to solve continuous problems efficiently.
However, it is usually quite efficient to find optimal solutions for such continuous problems, and if we are lucky, those solutions are (close to some) integral solutions.
In Constraint Programming, you can imagine your variables to be nodes in a network with a discrete set of possible values, and the constraints as links between two or more variables/nodes. It performs a "clever" brute force technique: you can pick a constraint, and see if the sets of possible values in the variables affected by the constraint are compatible. For example, if for a variable $x$ we have $\{1,2,3\}$ as possible options, and for variable $y$ we have $\{2,3,4\}$ as possible options, the constraint $x+y\leq 4$ can be used to determine that $y$ can never become $4$, so it can be safely removed from $y$'s set of possible values. It performs guessing (what happens if I assume $x$ should be $2$?), backtracking and repeatedly using constraints to update the possible values of each variable (this is called constraint propagation). It aims to search for a **feasible** solution that satisfies all constraints, not necessarily an optimal one. If it turns out one of the sets of potential values for a variable becomes empty, it is clear you need to backtrack. The advantage of this approach is that you do not need all your constraints to be linear. In fact, as long as a constraint can be efficiently used to prune possible values from the variables it affects, it can get as crazy as you want, and this is why Constraint Programming typically offers greater modeling flexibility compared to linear programming. The downside is, however, that it is very hard to deal with continuous variables in a basic setup.
Note that the IBM ILOG CP Solver has many advanced features that seem to combine ideas from Constraint Programming and Linear Optimization, as it does allow optimization and, I believe, continuous variables. | Regarding your question “The question is now to what kind of field of operations research CP belongs”, I will say that CP is not a subfield of operations research, but it is another field, closely related to OR, but it is another field.
If you really like to understand the fundamental of Constraint (Logic) Programming, you should read the paper *[In Pursuit of the Holy Grail](https://dl.acm.org/citation.cfm?doid=242224.242304)* by Eugene C. Freuder, where in the abstract he writes:
>
> Constraint programming represents one of the closest approaches computer science has yet made to the Holy Grail of programming: the user states the problem, the computer solves it.
>
>
>
The main focus of CP is not on a specific single problem or a single class of problems, but it is the design of a very general declarative computer language that would permit to solve any problem that can be stated using that computer language, regardless of the techniques used inside the solver. For instances, the plot reported by @Rob presents several different computer languages for different CP solvers.
This is quite different from a mathematical programming approach, were the focus is on the problem you must (efficiently) solve. A mathematician would study the mathematical properties of the problem of interest, and then, she would try to exploit as much as possible the mathematical structure of the given problem to design an efficient solution algorithm (e.g., Linear Programming relies on the strong duality theorem).
Once say that, indeed, if you look at the programming techniques used internally by CP and/or MP solvers, there is a growing intersection of methods, and several researchers are trying to unify the two worlds. Just to mention two seminal references, you can look at:
1. **Looking at OR from CP**: [Logic-based Methods for Optimization](https://onlinelibrary.wiley.com/doi/book/10.1002/9781118033036), by John Hooker.
2. **Looking at CP from OR**: [Constraint Integer Programming](https://opus4.kobv.de/opus4-zib/frontdoor/index/index/docId/1112), by Tobias Achterberg.
Finally, for looking deeper at the interplay between CP and OR, I would suggest to explore the proceeding of the [CPAIOR Conference Series](https://cpaior.org/), where you can find several papers related to scheduling problems close to yours. |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | Will this do?
```
[^\r]\n
```
Basically it matches a '\n' that is preceded with a character that is not '\r'.
If you want it to detect lines that start with just a single '\n' as well, then try
```
([^\r]|$)\n
```
Which says that it should match a '\n' but only those that is the first character of a line or those that are *not* preceded with '\r'
There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.
**EDIT:** credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:
```
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
``` | I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <http://www.regexbuddy.com/> |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | Will this do?
```
[^\r]\n
```
Basically it matches a '\n' that is preceded with a character that is not '\r'.
If you want it to detect lines that start with just a single '\n' as well, then try
```
([^\r]|$)\n
```
Which says that it should match a '\n' but only those that is the first character of a line or those that are *not* preceded with '\r'
There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.
**EDIT:** credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:
```
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
``` | Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13)) |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | It might be faster if you use this.
```
(?<!\r)\n
```
It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r | I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <http://www.regexbuddy.com/> |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | I was trying to do the code below to a string and it was not working.
```
myStr.Replace("(?<!\r)\n", "\r\n")
```
I used Regex.Replace and it worked
```
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
``` | ```
myStr.Replace("([^\r])\n", "$1\r\n");
```
$ may need to be a \ |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | It might be faster if you use this.
```
(?<!\r)\n
```
It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r | I was trying to do the code below to a string and it was not working.
```
myStr.Replace("(?<!\r)\n", "\r\n")
```
I used Regex.Replace and it worked
```
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
``` |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <http://www.regexbuddy.com/> | If I know the line endings must be one of CRLF or LF, something that works for me is
```
myStr.Replace("\r?\n", "\r\n");
```
This essentially does the same [neslekkiM](https://stackoverflow.com/a/31070/444402)'s answer except it performs only one replace operation on the string rather than two. This is also compatible with Regex engines that don't support negative lookbehinds or backreferences. |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | I was trying to do the code below to a string and it was not working.
```
myStr.Replace("(?<!\r)\n", "\r\n")
```
I used Regex.Replace and it worked
```
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
``` | Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13)) |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | It might be faster if you use this.
```
(?<!\r)\n
```
It basically looks for any \n that is not preceded by a \r. This would most likely be faster, because in the other case, almost every letter matches [^\r], so it would capture that, and then look for the \n after that. In the example I gave, it would only stop when it found a \n, and them look before that to see if it found \r | ```
myStr.Replace("([^\r])\n", "$1\r\n");
```
$ may need to be a \ |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | I was trying to do the code below to a string and it was not working.
```
myStr.Replace("(?<!\r)\n", "\r\n")
```
I used Regex.Replace and it worked
```
Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")
``` | I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <http://www.regexbuddy.com/> |
31,053 | How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
I know to do it using plan `String.Replace`, like:
```
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
```
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist). | 2008/08/27 | [
"https://Stackoverflow.com/questions/31053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | I guess that "myStr" is an object of type String, in that case, this is not regex.
\r and \n are the equivalents for CR and LF.
My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.
The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...
Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D
Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: <http://www.regexbuddy.com/> | ```
myStr.Replace("([^\r])\n", "$1\r\n");
```
$ may need to be a \ |
47,370,466 | Just starting with SQL and the first all-nighter is already here.
I have three tables:
```
student (student_id, first_name, last_name)
course (course_id, name)
exam (ref_to_student_id, ref_to_course_id, score)
```
How do I make a select statement and list out student name, last name and course name, for all cases where achieved exam score was > X ?
This is my best shot:
```
SELECT last_name FROM student WHERE student_id IN
(SELECT ref_to_student_id FROM exam WHERE score > 50)
UNION ALL
SELECT name FROM course WHERE course_id IN
(SELECT ref_to_course_id FROM exam WHERE score > 50)
```
It's faulty, because I get:
```
last_name
last_name
name
name
name
```
and there's no way of telling exactly which student scored above X on which exam/course.
In my mind, something like this:
```
SELECT first_name, last_name, name
FROM student, course
WHERE student_id, course_id
IN (SELECT ref_to_student_id, ref_to_course_id FROM exam WHERE score > 50)
```
would produce something like this:
```
John Doe Chemistry
Jane Dove English
...
```
But, it only produces a notification about an error in the syntax. | 2017/11/18 | [
"https://Stackoverflow.com/questions/47370466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8046711/"
] | You need to join these tables, not `union` them:
```
SELECT last_name, first_name, name, score
FROM student s
JOIN exam e ON s.student_id = e.ref_to_student_id
JOIN course c ON e.red_to_course_id = c.course_id
WHERE score > 50
``` | Friend, try this:
```
SELECT s.first_name, s.last_name, c.name
FROM exam e
JOIN student s ON s.student_id = e.ref_to_student_id
JOIN course c ON c.course_id = e.ref_to_course_id
WHERE e.score > 50
```
I hope to help you! |
47,370,466 | Just starting with SQL and the first all-nighter is already here.
I have three tables:
```
student (student_id, first_name, last_name)
course (course_id, name)
exam (ref_to_student_id, ref_to_course_id, score)
```
How do I make a select statement and list out student name, last name and course name, for all cases where achieved exam score was > X ?
This is my best shot:
```
SELECT last_name FROM student WHERE student_id IN
(SELECT ref_to_student_id FROM exam WHERE score > 50)
UNION ALL
SELECT name FROM course WHERE course_id IN
(SELECT ref_to_course_id FROM exam WHERE score > 50)
```
It's faulty, because I get:
```
last_name
last_name
name
name
name
```
and there's no way of telling exactly which student scored above X on which exam/course.
In my mind, something like this:
```
SELECT first_name, last_name, name
FROM student, course
WHERE student_id, course_id
IN (SELECT ref_to_student_id, ref_to_course_id FROM exam WHERE score > 50)
```
would produce something like this:
```
John Doe Chemistry
Jane Dove English
...
```
But, it only produces a notification about an error in the syntax. | 2017/11/18 | [
"https://Stackoverflow.com/questions/47370466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8046711/"
] | You can use inner join between tables like this:
```
SELECT s.first_name AS first_name, s.last_name AS last_name, c.name AS course_name
FROM student s
INNER JOIN exam e ON e.ref_to_student_id = s.student_id
INNER JOIN course ON c.course_id = e.ref_to_course_id
WHERE e.score > 50;
``` | Friend, try this:
```
SELECT s.first_name, s.last_name, c.name
FROM exam e
JOIN student s ON s.student_id = e.ref_to_student_id
JOIN course c ON c.course_id = e.ref_to_course_id
WHERE e.score > 50
```
I hope to help you! |
29,869,602 | Im getting this error: An object reference is required for the non-static field, method or property 'Android.App.FragmentManager.BeginTransaction()' in the line : FragmentTransaction transaction = FragmentManager.BeginTransaction();
```
void mEditar_Click (object sender, EventArgs e )
{
FragmentTransaction transaction = FragmentManager.BeginTransaction();
dialog_Editar_produto dialog_editar = new dialog_Editar_produto ();
dialog_editar.Show (transaction, "dialog fragment");
dialog_editar.mOnEditarComplete += dialog_editar_mOnEditarComplete;
}
```
What can I do? | 2015/04/25 | [
"https://Stackoverflow.com/questions/29869602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4738999/"
] | Better put that template inside angular `$templateCache` in run phase of angular & remove that template from directive
**Run Block**
```
app.run(function($templateCache) {
$templateCache.put('auratree2', '<item-placeholder></item-placeholder>' +
' <div ng-if="item.children">' +
' <div ng-repeat="item in item.children" ng-include="' +
"'" + 'auratree2' + "'" + '">' +
' <item-placeholder></item-placeholder></div>' +
' </div>'
);
});
```
**Directive** (template function)
```
template: function(element){
element.data("customListTemplate", element.find("item-template"));
var c= '<div ng-repeat="item in input" ng-include = "' + "'" +'auratree2' + "'"+ '"></div>';
return c;
},
``` | Your plunkr had JQuery, but your StackOverflow question doesn't, so I'll assume you are using JQuery (you might have to because of JQLite's limitations).
In your HTML file, modify the order of JQuery and Angular so that the former is listed first.
```
<head>
<meta charset="utf-8" />
<title>Aura Tree</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
``` |
29,869,602 | Im getting this error: An object reference is required for the non-static field, method or property 'Android.App.FragmentManager.BeginTransaction()' in the line : FragmentTransaction transaction = FragmentManager.BeginTransaction();
```
void mEditar_Click (object sender, EventArgs e )
{
FragmentTransaction transaction = FragmentManager.BeginTransaction();
dialog_Editar_produto dialog_editar = new dialog_Editar_produto ();
dialog_editar.Show (transaction, "dialog fragment");
dialog_editar.mOnEditarComplete += dialog_editar_mOnEditarComplete;
}
```
What can I do? | 2015/04/25 | [
"https://Stackoverflow.com/questions/29869602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4738999/"
] | I don't think your approach with `ng-template` works as you expect it. Even if you manage to replace the placeholder in the `ng-template`, if you had multiple `<auratree>` elements in the app, each with a different item template, then all would have the same (last compiled) template.
Using `ng-include` is a clever trick, but this problem is somewhat more complicated. Instead of relying on an `ng-include`d template, include the same directive at each level at `link`-time (which is what `ng-include` would do anyway), and make use of `transclude` for the `item-template`.
Because of some asymmetry between a root element (which only has an array of items), and each sub-tree (which has the values and `children`) I added another directive to represent each tree item:
The root directive only repeats each item and transcludes the `item-template`:
```
app.directive("tree", function(){
return {
restrict: "E",
scope: {
items: "="
},
transclude: true,
template: '<div ng-repeat="item in items">\
<tree-item item="item"></tree-item>\
</div>',
link: function(scope){
scope.$level = -1;
}
};
});
```
The `treeItem` directive transcludes the `item-template` from the parent, and repeats child items, if any:
```
app.directive("treeItem", function($compile){
return {
scope: {
item: "="
},
link: function(scope, element, attrs, ctrls, transclude){
scope.$index = scope.$parent.$index;
scope.$level = scope.$parent.$level + 1;
transclude(scope, function(clone){
element.append(clone.contents());
var repeater = angular.element('<div ng-repeat="child in item.children">');
var subtree = angular.element('<tree-item item="child">');
element.append(repeater.append(subtree));
$compile(repeater)(scope, null, { parentBoundTranscludeFn: transclude });
});
}
};
});
```
The usage is:
```
<tree items="items">
<item-template>
{{$level}}.{{$index}} | {{item.v}}
</item-template>
</tree>
```
**[Demo](http://plnkr.co/edit/fYDcQawwdWjavESl4Aa6?p=preview)** | Better put that template inside angular `$templateCache` in run phase of angular & remove that template from directive
**Run Block**
```
app.run(function($templateCache) {
$templateCache.put('auratree2', '<item-placeholder></item-placeholder>' +
' <div ng-if="item.children">' +
' <div ng-repeat="item in item.children" ng-include="' +
"'" + 'auratree2' + "'" + '">' +
' <item-placeholder></item-placeholder></div>' +
' </div>'
);
});
```
**Directive** (template function)
```
template: function(element){
element.data("customListTemplate", element.find("item-template"));
var c= '<div ng-repeat="item in input" ng-include = "' + "'" +'auratree2' + "'"+ '"></div>';
return c;
},
``` |
29,869,602 | Im getting this error: An object reference is required for the non-static field, method or property 'Android.App.FragmentManager.BeginTransaction()' in the line : FragmentTransaction transaction = FragmentManager.BeginTransaction();
```
void mEditar_Click (object sender, EventArgs e )
{
FragmentTransaction transaction = FragmentManager.BeginTransaction();
dialog_Editar_produto dialog_editar = new dialog_Editar_produto ();
dialog_editar.Show (transaction, "dialog fragment");
dialog_editar.mOnEditarComplete += dialog_editar_mOnEditarComplete;
}
```
What can I do? | 2015/04/25 | [
"https://Stackoverflow.com/questions/29869602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4738999/"
] | I don't think your approach with `ng-template` works as you expect it. Even if you manage to replace the placeholder in the `ng-template`, if you had multiple `<auratree>` elements in the app, each with a different item template, then all would have the same (last compiled) template.
Using `ng-include` is a clever trick, but this problem is somewhat more complicated. Instead of relying on an `ng-include`d template, include the same directive at each level at `link`-time (which is what `ng-include` would do anyway), and make use of `transclude` for the `item-template`.
Because of some asymmetry between a root element (which only has an array of items), and each sub-tree (which has the values and `children`) I added another directive to represent each tree item:
The root directive only repeats each item and transcludes the `item-template`:
```
app.directive("tree", function(){
return {
restrict: "E",
scope: {
items: "="
},
transclude: true,
template: '<div ng-repeat="item in items">\
<tree-item item="item"></tree-item>\
</div>',
link: function(scope){
scope.$level = -1;
}
};
});
```
The `treeItem` directive transcludes the `item-template` from the parent, and repeats child items, if any:
```
app.directive("treeItem", function($compile){
return {
scope: {
item: "="
},
link: function(scope, element, attrs, ctrls, transclude){
scope.$index = scope.$parent.$index;
scope.$level = scope.$parent.$level + 1;
transclude(scope, function(clone){
element.append(clone.contents());
var repeater = angular.element('<div ng-repeat="child in item.children">');
var subtree = angular.element('<tree-item item="child">');
element.append(repeater.append(subtree));
$compile(repeater)(scope, null, { parentBoundTranscludeFn: transclude });
});
}
};
});
```
The usage is:
```
<tree items="items">
<item-template>
{{$level}}.{{$index}} | {{item.v}}
</item-template>
</tree>
```
**[Demo](http://plnkr.co/edit/fYDcQawwdWjavESl4Aa6?p=preview)** | Your plunkr had JQuery, but your StackOverflow question doesn't, so I'll assume you are using JQuery (you might have to because of JQLite's limitations).
In your HTML file, modify the order of JQuery and Angular so that the former is listed first.
```
<head>
<meta charset="utf-8" />
<title>Aura Tree</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.