qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
45,835,422 | I have the following code:
```
def getContentComponents: Action[AnyContent] = Action.async {
contentComponentDTO.list().map(contentComponentsFuture =>
contentComponentsFuture.foreach(contentComponentFuture =>
contentComponentFuture.typeOf match {
case 5 =>
contentComponentDTO.getContentComponentText(contentComponentFuture.id.get).map(
text => contentComponentFuture.text = text.text
)
}
)
Ok(Json.toJson(contentComponentsFuture))
)
```
and get this error message while assigning a value:
[](https://i.stack.imgur.com/FzB9O.png)
Is there a way to solve this issue?
I thought about creating a copy but that would mean that I have do lots of other stuff later. It would be much easier for me if I could reassign the value.
thanks | 2017/08/23 | [
"https://Stackoverflow.com/questions/45835422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4367019/"
] | You could try using the SIM Card in a normal 3G USB Dongle and an application called "[Gammu](https://wammu.eu/docs/manual/gammu/)" which can answer a call and sendDTMF codes i.e. number presses. I have only used Gammu on linux systems but I believe it works on Windows as well. | Another possible solution:
1. Setup voicemail for that SIM card, and when you are asked to leave your voicemail message (the message which is played to whoever gets to the voicemail) just press the button #3.
2. When you want, use call forwarding to redirect all calls to the voicemail. Alternatively, turn off the phone (on most cellular networks this will redirect all calls to the voicemail). |
69,981,157 | I have a text in flexbox item `.learn--text` which needs to be vertically centered, but `word-break: break-word` rule doesn't work.
This is the current state
[](https://i.stack.imgur.com/tgQ3I.png)
and desired state
[](https://i.stack.imgur.com/sMm4I.png)
```css
.learn {
display: flex;
flex: 0 0 50px;
margin-top: auto;
align-items: stretch;
height: 50px;
border: 1px solid black;
width: 250px;
}
.learn--icon {
display: flex;
align-items: center;
justify-content: center;
padding: 0 6px;
}
.learn--text {
display: flex;
flex-wrap: wrap;
align-items: center;
flex: 1;
padding: 0 6px;
white-space: break-spaces;
word-break: break-word;
}
```
```html
<div class="learn"><div class="learn--icon">icon</div><span class="learn--text"><a href="#">Learn more</a> about content management →
</span></div>
``` | 2021/11/15 | [
"https://Stackoverflow.com/questions/69981157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968379/"
] | Erase all the flex settings from `learn--text` - they "divide" its content into two parts, the link and the following text, treating them as flex items and therefore units. If you erase that, the result is as follows:
```css
.learn {
display: flex;
flex: 0 0 50px;
margin-top: auto;
align-items: center;
height: 50px;
border: 1px solid black;
width: 250px;
}
.learn--icon {
display: flex;
align-items: center;
justify-content: center;
padding: 0 6px;
}
.learn--text {
padding: 0 6px;
white-space: break-spaces;
word-break: break-word;
}
```
```html
<div class="learn"><div class="learn--icon">icon</div><span class="learn--text"><a href="#">Learn more</a> about content management →
</span></div>
``` | This, is the answer:
```css
.learn {
display: flex;
flex: 0 0 70px;
margin-top: auto;
align-items: center;
height: 70px;
border: 1px solid black;
width: 250px;
}
.learn--icon {
display: flex;
align-items: center;
justify-content: center;
padding: 0 6px;
}
.learn--text {
display: inline-block;
flex-wrap: wrap;
align-items: center;
flex: 1;
padding: 0 6px;
white-space: break-spaces;
word-break: break-word;
overflow-wrap: break-word;
overflow: hidden;
}
```
```html
<div class="learn"><div class="learn--icon">icon</div><span class="learn--text"><a href="#">Learn more</a> about content management →
</span></div>
``` |
43,241,784 | I'm struggling with achieving following goal: I have the API requests typed in a manner that they return either a desired value, or an error when the status code wasn't indicating success, or when the auth token has been invalid etc: `Either String r`.
Now, I don't want to care about it when I'm `eval`ing my components queries. I am only interested in happy path (expected errors like invalid logon attempt is considered happy path, just want to keep unexpected stuff out of it), and the errors should be handled uniformily and globally (sending some notification to the bus).
For this, I've created transformer stack:
```
type App = ReaderT Env (ExceptT String (Aff AppEffects))
```
Now, to use it with `runUI`, I needed to provide natural transformation to be used with `hoist` (unless I'm missing other possibilities):
```
runApp :: Env -> App ~> Aff AppEffects
runApp env app = do
res <- runExceptT $ runReaderT app env
case res of
Right r -> pure unit
Left err -> do Bus.write err env.bus
-- what to return here?
```
Because we're using `~>` here, we're forced to retain the return type, but for the `Left` case I don't have it at hand!
How would one tackle such requirement? To reiterate - I only want to be able to 'cancel' the evaluation of my component query when the executed action encounters an error, but I want to do it silently and handle it from the top. | 2017/04/05 | [
"https://Stackoverflow.com/questions/43241784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590347/"
] | You have an exceptional case where the current thread can't continue, so the only thing to do would be to throw an exception in `Aff` using `throwError :: forall eff a. Error -> Aff eff a`. | I came to conclusion that what I wanted to achieve was undesirable in fact. Making components query evaluation oblivious to the fact that an error have happened is nothing good (in the light that component might not be interested in handling the error fully, but at least doing something with its state to not end up broken).
Therefore, what I really need is some kind of helper that handle the error, and return a simple indication of the fact the it happened, so that component can proceed with that. |
35,362,301 | I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35362301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851615/"
] | Here's an idea:
```
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
```
To make it neater and more efficient (`index` has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
```
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
``` | This answer is conceptual rather than efficient.
```
st1dict = dict((t.split('-')[1],t) for t in st1) #keys->titles
list2titles = list(st1dict[k] for k in list2) #ordered titles
extras = list(t for t in st1 if t not in list2titles) #extra titles
print(list2titles+extras) #the desired answer
``` |
35,362,301 | I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35362301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851615/"
] | Here's an idea:
```
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
```
To make it neater and more efficient (`index` has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
```
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
``` | One liner.
```
sorted_list = sorted(list1, key=lambda x: list2.index(x.split('-')[1]) if x.split('-')[1] in list2 else len(list2) + 1)
``` |
35,362,301 | I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35362301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851615/"
] | Here's an idea:
```
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
```
To make it neater and more efficient (`index` has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
```
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
``` | Use code below to achieve desired sorting:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Pear']
# note: converting to set would improve performance of further look up
list2 = set(list2)
def convert_key(item):
return int(not item.split('-')[1] in list2)
print sorted(list1, key=convert_key)
# ['Title1-Pear', 'Title1-Bananas', 'Title1-Apples', 'Title1-Oranges']
``` |
35,362,301 | I want to order list1 based on the strings in list2. Any elements in list1 that don't correspond to list2 should be placed at the end of the correctly ordered list1.
For example:
```
list1 = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
list2 = ['Bananas', 'Oranges', 'Pear']
list1_reordered_correctly= ['Title1-Bananas','Title1-Oranges','Title1-Pear','Title1-Apples']
``` | 2016/02/12 | [
"https://Stackoverflow.com/questions/35362301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5851615/"
] | Here's an idea:
```
>>> def keyfun(word, wordorder):
... try:
... return wordorder.index(word)
... except ValueError:
... return len(wordorder)
...
>>> sorted(list1, key=lambda x: keyfun(x.split('-')[1], list2))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
```
To make it neater and more efficient (`index` has to traverse the list to find the right item), consider defining your word-order as a dictionary, i.e.:
```
>>> wordorder = dict(zip(list2, range(len(list2))))
>>> wordorder
{'Pear': 2, 'Bananas': 0, 'Oranges': 1}
>>> sorted(list1, key=lambda x: wordorder.get(x.split('-')[1], len(wordorder)))
['Title1-Bananas', 'Title1-Oranges', 'Title1-Pear', 'Title1-Apples']
``` | something like this would get you going on this.
```
l = ['Title1-Apples', 'Title1-Oranges', 'Title1-Pear', 'Title1-Bananas']
l2 = ['Bananas', 'Oranges', 'Pear']
l3 = []
for elem_sub in l2:
for elem_super in l:
if elem_sub in elem_super:
l3.append(elem_super)
print(l3 + list(set(l)-set(l3)))
``` |
61,421,408 | I want to implement a profile popup like Books app on iOS. Do you know any package or something to make this? Thank a lot.
GIF below shows the behavior that I want to implement:
<https://gph.is/g/EvAxvVw> | 2020/04/25 | [
"https://Stackoverflow.com/questions/61421408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10398593/"
] | Use `in`: This will be simpler
```sh
if a in ('A', 'U'):
#do something
```
Understanding your code.
```sh
if (a == ("A" or "U")):
# do something
```
Python checks for `"A" or "U"` which `"A"` is return because of how truthfulness works. If the first is true, then the `or` is not evaluated. Since only empty string is False, the first none empty string will be selected and there your code is equivalent to:
```sh
if (a == "A"):
# do something
``` | It's not related to python. You can't further simplify the 2nd equation.
a == "A" is one boolean -> x
a == "U" is one boolean -> y
x || y -> simplified version.
Also, you can't apply distributive law to equality Operators(==, <, >).
You can use the membership operator `in` check achieve above.
```
if a in ["A", "U"]:
do_something()
``` |
61,421,408 | I want to implement a profile popup like Books app on iOS. Do you know any package or something to make this? Thank a lot.
GIF below shows the behavior that I want to implement:
<https://gph.is/g/EvAxvVw> | 2020/04/25 | [
"https://Stackoverflow.com/questions/61421408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10398593/"
] | **You can't check both the conditions using `(a == ("A" or "U"))`** because when you execute `"A" or "U"` in python interpreter you will get `"A"` (the first truthy value) similarly when you execute `"A" and "U"` you will get `"U"` (the last truthy value).
If you want simplified expression, you can use,
```
if a in ("A", "U"):
# TODO: perform a task
``` | Use `in`: This will be simpler
```sh
if a in ('A', 'U'):
#do something
```
Understanding your code.
```sh
if (a == ("A" or "U")):
# do something
```
Python checks for `"A" or "U"` which `"A"` is return because of how truthfulness works. If the first is true, then the `or` is not evaluated. Since only empty string is False, the first none empty string will be selected and there your code is equivalent to:
```sh
if (a == "A"):
# do something
``` |
61,421,408 | I want to implement a profile popup like Books app on iOS. Do you know any package or something to make this? Thank a lot.
GIF below shows the behavior that I want to implement:
<https://gph.is/g/EvAxvVw> | 2020/04/25 | [
"https://Stackoverflow.com/questions/61421408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10398593/"
] | **You can't check both the conditions using `(a == ("A" or "U"))`** because when you execute `"A" or "U"` in python interpreter you will get `"A"` (the first truthy value) similarly when you execute `"A" and "U"` you will get `"U"` (the last truthy value).
If you want simplified expression, you can use,
```
if a in ("A", "U"):
# TODO: perform a task
``` | It's not related to python. You can't further simplify the 2nd equation.
a == "A" is one boolean -> x
a == "U" is one boolean -> y
x || y -> simplified version.
Also, you can't apply distributive law to equality Operators(==, <, >).
You can use the membership operator `in` check achieve above.
```
if a in ["A", "U"]:
do_something()
``` |
41,887,434 | I have a data file ( users.dat) with entries like:
```
user1
user2
user4
user1
user2
user1
user4
...
user3
user2
```
which command I should ( grep? wc?) use to count how many times each word repeats and output it to user\_total.dat like this:
```
user1 80
user2 35
user3 18
user4 120
```
the issue is that I cannot specify "user1" or "user19287" because there are too many users with random, but repeating numbers.
But there are repeating users in that DAT file.
Thanks for your help!!! | 2017/01/27 | [
"https://Stackoverflow.com/questions/41887434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3741790/"
] | Use the `uniq` command to count the repetitions of a line. It requires the input to be sorted, so use `sort` first.
```
sort users.dat | uniq -c > user_total.dat
``` | ```
sort <users.dat | uniq -c > user_total.dat
```
If you want it further in order of occurance pass it through sort a 2nd time using some form the -n argument (read man page on that).
(on edit: bah... didn't realize how dumb the system rendered that bit of code) |
25,259,336 | I am using this url to download the magento. I registered and login but nothing happening. Every time on download it shows me login popup.
```
http://www.magentocommerce.com/download
```
Please help to let me know if i am doing something wrong. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25259336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1918324/"
] | The problem is apparently a local browser issue as I was able to log in, go to the downloads page, choose and be presented with the download popup.
If the downloads page is not working for you, you can always try the direct assets link with either a web browser or wget. For example, to get Magento 1.9.0.1:
<http://www.magentocommerce.com/downloads/assets/1.9.0.1/magento-1.9.0.1.tar.gz>
And if you know the version and file name, you should be able to work out the file URL for other versions. | I have tried and able to download by using following URL :-
<http://www.magentocommerce.com/download/>
I am using Firefox & Chrome. |
25,259,336 | I am using this url to download the magento. I registered and login but nothing happening. Every time on download it shows me login popup.
```
http://www.magentocommerce.com/download
```
Please help to let me know if i am doing something wrong. | 2014/08/12 | [
"https://Stackoverflow.com/questions/25259336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1918324/"
] | Best way to download Magento (at least v2+) without going via gated email signup is:
<https://github.com/magento/magento2/releases> | I have tried and able to download by using following URL :-
<http://www.magentocommerce.com/download/>
I am using Firefox & Chrome. |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | I *think* you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do `.every` instead of `.some`...
```
const data = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
const filter = { id: 'a', name: 'al' }
function filterByObject(filterObject, data) {
const matched = data.filter(object => {
return Object.entries(filterObject).some(([filterKey, filterValue]) => {
return object[filterKey].includes(filterValue)
})
})
return matched
}
console.log(filterByObject(filter, data))
``` | If I understand your question correctly, [startsWith](https://www.w3schools.com/jsref/jsref_startswith.asp) is the key term you looking for?
```js
const arr = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
];
const searchTerm = { id: 'a', name: 'al' }
const result = arr.filter(x =>
x.id === searchTerm.id ||
x.name.startsWith(searchTerm.name)
);
console.log(result)
``` |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | If I understand your question correctly, [startsWith](https://www.w3schools.com/jsref/jsref_startswith.asp) is the key term you looking for?
```js
const arr = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
];
const searchTerm = { id: 'a', name: 'al' }
const result = arr.filter(x =>
x.id === searchTerm.id ||
x.name.startsWith(searchTerm.name)
);
console.log(result)
``` | For the dynamic object filter. You can you `closure` and `reduce`
```js
const data = [
{id: 'a',name: 'Alan',age: 10},
{id: 'ab',name: 'alanis',age: 15},
{id: 'b',name: 'Alex',age: 13}
]
const queryObj = { id: 'a', name: 'al' }
const queryObj2 = { name: 'al', age: 13 }
const filterWith = obj => e => {
return Object.entries(obj).reduce((acc, [key, val]) => {
if(typeof val === 'string') return acc || e[key].startsWith(val)
else return acc || e[key] === val
}, false)
}
const filter1 = filterWith(queryObj)
const filter2 = filterWith(queryObj2)
console.log(data.filter(filter1))
console.log(data.filter(filter2))
``` |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | I *think* you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do `.every` instead of `.some`...
```
const data = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
const filter = { id: 'a', name: 'al' }
function filterByObject(filterObject, data) {
const matched = data.filter(object => {
return Object.entries(filterObject).some(([filterKey, filterValue]) => {
return object[filterKey].includes(filterValue)
})
})
return matched
}
console.log(filterByObject(filter, data))
``` | You can create a custom method that receives and object with pairs of `(key, regular expression)` and inside the [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) iterater over the [Object.entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) to check for some match.
```js
let input = [
{id: 'a', name: 'Alan', age: 10},
{id: 'ab', name: 'alanis', age: 15},
{id: 'b', name: 'Alex', age: 13}
];
const filterWithSome = (arr, obj) =>
{
return arr.filter(o =>
{
return Object.entries(obj).some(([k, v]) => o[k].match(v));
});
}
console.log(filterWithSome(input, {id: /^a/, name: /^al/}));
```
```css
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
```
If you instead want a match on every `(key, regular expression)` of the object passed as argument, then you can replace [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) by [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every):
```js
let input = [
{id: 'a', name: 'Alan', age: 10},
{id: 'ab', name: 'alanis', age: 15},
{id: 'b', name: 'Alex', age: 13}
];
const filterWithEvery = (arr, obj) =>
{
return arr.filter(o =>
{
return Object.entries(obj).every(([k, v]) => o[k].match(v));
});
}
console.log(filterWithEvery(input, {id: /^ab/, name: /^al/}));
```
```css
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
``` |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | I *think* you're looking for something like this? Would basically be doing a string.includes match on the value of each key in your filter object--if one of the key values matches then it will be included in the result. If you wanted the entire filter object to match you could do `.every` instead of `.some`...
```
const data = [
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab',
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
const filter = { id: 'a', name: 'al' }
function filterByObject(filterObject, data) {
const matched = data.filter(object => {
return Object.entries(filterObject).some(([filterKey, filterValue]) => {
return object[filterKey].includes(filterValue)
})
})
return matched
}
console.log(filterByObject(filter, data))
``` | For the dynamic object filter. You can you `closure` and `reduce`
```js
const data = [
{id: 'a',name: 'Alan',age: 10},
{id: 'ab',name: 'alanis',age: 15},
{id: 'b',name: 'Alex',age: 13}
]
const queryObj = { id: 'a', name: 'al' }
const queryObj2 = { name: 'al', age: 13 }
const filterWith = obj => e => {
return Object.entries(obj).reduce((acc, [key, val]) => {
if(typeof val === 'string') return acc || e[key].startsWith(val)
else return acc || e[key] === val
}, false)
}
const filter1 = filterWith(queryObj)
const filter2 = filterWith(queryObj2)
console.log(data.filter(filter1))
console.log(data.filter(filter2))
``` |
55,485,823 | I have an array of objects like so:
```js
[
{
id: 'a',
name: 'Alan',
age: 10
},
{
id: 'ab'
name: 'alanis',
age: 15
},
{
id: 'b',
name: 'Alex',
age: 13
}
]
```
I need to pass an object like this `{ id: 'a', name: 'al' }` so that it does a wildcard filter and returns an array with the first two objects.
So, the steps are:
1. For each object in the array, filter the relevant keys from the given filter object
2. For each key, check if the value starts with matching filter object key's value
At the moment I'm using lodash's filter function so that it does an exact match, but not a start with/wildcard type of match. This is what I'm doing:
`filter(arrayOfObjects, filterObject)` | 2019/04/03 | [
"https://Stackoverflow.com/questions/55485823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183384/"
] | You can create a custom method that receives and object with pairs of `(key, regular expression)` and inside the [Array.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) iterater over the [Object.entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) to check for some match.
```js
let input = [
{id: 'a', name: 'Alan', age: 10},
{id: 'ab', name: 'alanis', age: 15},
{id: 'b', name: 'Alex', age: 13}
];
const filterWithSome = (arr, obj) =>
{
return arr.filter(o =>
{
return Object.entries(obj).some(([k, v]) => o[k].match(v));
});
}
console.log(filterWithSome(input, {id: /^a/, name: /^al/}));
```
```css
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
```
If you instead want a match on every `(key, regular expression)` of the object passed as argument, then you can replace [Array.some()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) by [Array.every()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every):
```js
let input = [
{id: 'a', name: 'Alan', age: 10},
{id: 'ab', name: 'alanis', age: 15},
{id: 'b', name: 'Alex', age: 13}
];
const filterWithEvery = (arr, obj) =>
{
return arr.filter(o =>
{
return Object.entries(obj).every(([k, v]) => o[k].match(v));
});
}
console.log(filterWithEvery(input, {id: /^ab/, name: /^al/}));
```
```css
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
``` | For the dynamic object filter. You can you `closure` and `reduce`
```js
const data = [
{id: 'a',name: 'Alan',age: 10},
{id: 'ab',name: 'alanis',age: 15},
{id: 'b',name: 'Alex',age: 13}
]
const queryObj = { id: 'a', name: 'al' }
const queryObj2 = { name: 'al', age: 13 }
const filterWith = obj => e => {
return Object.entries(obj).reduce((acc, [key, val]) => {
if(typeof val === 'string') return acc || e[key].startsWith(val)
else return acc || e[key] === val
}, false)
}
const filter1 = filterWith(queryObj)
const filter2 = filterWith(queryObj2)
console.log(data.filter(filter1))
console.log(data.filter(filter2))
``` |
3,997,905 | I have a webpage having four Checkboxes as follows:
```
<p>Buy Samsung 2230<label>
<input type="checkbox" name="checkbox1" id="checkbox1" />
</label></p>
<div id="checkbox1_compare" style="display: none;"><a href="#">Compair</a></div>
<p>Buy Nokia N 95<label>
<input type="checkbox" name="checkbox2" id="checkbox2" /></label></p>
<div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy Motorola M 100<label>
<input type="checkbox" name="checkbox3" id="checkbox3" /></label></p>
<div id="checkbox3_compare" style="display: none;"><a href="#">Compair</a></div>
<div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy LG 2000<label>
<input type="checkbox" name="checkbox4" id="checkbox4" /></label></p>
<div id="checkbox4_compare" style="display: none;"><a href="#">Compair</a></div>
```
If I check two or more Checkbox then after every last checked check box I need a div which initially should be in hidden state to be displayed as a link that is **Compare**.
Below is my code:
However, It should be displayed under the last checked checkbox, if only two or more checkboxarees checked and that is the ***compare*** link.
You can also get a clear understanding if you check my code:
```
$(document).ready(function() {
$('input[type=checkbox]').change(function() {
if ($('input:checked').size() > 1) {
$('#checkbox1_compare').show();
}
else {
$('#checkbox1_compare').hide();
}
})
});
``` | 2010/10/22 | [
"https://Stackoverflow.com/questions/3997905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484156/"
] | This might be what you want:
```
$(function() {
$('input:checkbox').change(function() {
var $ck = $('input:checkbox:checked');
$('input:checkbox').each(function() {
$('#' + this.id + '_compare').hide();
});
if ($ck.length > 1) {
$ck.each(function() {
$('#' + this.id + '_compare').show();
});
}
});
});
```
That always starts by hiding all the "compare" `<div>` elements, then shows the ones corresponding to the checked checkboxes when 2 or more are checked. | You should try a more general model, for instance have the checkboxes contain a certain class, then use `jQuery.each()` to loop through them, calculate the values, and render their children divs accordingly inside the loop: `jQuery(this).children('.hidden-div').show()`
More info: [jQuery.each()](http://api.jquery.com/jQuery.each/), [.children()](http://api.jquery.com/children/) |
38,193,503 | I think I'm being dense here because I keep getting a `stack too deep` error...
I have a `Child` and a `Parent` relational objects. I want 2 things to happen:
* if you try to update the `Child`, you cannot update its `status_id` to `1` unless it has a `Parent` association
* if you create a `Parent` and then attach it to the `Child`, then the `Child`'s status should be auto-set to `1`.
Here's how the `Parent` association gets added:
```
parent = Parent.new
if parent.save
child.update_attributes(parent_id:1)
end
```
I have these callbacks on the `Child` model:
```
validate :mark_complete
after_update :set_complete
# this callback is here because there is a way to update the Child model attributes
def mark_complete
if self.status_id == 1 && self.parent.blank?
errors[:base] << ""
end
end
def set_complete
if self.logistic.present?
self.update_attribute(:status_id, 1)
end
end
```
The code above is actually not that efficient because it's 2 db hits when ideally it would be 1, done all at once. But I find it too brain draining to figure out why... I'm not sure why it's not even working, and therefore can't even begin to think about making this a singular db transaction.
**EXAMPLE**
Hopefully this helps clarify. Imagine a `Charge` model and an `Item` model. Each `Item` has a `Charge`. The `Item` also has an attribute `paid`. Two things:
* If you update the `Item`, you cannot update the `paid` to `true` until the `Item` has been associated with a `Charge` object
* If you link a `Charge` object to a `Item` by updating the `charge_id` attribute on the `Item`, then code should save you time and auto set the `paid` as `true` | 2016/07/04 | [
"https://Stackoverflow.com/questions/38193503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2731253/"
] | There's a lot that I find confusing here, but it seems to me that you call `:set_complete` after\_update and within `set_complete` you are updating attributes, thus you seem to have a perpetual loop there. There might be other loops that I can't see but that one stands out to me. | One way to avoid a circularly recursive situation like this is to provide a *flag* as a parameter (or otherwise) that will stop the loop from continuing.
In this case, (though I am not sure about the case entirely) I think you could provide a flag indicating the origin of the call. If the origin of the update is a charge being attached, then pass a flag that will stop the check from happening or modify it to keep the loop from happening. Perhaps a secondary set of logic is in order for such a case? |
38,193,503 | I think I'm being dense here because I keep getting a `stack too deep` error...
I have a `Child` and a `Parent` relational objects. I want 2 things to happen:
* if you try to update the `Child`, you cannot update its `status_id` to `1` unless it has a `Parent` association
* if you create a `Parent` and then attach it to the `Child`, then the `Child`'s status should be auto-set to `1`.
Here's how the `Parent` association gets added:
```
parent = Parent.new
if parent.save
child.update_attributes(parent_id:1)
end
```
I have these callbacks on the `Child` model:
```
validate :mark_complete
after_update :set_complete
# this callback is here because there is a way to update the Child model attributes
def mark_complete
if self.status_id == 1 && self.parent.blank?
errors[:base] << ""
end
end
def set_complete
if self.logistic.present?
self.update_attribute(:status_id, 1)
end
end
```
The code above is actually not that efficient because it's 2 db hits when ideally it would be 1, done all at once. But I find it too brain draining to figure out why... I'm not sure why it's not even working, and therefore can't even begin to think about making this a singular db transaction.
**EXAMPLE**
Hopefully this helps clarify. Imagine a `Charge` model and an `Item` model. Each `Item` has a `Charge`. The `Item` also has an attribute `paid`. Two things:
* If you update the `Item`, you cannot update the `paid` to `true` until the `Item` has been associated with a `Charge` object
* If you link a `Charge` object to a `Item` by updating the `charge_id` attribute on the `Item`, then code should save you time and auto set the `paid` as `true` | 2016/07/04 | [
"https://Stackoverflow.com/questions/38193503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2731253/"
] | There's a lot that I find confusing here, but it seems to me that you call `:set_complete` after\_update and within `set_complete` you are updating attributes, thus you seem to have a perpetual loop there. There might be other loops that I can't see but that one stands out to me. | I faced a `stack level too deep` problem some time back when working with ActiveRecord callbacks.
In my case the problem was with `update_attribute` after the update goes through the callback i.e. `set_complete` in your case is called again in which the `update_attribute` is triggered again in turn and this repeats endlessly.
I got around that by using `update_column` instead which does not trigger any callbacks or validations however setting a flag is what was advised more often online.
At this point I do not have an answer for reducing your database write operations, and will add to this answer if I can think of anything.
Hope this helps |
207,586 | I would like to have the words 'to mean' and the following mathematical statement to be on the same straight line. Thank you very much!
```
\documentclass[11pt,a4paper]{article}
\usepackage{blindtext}
\usepackage{mathtools}
\DeclareMathOperator{\sgn}{sgn}
\begin{document}
\begin{flalign*}
3=+1+1+1
\end{flalign*}
to mean
\begin{flalign*}
(+1+1+1)=+1+1+1,
\end{flalign*}
\end{document}
``` | 2014/10/17 | [
"https://tex.stackexchange.com/questions/207586",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/61127/"
] | Try this.
```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{flalign*}
&3=+1+1+1 & \\
\intertext{to mean}
&(+1+1+1)=+1+1+1,&
\end{flalign*}
\end{document}
```
 | your code should be
```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
3 &=+1+1+1 \\
\intertext{to mean}\\
(+1+1+1) &=+1+1+1,
\end{align*}
\end{document}
```
 |
207,586 | I would like to have the words 'to mean' and the following mathematical statement to be on the same straight line. Thank you very much!
```
\documentclass[11pt,a4paper]{article}
\usepackage{blindtext}
\usepackage{mathtools}
\DeclareMathOperator{\sgn}{sgn}
\begin{document}
\begin{flalign*}
3=+1+1+1
\end{flalign*}
to mean
\begin{flalign*}
(+1+1+1)=+1+1+1,
\end{flalign*}
\end{document}
``` | 2014/10/17 | [
"https://tex.stackexchange.com/questions/207586",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/61127/"
] | Try this.
```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{flalign*}
&3=+1+1+1 & \\
\intertext{to mean}
&(+1+1+1)=+1+1+1,&
\end{flalign*}
\end{document}
```
 | ```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
3 =+1+1+1 & \qquad \quad to~{} mean & (+1+1+1) =+1+1+1,
\end{align*}
\end{document}
```
 |
207,586 | I would like to have the words 'to mean' and the following mathematical statement to be on the same straight line. Thank you very much!
```
\documentclass[11pt,a4paper]{article}
\usepackage{blindtext}
\usepackage{mathtools}
\DeclareMathOperator{\sgn}{sgn}
\begin{document}
\begin{flalign*}
3=+1+1+1
\end{flalign*}
to mean
\begin{flalign*}
(+1+1+1)=+1+1+1,
\end{flalign*}
\end{document}
``` | 2014/10/17 | [
"https://tex.stackexchange.com/questions/207586",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/61127/"
] | your code should be
```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
3 &=+1+1+1 \\
\intertext{to mean}\\
(+1+1+1) &=+1+1+1,
\end{align*}
\end{document}
```
 | ```
\documentclass[11pt,a4paper]{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
3 =+1+1+1 & \qquad \quad to~{} mean & (+1+1+1) =+1+1+1,
\end{align*}
\end{document}
```
 |
12,419,812 | Is there any way to find the version of Jquery using normal plain javascript.
I know to do this using JQuery itself by using the following code.
```
jQuery.fn.jquery;
```
or
```
$().jquery;
```
But this wont works for me beacuse I am not allowed to use Jquery code. Please suggest any alternative methods using only plain javascript.
Thanks in advance. | 2012/09/14 | [
"https://Stackoverflow.com/questions/12419812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648144/"
] | ```
jQuery.fn.jquery
```
is a plain JavaScript property. This has nothing to do with 'using jQuery', so that's a proper 'JavaScript' way of getting jQuery's version.
*Edit:* If you just need to check, if a version of jQuery already exists, you can simply test for `window.jQuery`:
```
if ("jQuery" in window) {
// get its version:
var jquery_version = window.jQuery.fn.jquery;
}
```
(If you haven't seen that before: `window.jQuery` is basically the same as a global variable with the name `jQuery` in most cases.) | What do you mean by 'jquery code' - it's all just JavaScript.
This is how you reference the JavaScript function named '$':
```
$
```
This is how you call that function:
```
$()
```
This is how you access the `jquery` property of the return value of that function:
```
$().jquery
```
Which gives you what you need! |
12,419,812 | Is there any way to find the version of Jquery using normal plain javascript.
I know to do this using JQuery itself by using the following code.
```
jQuery.fn.jquery;
```
or
```
$().jquery;
```
But this wont works for me beacuse I am not allowed to use Jquery code. Please suggest any alternative methods using only plain javascript.
Thanks in advance. | 2012/09/14 | [
"https://Stackoverflow.com/questions/12419812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648144/"
] | ```
jQuery.fn.jquery
```
is a plain JavaScript property. This has nothing to do with 'using jQuery', so that's a proper 'JavaScript' way of getting jQuery's version.
*Edit:* If you just need to check, if a version of jQuery already exists, you can simply test for `window.jQuery`:
```
if ("jQuery" in window) {
// get its version:
var jquery_version = window.jQuery.fn.jquery;
}
```
(If you haven't seen that before: `window.jQuery` is basically the same as a global variable with the name `jQuery` in most cases.) | Do you mean you can't use the word `$` or `jQuery` in your code?
What about:
```
window[String.fromCharCode(36)]()[String.fromCharCode(106,113,117,101,114,121)]
``` |
12,419,812 | Is there any way to find the version of Jquery using normal plain javascript.
I know to do this using JQuery itself by using the following code.
```
jQuery.fn.jquery;
```
or
```
$().jquery;
```
But this wont works for me beacuse I am not allowed to use Jquery code. Please suggest any alternative methods using only plain javascript.
Thanks in advance. | 2012/09/14 | [
"https://Stackoverflow.com/questions/12419812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648144/"
] | Declare a variable and try to get the version using
```
var jVersion;
jVersion = jQuery.fn.jquery;
console.log(jVersion);
```
Use this method if you are using any normal JS code | What do you mean by 'jquery code' - it's all just JavaScript.
This is how you reference the JavaScript function named '$':
```
$
```
This is how you call that function:
```
$()
```
This is how you access the `jquery` property of the return value of that function:
```
$().jquery
```
Which gives you what you need! |
12,419,812 | Is there any way to find the version of Jquery using normal plain javascript.
I know to do this using JQuery itself by using the following code.
```
jQuery.fn.jquery;
```
or
```
$().jquery;
```
But this wont works for me beacuse I am not allowed to use Jquery code. Please suggest any alternative methods using only plain javascript.
Thanks in advance. | 2012/09/14 | [
"https://Stackoverflow.com/questions/12419812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1648144/"
] | Declare a variable and try to get the version using
```
var jVersion;
jVersion = jQuery.fn.jquery;
console.log(jVersion);
```
Use this method if you are using any normal JS code | Do you mean you can't use the word `$` or `jQuery` in your code?
What about:
```
window[String.fromCharCode(36)]()[String.fromCharCode(106,113,117,101,114,121)]
``` |
599,960 | I guess `~/.config` (`XDG_CONFIG_HOME`) is not correct because that way users have to be constantly aware which files are safe to commit to their dotfiles repository. | 2020/07/23 | [
"https://unix.stackexchange.com/questions/599960",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/4393/"
] | You'd rather want:
```
grep -rilZ 'first_string' . | xargs -r0 grep -Hi 'second_string'
```
assuming GNU utilities (which you seem to be having as you're already using the `-r` GNU extension).
That is:
* use `-Z` and `xargs -0` to reliably pass the list of paths (which on Unix-like systems can contain any byte value except 0, while `xargs` without `-0` expects a very specific format).
* use `-r` for `xargs` to avoid running the second `grep` if the first one doesn't find any file (ommiting it here is no big deal, it would just cause the second `grep` to grep its empty stdin).
* options should be placed before non-option arguments.
* we use the `-H` option for the second `grep` to make sure the file name is always printed (even if only one file path ends up being passed to it) so we know where the matches are. For `grep` implementations that don't support `-H`, an alternative is to add `/dev/null` to the list of files for `grep` to look in. Then, `grep` being passed more than one filename will always print the filename. | `find . | perl -ne 'open($fh, $_); $s1=0; $s2=0; while($line = <$fh>) { $s1=1 if($line=~/string 1/); $s2=1 if($line=~/string 2/); } ; print $_ if($s1==1 and $s2 ==1); close $fh;' | sort | uniq`
(It's a bit long to see, but this goes all on 1 line)
**Edit:** Some explanation:
* `find . |` sends a list of all files in the directory you want to search through (`.`) to the next command (`perl`)
* `perl -ne 'COMMANDS'` loops through all the lines it receives on STDIN (so all files) and runs `COMMANDS` on each of them. The name of each file will each time end up in `$_`
* `open($fh, $_); COMMANDS; close $fh;` opens a file, binds it to the filehandle `$fh`, runs `COMMANDS` and closes it again.
* `$s1=0; $s2=0;` these vars are set to 0 again every time the next file starts (if we find a string in the current file it's set to 1)
* `while($line = <$fh>) { COMMANDS } ;` runs `COMMANDS` on every line in the file.
* `$s1=1 if($line=~/string 1/); $s2=1 if($line=~/string 2/);` if `string 1` is found in the current file `$s1` will become 1, same for `$s2`
* `print $_ if($s1==1 and $s2 ==1);` prints the filename if the strings are found.
* `| sort | uniq` sorts the filenames and filters out doubles (this should actually not be necessary) |
6,707,720 | I would like to know how I can change the date in my "selectedDate" with jquery datepick. Here's my HTML where I want the magic to show
```
<h3>Historique des tâches (<span class="selectedDate"><?= date("Y-m-d");?></span>) <span class="chooseDate">Choisir date</span> <span class="taskDate"></span></h3>
```
And the javascript
```
$(".chooseDate").toggle(function() {
$(this).text("Choisir date");
$(".taskDate").datepick({
onSelect: function(date) {
alert($.datepick.formatDate(date))
}
});
},
function() {
$(this).text("Choisir date");
$(".taskDate").datepick('destroy');
});
```
When I select a date it should popup an alert message with the selected date in yyyy-mm-dd format but nothing happens.
Could someone help me?
Thanks
Update (Found it):
```
$(".taskDate").datepick({
onSelect: function(test){
var newDate = new Date(test);
alert(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
}
});
```
I've just reformat the date it gave me to the one I wanted. Event by telling it the show it in yyyy-mm-dd format it was still showing me the full date with day , time zone, etc...
Thanks guys | 2011/07/15 | [
"https://Stackoverflow.com/questions/6707720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845217/"
] | Usually the downgrade in performance is only when creating the connection to the database. That operation is intensive for all provider types.
Someone please correct me if I'm wrong, but as of .NET4 Microsoft has created an Oracle driver which I believe allows LINQ to SQL. I know it was in the works at one point and I know the Oracle driver is for .NET4, so I'm assuming that's the same one.
However, LINQ to Entities is db agnostic so as long as you stick with that you should be ok. | I can't discuss the performance, but do you store the connection string to the database in a configuration file? It seems to me that changing the connection mechanism is the more complicated solution to changing the connection string to find the correct server. |
6,707,720 | I would like to know how I can change the date in my "selectedDate" with jquery datepick. Here's my HTML where I want the magic to show
```
<h3>Historique des tâches (<span class="selectedDate"><?= date("Y-m-d");?></span>) <span class="chooseDate">Choisir date</span> <span class="taskDate"></span></h3>
```
And the javascript
```
$(".chooseDate").toggle(function() {
$(this).text("Choisir date");
$(".taskDate").datepick({
onSelect: function(date) {
alert($.datepick.formatDate(date))
}
});
},
function() {
$(this).text("Choisir date");
$(".taskDate").datepick('destroy');
});
```
When I select a date it should popup an alert message with the selected date in yyyy-mm-dd format but nothing happens.
Could someone help me?
Thanks
Update (Found it):
```
$(".taskDate").datepick({
onSelect: function(test){
var newDate = new Date(test);
alert(newDate.getFullYear()+'-'+(newDate.getMonth()+1)+'-'+newDate.getDate());
}
});
```
I've just reformat the date it gave me to the one I wanted. Event by telling it the show it in yyyy-mm-dd format it was still showing me the full date with day , time zone, etc...
Thanks guys | 2011/07/15 | [
"https://Stackoverflow.com/questions/6707720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845217/"
] | Ok, I figured it out on my own. I did a benchmark of the code using the SQL driver against the same exact code using the ODBC driver.
My results are below.
* ODBC DRIVER: 100% connection success. Average duration 796
Millisecond.
* SQL DRIVER: 100% connection success! Average duration
641 Millisecond.
The ODBC driver performs slightly slower. I still might use because this benchmark was again 20 thousand records so the difference should be very minimal.
Thanks you all for your help!
Paul | I can't discuss the performance, but do you store the connection string to the database in a configuration file? It seems to me that changing the connection mechanism is the more complicated solution to changing the connection string to find the correct server. |
30,694,305 | This code gives me... array? with columns and data, as i understand
console.log
```
{ columns: [ 'n.name' ],
data: [ [ '(' ], [ 'node_name' ], [ ';' ], [ 'CREATE' ], [ ')' ] ] }
```
Code
```
function show() {
var cypher = [
'MATCH (n)-[r:CREATE_NODE_COMMAND]->(s)RETURN n.name'
].join('\n');
db.queryRaw(cypher, {}, function(err, result) {
if (err) throw err;
for (var key in result) {
}
console.log(result);
})}
```
How to get clean data: keys like this (n.name;CREATE) ? | 2015/06/07 | [
"https://Stackoverflow.com/questions/30694305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4967368/"
] | If you want to return a map of `key : value` in the cypher result set you can change the return statement to something like this...
```
return { name : n.name }
``` | result.data.join('') by **jonpacker** <https://github.com/brikteknologier/seraph/issues/166> |
34,490 | I'm new to the Raspberry Pi community and to working with electricity, so I'm looking for some advice.
I've brought the WS2801 LED strip from eBay (but I think it's the same as this: <https://www.sparkfun.com/products/retired/11272>). Using a computer PSU I've connected the LED strip power to my 5V molex rail and data to my Raspberry Pi. Everything seems to work as it should.
Similar to this, but power drawn from my PSU rather then a DC Jack:
[](https://i.stack.imgur.com/T5bRL.png)
After reading a bit more about this setup online, I found out that it might not be wise to connect the power directly to the GPIO. Apart from that I also don't want to use a bulky PSU to power this, but rather a smaller power brick if possible.
What I intend to do is to use a male molex connector and connect it to micro USB header and to the power pins of the same connector used by the power strip. This way I intend to power both the LED strip and my PI using the 5V provided. When it comes to the data connection I'm going to do the same as in the picture and use the GPIO as previously. Is it possible/a good idea to split the power between the LED strip and my RPi this way or is there something I should be aware of?
I think about using a Molex connector in the beginning, just to verify that everything works. Then trying to measure the current needed and replace my Molex and PSU with a DC Jack connector and suited power brick. I have one that says 5V/8A max (5V 8A 8000mA AC-DC Switching Adapter Desktop Power Supply YT-0508 PSU 2.5/2.1), but I'm not sure if that's ridiculous high amount of amps and if it's ok to be trusted...
Any suggestions on this or things I should be careful about would be awesome!
**Edit:**
This is the micro usb connector I intend to use. I plan to just remove the red and black and replace it with my own from the molex power connector. I've that the usb connector has a connector on the side as well (Ground?). Do I have to connect this one to ground (the other black cable that already goes to the connector) as well or just leave it? | 2015/08/16 | [
"https://raspberrypi.stackexchange.com/questions/34490",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/33814/"
] | What you are suggesting sounds fine to me (but I'm not an electronics type so treat anything I say with caution).
As the Pi and LED strip will have a common ground you don't need to connect a Pi ground to the LED strip ground. If you ever use a separate power supply for the Pi and the LED strip you will have to join the grounds. | Powering the Pi and the LED strip the way as shown in the schematics is possible. There is however one issue to consider: back feeding the supply voltage to the Pi via the GPIO pin connector bypasses the polyfuse of the Pi and might render the overvoltage protection (D16) non-operative.
Compare [schematics](https://web.archive.org/web/20160305080241/https://www.raspberrypi.org/documentation/hardware/raspberrypi/schematics/Raspberry-Pi-Rev-2.1-Model-AB-Schematics.pdf), page 1, top left. |
14,286,230 | Is it possible to test two `EXISTS` conditions in a single `IF` SQL statement? I've tried the following.
```
IF EXIST (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 = @parm2)
OR
EXIST (SELECT * FROM tblTwo WHERE field1 = @parm5 AND field2 = @parm3)
```
I've tried playing with adding additional `IF` and parenthesis in there, but to no avail.
Can you help me out with the proper syntax? | 2013/01/11 | [
"https://Stackoverflow.com/questions/14286230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142433/"
] | If SQL Server
```
IF EXISTS (SELECT *
FROM tblOne
WHERE field1 = @parm1
AND field2 = @parm2)
OR EXISTS (SELECT *
FROM tblTwo
WHERE field1 = @parm5
AND field2 = @parm3)
PRINT 'YES'
```
Is fine, note the only thing changed is `EXISTS` not `EXIST`. The plan for this will probably be a `UNION ALL` that short circuits if the first one tested is true. | You missed an S at the end of EXIST
EXIST**S**, not EXIST |
14,286,230 | Is it possible to test two `EXISTS` conditions in a single `IF` SQL statement? I've tried the following.
```
IF EXIST (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 = @parm2)
OR
EXIST (SELECT * FROM tblTwo WHERE field1 = @parm5 AND field2 = @parm3)
```
I've tried playing with adding additional `IF` and parenthesis in there, but to no avail.
Can you help me out with the proper syntax? | 2013/01/11 | [
"https://Stackoverflow.com/questions/14286230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142433/"
] | If SQL Server
```
IF EXISTS (SELECT *
FROM tblOne
WHERE field1 = @parm1
AND field2 = @parm2)
OR EXISTS (SELECT *
FROM tblTwo
WHERE field1 = @parm5
AND field2 = @parm3)
PRINT 'YES'
```
Is fine, note the only thing changed is `EXISTS` not `EXIST`. The plan for this will probably be a `UNION ALL` that short circuits if the first one tested is true. | You could also write an IN statement
```
IF EXISTS (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 IN (@parm2,@parm3)
``` |
14,286,230 | Is it possible to test two `EXISTS` conditions in a single `IF` SQL statement? I've tried the following.
```
IF EXIST (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 = @parm2)
OR
EXIST (SELECT * FROM tblTwo WHERE field1 = @parm5 AND field2 = @parm3)
```
I've tried playing with adding additional `IF` and parenthesis in there, but to no avail.
Can you help me out with the proper syntax? | 2013/01/11 | [
"https://Stackoverflow.com/questions/14286230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142433/"
] | You missed an S at the end of EXIST
EXIST**S**, not EXIST | You could also write an IN statement
```
IF EXISTS (SELECT * FROM tblOne WHERE field1 = @parm1 AND field2 IN (@parm2,@parm3)
``` |
69,792,953 | I have Json Data through which I'm doing this .
```
fun getFact(context: Context) = viewModelScope.launch{
try {
val format = Json {
ignoreUnknownKeys = true
prettyPrint = true
isLenient = true
}
val factJson = context.assets.open("Facts.json").bufferedReader().use {
it.readText()
}
val factList = format.decodeFromString<List<FootballFact>>(factJson)
_uiState.value = ViewState.Success(factList)
} catch (e: Exception) {
_uiState.value = ViewState.Error(exception = e)
}
}
```
This is the way i m getting my job from viewModle in Ui sceeen
```
viewModel.getFact(context)
when (val result =
viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
factsLists.value.shuffled()
}
}
}
```
I have fact card where i want to show that fact .also i have there a lambda for click where i want my factList to refresh every time whenever is clicked.
```
@Composable
fun FactCard(quote: String , onClick : ()-> Unit) {
val fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable { onClick() }
) {
Text(.. )
}
}
```
I don't know how to approach this, i think there is silly thing I'm doing. | 2021/11/01 | [
"https://Stackoverflow.com/questions/69792953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11630186/"
] | Composables can only recompose when you update state data. You aren't doing that. Your click event should return the new quote that you want to display. You then set `fact.value` to the new quote. Calling `fact.value` with a new value is what triggers a recompose:
```
when (val result = viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
return factsLists.value.shuffled()[0]
}
}
}
@Composable
fun FactCard(quote: String , onClick : ()-> String) {
var fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable {
fact.value = onClick()
}
) {
Text(.. )
}
}
``` | `factsLists.shuffled()` returns a new list with the elements of this list randomly shuffled. |
37,310,398 | I want to make the length of one of my divs longer on a button click, however the jquery doesn't seem to be working. Here's the script.
```
<script type="text/javascript">
$(document).ready(function(){
function extendContainer() {
$('#thisisabutton').click(function() {
$('#one').animate({
height: "200px"
},
300);
});
}
})
</script>
```
Here's the html, with the code for the button
```
<div id="div1" id="buttons" >
<ul class="actions">
<li><input id="thisisabutton" type="button" onclick="extendContainer()" onclick="loadXMLDocTraditional()" value="Traditional" class="special"/></li>
</ul>
</div>
```
And here's the css just in case.
```
#one .container {
width: 50em;
height: 22em; /* Height of the #one section*/
}
``` | 2016/05/18 | [
"https://Stackoverflow.com/questions/37310398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6304516/"
] | The solution you came up with yourself for now is the best what you could do.
We discussed whether we should expose any other API for singular backlinks, but as there is no way to enforce their multiplicity on the data storage layer, it didn't made sense so far. In addition, you would still need a wrapper object, so that we can propagate updates. For that reason a unified way to retrieve the value via `LinkedObjects` seemed to be the way so far. | What about specifiying the relation the other way around?
* Specify the connection on the 'one'-side
* Do a query in the getter on the 'many'-side:
So it should read like this:
```
class Child: Object {
dynamic var name:String = ""
dynamic var parent:Parent? = nil
}
class Parent: Object {
dynamic var name:String = ""
var children:Results<Child>? {
return realm?.objects(Child.self).filter(NSPredicate(format: "parent == %@", self))
}
}
``` |
18,561 | In the Pokemon School, you can create a group and other players can join. I created and some friends of mine joined. The NPC says something about syncing events.
What does being in a group do? What kind of things does it sync? | 2011/03/18 | [
"https://gaming.stackexchange.com/questions/18561",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/7902/"
] | >
> Joining a group is a feature introduced in Generation IV. Players in the same group encounter the same swarming Pokémon, weather conditions, changing Pokémon in the Great Marsh, Feebas location, and other things each day. Group members can compare records on the third floor of Jubilife TV.
>
>
>
Source: [Bulbapedia](http://bulbapedia.bulbagarden.net/wiki/Groups) | I always created a group with my friend when we wanted to enter the Doubles Battle Tower together. I assume that "event" in this context refers to any multiplayer event that can be done with a friend in HGSS. They use groups for all of them so that it remains consistent. |
50,898,924 | I have coo\_matrix `X` and indexes `trn_idx` by which I would like to get access of that maxtrix
```
print (type(X ), X.shape)
print (type(trn_idx), trn_idx.shape)
<class 'scipy.sparse.coo.coo_matrix'> (1503424, 2795253)
<class 'numpy.ndarray'> (1202739,)
```
Calling this way:
```
X[trn_idx]
TypeError: only integer scalar arrays can be converted to a scalar index
```
Either this way:
```
X[trn_idx.astype(int)] #same error
```
How to access by index? | 2018/06/17 | [
"https://Stackoverflow.com/questions/50898924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739325/"
] | The `coo_matrix` class does not support indexing. You'll have to convert it to a different sparse format.
Here's an example with a small `coo_matrix`:
```
In [19]: import numpy as np
In [20]: from scipy.sparse import coo_matrix
In [21]: m = coo_matrix([[0, 0, 0, 1], [2, 0, 0 ,0], [0, 0, 0, 0], [0, 3, 4, 0]])
```
Attempting to index `m` fails:
```
In [22]: m[0,0]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-1f78c188393f> in <module>()
----> 1 m[0,0]
TypeError: 'coo_matrix' object is not subscriptable
In [23]: idx = np.array([2, 3])
In [24]: m[idx]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-a52866a6fec6> in <module>()
----> 1 m[idx]
TypeError: only integer scalar arrays can be converted to a scalar index
```
If you convert `m` to a CSR matrix, you can index it with `idx`:
```
In [25]: m.tocsr()[idx]
Out[25]:
<2x4 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>
```
If you are going to do more indexing, it would be better to save the new array in a variable, and use it as needed:
```
In [26]: a = m.tocsr()
In [27]: a[idx]
Out[27]:
<2x4 sparse matrix of type '<class 'numpy.int64'>'
with 2 stored elements in Compressed Sparse Row format>
In [28]: a[0,0]
Out[28]: 0
``` | Try reading this.
>
> <https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.sparse.csr_matrix.todense.html>
>
>
>
You need to convert to a dense matrix before accessing via an index.
Try toarray() method on sparse matrix then you can access then by indexing. |
50,645,382 | I am creating several mobile applications in react-native that share common components. I have difficulties handling the dependencies. Here is what I do, which is tedious, is there a better way?
* A repository "common-modules" has shared components
* Several repositories include the common one as a dependency like this:
### Package.json
```
"dependencies": {
"common-components": "file:../common-components"
},
```
I use it like that in the different apps:
```
import XXX from 'common-components/src/...'
```
Now this is great because all other dependencies are in "common-components", but as soon as one of them has native code, I am forced to link the library again in each app.
For instance, if I use "react-native-image-picker", I have to install it again in each application and link it in XCode, edit build.gradle etc. etc.
* It takes forever
* Are my linked dependencies bundled twice?
* I fear the day when I must change/upgrade one of them...
Is there a better way? | 2018/06/01 | [
"https://Stackoverflow.com/questions/50645382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2197181/"
] | I've heard of projects that share code being managed in a monorepo. That may help managing shared code but won't solve the problem of linking native modules N times for N apps.
However, there is `react-native link` that should automate the process, and ease linking the native modules a lot. Note there is no need to re-link if you just upgrade a native dependency.
Alternatively, I think it should be possible to wrap multiple native modules into one. If you take a look at [MainReactPackage.java](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.java) in RN repo, it wraps several native modules. I imagine similar mechanism can be employed on iOS, with static libraries. Obviously, this means that it won't be easy to selectively include some modules and others not. | Like you said yourself it is easier to work with a duplicated codebase. To deal with that you can create your own package manager for your shared components. Make a script for each component which will add it's dependencies to package.json and configure gradle and XCode. Add a simple GUI to include your components with a single click.
This may seem like a lot of work upfront, but:
- you will keep full control
- once you have a script to install a component you will save time each time you use it on a new app
- in the case of updates you can create a script to handle that as well |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | In short, you wanted to do micro-batching calculations with in storm’s running tuples.
First you need to define/find key in tuple set.
Do field grouping(don't use shuffle grouping) between bolts using that key. This will guarantee related tuples will always send to same task of downstream bolt for same key.
Define class level collection List/Map to maintain old values and add new value in same for calculation, don’t worry they are thread safe between different executors instance of same bolt. | I'm afraid there is no such built-in functionality as of today.
But you can use any kind of distributed cache, like memcached or Redis. Those caching solutions are really easy to use. |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | I'm afraid there is no such built-in functionality as of today.
But you can use any kind of distributed cache, like memcached or Redis. Those caching solutions are really easy to use. | There are a couple of approaches to do that but it depends on your system requirements, your team skills and your infrastructure.
You could use Apache Cassandra for you events storing and you pass the row's key in the tuple so the next bolt could retrieve it.
If your data is time series in nature, then maybe you would like to have a look at [OpenTSDB](http://opentsdb.net/) or [InfluxDB](http://influxdb.com/).
You could of course fall back to something like Software Transaction Memory but I think that would needs good amount of crafting. |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | I'm afraid there is no such built-in functionality as of today.
But you can use any kind of distributed cache, like memcached or Redis. Those caching solutions are really easy to use. | Uou can use CacheBuilder to remember your data within your extended BaseRichBolt (put this in the prepare method):
```
// init your cache.
this.cache = CacheBuilder.newBuilder()
.maximumSize(maximumCacheSize)
.expireAfterWrite(expireAfterWrite, TimeUnit.SECONDS)
.build();
```
Then in execute, you can use the cache to see if you have already seen that key entry or not. from there you can add your business logic:
```
// if we haven't seen it before, we can emit it.
if(this.cache.getIfPresent(key) == null) {
cache.put(key, nearlyEmptyList);
this.collector.emit(input, input.getValues());
}
this.collector.ack(input);
``` |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | I'm afraid there is no such built-in functionality as of today.
But you can use any kind of distributed cache, like memcached or Redis. Those caching solutions are really easy to use. | This question is a good candidate to demonstrate Apache Spark's in memory computation over the micro batches. However, your use case is trivial to implement in Storm.
1. Make sure the bolt uses fields grouping. It will consistently hash the incoming tuple to the same bolt so we do not lose out on any tuple.
2. Maintain a Map<String, Integer> in the bolt's local cache. This map will keep the last known value of a "variable".
```java
class CumulativeDiffBolt extends InstrumentedBolt{
Map<String, Integer> lastKnownVariableValue;
@Override
public void prepare(){
this.lastKnownVariableValue = new HashMap<>();
....
@Override
public void instrumentedNextTuple(Tuple tuple, Collector collector){
.... extract variable from tuple
.... extract current value from tuple
Integer lastValue = lastKnownVariableValue.getOrDefault(variable, 0)
Integer newValue = currValue - lastValue
lastKnownVariableValue.put(variable, newValue)
emit(new Fields(variable, newValue));
...
}
``` |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | In short, you wanted to do micro-batching calculations with in storm’s running tuples.
First you need to define/find key in tuple set.
Do field grouping(don't use shuffle grouping) between bolts using that key. This will guarantee related tuples will always send to same task of downstream bolt for same key.
Define class level collection List/Map to maintain old values and add new value in same for calculation, don’t worry they are thread safe between different executors instance of same bolt. | There are a couple of approaches to do that but it depends on your system requirements, your team skills and your infrastructure.
You could use Apache Cassandra for you events storing and you pass the row's key in the tuple so the next bolt could retrieve it.
If your data is time series in nature, then maybe you would like to have a look at [OpenTSDB](http://opentsdb.net/) or [InfluxDB](http://influxdb.com/).
You could of course fall back to something like Software Transaction Memory but I think that would needs good amount of crafting. |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | In short, you wanted to do micro-batching calculations with in storm’s running tuples.
First you need to define/find key in tuple set.
Do field grouping(don't use shuffle grouping) between bolts using that key. This will guarantee related tuples will always send to same task of downstream bolt for same key.
Define class level collection List/Map to maintain old values and add new value in same for calculation, don’t worry they are thread safe between different executors instance of same bolt. | Uou can use CacheBuilder to remember your data within your extended BaseRichBolt (put this in the prepare method):
```
// init your cache.
this.cache = CacheBuilder.newBuilder()
.maximumSize(maximumCacheSize)
.expireAfterWrite(expireAfterWrite, TimeUnit.SECONDS)
.build();
```
Then in execute, you can use the cache to see if you have already seen that key entry or not. from there you can add your business logic:
```
// if we haven't seen it before, we can emit it.
if(this.cache.getIfPresent(key) == null) {
cache.put(key, nearlyEmptyList);
this.collector.emit(input, input.getValues());
}
this.collector.ack(input);
``` |
28,249,388 | How to store the temporary data in Apache storm?
In storm topology, bolt needs to access the previously processed data.
```
Eg: if the bolt processes varaiable1 with result as 20 at 10:00 AM.
```
and again `varaiable1` is received as `50` at `10:15 AM` then the result should be `30 (50-20)`
later if varaiable1 receives `70` then the result should be `20 (70-50)` at `10:30`.
How to achieve this functionality. | 2015/01/31 | [
"https://Stackoverflow.com/questions/28249388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2431957/"
] | In short, you wanted to do micro-batching calculations with in storm’s running tuples.
First you need to define/find key in tuple set.
Do field grouping(don't use shuffle grouping) between bolts using that key. This will guarantee related tuples will always send to same task of downstream bolt for same key.
Define class level collection List/Map to maintain old values and add new value in same for calculation, don’t worry they are thread safe between different executors instance of same bolt. | This question is a good candidate to demonstrate Apache Spark's in memory computation over the micro batches. However, your use case is trivial to implement in Storm.
1. Make sure the bolt uses fields grouping. It will consistently hash the incoming tuple to the same bolt so we do not lose out on any tuple.
2. Maintain a Map<String, Integer> in the bolt's local cache. This map will keep the last known value of a "variable".
```java
class CumulativeDiffBolt extends InstrumentedBolt{
Map<String, Integer> lastKnownVariableValue;
@Override
public void prepare(){
this.lastKnownVariableValue = new HashMap<>();
....
@Override
public void instrumentedNextTuple(Tuple tuple, Collector collector){
.... extract variable from tuple
.... extract current value from tuple
Integer lastValue = lastKnownVariableValue.getOrDefault(variable, 0)
Integer newValue = currValue - lastValue
lastKnownVariableValue.put(variable, newValue)
emit(new Fields(variable, newValue));
...
}
``` |
67,723,390 | **I'm trying to predict probability of X\_test and getting 2 values in an array. I need to compare those 2 values and make it 1.**
when I write code
```
y_pred = classifier.predict_proba(X_test)
y_pred
```
It gives output like
```
array([[0.5, 0.5],
[0.6, 0.4],
[0.7, 0.3],
...,
[0.5, 0.5],
[0.4, 0.6],
[0.3, 0.7]])
```
**We know that if values if >= 0.5 then it's and 1 and if it's less than 0.5 it's 0**
I converted the above array into pandas using below code
```
proba = pd.DataFrame(proba)
proba.columns = [['pred_0', 'pred_1']]
proba.head()
```
And output is
```
pred_0 pred_1
0 0.5 0.5
1 0.6 0.4
2 0.7 0.3
3 0.4 0.6
4 0.3 0.7
```
How to iterate the above rows and write a condition that if row value of column 1 is greater than equal to 0.5 with row value of 2, then it's 1 and if row value of column 1 is less than 0.5 when compared to row value of column 2.
For example, by seeing the above data frame the output must be
```
output
0 0
1 1
2 1
3 1
4 1
``` | 2021/05/27 | [
"https://Stackoverflow.com/questions/67723390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15224778/"
] | Try
```
"string0;string1;string2".split(';')
```
Further reading:
<https://python-reference.readthedocs.io/en/latest/docs/str/split.html> | This should work:
```
raw_string = 2008-01;12.759358;6.297382
formatted = raw_string.split(';')
``` |
32,602,441 | I have 3 unread messages. For this reason, I have to show `3` at the top of a message like this picture:
[](https://i.stack.imgur.com/iSjcI.png)
How can I do this? PLease help me. | 2015/09/16 | [
"https://Stackoverflow.com/questions/32602441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282443/"
] | I think this repo will help you.
<https://github.com/jgilfelt/android-viewbadger>
[](https://i.stack.imgur.com/ZEyse.png) | If you are using a relative layout to show your icons, than you can put another relative layout(rl2) over message icon with relative margins containing circular imageview and an textView above it, control the visibility of rl2 from activity along with the text of textview,
Suppose,
There is are 3 new messages, set visibility of rl2 visible and set text of the textview to 3, In case there are now new messages, set visibility of rl2 to invisible. |
2,090,753 | I know that a symmetric tensor of symmetric rank $1$ can be viewed as a point on the so-called *Veronese variety*. A symmetric tensor of rank $r$ is then in the linear space spanned by $r$ points of the Veronese variety. My question is the following: can any given symmetric tensor of **rank $1$** ever reside in the linear space spanned by $r$ *other* points of the Veronese *variety*, *i.e.* be written as a linear combination of $r$ *other* symmetric rank-$1$ symmetric tensors?
I am an engineer, currently working on tensor decompositions for signal processing applications. I'm not very familiar with algebraic geometry, but it seems that I need the answer to the question above, to ensure uniqueness of one such decomposition. I looked for (a hint toward) an answer in the literature on Veronese varieties, but it is rather hard to dig into. | 2017/01/09 | [
"https://math.stackexchange.com/questions/2090753",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/405499/"
] | Your question is: Can a given symmetric tensor of rank $1$ be written as a linear combination of other symmetric tensors of rank $1$? The answer is yes. Yes, a symmetric tensor of rank $1$ can be written as a linear combination of other symmetric tensors of rank $1$. This is true over the complex numbers, the real numbers, and other fields. For simplicity I'll write this answer over a field of characteristic zero; everything I say will be valid over real numbers and over complex numbers. (It can also be valid over other fields with mild conditions but I will ignore that for now.)
Before proceeding with generalities, perhaps a concrete example might be helpful? Let $V$ be a two-dimensional vector space with basis $x,y$. (You are welcome to think of this as $V = \mathbb{R}^2$ and $x = (1,0)$, $y=(0,1)$.) One of the symmetric tensors of rank $1$, and order $3$, in $V \otimes V \otimes V$, is $x \otimes x \otimes x$, which for short we might denote $x^3$. Can we write this $x^3$ as a linear combination of other rank $1$ symmetric tensors? Yes, in various ways; here is one.
$$
\begin{split}
(x+y) \otimes (x+y) \otimes (x+y) &= x \otimes x \otimes x + x \otimes x \otimes y \\
&\quad + x \otimes y \otimes x + y \otimes x \otimes x \\
&\quad + x \otimes y \otimes y + y \otimes x \otimes y \\
&\quad + y \otimes y \otimes x + y \otimes y \otimes y \\
&= x^3 + 3x^2y + 3xy^2 + y^3,
\end{split}
$$
where $x^3 = x \otimes x \otimes x$, $x^2y = \frac{1}{3}(x \otimes x \otimes y + x \otimes y \otimes x + y \otimes x \otimes x)$, and in general $xyz = \frac{1}{6}(x \otimes y \otimes z + \text{all permutations})$.
Well,
$$
(x+y)^3 + (x-y)^3 = x^3 + 6xy^2,
$$
and
$$
(x+2y)^3 + (x-2y)^3 = x^3 + 24xy^2 .
$$
So therefore
$$
4(x+y)^3 + 4(x-y)^3 - (x+2y)^3 - (x-2y)^3 = 3x^3.
$$
So the rank $1$ symmetric tensor $x^3$ is in the span of the $4$ rank $1$ symmetric tensors $(x \pm y)^3$ and $(x \pm 2y)^3$.
Now, this example begins to point the way to a more general answer. Because when we consider the space of symmetric tensors in $V \otimes V \otimes V$—it is a subspace that can be denoted $S^3 V$ ($S$ for Symmetric), or $S\_3 V$, depending on the author—we see that it has dimension $4$. A basis is given by $x^3, x^2y, xy^2, y^3$. And another different basis is given by $(x\pm y)^3$, $(x \pm 2y)^3$. At that point it becomes clear that *every* symmetric tensor is a linear combination of those $4$ symmetric rank $1$ tensors, *including* all the symmetric rank $1$ tensors such as $x^3$.
So we have the first answer to your question: Let $V$ be any finite dimensional vector space. Let $d \geq 1$. Let $N$ be the dimension of $S^d V$. Now $S^d V$ is spanned by the symmetric rank $1$ tensors, so we can take some $N$ of them to form a basis. And now all the symmetric rank $1$ tensors can be written as linear combinations of those.
Now there is a reasonable follow-up question, which might perhaps be a natural question from a standpoint of an engineer who is interested in identifiability issues: Okay, if some symmetric rank $1$ tensor is equal to a linear combination of some $r$ other symmetric rank $1$ tensors, then what is $r$?
We can certainly have such linear combinations when $r=N$ (the dimension of $S^d V$) but unfortunately it can happen sooner than that. It happens as soon as $r=d+1$. Because if $V$ has a basis $x\_1,\dotsc,x\_n$, then $x\_1^d$ can be written as a linear combination of $(x\_1 + t\_i x\_2)^d$ for any (!) $d+1$ nonzero values of $t\_i$. (Nutshell: with Vandermonde matrices you can show these are linearly independent, and there are enough of them to span all the degree $d$ polynomials in $x\_1,x\_2$, including $x\_1^d$.)
I believe the converse may be true: if $L^d$ is a linear combination of some $r$ other symmetric rank $1$ tensors, then $r \geq d+1$. But at the moment I'm not sure where to find a result along those lines. (I looked in some papers of Reznick and the book of Iarrobino-Kanev; it might be in there somewhere but so far I have not been able to find it.) If you are interested, please let me know and I will be happy to resume the search. | First let me make a point about the terminology. I believe what you mean by "rank-$1$ tensor" is what most people call a "pure" tensor: it is a tensor $t$ that can be written $v\_1\otimes\cdots\otimes v\_n$ for some possibly different vectors $v\_i$. I believe what you mean by "pure symmetric" is that all the $v\_i$ are the same; you can prove that this is equivalent to being pure and symmetric separately, so the language "symmetric pure symmetric" is redundant.
Let $t=v\otimes\cdots\otimes v$ be a pure symmetric tensor. Choose a basis $E\_i$ in which $v=E\_1$, and suppose $v$ can be written as a linear combination of pure tensors. Then
$$E\_1\otimes\dots\otimes E\_1 = v\otimes\dots\otimes v = \sum\_k w^k\_1\otimes...\otimes w\_1^k$$
for some vectors $w\_k=\sum\_i c\_k^i E\_i$. Thus
$$E\_1\otimes\dots\otimes E\_1=\sum\_{k,J}c\_k^{i\_1}\cdots c\_k^{i\_j}E\_{i\_1}\otimes\cdots\otimes E\_{i\_j}$$
A basis representation of a vector is unique, so equating the coefficients on both sides, we see that the coefficient of each $E\_{i\_1}\otimes\cdots\otimes E\_{i\_k}$ on the right is a polynomial in the $c\_i^k$ that must be equal to $0$ or, in the case $i\_1=\cdots=i\_j=1$, equal to $1$; the solution is obtained by checking the common solutions of these equations. In particular for $n\ne 1$,
$$\sum\_k c\_k^n\cdots c\_k^n = 0$$
If your vector space is even dimensional and real, then each term in this sum is an even power of a real number, thus positive, and thus each term must be zero. In other words, $c\_k^n=0$ for $n\ne 1$. This means each $w\_i$ is a scalar multiple of $E\_1$, so the answer to your question is no.
For odd dimensional real vector spaces and complex vector spaces it seems like the solution would be more complicated. |
308,615 | I am fairly new to JavaEE, so I have some concepts still missing.
I am learning Docker to use it in our DEV / CI Build environments. I could make it work on my machine. But for it to work in the CI server, my current approach would be to store the docker-compose.yml and dockerfiles in git and, in the CI server download it, build the images and start it.
To setup the docker image for the web container (Wildfly) I had to add:
* DB Drivers (.jar files)
* Standalone.xml (.xml file)
* Modules we use (mix of .xml and .jar files)
But these files are not present in the CI server.
I could download the DB drivers when building the image, but the modules and standalone.xml are not available online.
Is this approach the reasonable? If so, where would one store these files so they get updated when needed and the CI Server is able to download them to build the image? | 2016/01/28 | [
"https://softwareengineering.stackexchange.com/questions/308615",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/7764/"
] | For point 1. and 3. You could create private Ivy repository and fetch DB Drivers and Modules from it via your Build tool ( Mvn, Ant, Gradle support getting dependencies from Ivy repos ) when building your app.
And for `.xml` files - you can have git repository for your Test Environment config files. Or have them encrypted in your app repository, and configure CI script to encrypt those files with key that will be embedded in that CI script. ( encrypt, so people with git access to your app won't get password to your test DB ) | You need a reproducible build - this means you do not want your CI server downloading things from the internet on demand. You need to download them and otherwise collect everything needed for the build and store it somewhere accessible to the CI server.
Now the easiest and most future-proof way of doing that is to store these things in their own source-controlled repository. Then you can update it or create a new set from different configurations with ease. You can also build a historical version if necessary.
So: create a new repo for your Docker config, put what you need in there, and have your CI server grab both the docker config and application files from both repositories when it builds. You could even put the docker config in your source repo in a different directory if it makes more sense to you.
Alternatively, you can store these things on the CI server directly as an installation of build tools (eg you already have to install a JDK) and simply keep it referenced as a known pre-requisite to setting up your system. The decision over which to use usually comes down to the size of the files. |
35,214,887 | I have this call:
```
get_users('meta_key=main_feature&value=yes');
```
but the query is also returning users with the meta key 'featured' set to yes as well. I have a plugin that allows me to check all the user meta and have confirmed that the meta key for users that shouldn't be showing up is empty.
Is there something I'm doing wrong here? | 2016/02/05 | [
"https://Stackoverflow.com/questions/35214887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
jQuery(document).ready(function($) {
var e = "mailto:[email protected]";
$("footer .copyright").append('<div> Website by <a href="' + e + '" target="_top">John Bob</a></div>');
});
```
Pretty close. | Another interesting & clean approach is to use [chaining](http://blog.pengoworks.com/index.cfm/2007/10/26/jQuery-Understanding-the-chain).
```
$("<a target='_top'>")
.text("John Bob")
.attr("href", "mailto:[email protected]")
.appendTo("<div>Website by </div>")
.parent()
.appendTo("footer .copyright")
.end();
```
Demo: <https://jsfiddle.net/6ptc3d8u/1/> |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | Slightly clumsy, but you can use one `cy.intercept()` with a [Function routeHandler](https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response), and count the calls.
Something like,
```
let interceptCount = 0;
cy.intercept('http://localhost:4200/testcall', (req) => {
req.reply(res => {
if (interceptCount === 0 ) {
interceptCount += 1;
res.send({ fixture: 'example.json' })
} else {
res.send({ fixture: 'example2.json' })
}
});
});
```
Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time. | ```
const requestsCache = {};
export function reIntercept(type: 'GET' | 'POST' | 'PUT' | 'DELETE', url, options: StaticResponse) {
requestsCache[type + url] = options;
cy.intercept(type, url, req => req.reply(res => {
console.log(url, ' => ', requestsCache[type + url].fixture);
return res.send(requestsCache[type + url]);
}));
}
```
Make sure to clean requestsCache when needed. |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | Slightly clumsy, but you can use one `cy.intercept()` with a [Function routeHandler](https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response), and count the calls.
Something like,
```
let interceptCount = 0;
cy.intercept('http://localhost:4200/testcall', (req) => {
req.reply(res => {
if (interceptCount === 0 ) {
interceptCount += 1;
res.send({ fixture: 'example.json' })
} else {
res.send({ fixture: 'example2.json' })
}
});
});
```
Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time. | Cypress command [cy.intercept](https://on.cypress.io/intercept) has the
`times` parameter that you can use to create intercepts that only are used N times. In your case it would be
```js
cy.intercept('http://localhost:4200/testcall', {
fixture: 'example.json',
times: 1
});
...
cy.intercept('http://localhost:4200/testcall', {
fixture: 'example2.json',
times: 1
});
```
See the `cy.intercept` example in the Cypress recipes repo <https://github.com/cypress-io/cypress-example-recipes#network-stubbing-and-spying> |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | Slightly clumsy, but you can use one `cy.intercept()` with a [Function routeHandler](https://docs.cypress.io/api/commands/intercept.html#Intercepting-a-response), and count the calls.
Something like,
```
let interceptCount = 0;
cy.intercept('http://localhost:4200/testcall', (req) => {
req.reply(res => {
if (interceptCount === 0 ) {
interceptCount += 1;
res.send({ fixture: 'example.json' })
} else {
res.send({ fixture: 'example2.json' })
}
});
});
```
Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time. | As of Cypress [v7.0.0](https://github.com/cypress-io/cypress/releases/tag/v7.0.0) released 04/05/2021, `cy.intercept()` allows over-riding.
>
> We introduced several breaking changes to cy.intercept().
>
>
> * Request handlers supplied to cy.intercept() are **now matched starting with the most recently defined request interceptor**. This allows users to override request handlers by calling cy.intercept() again.
>
>
>
So your example code above now works
```js
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
``` |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | Cypress command [cy.intercept](https://on.cypress.io/intercept) has the
`times` parameter that you can use to create intercepts that only are used N times. In your case it would be
```js
cy.intercept('http://localhost:4200/testcall', {
fixture: 'example.json',
times: 1
});
...
cy.intercept('http://localhost:4200/testcall', {
fixture: 'example2.json',
times: 1
});
```
See the `cy.intercept` example in the Cypress recipes repo <https://github.com/cypress-io/cypress-example-recipes#network-stubbing-and-spying> | ```
const requestsCache = {};
export function reIntercept(type: 'GET' | 'POST' | 'PUT' | 'DELETE', url, options: StaticResponse) {
requestsCache[type + url] = options;
cy.intercept(type, url, req => req.reply(res => {
console.log(url, ' => ', requestsCache[type + url].fixture);
return res.send(requestsCache[type + url]);
}));
}
```
Make sure to clean requestsCache when needed. |
65,044,704 | I am trying to write a test with the new cypress 6 interceptor method ([Cypress API Intercept](https://docs.cypress.io/api/commands/intercept.html)). For the test I am writing I need to change the reponse of one endpoint after some action was performed.
**Expectation:**
I am calling cy.intercept again with another fixture and expect it to change all upcomming calls to reponse with this new fixture.
**Actual Behaviour:**
Cypress still response with the first fixture set for the call.
**Test Data:**
In a test project I have recreated the problem:
test.spec.js
```js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
```
example.json
```json
{
"text": "111"
}
```
example2.json
```json
{
"text": "222"
}
```
app.component.ts
```ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
```
app.component.html
```html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
``` | 2020/11/27 | [
"https://Stackoverflow.com/questions/65044704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2844348/"
] | As of Cypress [v7.0.0](https://github.com/cypress-io/cypress/releases/tag/v7.0.0) released 04/05/2021, `cy.intercept()` allows over-riding.
>
> We introduced several breaking changes to cy.intercept().
>
>
> * Request handlers supplied to cy.intercept() are **now matched starting with the most recently defined request interceptor**. This allows users to override request handlers by calling cy.intercept() again.
>
>
>
So your example code above now works
```js
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
``` | ```
const requestsCache = {};
export function reIntercept(type: 'GET' | 'POST' | 'PUT' | 'DELETE', url, options: StaticResponse) {
requestsCache[type + url] = options;
cy.intercept(type, url, req => req.reply(res => {
console.log(url, ' => ', requestsCache[type + url].fixture);
return res.send(requestsCache[type + url]);
}));
}
```
Make sure to clean requestsCache when needed. |
44,879,049 | I do not want to manually type in thousands of posts from my old website on the front end of my new website. I simply want to merge the database from the old into the new website in phpmyadmin. I'll tweak the tables to suit the new software afterwards.
1. I think there are only four tables that need to be merged for my purposes: wp\_postmeta, wp\_posts, wp\_usermeta and wp\_users.
2. The old website is still live, and the most recent post is post\_id 28,556. So to be safe and neat, I want all my new website post ids to begin at 30,000.
I found this code which is sort of what I'm looking for, but not really: <https://gist.github.com/jazzsequence/99dbee218c1b9a84df0d>. This code simply adds +1 to every row, ignoring all associations with usermeta, users, post\_ids inside postmeta etc. It cannot be used.
If you are unable to answer the question in it's entirety (it will help thousands of wordpress users if you do it properly), please tell me how to add 30,000 to every value in a given column. eg. If the column is called ID and the existing values are 1,2,4,9,13,24,25,26,28, then they would become 30001,30002,30004,30009,30013,30024,30025,30026,30028. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44879049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069432/"
] | **Setup**
Consider the dataframes `inventory` and `replace_with`
```
inventory = pd.DataFrame(dict(Partnumbers=['123AAA', '123BBB', '123CCC']))
replace_with = pd.DataFrame(dict(
oldPartnumbers=['123AAA', '123BBB', '123CCC'],
newPartnumbers=['123ABC', '123DEF', '123GHI']
))
```
**Option 1**
*`map`*
```
d = replace_with.set_index('oldPartnumbers').newPartnumbers
inventory['Partnumbers'] = inventory['Partnumbers'].map(d)
inventory
Partnumbers
0 123ABC
1 123DEF
2 123GHI
```
---
**Option 2**
*`replace`*
```
d = replace_with.set_index('oldPartnumbers').newPartnumbers
inventory['Partnumbers'].replace(d, inplace=True)
inventory
Partnumbers
0 123ABC
1 123DEF
2 123GHI
``` | This solution is relatively fast - it uses pandas data alignment and the numpy "copyto" function.
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'partNumbers': ['123AAA', '123BBB', '123CCC', '123DDD']})
df2 = pd.DataFrame({'oldPartnumbers': ['123AAA', '123BBB', '123CCC'],
'newPartnumbers': ['123ABC', '123DEF', '123GHI']})
# assign index in each dataframe to original part number columns
# (faster than set_index method, but use set_index if original index must be preserved)
df1.index = df1.partNumbers
df2.index = df2.oldPartnumbers
# use pandas index data alignment
df1['updatedPartNumbers'] = df2.newPartnumbers
# use numpy to copy in old part num when a new part num is not found
np.copyto(df1.updatedPartNumbers.values,
df1.partNumbers.values,
where=pd.isnull(df1.updatedPartNumbers))
# reset index
df1.reset_index(drop=True, inplace=True)
```
df1:
```
partNumbers updatedPartNumbers
0 123AAA 123ABC
1 123BBB 123DEF
2 123CCC 123GHI
3 123DDD 123DDD
``` |
44,879,049 | I do not want to manually type in thousands of posts from my old website on the front end of my new website. I simply want to merge the database from the old into the new website in phpmyadmin. I'll tweak the tables to suit the new software afterwards.
1. I think there are only four tables that need to be merged for my purposes: wp\_postmeta, wp\_posts, wp\_usermeta and wp\_users.
2. The old website is still live, and the most recent post is post\_id 28,556. So to be safe and neat, I want all my new website post ids to begin at 30,000.
I found this code which is sort of what I'm looking for, but not really: <https://gist.github.com/jazzsequence/99dbee218c1b9a84df0d>. This code simply adds +1 to every row, ignoring all associations with usermeta, users, post\_ids inside postmeta etc. It cannot be used.
If you are unable to answer the question in it's entirety (it will help thousands of wordpress users if you do it properly), please tell me how to add 30,000 to every value in a given column. eg. If the column is called ID and the existing values are 1,2,4,9,13,24,25,26,28, then they would become 30001,30002,30004,30009,30013,30024,30025,30026,30028. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44879049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1069432/"
] | Let say you have 2 df as follows:
```
import pandas as pd
df1 = pd.DataFrame([[1,3],[5,4],[6,7]], columns = ['PN','name'])
df2 = pd.DataFrame([[2,22],[3,33],[4,44],[5,55]], columns = ['oldname','newname'])
```
df1:
```
PN oldname
0 1 3
1 5 4
2 6 7
```
df2:
```
oldname newname
0 2 22
1 3 33
2 4 44
3 5 55
```
run left join between them:
```
temp = df1.merge(df2,'left',left_on='name',right_on='oldname')
```
temp:
```
PN name oldname newname
0 1 3 3.0 33.0
1 5 4 4.0 44.0
2 6 7 NaN NaN
```
then calculate the new `name` column and replace it:
```
df1['name'] = temp.apply(lambda row: row['newname'] if pd.notnull(row['newname']) else row['name'], axis=1)
```
df1:
```
PN name
0 1 33.0
1 5 44.0
2 6 7.0
```
or, as **one liner**:
```
df1['name'] = df1.merge(df2,'left',left_on='name',right_on='oldname').apply(lambda row: row['newname'] if pd.notnull(row['newname']) else row['name'], axis=1)
``` | This solution is relatively fast - it uses pandas data alignment and the numpy "copyto" function.
```
import pandas as pd
import numpy as np
df1 = pd.DataFrame({'partNumbers': ['123AAA', '123BBB', '123CCC', '123DDD']})
df2 = pd.DataFrame({'oldPartnumbers': ['123AAA', '123BBB', '123CCC'],
'newPartnumbers': ['123ABC', '123DEF', '123GHI']})
# assign index in each dataframe to original part number columns
# (faster than set_index method, but use set_index if original index must be preserved)
df1.index = df1.partNumbers
df2.index = df2.oldPartnumbers
# use pandas index data alignment
df1['updatedPartNumbers'] = df2.newPartnumbers
# use numpy to copy in old part num when a new part num is not found
np.copyto(df1.updatedPartNumbers.values,
df1.partNumbers.values,
where=pd.isnull(df1.updatedPartNumbers))
# reset index
df1.reset_index(drop=True, inplace=True)
```
df1:
```
partNumbers updatedPartNumbers
0 123AAA 123ABC
1 123BBB 123DEF
2 123CCC 123GHI
3 123DDD 123DDD
``` |
1,246,300 | So this is probably really simple but for some reason I can't figure it out. When I run the below code I can't get it to go into the `if` statement even though when I go into the debugger console in xcode and I execute `po [resultObject valueForKey:@"type"]` it returns `0`. What am I doing wrong? Thanks for your help!
```
NSManagedObject *resultObject = [qResult objectAtIndex:i];
if (([resultObject valueForKey:@"type"])== 0) {
//do something
}
``` | 2009/08/07 | [
"https://Stackoverflow.com/questions/1246300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149839/"
] | The result of `valueForKey:` is always an object — and the only object equal to 0 is nil. In the case of a numerical value, it will be an NSNumber. At any rate, I think you want to ask for `[[resultObject valueForKey:@"type"] intValue]`. | You could try casting the NSManagedObject to an int (if thats what it actually is...)
Also you don't need the extra parentheses around the [ ]
```
NSManagedObject *resultObject = [qResult objectAtIndex:i];
if ((int)[resultObject valueForKey:@"type"] == 0) {
//do something
}
``` |
71,860,572 | ```
#include <string>
void foo(int x, short y, int z) { std::cout << "normal int" << std::endl; } //F1
void foo(double x, int y, double z) { std::cout << "normal double" << std::endl; } //F2
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
Based on function overloading rules,
F1( Exact = 1, Promote = 0, Convert = 2 ) and
F2( Exact = 2, Promote = 1, Convert = 0 ). Shouldn't F2 be called? Why is the call ambiguous? | 2022/04/13 | [
"https://Stackoverflow.com/questions/71860572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14250223/"
] | Overload resolution can get complicated. But here it's fairly straightforward. I'll rewrite the function prototypes to remove the third argument, since it doesn't affect the analysis.
```
void foo(int, short);
void foo(double, int);
double d = 1.0;
short s = 2;
f(d, s); // ambiguous
```
The rule is that you look at each argument, one at a time, and determine which function has the "best" conversion **for that argument**. If one function has the best conversion for every argument, that's the one that's called. If there's no function that's best for every argument, the call is ambiguous.
For the first argument, the type of the argument is `double`. Calling the first version of `foo` requires a conversion from `double` to `int`; calling the second version of `foo` requires no conversion; it's an exact match. So for the first argument, the second version of `foo` has the best conversion.
For the second argument, the type of the argument is `short`. Calling the first version of `foo` requires no conversion; it's an exact match. Calling the second version of `foo` requires a promotion from `short` to `int`. So for the second argument, the first version of `foo` has the best conversion.
Since the first version of `foo` has the best match for the second argument and the second version of `foo` has the best match for the first argument, there is no function with the best match on all arguments, and the call is ambiguous. | The ranking of conversion sequences matters only when comparing ranking of the conversion sequences applied to the same argument.
If one argument's conversion rank is better in the first overload than in the second one and the other way around for another argument's conversion rank, then neither overload is considered better than the other and the overload resolution is ambiguous.
This applies here. The first and third argument have a better conversion rank (exact rather than conversion) in the second overload, while the second argument has a better conversion rank in the first overload (exact rather than promotion). |
71,860,572 | ```
#include <string>
void foo(int x, short y, int z) { std::cout << "normal int" << std::endl; } //F1
void foo(double x, int y, double z) { std::cout << "normal double" << std::endl; } //F2
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
Based on function overloading rules,
F1( Exact = 1, Promote = 0, Convert = 2 ) and
F2( Exact = 2, Promote = 1, Convert = 0 ). Shouldn't F2 be called? Why is the call ambiguous? | 2022/04/13 | [
"https://Stackoverflow.com/questions/71860572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14250223/"
] | Overload resolution ranks the viable candidate functions by comparing how each argument of the call matches the corresponding parameter of the candidates. Moreover, for one candidate to be considered better than another, the **better candidate cannot have any of its parameters be a worse match than the
corresponding parameter in the other candidate**.
Now, let's apply this to your given example snippet.
```
void foo(int x, short y, int z);
void foo(double x, int y, double z) ;
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
In the above snippet, For the case of first overloaded `foo`, the second argument matches exactly with the type of the second parameter. But the first and third argument have type `double` while the corresponding parameters have type `int` and so the first and the third argument requires a conversion to `int` in this case.
On the other hand, for the case of second overloaded `foo`, the first and third argument matches exactly with the first and third parameter respectively. But in this case, the second argument is of type `short` while the second parameter is of type `int`. So a promotion to `int` is needed for the second argument.
---
#### Result 1
Now, according to the highlighted part at the beginning of my answer, for the first candidate to be considered a better match than the second candidate, none of the first candidate's parameter can be a worse match than the corresponding parameter in the second candidate. But we already discussed that the first and third parameter of first overloaded candidate are worse match than the corresponding parameters in the second overloaded candidate since they require conversion to `int`. Thus, the first overloaded candidate is not a better match than the second overloaded candidate.
---
#### Result 2
Similarly, for the second candidate to be considered a better match than the first candidate, none of the second candidate's parameter can be a worse match than the corresponding parameter in the first candidate. But here also we already discussed that the second parameter in the second candidate is worse match than the corresponding parameter in the first candidate since it requires a promotion. Thus, the second candidate is not a better match than the first candidate.
---
#### Conclusion
Combining both of the results above, we get to the conclusion that none of the candidates is better than the other. Hence the call is ambiguous. | The ranking of conversion sequences matters only when comparing ranking of the conversion sequences applied to the same argument.
If one argument's conversion rank is better in the first overload than in the second one and the other way around for another argument's conversion rank, then neither overload is considered better than the other and the overload resolution is ambiguous.
This applies here. The first and third argument have a better conversion rank (exact rather than conversion) in the second overload, while the second argument has a better conversion rank in the first overload (exact rather than promotion). |
71,860,572 | ```
#include <string>
void foo(int x, short y, int z) { std::cout << "normal int" << std::endl; } //F1
void foo(double x, int y, double z) { std::cout << "normal double" << std::endl; } //F2
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
Based on function overloading rules,
F1( Exact = 1, Promote = 0, Convert = 2 ) and
F2( Exact = 2, Promote = 1, Convert = 0 ). Shouldn't F2 be called? Why is the call ambiguous? | 2022/04/13 | [
"https://Stackoverflow.com/questions/71860572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14250223/"
] | Overload resolution can get complicated. But here it's fairly straightforward. I'll rewrite the function prototypes to remove the third argument, since it doesn't affect the analysis.
```
void foo(int, short);
void foo(double, int);
double d = 1.0;
short s = 2;
f(d, s); // ambiguous
```
The rule is that you look at each argument, one at a time, and determine which function has the "best" conversion **for that argument**. If one function has the best conversion for every argument, that's the one that's called. If there's no function that's best for every argument, the call is ambiguous.
For the first argument, the type of the argument is `double`. Calling the first version of `foo` requires a conversion from `double` to `int`; calling the second version of `foo` requires no conversion; it's an exact match. So for the first argument, the second version of `foo` has the best conversion.
For the second argument, the type of the argument is `short`. Calling the first version of `foo` requires no conversion; it's an exact match. Calling the second version of `foo` requires a promotion from `short` to `int`. So for the second argument, the first version of `foo` has the best conversion.
Since the first version of `foo` has the best match for the second argument and the second version of `foo` has the best match for the first argument, there is no function with the best match on all arguments, and the call is ambiguous. | Overload resolution ranks the viable candidate functions by comparing how each argument of the call matches the corresponding parameter of the candidates. Moreover, for one candidate to be considered better than another, the **better candidate cannot have any of its parameters be a worse match than the
corresponding parameter in the other candidate**.
Now, let's apply this to your given example snippet.
```
void foo(int x, short y, int z);
void foo(double x, int y, double z) ;
int main()
{
short x = 2;
foo(5.0, x, 8.0);
}
```
In the above snippet, For the case of first overloaded `foo`, the second argument matches exactly with the type of the second parameter. But the first and third argument have type `double` while the corresponding parameters have type `int` and so the first and the third argument requires a conversion to `int` in this case.
On the other hand, for the case of second overloaded `foo`, the first and third argument matches exactly with the first and third parameter respectively. But in this case, the second argument is of type `short` while the second parameter is of type `int`. So a promotion to `int` is needed for the second argument.
---
#### Result 1
Now, according to the highlighted part at the beginning of my answer, for the first candidate to be considered a better match than the second candidate, none of the first candidate's parameter can be a worse match than the corresponding parameter in the second candidate. But we already discussed that the first and third parameter of first overloaded candidate are worse match than the corresponding parameters in the second overloaded candidate since they require conversion to `int`. Thus, the first overloaded candidate is not a better match than the second overloaded candidate.
---
#### Result 2
Similarly, for the second candidate to be considered a better match than the first candidate, none of the second candidate's parameter can be a worse match than the corresponding parameter in the first candidate. But here also we already discussed that the second parameter in the second candidate is worse match than the corresponding parameter in the first candidate since it requires a promotion. Thus, the second candidate is not a better match than the first candidate.
---
#### Conclusion
Combining both of the results above, we get to the conclusion that none of the candidates is better than the other. Hence the call is ambiguous. |
19,724,319 | In JavaScript, I have complex objects comprising functions, variables and closures.
These objects are very large, very complex and created and destroyed over and over again. I will be working on a very low-powered, very low-memory device, so it's important to me that when the objects are deleted that they are really gone.
Here's a code example:
```
window["obj"] = {};
obj.fun1 = function(){
console.log(1);
};
(function(){
var n = 2;
function fun(){
console.log(n);
}
obj.fun2 = fun;
})();
(function(){
var w = "Three";
function fun(){
console.log(w);
}
obj.fun3 = fun;
})();
(function(){
var w = "f.o.u.r.";
function fun(){
setInterval(function(){
console.log(w);
}, 1e3); // e.g. a timeout
}
obj.fun4 = fun;
})();
obj.fun1();
obj.fun2();
obj.fun3();
obj.fun4();
var fun2 = obj.fun2;
// window.obj = null;
// window.obj = undefined;
delete window.obj;
console.log(typeof obj); // undefined
```
A secondary issue is the question of "lingering references", such as the following:
```
fun2(); // 2
// Interval: "f.o.u.r.", "f.o.u.r.", "f.o.u.r.", "f.o.u.r." ...
```
Is there anything that can be done about those (except a manual clean up before deleting the object)?
A JSFiddle of the code above is here: <http://jsfiddle.net/8nE2f/> | 2013/11/01 | [
"https://Stackoverflow.com/questions/19724319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681800/"
] | You will have the best effect by doing this
```
window.obj = null;
delete window.obj;
```
Setting objects to null removes any references to it. Also remember that the delete command has no effect on regular variables, only properties.
To better ensure object destruction you may consider not using the global context at all, that is usually considered as an antipattern. | The only way to get rid of an object is for JavaScript to garbage-collect it, so making sure there really aren't any references to the object left and praying is the only way to go.
If you're repeatedly creating and destroying the same object, consider using an [object pool](http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/). |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | Top answer is correct. You can debug this with "Pause" option. Most common way to block main thread is to call `dispatch_sync` on the same thread you dispatching. Sometimes you call same code from `dispatch_once`. | I have similar case in my project and the reason was another developer who added `setNeedsLayout()` inside method `layoutSubviews()` and this make infinite loop and freeze the app. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | Top answer is correct. You can debug this with "Pause" option. Most common way to block main thread is to call `dispatch_sync` on the same thread you dispatching. Sometimes you call same code from `dispatch_once`. | The same Issue Happened to me with ios 13.4 and then I tried the above solution but it doesn't solve it. so I had one element with break constraint on the storyboard. So after resolving the constraint it solve the problem. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. | I suggest checking your sizes especially in collection views if they are not fitted they will freeze your app and also check your constraints |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | Besides pausing and following the stacktrace I think as an additional thing to do, is to check in the code if there's any loop causing the app freezes.
I recently ran into a similar problem, but stack trace didn't help much, I figured out that I was having an eternal loop when calling a `reloadData()` inside layoutsubviews method and that was causing a freeze with no errors and no help from instruments. | The same Issue Happened to me with ios 13.4 and then I tried the above solution but it doesn't solve it. so I had one element with break constraint on the storyboard. So after resolving the constraint it solve the problem. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | I have similar case in my project and the reason was another developer who added `setNeedsLayout()` inside method `layoutSubviews()` and this make infinite loop and freeze the app. | The same Issue Happened to me with ios 13.4 and then I tried the above solution but it doesn't solve it. so I had one element with break constraint on the storyboard. So after resolving the constraint it solve the problem. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. | The same Issue Happened to me with ios 13.4 and then I tried the above solution but it doesn't solve it. so I had one element with break constraint on the storyboard. So after resolving the constraint it solve the problem. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. | Top answer is correct. You can debug this with "Pause" option. Most common way to block main thread is to call `dispatch_sync` on the same thread you dispatching. Sometimes you call same code from `dispatch_once`. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | I have similar case in my project and the reason was another developer who added `setNeedsLayout()` inside method `layoutSubviews()` and this make infinite loop and freeze the app. | I suggest checking your sizes especially in collection views if they are not fitted they will freeze your app and also check your constraints |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. | Besides pausing and following the stacktrace I think as an additional thing to do, is to check in the code if there's any loop causing the app freezes.
I recently ran into a similar problem, but stack trace didn't help much, I figured out that I was having an eternal loop when calling a `reloadData()` inside layoutsubviews method and that was causing a freeze with no errors and no help from instruments. |
10,196,344 | Does any body know what I have to check if my app freezes? I mean, I can see the app in the iPad screen but no buttons respond. I have tried debugging the code when I click on the button, but I haven't seen anything yet. I was reading about the Instruments tools; specifically how do I use them?
Can anybody help me? I just need an explanation about how use the tools. | 2012/04/17 | [
"https://Stackoverflow.com/questions/10196344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013554/"
] | It sounds like you've blocked the main thread somehow. To debug, run the app in the debugger and when the app freezes, hit the pause button above the log area at the bottom of Xcode. Then on the left side, you'll be able to see exactly what each thread is doing, and you can see where it's getting stuck.
[](https://i.stack.imgur.com/utV2J.png)
Probably either a long loop on the main thread or a sync deadlock. | I have similar case in my project and the reason was another developer who added `setNeedsLayout()` inside method `layoutSubviews()` and this make infinite loop and freeze the app. |
71,198,618 | ```
const howLong = 5
```
```
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)].push
}
```
console prints undefined 5x, my goal is to make it copy 5 random characters from the "special" array into a new var "finalPassword" | 2022/02/20 | [
"https://Stackoverflow.com/questions/71198618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978619/"
] | you should remove the .push call
```
const howLong = 5;
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = "";
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)]
}
``` | In your example you simply have to remove `.push` it seems.
```js
let special = ["!", "@", "#", "$", "%", "+", "&"];
let finalPassword = [];
for (let i = 0; i < 5; i++) {
finalPassword += special[Math.floor(Math.random() * 5)];
}
console.log({ finalPassword });
``` |
71,198,618 | ```
const howLong = 5
```
```
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)].push
}
```
console prints undefined 5x, my goal is to make it copy 5 random characters from the "special" array into a new var "finalPassword" | 2022/02/20 | [
"https://Stackoverflow.com/questions/71198618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978619/"
] | Depending on what your expected output requirements are you can either concatenate "special" characters on to a string:
```js
const howLong = 5;
let special=["!","@","#","$","%","+","&"];
let finalPassword = '';
for (let i = 0; i < howLong; i++) {
const rnd = Math.floor(Math.random() * howLong);
finalPassword += special[rnd];
}
console.log(finalPassword);
```
...or you can push those "special" characters into an array (and then maybe `join` up that array of elements into a string).
```js
const howLong = 5;
let special=["!","@","#","$","%","+","&"];
let finalPassword = [];
for (let i = 0; i < howLong; i++) {
const rnd = Math.floor(Math.random() * howLong);
finalPassword.push(special[rnd]);
}
console.log(finalPassword);
console.log(finalPassword.join(''));
```
But you can't do both operations at the same time. | In your example you simply have to remove `.push` it seems.
```js
let special = ["!", "@", "#", "$", "%", "+", "&"];
let finalPassword = [];
for (let i = 0; i < 5; i++) {
finalPassword += special[Math.floor(Math.random() * 5)];
}
console.log({ finalPassword });
``` |
71,198,618 | ```
const howLong = 5
```
```
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)].push
}
```
console prints undefined 5x, my goal is to make it copy 5 random characters from the "special" array into a new var "finalPassword" | 2022/02/20 | [
"https://Stackoverflow.com/questions/71198618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17978619/"
] | In the for loop iteration, generate a random index and then access the special array in that index to fetch the special character.
```js
const howLong = 5;
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
const currentRandom = Math.floor(Math.random() * howLong);
finalPassword.push(special[currentRandom]);
}
console.log(finalPassword);
``` | In your example you simply have to remove `.push` it seems.
```js
let special = ["!", "@", "#", "$", "%", "+", "&"];
let finalPassword = [];
for (let i = 0; i < 5; i++) {
finalPassword += special[Math.floor(Math.random() * 5)];
}
console.log({ finalPassword });
``` |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | The formula $f'(x) = \lim\_{h \to 0} \frac{f(x+h)-f(x)}{h}$ is equivalent to
$\lim\_{h \to 0} \frac{f(x+h)-f(x)-f'(x)h}{h} = 0$.
This in turn is equivalent to the function $g(h) = f(x+h)-f(x)-f'(x)h$ satisfying $\lim\_{h \to 0} \frac{g(h)}{h} = 0$.
Such a function is referred to as 'little o' or $o(h)$, and we say $g$ is 'little o' of $h$, or simply just write $o(h)$.
That is, we abuse notation and write $f(x+h)-f(x)-f'(x)h = o(h)$, which gives rise to $f(x+h) = f(x)+f'(x)h + o(h)$.
**Note**: This is $o(h)$, not $O(h)$. The function $f(x) = |x|$ is not differentiable at $x=0$, but we can write $f(h)=f(0)+0.h + O(h)$, but you cannot replace the $O(h)$ by $o(h)$, if you see what I mean. | By the definition of differentiability
$$f(x+h)-f(x)=f'(x)h+o(h),\,\,h\to{0}.$$
In your's second formula must be $o(1),$ not $O(h).$ |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | Let $f(x)=|x|^{3/2}$. Then $f'(0)=0$. But $\dfrac{|h|^{3/2}-0}{h}$ is not $O(h)$. | By the definition of differentiability
$$f(x+h)-f(x)=f'(x)h+o(h),\,\,h\to{0}.$$
In your's second formula must be $o(1),$ not $O(h).$ |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | The formula $f'(x) = \lim\_{h \to 0} \frac{f(x+h)-f(x)}{h}$ is equivalent to
$\lim\_{h \to 0} \frac{f(x+h)-f(x)-f'(x)h}{h} = 0$.
This in turn is equivalent to the function $g(h) = f(x+h)-f(x)-f'(x)h$ satisfying $\lim\_{h \to 0} \frac{g(h)}{h} = 0$.
Such a function is referred to as 'little o' or $o(h)$, and we say $g$ is 'little o' of $h$, or simply just write $o(h)$.
That is, we abuse notation and write $f(x+h)-f(x)-f'(x)h = o(h)$, which gives rise to $f(x+h) = f(x)+f'(x)h + o(h)$.
**Note**: This is $o(h)$, not $O(h)$. The function $f(x) = |x|$ is not differentiable at $x=0$, but we can write $f(h)=f(0)+0.h + O(h)$, but you cannot replace the $O(h)$ by $o(h)$, if you see what I mean. | $f'(x)=\frac{f(x+h)-f(x)}{h}+\Big(f'(x)-\frac{f(x+h)-f(x)}{h}\Big)=\frac{f(x+h)-f(x)}{h}+o(h)$, assuming $f'(x)$ exists (since $\Big(f'(x)-\frac{f(x+h)-f(x)}{h}\Big)$ goes to $0$ as $h\to 0$). It's true that if something is $o(h)$ it is also $O(h)$, so it's also true that $f'(x)=\frac{f(x+h)-f(x)}{h}+O(h)$. Also if $g(x)=\frac{f(x+h)-f(x)}{h}+o(h)$, then by taking $h\to 0$, we get that $g(x)=f'(x)$. |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | Let $f(x)=|x|^{3/2}$. Then $f'(0)=0$. But $\dfrac{|h|^{3/2}-0}{h}$ is not $O(h)$. | $f'(x)=\frac{f(x+h)-f(x)}{h}+\Big(f'(x)-\frac{f(x+h)-f(x)}{h}\Big)=\frac{f(x+h)-f(x)}{h}+o(h)$, assuming $f'(x)$ exists (since $\Big(f'(x)-\frac{f(x+h)-f(x)}{h}\Big)$ goes to $0$ as $h\to 0$). It's true that if something is $o(h)$ it is also $O(h)$, so it's also true that $f'(x)=\frac{f(x+h)-f(x)}{h}+O(h)$. Also if $g(x)=\frac{f(x+h)-f(x)}{h}+o(h)$, then by taking $h\to 0$, we get that $g(x)=f'(x)$. |
519,113 | Why I can write formula derivative $$ f'(x) = \lim\_{h\rightarrow 0}\frac{f(x+h)-f(x)}{h}$$ in this form: $$ f'(x)=\frac{f(x+h)-f(h)}{h}+O(h)$$
I know, that it's easy but unfortunately I forgot. | 2013/10/08 | [
"https://math.stackexchange.com/questions/519113",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/99324/"
] | The formula $f'(x) = \lim\_{h \to 0} \frac{f(x+h)-f(x)}{h}$ is equivalent to
$\lim\_{h \to 0} \frac{f(x+h)-f(x)-f'(x)h}{h} = 0$.
This in turn is equivalent to the function $g(h) = f(x+h)-f(x)-f'(x)h$ satisfying $\lim\_{h \to 0} \frac{g(h)}{h} = 0$.
Such a function is referred to as 'little o' or $o(h)$, and we say $g$ is 'little o' of $h$, or simply just write $o(h)$.
That is, we abuse notation and write $f(x+h)-f(x)-f'(x)h = o(h)$, which gives rise to $f(x+h) = f(x)+f'(x)h + o(h)$.
**Note**: This is $o(h)$, not $O(h)$. The function $f(x) = |x|$ is not differentiable at $x=0$, but we can write $f(h)=f(0)+0.h + O(h)$, but you cannot replace the $O(h)$ by $o(h)$, if you see what I mean. | Let $f(x)=|x|^{3/2}$. Then $f'(0)=0$. But $\dfrac{|h|^{3/2}-0}{h}$ is not $O(h)$. |
18,863 | I have this code
```
$collection = Mage::getModel("news/views");
->addFieldToSelect('post_id', array('eq' => $this->getRequest()->getParam("id")));
```
And when i'm trying to save my post i get en error:
>
> Invalid method Iv\_News\_Model\_Views::addFieldToSelect(Array ( [0] =>
> post\_id [1] => Array ( [eq] => 13 ) ) )
>
>
> | 2014/04/25 | [
"https://magento.stackexchange.com/questions/18863",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/6086/"
] | The `addFieldToSelect` is available for collection objects. It is defined in `Mage_Core_Model_Resource_Db_Collection_Abstract` so it is available in all its child classes.
You are calling it on a model object that most probably is a child of `Mage_Core_Model_Abstract`.
I think you meant to do this:
```
$collection = Mage::getModel("news/views")->getCollection()
->addFieldToSelect('post_id', array('eq' => $this->getRequest()->getParam("id")));
``` | According to problem from comment the soulution was to change
```
AddFieldToSelect()
```
to
```
AddFieldToFilter()
```
and it worked. |
46,303,233 | I cannot find a solution to this particular demand.
I have a mysql dump on my computer and I want to import it in a web server using SSH.
How do I do that ?
Can I add the ssh connection to the mysql command ?
Edit :
I did it with SCP
```
scp -r -p /Users/me/files/dump.sql user@server:/var/www/private
mysql -hxxx -uxxx -pxxx dbname < dump.sql
``` | 2017/09/19 | [
"https://Stackoverflow.com/questions/46303233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1787994/"
] | As the comment above says, the simplest solution is to scp the whole dump file up to your server, and then restore it normally. But that means you have to have enough free disk space to store the dump file on your webserver. You might not.
An alternative is to set up a temporary ssh tunnel to your web server. Read <https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/> for full instructions, but it would look something like this:
```
nohup ssh -L 8001:localhost:3306 -N user@webserver >/dev/null 2>&1 &
```
This means when I connect to port 8001 on my local host (you can pick any unused port number here), it's really being given a detour through the ssh tunnel to the webserver, where it connects to port 3306, the MySQL default port.
In the example above, your `user@webserver` is just a placeholder, so you must replace it with your username and your webserver hostname.
Then restore your dump file as if you're restoring to a hypothetical MySQL instance running on port 8001 on the local host. This way you don't have to scp the dump file up to your webserver. It will be streamed up to the webserver via the ssh tunnel, and then applied to your database directly.
```
pv -pert mydumpfile.sql | mysql -h 127.0.0.1 -P 8001
```
You have to specify 127.0.0.1, because the MySQL client uses "localhost" as a special name for a non-network connection.
I like to use `pv` to read the dumpfile, because it outputs a progress bar. | You can try this solution for your problem :
**Login using SSH details :-**
```
SSH Host name : test.com
SSH User : root
SSH Password : 123456
```
**Connect SSH :-**
```
ssh [email protected]
enter password : 123456
```
**Login MySQL :-**
```
mysql -u [MySQL User] -p
Enter Password :- MySQL Password
```
**Used following command for Import databases :-**
```
show databases; // List of Databased
use databasedname; // Enter You databased name to Import databased
source path; // Set path for Import databased for ex : /home/databased/import.sql
```
I hope this will helps you. |
46,303,233 | I cannot find a solution to this particular demand.
I have a mysql dump on my computer and I want to import it in a web server using SSH.
How do I do that ?
Can I add the ssh connection to the mysql command ?
Edit :
I did it with SCP
```
scp -r -p /Users/me/files/dump.sql user@server:/var/www/private
mysql -hxxx -uxxx -pxxx dbname < dump.sql
``` | 2017/09/19 | [
"https://Stackoverflow.com/questions/46303233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1787994/"
] | You can try this solution for your problem :
**Login using SSH details :-**
```
SSH Host name : test.com
SSH User : root
SSH Password : 123456
```
**Connect SSH :-**
```
ssh [email protected]
enter password : 123456
```
**Login MySQL :-**
```
mysql -u [MySQL User] -p
Enter Password :- MySQL Password
```
**Used following command for Import databases :-**
```
show databases; // List of Databased
use databasedname; // Enter You databased name to Import databased
source path; // Set path for Import databased for ex : /home/databased/import.sql
```
I hope this will helps you. | Yes, you can do it with one command, just use 'Pipeline' or 'Process Substitution'
**For your example with 'Pipeline':**
```
ssh user@server "cat /Users/me/files/dump.sql" | mysql -hxxx -uxxx -pxxx dbname
```
or use 'Process Substitution':
```
mysql -hxxx -uxxx -pxxx dbname < <(ssh user@server "cat /Users/me/files/dump.sql")
```
**Example 2, get database dump from remote server1 and restore on remote server2 with 'Pipeline':**
```
ssh user@server1 "mysqldump -uroot -p'xxx' dbname" | ssh user@server2 "mysql -uroot -p'xxx' dbname"
```
or 'Process Substitution':
```
ssh user@server2 "mysql -uroot -p'xxx' dbname" < <(ssh user@server1 "mysqldump -uroot -p'xxx' dbname")
```
*Additional links:*
*what is 'Process Substitution':*
<http://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html>
*what is 'Pipeline':*
<http://www.gnu.org/software/bash/manual/html_node/Pipelines.html> |
46,303,233 | I cannot find a solution to this particular demand.
I have a mysql dump on my computer and I want to import it in a web server using SSH.
How do I do that ?
Can I add the ssh connection to the mysql command ?
Edit :
I did it with SCP
```
scp -r -p /Users/me/files/dump.sql user@server:/var/www/private
mysql -hxxx -uxxx -pxxx dbname < dump.sql
``` | 2017/09/19 | [
"https://Stackoverflow.com/questions/46303233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1787994/"
] | As the comment above says, the simplest solution is to scp the whole dump file up to your server, and then restore it normally. But that means you have to have enough free disk space to store the dump file on your webserver. You might not.
An alternative is to set up a temporary ssh tunnel to your web server. Read <https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/> for full instructions, but it would look something like this:
```
nohup ssh -L 8001:localhost:3306 -N user@webserver >/dev/null 2>&1 &
```
This means when I connect to port 8001 on my local host (you can pick any unused port number here), it's really being given a detour through the ssh tunnel to the webserver, where it connects to port 3306, the MySQL default port.
In the example above, your `user@webserver` is just a placeholder, so you must replace it with your username and your webserver hostname.
Then restore your dump file as if you're restoring to a hypothetical MySQL instance running on port 8001 on the local host. This way you don't have to scp the dump file up to your webserver. It will be streamed up to the webserver via the ssh tunnel, and then applied to your database directly.
```
pv -pert mydumpfile.sql | mysql -h 127.0.0.1 -P 8001
```
You have to specify 127.0.0.1, because the MySQL client uses "localhost" as a special name for a non-network connection.
I like to use `pv` to read the dumpfile, because it outputs a progress bar. | Yes, you can do it with one command, just use 'Pipeline' or 'Process Substitution'
**For your example with 'Pipeline':**
```
ssh user@server "cat /Users/me/files/dump.sql" | mysql -hxxx -uxxx -pxxx dbname
```
or use 'Process Substitution':
```
mysql -hxxx -uxxx -pxxx dbname < <(ssh user@server "cat /Users/me/files/dump.sql")
```
**Example 2, get database dump from remote server1 and restore on remote server2 with 'Pipeline':**
```
ssh user@server1 "mysqldump -uroot -p'xxx' dbname" | ssh user@server2 "mysql -uroot -p'xxx' dbname"
```
or 'Process Substitution':
```
ssh user@server2 "mysql -uroot -p'xxx' dbname" < <(ssh user@server1 "mysqldump -uroot -p'xxx' dbname")
```
*Additional links:*
*what is 'Process Substitution':*
<http://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html>
*what is 'Pipeline':*
<http://www.gnu.org/software/bash/manual/html_node/Pipelines.html> |
17,058 | We have ants in our house, and nothing I've tried so far has been sufficiently successful. Now I'm considering using ant traps, but only under the kitchen cabinets behind the plinth, a place where neither my cats nor my kids (a baby and a toddler) would ever be able to reach them (no chance of them getting in there). Would that be safe? Are there other aspects we'd need to consider? | 2017/05/09 | [
"https://pets.stackexchange.com/questions/17058",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/2554/"
] | I don't think it is overstocked at the moment.
But these are all schooling fish and they might be happier if the schools are a bit bigger.
A better mix would be to remove 2 species (eg the tetra's and the barbs) and replace them with the other species (more corys and rainbows for example).
6-7 fish for a 'school' is usually really them minimum. | Yah. Not overstocked but it will be if you have their appropriate schools. Try two or three schools of the smaller species like zebra danios and turquoise rainbows. You could possibly put some guppies in if you are interested. |
17,058 | We have ants in our house, and nothing I've tried so far has been sufficiently successful. Now I'm considering using ant traps, but only under the kitchen cabinets behind the plinth, a place where neither my cats nor my kids (a baby and a toddler) would ever be able to reach them (no chance of them getting in there). Would that be safe? Are there other aspects we'd need to consider? | 2017/05/09 | [
"https://pets.stackexchange.com/questions/17058",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/2554/"
] | I don't think it is overstocked at the moment.
But these are all schooling fish and they might be happier if the schools are a bit bigger.
A better mix would be to remove 2 species (eg the tetra's and the barbs) and replace them with the other species (more corys and rainbows for example).
6-7 fish for a 'school' is usually really them minimum. | So, I'm going to slightly disagree with the idea to keep AND add to the rainbows pop. This is one of my favorite breeds of freshwater community fish too, so although my heart says keep those beauties, my experience says differently.
They get about 4" (10 cm) in length and need a decent sized school to be happy. It's said that if you have a proper school a 50+ gallon (190+ liters) tank is what's necessary. Volume isn't the issue with these guys, it's the length of the tank that's needed for their swimming patterns. They are lateral swimmers, middle dwellers, and need the length of 48" (around 120 cm) of more unfortunately.
I'd say remove the two turquoise rainbows (especially since they'll get the biggest), two more zebra danios and add two more corys. I think your 5 cherry barb and 5 serpae tetras WILL be fine the way they are. Since it's a 30 gallon, and since your question shows your concern for overcrowding. Good luck and have fun! |
17,058 | We have ants in our house, and nothing I've tried so far has been sufficiently successful. Now I'm considering using ant traps, but only under the kitchen cabinets behind the plinth, a place where neither my cats nor my kids (a baby and a toddler) would ever be able to reach them (no chance of them getting in there). Would that be safe? Are there other aspects we'd need to consider? | 2017/05/09 | [
"https://pets.stackexchange.com/questions/17058",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/2554/"
] | So, I'm going to slightly disagree with the idea to keep AND add to the rainbows pop. This is one of my favorite breeds of freshwater community fish too, so although my heart says keep those beauties, my experience says differently.
They get about 4" (10 cm) in length and need a decent sized school to be happy. It's said that if you have a proper school a 50+ gallon (190+ liters) tank is what's necessary. Volume isn't the issue with these guys, it's the length of the tank that's needed for their swimming patterns. They are lateral swimmers, middle dwellers, and need the length of 48" (around 120 cm) of more unfortunately.
I'd say remove the two turquoise rainbows (especially since they'll get the biggest), two more zebra danios and add two more corys. I think your 5 cherry barb and 5 serpae tetras WILL be fine the way they are. Since it's a 30 gallon, and since your question shows your concern for overcrowding. Good luck and have fun! | Yah. Not overstocked but it will be if you have their appropriate schools. Try two or three schools of the smaller species like zebra danios and turquoise rainbows. You could possibly put some guppies in if you are interested. |
5,058 | When running MSM add-on, how can I manage the file upload folders etc, via a config.php file?
Ideally I would want to use a hook to do it, but it doesn't seem to work.
Normally I would do this:
>
>
> ```
> $config['upload_preferences'] = array(
> 1 => array(
> 'name' => 'Images',
> 'server_path' => $uploads_path . "/images/",
> 'url' => $uploads_url . "/images/"
> ),
> 2 => array(
> 'name' => 'Files',
> 'server_path' => $uploads_path . "/files/",
> 'url' => $uploads_url . "/files/"
> ),
> 3 => array(
> 'name' => 'Icons',
> 'server_path' => $uploads_path . "/icons/",
> 'url' => $uploads_url . "/icons/"
> )
> );
>
> ```
>
> | 2013/01/18 | [
"https://expressionengine.stackexchange.com/questions/5058",
"https://expressionengine.stackexchange.com",
"https://expressionengine.stackexchange.com/users/362/"
] | Actually, every upload location you create is going to have a different ID, be it one site or in multiple sites using MSM. You can thus safely keep everything in config.php becuse every upload location you define (even if you share physical folders) is going to have a different ID anyway.
Basically:
* Step 1: create all your upload location in the CP for all sites
* Step 2: take the upload location id and configure all upload location
in your central config.php file for all sites. Since they all have
specific ids, no conflict problem whatsoever | If you want to override MSM settings then you should move this code into the index.php file of the sites respectively.
```
$assign_to_config['upload_preferences'] = array(
1 => array(
'name' => 'Images',
'server_path' => $uploads_path . "/images/",
'url' => $uploads_url . "/images/"
),
2 => array(
'name' => 'Files',
'server_path' => $uploads_path . "/files/",
'url' => $uploads_url . "/files/"
),
3 => array(
'name' => 'Icons',
'server_path' => $uploads_path . "/icons/",
'url' => $uploads_url . "/icons/"
)
);
```
Be mindful though, I've experienced a known bug where some values are set in the config of MSM sites but aren't reflected in the CP. |
71,595,153 | I made a simple 1 button LED dimmer and I would like to have the LED go back to full brightness after the button has not been touched for a set amount of time. But the code I came up with does not seem to be working as I cannot dim the LED
```
int buttonPin = 12;
int LEDPin = 3;
int buttonVal;
int LEDbright = 0;
int dt = 500;
int fdt = 60000;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
static unsigned long whenButtonWasTouchedMs = 0;
buttonVal = digitalRead(buttonPin);
Serial.print("Button = ");
Serial.print(buttonVal);
Serial.print(", ");
delay(dt);
if (buttonVal == 1) {
LEDbright = LEDbright + 20;
whenButtonWasTouchedMs = millis();
}
Serial.println(LEDbright);
//
if (LEDbright > 255) {
LEDbright = 255;
delay(dt);
}
unsigned long afterButtonWasTouchedMs = millis() - whenButtonWasTouchedMs;
if (afterButtonWasTouchedMs >= 60000) {
LEDbright = 0;
analogWrite(LEDPin, LEDbright);
}
}
``` | 2022/03/23 | [
"https://Stackoverflow.com/questions/71595153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14318258/"
] | Your question doesn't seem to line up with how the code was written. It looks like you want to do the opposite (have the light get brighter when the button is held down, and then switch off 60 seconds after the button was released).
Here's the code I came up with to help with your stated problem:
```
int buttonPin = 12;
int LEDPin = 3;
int buttonVal;
int whenButtonWasTouched;
unsigned int LEDbright = 255;
int dt = 500;
int fdt = 60000;
unsigned long whenButtonWasTouchedMs = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
//static unsigned long whenButtonWasTouchedMs = 0;
buttonVal = digitalRead(buttonPin);
Serial.print("Button = ");
Serial.print(buttonVal);
Serial.print(", ");
delay(dt);
if (buttonVal == 1) {
LEDbright = LEDbright - 20;
whenButtonWasTouchedMs = millis();
}
//
if (LEDbright < 20 || LEDbright > 255) { // The LEDbright > 255 part is because sometimes there can be an integer overflow if we don't keep this.
LEDbright = 0;
}
Serial.println(LEDbright);
unsigned long afterButtonWasTouchedMs = millis() - whenButtonWasTouched;
if (afterButtonWasTouchedMs >= 60000) {
LEDbright = 255;
}
analogWrite(LEDPin, LEDbright);
}
```
As you can see I changed it so that analogWrite is not in the if statement, it checks for integer overflows, and prints out the adjusted value for the led brightness. To make it grow brighter as the button is held and then switch off after 60 seconds just change the minus sign to a plus sign in the LEDbright adjustment line, and change some of the other values around. | ```
int buttonPin = 12;
int LEDPin = 3;
int buttonVal;
unsigned int LEDbright = 0;
int dt = 500;
int fdt = 60000;
unsigned long whenButtonWasTouchedMs = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
//static unsigned long whenButtonWasTouchedMs = 0;
buttonVal = digitalRead(buttonPin);
Serial.print("Button = ");
Serial.print(buttonVal);
Serial.print(", ");
delay(dt);
if (buttonVal == 1) {
LEDbright = LEDbright + 20;
whenButtonWasTouchedMs = millis();
}
if (LEDbright > 255) {
LEDbright = 255;
delay(dt);
}
Serial.println(LEDbright);
unsigned long afterButtonWasTouchedMs = millis() - whenButtonWasTouchedMs;
if (afterButtonWasTouchedMs >= 60000) {
LEDbright = 0;
}
analogWrite(LEDPin, LEDbright);
}
``` |
6,542,566 | How do you get last 3 words from the string?
I managed to get working doing like this:
```
$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;
```
Is there a shorter way? Maybe there is a PHP function that I did not know.. | 2011/07/01 | [
"https://Stackoverflow.com/questions/6542566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622378/"
] | explode() is good, but once you've done that you can use
```
$size = sizeof($statusMessage);
```
and last 3 are
```
$statusmessage[$size-1];
$statusmessage[$size-2];
$statusmessage[$size-3];
``` | ```
preg_match('#(?:\s\w+){3}$#', $statusMessage );
``` |
6,542,566 | How do you get last 3 words from the string?
I managed to get working doing like this:
```
$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;
```
Is there a shorter way? Maybe there is a PHP function that I did not know.. | 2011/07/01 | [
"https://Stackoverflow.com/questions/6542566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622378/"
] | explode() is good, but once you've done that you can use
```
$size = sizeof($statusMessage);
```
and last 3 are
```
$statusmessage[$size-1];
$statusmessage[$size-2];
$statusmessage[$size-3];
``` | preg\_match("/(?:\w+\s\*){1,3}$/", $input\_line, $output\_array);
this catches 1 to 3 words and if the row is only 3 long, other regex one was close |
6,542,566 | How do you get last 3 words from the string?
I managed to get working doing like this:
```
$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;
```
Is there a shorter way? Maybe there is a PHP function that I did not know.. | 2011/07/01 | [
"https://Stackoverflow.com/questions/6542566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/622378/"
] | ```
preg_match('#(?:\s\w+){3}$#', $statusMessage );
``` | preg\_match("/(?:\w+\s\*){1,3}$/", $input\_line, $output\_array);
this catches 1 to 3 words and if the row is only 3 long, other regex one was close |
64,037,433 | I have some code but I just found out it works on like 90% of the computers. Here is the distinguishedName:
*CN=2016-10-05T12:19:16-05:00{393DA5A5-4EEF-4394-90F7-CBD0D2F20CC9},CN=**Computer01-T2**,OU=Product,OU=Workstations,OU=KDUYA,DC=time,DC=local*
What I am trying to do is parse out just the ComputerName. 3 of the 27 OU we have use 3 letter Names instead of the 5 which all the other sites use. Ive been banging my head against the wall and reaching out for some help and or guidance. Watching some videos on regex understand the basics but still working on more complicated things like this.
Here is what I have. Any advice or help would be greatly appreciated.
```
let str = "CN=2016-10-05T12:19:16-05:00{393DA5A5-4EEF-4394-90F7-CBD0D2F20CC9},CN=Computer01-T2,OU=Product,OU=Workstations,OU=KDUYA,DC=time,DC=local";
str = str.substring(70, str.length -53);
console.log(str);+
``` | 2020/09/23 | [
"https://Stackoverflow.com/questions/64037433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12201298/"
] | I don't think they have support for geometry buffers at this stage. ST\_AREA isn't going to help you. Last I heard they are working on improving their geospatial support.
That said, can you buffer your data somewhere else in your workflow? Such as using shapely buffer in python, or turf circle/buffer in javascript? | As said above you can find all geospatial functions here: <https://docs.snowflake.com/en/sql-reference/functions-geospatial.html>
Regarding ST\_BUFFER I think the function ST\_AREA sounds good: <https://docs.snowflake.com/en/sql-reference/functions/st_area.html> |
3,402,360 | Given any bounded set $E$ in $\mathbb{R}^{N}$, is there a general way to choose a sequence $(G\_{n})$ of open sets such that $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise?
Here $\chi$ denotes the characteristic/indicator function on $E$.
One may think of $G\_{n}:=E+B(0,1/n)$, but we have instead that $\chi\_{G\_{n}}\downarrow\chi\_{\overline{E}}$ pointwise.
So if $E$ is closed, then it follows.
**As @TheoBendit has noted in the comment box that it is what $G\_{\delta}$ set is meant to be.**
So the answer is no.
Let me loose a little bit. What if I require only that $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise almost everywhere?
One may think of remove the boundary $\partial E$ of the set $E$, but note that the boundary need no to be of measure zero, for example, $\partial(\mathbb{Q}\cap[0,1])=[0,1]$.
I also hope to have something like $\chi\_{G\_{n}}\downarrow\chi\_{E}$ pointwise quasi-everywhere with respect to $\text{Cap}\_{\alpha,s}$.
Here I introduce briefly the definition of $\text{Cap}\_{\alpha,s}$.
For compact sets $K$, we let $\text{Cap}\_{\alpha,s}(K)=\inf\{\|\varphi\|\_{W^{\alpha,s}}^{s}:\varphi\geq 1~\text{on}~K\}$.
For open sets $G$, we let $\text{Cap}\_{\alpha,s}(G)=\sup\{\text{Cap}\_{\alpha,s}(K): K~\text{is compact in}~G\}$.
For arbitrary sets $E$, we let $\text{Cap}\_{\alpha,s}(E)=\inf\{\text{Cap}\_{\alpha,s}(G): G~\text{is open that contains}~E\}$. | 2019/10/21 | [
"https://math.stackexchange.com/questions/3402360",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/284331/"
] | Let $\mu$ denote Lebesgue measure on $\Bbb R^N. $
If $E$ is $\mu$-measurable then there exists a sequence $(G\_n)\_n$ of open sets such that $E\subset \cap\_nG\_n$ and $\mu(\,(\cap\_nG\_n)\setminus E\,)=0.$
Let $H\_n=\cap \{G\_j:j\le n\}.$
If $p\in E$ then $\chi\_{H\_n}(p)=1=\chi\_E(p)$ for all $n.$
If $p\not \in \cap\_n H\_n$ then $\{n:p\in H\_n\}$ is finite. So for all but finitely many $n$ we have $\chi\_{H\_n} (p)=0=\chi\_E(p).$
So if $\chi\_{H\_n}(p)$ does not converge to $\chi\_E(p)$ then $p\in (\cap\_nH\_n)\setminus E, $which is a set of measure $0.$ | For arbitrary bounded set $E$, then $\text{Cap}(E)<\infty$ and hence by outer regularity, we have $G\_{n}\supseteq E$ such that $\text{Cap}(E)\leq\text{Cap}(G\_{n})<\text{Cap}(E)+1/n$ for each $n=1,2,...$
Then $E\subseteq\displaystyle\bigcap\_{n}G\_{n}$. But $\text{Cap}\left(\displaystyle\bigcap\_{n}G\_{n}-E\right)+\text{Cap}\left(E\right)\geq\text{Cap}\left(\displaystyle\bigcap\_{n}G\_{n}\right)$, so the trick by @DanielWainfleet may fail for capacity case.
Nevertheless, if $\text{Cap}(E)=0$, then it follows:
Choosing decreasing $G\_{n}\supseteq E$ such that $\text{Cap}(G\_{n})<1/n$, then $\text{Cap}\left(\displaystyle\bigcap\_{n}G\_{n}-E\right)\leq\text{Cap}\left(\displaystyle\bigcap\_{n}G\_{n}\right)\leq\text{Cap}(G\_{n})<1/n$ for each $n=1,2,...$, so in this case, $\text{Cap}\left(\displaystyle\bigcap\_{n}G\_{n}-E\right)=0$.
The rest follows by the trick of @DanielWainfleet. |
10,663 | I received a new iPhone yesterday and connected it to my home Wifi network.
On content heavy sites it runs perfectly fine, but if I use either the Youtube site or the Youtube app I can't watch anything. It takes forever to watch 5 seconds of video.
My first question is, how can I be sure that my phone is using local Wifi for the internet connection and Youtube app (it says connected in the settings, but is there an icon in the display etc. to confirm Wifi connection)?
Any suggestions as to why Youtube runs slow when other heavy sites load without problem? | 2011/03/22 | [
"https://apple.stackexchange.com/questions/10663",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1434/"
] | Yes, you can have both versions. In fact you can install the new Firefox in your home directory's Application folder (and it will be only accessible with your account). If you don't have ~/Applications folder, you can create it (and Finder will mark it with the same icon as the /Applications one). Note that you cannot use both versions simultaneously. You can also rename the Firefox.app to Firefox 4.app, and install it in /Applications - it'll work flawlesly.
ps. I prefer the first method - Install applications that I'm testing in my home Applications folder, and when I'm sure they're ok, move them/replace application in /Applications. | [OS X: Install and Run Firefox 3 and Firefox 4 on the Same Computer | Mozilla Firefox | Tech-Recipes](http://www.tech-recipes.com/rx/2828/os_x_install_firefox_2_firefox_3_same_computer/)
Or just make copies of `~/Library/Preferences/org.mozilla.firefox.plist` and `~/Library/Application Support/Firefox/`. |
10,663 | I received a new iPhone yesterday and connected it to my home Wifi network.
On content heavy sites it runs perfectly fine, but if I use either the Youtube site or the Youtube app I can't watch anything. It takes forever to watch 5 seconds of video.
My first question is, how can I be sure that my phone is using local Wifi for the internet connection and Youtube app (it says connected in the settings, but is there an icon in the display etc. to confirm Wifi connection)?
Any suggestions as to why Youtube runs slow when other heavy sites load without problem? | 2011/03/22 | [
"https://apple.stackexchange.com/questions/10663",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1434/"
] | Yes, you can have both versions. In fact you can install the new Firefox in your home directory's Application folder (and it will be only accessible with your account). If you don't have ~/Applications folder, you can create it (and Finder will mark it with the same icon as the /Applications one). Note that you cannot use both versions simultaneously. You can also rename the Firefox.app to Firefox 4.app, and install it in /Applications - it'll work flawlesly.
ps. I prefer the first method - Install applications that I'm testing in my home Applications folder, and when I'm sure they're ok, move them/replace application in /Applications. | Once you install it in separate directories, you can in fact **run them both simultaneously**.
It just takes a little Firefox flags magic as explained here in [this article](http://www.shankrila.com/firefox/howto-run-firefox4-firefox3-simultaneously/). |
10,663 | I received a new iPhone yesterday and connected it to my home Wifi network.
On content heavy sites it runs perfectly fine, but if I use either the Youtube site or the Youtube app I can't watch anything. It takes forever to watch 5 seconds of video.
My first question is, how can I be sure that my phone is using local Wifi for the internet connection and Youtube app (it says connected in the settings, but is there an icon in the display etc. to confirm Wifi connection)?
Any suggestions as to why Youtube runs slow when other heavy sites load without problem? | 2011/03/22 | [
"https://apple.stackexchange.com/questions/10663",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/1434/"
] | [OS X: Install and Run Firefox 3 and Firefox 4 on the Same Computer | Mozilla Firefox | Tech-Recipes](http://www.tech-recipes.com/rx/2828/os_x_install_firefox_2_firefox_3_same_computer/)
Or just make copies of `~/Library/Preferences/org.mozilla.firefox.plist` and `~/Library/Application Support/Firefox/`. | Once you install it in separate directories, you can in fact **run them both simultaneously**.
It just takes a little Firefox flags magic as explained here in [this article](http://www.shankrila.com/firefox/howto-run-firefox4-firefox3-simultaneously/). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.