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
|
---|---|---|---|---|---|
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Since your asking for a canonical answer, here's an approach that avoids editing the provided object in-place, provides type hints, has a docstring, can be invoked with the `remove` parameter to remove different values, and errors with a `TypeError` as appropriate:
```
from collections import abc
from typing import Dict, List, Union
def without_nulls(d: Union[List, Dict], remove: tuple = ('NULL', 'null')) -> Union[List, Dict]:
""" Given a list or dict, returns an object of the same structure without null dict values. """
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if isinstance(d, collection_types):
return [without_nulls(x, remove) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: without_nulls(x, remove) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if v not in remove}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
Usage:
```
>>> cleaned_d = without_nulls(d)
>>> cleaned_d
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
>>> d # d is unchanged
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
```
If I wanted to have it remove `None` instead of `'NULL'`, I could call it like this:
```
without_nulls(d, remove=(None,))
```
---
Here's an even more generalized version - the sort of thing I'd expect to find in a general-purpose Python toolkit:
```
from collections import abc
from typing import Any, Callable, Dict, List, Optional, Union
def filter_dicts(d: Union[List, Dict],
value_filter: Optional[Callable[[Any], bool]] = None) -> Union[List, Dict]:
"""
Given a list or dict, returns an object of the same structure without filtered values.
By default, key-value pairs where the value is 'None' are removed. The `value_filter` param
must be a function which takes values from the provided dict/list structure, and returns a
truthy value if the key-value pair is to be removed, and a falsey value otherwise.
"""
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if value_filter is None:
value_filter = lambda x: x is None
if isinstance(d, collection_types):
return [filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if not value_filter(v)}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
We can use it like this:
```
>>> filter_dicts(d)
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
>>> filter_dicts(d) == d
True
>>> filter_dicts(d, lambda x: x in (None, 'NULL', 'null'))
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
The benefit of this version is that it allows the caller to completely customize what criteria is employed when removing values. The function handles traversing the structure, and building up a new one to be returned, while the caller gets to decide what gets removed. | **Solution:**
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
for element in list(d):
for key, value in element.copy().items():
if value == "NULL":
element.pop(key, None)
elif isinstance(value, dict):
for inner_key, inner_value in value.copy().items():
if inner_value == "NULL":
value.pop(inner_key, None)
elif isinstance(inner_value, dict):
for nested_inner_key, nested_inner_value in inner_value.copy().items():
if nested_inner_value == "NULL":
inner_value.pop(nested_inner_key, None)
print(d)
```
**Output:**
```
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
Doing `.copy()` of each dictionary / nested dictionary, else you'll end up with [this](https://stackoverflow.com/questions/10107676/python-runtimeerror-dictionary-changed-size-during-iteration) error.
Check out the same [here](https://onlinegdb.com/wYDUvPhFQ) also. |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | **Solution:**
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
for element in list(d):
for key, value in element.copy().items():
if value == "NULL":
element.pop(key, None)
elif isinstance(value, dict):
for inner_key, inner_value in value.copy().items():
if inner_value == "NULL":
value.pop(inner_key, None)
elif isinstance(inner_value, dict):
for nested_inner_key, nested_inner_value in inner_value.copy().items():
if nested_inner_value == "NULL":
inner_value.pop(nested_inner_key, None)
print(d)
```
**Output:**
```
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
Doing `.copy()` of each dictionary / nested dictionary, else you'll end up with [this](https://stackoverflow.com/questions/10107676/python-runtimeerror-dictionary-changed-size-during-iteration) error.
Check out the same [here](https://onlinegdb.com/wYDUvPhFQ) also. | >
> I am using Python 3.9, so it is possible to use walrus operator.
>
>
>
Well then, let's throw one in there since no one else did:
```
from collections import deque
def remove_null(thing):
if isinstance(thing, list):
deque(map(remove_null, thing), maxlen=0)
elif isinstance(thing, dict):
for key in thing.copy():
if (value := thing[key]) == 'NULL':
del thing[key]
else:
remove_null(value)
```
Note that I'm using `map` instead of a loop to show an alternative to the other answers. However, this creates the same situation that I commented on @AnnZen about, using an operation that returns a result and then ignoring it. To force the `map` lazy evaluation, I use an empty `deque` to consume it. |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Here is how you can do this with recursion:
```
def remove_null(d):
if isinstance(d, list):
for i in d:
remove_null(i)
elif isinstance(d, dict):
for k, v in d.copy().items():
if v == 'NULL':
d.pop(k)
else:
remove_null(v)
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
remove_null(d)
print(d)
```
Output:
```
[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]
``` | Since your asking for a canonical answer, here's an approach that avoids editing the provided object in-place, provides type hints, has a docstring, can be invoked with the `remove` parameter to remove different values, and errors with a `TypeError` as appropriate:
```
from collections import abc
from typing import Dict, List, Union
def without_nulls(d: Union[List, Dict], remove: tuple = ('NULL', 'null')) -> Union[List, Dict]:
""" Given a list or dict, returns an object of the same structure without null dict values. """
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if isinstance(d, collection_types):
return [without_nulls(x, remove) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: without_nulls(x, remove) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if v not in remove}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
Usage:
```
>>> cleaned_d = without_nulls(d)
>>> cleaned_d
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
>>> d # d is unchanged
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
```
If I wanted to have it remove `None` instead of `'NULL'`, I could call it like this:
```
without_nulls(d, remove=(None,))
```
---
Here's an even more generalized version - the sort of thing I'd expect to find in a general-purpose Python toolkit:
```
from collections import abc
from typing import Any, Callable, Dict, List, Optional, Union
def filter_dicts(d: Union[List, Dict],
value_filter: Optional[Callable[[Any], bool]] = None) -> Union[List, Dict]:
"""
Given a list or dict, returns an object of the same structure without filtered values.
By default, key-value pairs where the value is 'None' are removed. The `value_filter` param
must be a function which takes values from the provided dict/list structure, and returns a
truthy value if the key-value pair is to be removed, and a falsey value otherwise.
"""
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if value_filter is None:
value_filter = lambda x: x is None
if isinstance(d, collection_types):
return [filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if not value_filter(v)}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
We can use it like this:
```
>>> filter_dicts(d)
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
>>> filter_dicts(d) == d
True
>>> filter_dicts(d, lambda x: x in (None, 'NULL', 'null'))
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
The benefit of this version is that it allows the caller to completely customize what criteria is employed when removing values. The function handles traversing the structure, and building up a new one to be returned, while the caller gets to decide what gets removed. |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Here is how you can do this with recursion:
```
def remove_null(d):
if isinstance(d, list):
for i in d:
remove_null(i)
elif isinstance(d, dict):
for k, v in d.copy().items():
if v == 'NULL':
d.pop(k)
else:
remove_null(v)
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
remove_null(d)
print(d)
```
Output:
```
[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]
``` | >
> I am using Python 3.9, so it is possible to use walrus operator.
>
>
>
Well then, let's throw one in there since no one else did:
```
from collections import deque
def remove_null(thing):
if isinstance(thing, list):
deque(map(remove_null, thing), maxlen=0)
elif isinstance(thing, dict):
for key in thing.copy():
if (value := thing[key]) == 'NULL':
del thing[key]
else:
remove_null(value)
```
Note that I'm using `map` instead of a loop to show an alternative to the other answers. However, this creates the same situation that I commented on @AnnZen about, using an operation that returns a result and then ignoring it. To force the `map` lazy evaluation, I use an empty `deque` to consume it. |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Here is how you can do this with recursion:
```
def remove_null(d):
if isinstance(d, list):
for i in d:
remove_null(i)
elif isinstance(d, dict):
for k, v in d.copy().items():
if v == 'NULL':
d.pop(k)
else:
remove_null(v)
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
remove_null(d)
print(d)
```
Output:
```
[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]
``` | Maybe something like:
```
def remove_nulls(d):
res = {}
for k, v in d.items():
if v == "NULL":
continue
if isinstance(v, dict):
res[k] = remove_nulls(v)
else:
res[k] = v
return res
print([remove_nulls(d) for d in lt])
``` |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Since your asking for a canonical answer, here's an approach that avoids editing the provided object in-place, provides type hints, has a docstring, can be invoked with the `remove` parameter to remove different values, and errors with a `TypeError` as appropriate:
```
from collections import abc
from typing import Dict, List, Union
def without_nulls(d: Union[List, Dict], remove: tuple = ('NULL', 'null')) -> Union[List, Dict]:
""" Given a list or dict, returns an object of the same structure without null dict values. """
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if isinstance(d, collection_types):
return [without_nulls(x, remove) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: without_nulls(x, remove) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if v not in remove}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
Usage:
```
>>> cleaned_d = without_nulls(d)
>>> cleaned_d
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
>>> d # d is unchanged
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
```
If I wanted to have it remove `None` instead of `'NULL'`, I could call it like this:
```
without_nulls(d, remove=(None,))
```
---
Here's an even more generalized version - the sort of thing I'd expect to find in a general-purpose Python toolkit:
```
from collections import abc
from typing import Any, Callable, Dict, List, Optional, Union
def filter_dicts(d: Union[List, Dict],
value_filter: Optional[Callable[[Any], bool]] = None) -> Union[List, Dict]:
"""
Given a list or dict, returns an object of the same structure without filtered values.
By default, key-value pairs where the value is 'None' are removed. The `value_filter` param
must be a function which takes values from the provided dict/list structure, and returns a
truthy value if the key-value pair is to be removed, and a falsey value otherwise.
"""
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if value_filter is None:
value_filter = lambda x: x is None
if isinstance(d, collection_types):
return [filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if not value_filter(v)}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
We can use it like this:
```
>>> filter_dicts(d)
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
>>> filter_dicts(d) == d
True
>>> filter_dicts(d, lambda x: x in (None, 'NULL', 'null'))
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
The benefit of this version is that it allows the caller to completely customize what criteria is employed when removing values. The function handles traversing the structure, and building up a new one to be returned, while the caller gets to decide what gets removed. | >
> I am using Python 3.9, so it is possible to use walrus operator.
>
>
>
Well then, let's throw one in there since no one else did:
```
from collections import deque
def remove_null(thing):
if isinstance(thing, list):
deque(map(remove_null, thing), maxlen=0)
elif isinstance(thing, dict):
for key in thing.copy():
if (value := thing[key]) == 'NULL':
del thing[key]
else:
remove_null(value)
```
Note that I'm using `map` instead of a loop to show an alternative to the other answers. However, this creates the same situation that I commented on @AnnZen about, using an operation that returns a result and then ignoring it. To force the `map` lazy evaluation, I use an empty `deque` to consume it. |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Since your asking for a canonical answer, here's an approach that avoids editing the provided object in-place, provides type hints, has a docstring, can be invoked with the `remove` parameter to remove different values, and errors with a `TypeError` as appropriate:
```
from collections import abc
from typing import Dict, List, Union
def without_nulls(d: Union[List, Dict], remove: tuple = ('NULL', 'null')) -> Union[List, Dict]:
""" Given a list or dict, returns an object of the same structure without null dict values. """
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if isinstance(d, collection_types):
return [without_nulls(x, remove) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: without_nulls(x, remove) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if v not in remove}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
Usage:
```
>>> cleaned_d = without_nulls(d)
>>> cleaned_d
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
>>> d # d is unchanged
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
```
If I wanted to have it remove `None` instead of `'NULL'`, I could call it like this:
```
without_nulls(d, remove=(None,))
```
---
Here's an even more generalized version - the sort of thing I'd expect to find in a general-purpose Python toolkit:
```
from collections import abc
from typing import Any, Callable, Dict, List, Optional, Union
def filter_dicts(d: Union[List, Dict],
value_filter: Optional[Callable[[Any], bool]] = None) -> Union[List, Dict]:
"""
Given a list or dict, returns an object of the same structure without filtered values.
By default, key-value pairs where the value is 'None' are removed. The `value_filter` param
must be a function which takes values from the provided dict/list structure, and returns a
truthy value if the key-value pair is to be removed, and a falsey value otherwise.
"""
collection_types = (list, tuple) # avoid including 'str' here
mapping_types = (abc.Mapping,)
all_supported_types = (*mapping_types, *collection_types)
if value_filter is None:
value_filter = lambda x: x is None
if isinstance(d, collection_types):
return [filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x for x in d]
elif isinstance(d, mapping_types):
clean_val = lambda x: filter_dicts(x, value_filter) if isinstance(x, all_supported_types) else x
return {k: clean_val(v) for k, v in d.items() if not value_filter(v)}
raise TypeError(f"Unsupported type '{type(d)}': {d!r}")
```
We can use it like this:
```
>>> filter_dicts(d)
[{'key1': 'value1', 'key2': {'key3': 'value3', 'key4': 'NULL', 'z': {'z1': 'NULL', 'z2': 'zzz'}}, 'key5': 'NULL'}, {'KEY': 'NULL', 'AAA': 'BBB'}]
>>> filter_dicts(d) == d
True
>>> filter_dicts(d, lambda x: x in (None, 'NULL', 'null'))
[{'key1': 'value1', 'key2': {'key3': 'value3', 'z': {'z2': 'zzz'}}}, {'AAA': 'BBB'}]
```
The benefit of this version is that it allows the caller to completely customize what criteria is employed when removing values. The function handles traversing the structure, and building up a new one to be returned, while the caller gets to decide what gets removed. | Maybe something like:
```
def remove_nulls(d):
res = {}
for k, v in d.items():
if v == "NULL":
continue
if isinstance(v, dict):
res[k] = remove_nulls(v)
else:
res[k] = v
return res
print([remove_nulls(d) for d in lt])
``` |
67,806,380 | I have an array of complex *dict* that have some value as a string "NULL" and I want to remove, my dict looks like this:
```
d = [{
"key1": "value1",
"key2": {
"key3": "value3",
"key4": "NULL",
"z": {
"z1": "NULL",
"z2": "zzz",
},
},
"key5": "NULL"
}, {
"KEY": "NULL",
"AAA": "BBB",
}]
```
And I want to wipe out all keys that have **NULL** as value
Like this:
`[{"key1": "value1", "key2": {"key3": "value3", "z": {"z2": "zzz"}}}, {"AAA": "BBB"}]`
I am using Python 3.9, so it is possible to use walrus operator. | 2021/06/02 | [
"https://Stackoverflow.com/questions/67806380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832490/"
] | Maybe something like:
```
def remove_nulls(d):
res = {}
for k, v in d.items():
if v == "NULL":
continue
if isinstance(v, dict):
res[k] = remove_nulls(v)
else:
res[k] = v
return res
print([remove_nulls(d) for d in lt])
``` | >
> I am using Python 3.9, so it is possible to use walrus operator.
>
>
>
Well then, let's throw one in there since no one else did:
```
from collections import deque
def remove_null(thing):
if isinstance(thing, list):
deque(map(remove_null, thing), maxlen=0)
elif isinstance(thing, dict):
for key in thing.copy():
if (value := thing[key]) == 'NULL':
del thing[key]
else:
remove_null(value)
```
Note that I'm using `map` instead of a loop to show an alternative to the other answers. However, this creates the same situation that I commented on @AnnZen about, using an operation that returns a result and then ignoring it. To force the `map` lazy evaluation, I use an empty `deque` to consume it. |
35,783,817 | I am programming an application that is non-modal dialog based. I am using the Visual Studio resource editor to build the dialog and create the application. Everything is going great so far. However, I have reached a brick wall when it comes to handling keyboard input. My research has shown that windows captures keyboard input before it reaches the dialog callback procedure to implement the ability to move the focus using the keyboard.
I created a bare bones dialog to test this and, when I have a dialog without any controls on it, everything works as I would expect it to. When I add a control, it stops working.
Here is the code from the bare bones project:
```
#include <Windows.h>
#include <CommCtrl.h>
#include <tchar.h>
#include "resource.h"
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
HWND dlghandle;
int WINAPI _tWinMain(HINSTANCE hInst, HINSTANCE h0, LPTSTR lpCmdLine, int nCmdShow)
{
HWND hDlg;
MSG msg;
BOOL ret;
hDlg = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_DIALOG1), 0, DialogProc, 0);
ShowWindow(hDlg, nCmdShow);
dlghandle = hDlg;
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
if (ret == -1)
return -1;
if (!IsDialogMessage(hDlg, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_KEYDOWN:
MessageBox(NULL, L"Test", L"Test", MB_OK);
break;
case WM_CLOSE:
DestroyWindow(hDlg);
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;
}
return 0;
}
```
What options do I have? | 2016/03/03 | [
"https://Stackoverflow.com/questions/35783817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1813678/"
] | The first place keyboard input appears is your message loop, so just check for the keypress you're looking for before passing it off to `IsDialogMessage()` / `TranslateMessage()` / `DispatchMessage()`. For example:
```
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
if (ret == -1)
return -1;
if (msg.message == WM_KEYDOWN && msg.wParam == 'Q')
{
// trap and handle the Q key no matter which control has focus
}
else
if (!IsDialogMessage(hDlg, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
```
If you wanted you could even wrap this in a function to make it neater, e.g.:
```
#define MYMSG_DOSOMETHING (WM_APP + 1)
BOOL MyIsDialogMessage(HWND hDlg, MSG* pMsg)
{
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == 'Q')
{
PostMessage(hDlg, MYMSG_DOSOMETHING, 0, 0);
return TRUE;
}
return IsDialogMessage(hDlg, pMsg);
}
// then your message loop would be:
while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
if (ret == -1)
return -1;
if (!MyIsDialogMessage(hDlg, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
``` | You could also use **SetWindowsHook** to create low level keyboard proc.
**NOTE** this looks a bit complex and advanced but it works great with Dialogs without doing any extra effort to message loop.
```
HHOOK g_hLowLevelKeyHook;
//windows Main.
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
g_hLowLevelKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), NULL);
........
.......
}
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
KBDLLHOOKSTRUCT *pkbhs = (KBDLLHOOKSTRUCT *)lParam;
if (nCode == HC_ACTION && wParam == WM_KEYUP)
{
if (pkbhs->vkCode == VK_F1)
MessageBoxA(NULL"F1 Pressed","INFO",MB_ICONINFORMATION);
}
return CallNextHookEx(g_hLowLevelKeyHook, nCode, wParam, lParam);
}
``` |
36,278,293 | I'm using `templateRest` to post `User` object to `Rest Server` but I encoutered the following error:
>
> Exception in thread "main" java.lang.NoClassDefFoundError:
> com/fasterxml/jackson/core/JsonProcessingException at
> edu.java.spring.service.client.RestClientTest.main(RestClientTest.java:33)
> Caused by: java.lang.ClassNotFoundException:
> com.fasterxml.jackson.core.JsonProcessingException at
> java.net.URLClassLoader.findClass(Unknown Source) at
> java.lang.ClassLoader.loadClass(Unknown Source) at
> sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at
> java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more
>
>
>
Here is the file `RestClientTest.java`
```
public class RestClientTest {
public static void main(String[] args) throws IOException{
RestTemplate rt = new RestTemplate();
// System.out.println("Rest Response" + loadUser("quypham"));
// URL url = new URL("http://localhost:8080/rest/user/create");
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
// Map<String,String> vars = new HashMap<String,String>();
User user = new User();
user.setUserName("datpham");
user.setPassWord("12345");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,1960);
user.setBirthDay(calendar.getTime());
user.setAge(12);
String uri = new String("http://localhost:8080/rest/user/create");
User returns = rt.postForObject(uri, user,User.class);
// createUser(user);
System.out.println("Rest Response" + loadUser("datpham"));
}
```
Here is the file `UserRestServiceController.java`
```
@Controller
public class UserRestServiceController {
@Autowired
public UserDao userDao;
@RequestMapping(value = "/rest/user/create",method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void addUser(@RequestBody User user){
userDao.save(user);
}
```
Here is the file pom.xml
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.java.spring.service</groupId>
<artifactId>springDAT-service</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springDAT-service Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.12.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>springMOTHER-service</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12.4</version>
<configuration>
<skipTests>true</skipTests>
<argLine>-Xmx2524m</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<fork>true</fork>
<compilerArgs>
<arg>-XDignore.symbol.file</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.0.M1</version>
<configuration>
<jvmArgs>-Xmx1048m -Xms536m
-XX:PermSize=128m -XX:MaxPermSize=512m</jvmArgs>
<reload>manual</reload>
<systemProperties>
<systemProperty>
<name>lib</name>
<value>${basedir}/target/spring-mvc/WEB-INF/lib</value>
</systemProperty>
</systemProperties>
<scanIntervalSeconds>3</scanIntervalSeconds>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<contextPath>/</contextPath>
<webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory>
<webXml>${basedir}/src/main/webapp/WEB-INF/web.xml</webXml>
<classesDirectory>${basedir}/target/classes</classesDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
I have browsed information on google, afterwards I have tried to add jackson 2.4 in pom.xml but didn't seem to work:
```
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.0-rc3</version>
</dependency>
``` | 2016/03/29 | [
"https://Stackoverflow.com/questions/36278293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5957380/"
] | Add this :
```
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
```
You can replace `${jackson.version}` with any version you want,or just add `<jackson.version>2.x.x</jackson.version>`at top of your pom.xml
p/s:Mine is version `2.7.3` | Try add to your pom.xml
```
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
``` |
5,126,633 | When I run rspec 2 with rails 3 I use
```
rake rspec
```
sometimes I'd like to use a different formatter, perhaps doc.
```
rake rspec --format doc
```
but unfortunately the option doesn't make it through to the rspec runner. How can I choose a different format when I run the command? | 2011/02/26 | [
"https://Stackoverflow.com/questions/5126633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162337/"
] | You can add default options to an .rspec file in the rails root folder. e.g.
```
--colour
--format documentation
``` | You can also skip rake and use the rspec command directly. In this case the --format option can be used to tell RSpec how to format the output, "documentation" (or "doc") and "progress" are valid options:
```
rspec spec --format doc
```
This is especially useful if you want to run a single test/spec file
```
rspec spec/models/your_model.rb --format doc
``` |
14,692 | I found this sentence on the internet:
>
> Seems like society **leveled itself out** once again.
>
>
>
What does *level out* mean here? I have looked up OALD, and it defines *level out/off* as:
>
> level off/out
>
> 1 to stop rising or falling and remain horizontal.
>
> *The plane levelled off at 1500 feet.*
>
> *After the long hill, the road levelled out.*
>
> 2 to stay at a steady level of development or progress after a period of sharp rises or falls.
>
> *Sales have levelled off after a period of rapid growth.*
>
>
>
However, I'm not quite sure whether either of them fits the context. | 2013/12/20 | [
"https://ell.stackexchange.com/questions/14692",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1473/"
] | (To)Level out stands for work on an area to make it even, smooth and free of indents, dents or dings.
Figuratively, if some person or group levels out, it comes ahead of its shortcomings, no more ups and downs, and it can have a smooth riding future. | I couldn't find OALD, but I believe that the online [Oxford Dictionary](http://www.oxforddictionaries.com/definition/english/level) should be close enough. A similar definition for ***level out***/***off*** can be found under *verb* sense 2.
>
> 2 [*no object*] (**level off/out**) begin to fly horizontally after climbing or diving:
>
> *he quickly levelled off at 1500 ft*
>
> - (of a path, road, or incline) cease to slope:
>
> *the track levelled out and there below us was the bay*
>
> - remain at a steady level after falling or rising:
>
> *inflation has levelled out at an acceptable rate*
>
>
>
This definition is for **level out** being used as an intransitive verb (denoted by [*no object*]), which is quite different from your quoted sentence:
>
> *"Seems like **society leveled itself out** once again."*
>
>
>
where sense 1 (give a flat and even surface to) and sense 3 (make [something, especially a score in sport] equal or similar) are more relevant.
Thus, the phrase ***society leveled itself out*** should not be understood as the society has changed its direction to continue at a steady level. (It might be possible if it were about the future direction of economy.) In this context, it just means: ***everyone has an equal chance***. |
415,877 | I followed some advice I found here for a replacement for Disk Inventory X
[OSX disk space shows 200GB as "other"](https://apple.stackexchange.com/questions/388549/osx-disk-space-shows-200gb-as-other#answer-388581)
I installed the DaisyDisk app and it worked very well, however now my machine is constantly overheating and mds\_stores is consuming 99% of the cpu.
DaisyDisk does not appear in the Applications folder.
How do I uninstall it? Does anyone know? They don't have any information on their website. I should have been more careful.
<https://daisydiskapp.com/> | 2021/03/16 | [
"https://apple.stackexchange.com/questions/415877",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/131099/"
] | You may want to reinstall it and use "[AppCleaner](http://freemacsoft.net/appcleaner/)" to properly remove it and all of its remnants. | If you installed it from the App Store you can delete it from LaunchPad or Finder. Finder moving it to trash works for the direct download version of the app. Spotlight should reveal the location of the app in most cases. |
12,421,312 | I am getting error when using load data to insert the query .
```
"load data infile '/home/bharathi/out.txt' into table Summary"
```
This file is there in the location . But mysql throws the below error .
**ERROR 29 (HY000): File '/home/bharathi/out.txt' not found (Errcode: 13)**
```
show variables like 'data%';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
```
Data Dir is pointing to root permissioned folder . I can't change this variable because it's readonly .
How can I do the load data infile operation ?
I tried changing file permissions , load data local infile . It wont work . | 2012/09/14 | [
"https://Stackoverflow.com/questions/12421312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449101/"
] | As documented under [`LOAD DATA INFILE` Syntax](http://dev.mysql.com/doc/en/load-data.html):
>
> For security reasons, when reading text files located on the server, the files must either reside in the database directory or be readable by all. Also, to use [`LOAD DATA INFILE`](http://dev.mysql.com/doc/en/load-data.html) on server files, you must have the [`FILE`](http://dev.mysql.com/doc/en/privileges-provided.html#priv_file) privilege. See [Section 6.2.1, “Privileges Provided by MySQL”](http://dev.mysql.com/doc/en/privileges-provided.html). For non-`LOCAL` load operations, if the [`secure_file_priv`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_secure_file_priv) system variable is set to a nonempty directory name, the file to be loaded must be located in that directory.
>
>
>
You should therefore either:
* Ensure that your MySQL user has the `FILE` privilege and, assuming that the `secure_file_priv` system variable is not set:
+ make the file readable by all; or
+ move the file into the database directory.
* Or else, use the `LOCAL` keyword to have the file read by your client and transmitted to the server. However, note that:
>
> `LOCAL` works only if your server and your client both have been configured to permit it. For example, if [*`mysqld`*](http://dev.mysql.com/doc/en/mysqld.html) was started with [`--local-infile=0`](http://dev.mysql.com/doc/en/server-system-variables.html#sysvar_local_infile), `LOCAL` does not work. See [Section 6.1.6, “Security Issues with `LOAD DATA LOCAL`”](http://dev.mysql.com/doc/en/load-data-local.html).
>
>
> | The solution which really worked for me was to:
```
sudo chown mysql:mysql /path/to/the/file/to/be/read.csv
```
Adding it for future reference. |
117,931 | I can add custom fields to the user registration form, if I add the fields to the user profile: admin/config/people/accounts/fields
There is a checkbox "Show on user registraion" which is inactive:

The checkbox only gets active if I check "Mandatory field", but some of the fields must not be mandatory. Is that a bug? Is there a workaround (without using module 'Profil2') ?
I'm using Drupal Core 7.28 | 2014/06/11 | [
"https://drupal.stackexchange.com/questions/117931",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/17039/"
] | I have never encountered such problem before. But since you have such problem then I think the best way is to write a hook\_form\_alter. And set the required field that you don't want as mandatory to false.
```
function mymodule_form_alter(&$form, $form_state, $form_id){
switch ($form_id) {
case 'registration_form_id':
$form['field_name']['und'][0]['value']['#required'] = FALSE;
break;
}
}
```
Hope this helps. | It sounds like something is missing. Both of those options can be found on the field edit page. Both are usually available for checking. However, when you check the 'Required field' option, the 'Display on user registration form' option gets an automatic check and locked (making it virtually impossible to un-check it.) Otherwise when the 'required' option is not checked, the 'Display on user registration form' option should be completely accessible (not automatically checked and available for checking.) If this option is not available (when the 'required' option is not checked,) there may be something wrong with your Drupal Installation. |
73,248,935 | ```
public Void traverseQuickestRoute(){ // Void return-type from interface
findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.ifPresent(this::walkThroughForestPath) // return in this case
if(isBikePresent()){
return cycleQuickestRoute()
}
....
}
```
Is there a way to exit the method at the `ifPresent`?
In case it is not possible, for other people with similar use-cases: I see two alternatives
```
Optional<MappedRoute> woodsShortCut = findShortCutThroughWoods();
if(woodsShortCut.isPresent()){
TerrainDifficulty terrainDifficulty = woodsShortCut.get().getTerrainDifficulty();
return walkThroughForrestPath(terrainDifficulty);
}
```
This feels more ugly than it needs to be and combines if/else with functional programming.
A chain of `orElseGet(...)` throughout the method does not look as nice, but is also a possibility. | 2022/08/05 | [
"https://Stackoverflow.com/questions/73248935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321414/"
] | `return` is a control statement. Neither lambdas (arrow notation), nor method refs (`WoodsShortcut::getTerrainDifficulty`) support the idea of control statements that move control to outside of themselves.
Thus, the answer is a rather trivial: Nope.
You have to think of the stream 'pipeline' as the thing you're working on. So, the question could be said differently: Can I instead change this code so that I can modify how this one pipeline operation works (everything starting at `findShortCut()` to the semicolon at the end of all the method invokes you do on the stream/optional), and then make this one pipeline operation the whole method.
Thus, the answer is: **`orElseGet` is probably it.**
Disappointing, perhaps. 'functional' does not strike me as the right answer here. The problem is, there are things for/if/while loops can do that 'functional' cannot do. So, if you are faced with a problem that is simpler to tackle using 'a thing that for/if/while is good at but functional is bad at', then it is probably a better plan to just use for/if/while then.
One of the core things lambdas can't do are about the transparencies. Lambdas are non-transparant in regards to these 3:
* Checked exception throwing. `try { list.forEach(x -> throw new IOException()); } catch (IOException e) {}` isn't legal even though your human brain can trivially tell it should be fine.
* (Mutable) local variables. `int x = 5; list.forEach(y -> x += y);` does not work. Often there are ways around this (`list.mapToInt(Integer::intValue).sum()` in this example), but not always.
* Control flow. `list.forEach(y -> {if (y < 0) return y;});` does not work.
So, keep in mind, you really have only 2 options:
* Continually retrain yourself to not think in terms of such control flow. You find `orElseGet` 'not as nice'. I concur, but if you really want to blanket apply functional to as many places as you can possibly apply it, the whole notion of control flow out of a lambda needs not be your go-to plan, and you definitely can't keep thinking 'this code is not particularly nice because it would be simpler if I could control flow out', you're going to be depressed all day programming in this style. The day you never even think about it anymore is the day you have succeeded in retraining yourself to 'think more functional', so to speak.
* Stop thinking that 'functional is always better'. Given that there are so many situations where their downsides are so significant, perhaps it is not a good idea to pre-suppose that the lambda/methodref based solution must somehow be superior. Apply what seems correct. That should often be "Actually just a plain old for loop is fine. Better than fine; it's the right, most elegant1 answer here".
[1] "This code is elegant" is, of course, a non-falsifiable statement. It's like saying "The Mona Lisa is a pretty painting". You can't make a logical argument to prove this and it is insanity to try. "This code is elegant" boils down to saying "*I* think it is prettier", it cannot boil down to an objective fact. That also means in team situations there's no point in debating such things. Either everybody gets to decide what 'elegant' is (hold a poll, maybe?), or you install a dictator that decrees what elegance is. If you want to fix that and have meaningful debate, the term 'elegant' needs to be defined in terms of objective, falsifiable statements. I would posit that things like:
* in face of expectable future change requests, this style is easier to modify
* A casual glance at code leaves a first impression. Whichever style has the property that this first impression is accurate - is better (in other words, code that confuses or misleads the casual glancer is bad). Said even more differently: Code that really needs comments to avoid confusion is worse than code that is self-evident.
* this code looks familiar to a wide array of java programmers
* this code consists of fewer AST nodes (the more accurate from of 'fewer lines = better')
* this code has simpler semantic hierarchy (i.e. fewer indents)
Those are the kinds of things that should *define* 'elegance'. Under almost all of those definitions, 'an `if` statement' is as good or better in this specific case! | For example:
```
public Void traverseQuickestRoute() {
return findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.map(this::walkThroughForestPath)
.orElseGet(() -> { if (isBikePresent()) { return cycleQuickestRoute(); } });
}
``` |
73,248,935 | ```
public Void traverseQuickestRoute(){ // Void return-type from interface
findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.ifPresent(this::walkThroughForestPath) // return in this case
if(isBikePresent()){
return cycleQuickestRoute()
}
....
}
```
Is there a way to exit the method at the `ifPresent`?
In case it is not possible, for other people with similar use-cases: I see two alternatives
```
Optional<MappedRoute> woodsShortCut = findShortCutThroughWoods();
if(woodsShortCut.isPresent()){
TerrainDifficulty terrainDifficulty = woodsShortCut.get().getTerrainDifficulty();
return walkThroughForrestPath(terrainDifficulty);
}
```
This feels more ugly than it needs to be and combines if/else with functional programming.
A chain of `orElseGet(...)` throughout the method does not look as nice, but is also a possibility. | 2022/08/05 | [
"https://Stackoverflow.com/questions/73248935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321414/"
] | `return` is a control statement. Neither lambdas (arrow notation), nor method refs (`WoodsShortcut::getTerrainDifficulty`) support the idea of control statements that move control to outside of themselves.
Thus, the answer is a rather trivial: Nope.
You have to think of the stream 'pipeline' as the thing you're working on. So, the question could be said differently: Can I instead change this code so that I can modify how this one pipeline operation works (everything starting at `findShortCut()` to the semicolon at the end of all the method invokes you do on the stream/optional), and then make this one pipeline operation the whole method.
Thus, the answer is: **`orElseGet` is probably it.**
Disappointing, perhaps. 'functional' does not strike me as the right answer here. The problem is, there are things for/if/while loops can do that 'functional' cannot do. So, if you are faced with a problem that is simpler to tackle using 'a thing that for/if/while is good at but functional is bad at', then it is probably a better plan to just use for/if/while then.
One of the core things lambdas can't do are about the transparencies. Lambdas are non-transparant in regards to these 3:
* Checked exception throwing. `try { list.forEach(x -> throw new IOException()); } catch (IOException e) {}` isn't legal even though your human brain can trivially tell it should be fine.
* (Mutable) local variables. `int x = 5; list.forEach(y -> x += y);` does not work. Often there are ways around this (`list.mapToInt(Integer::intValue).sum()` in this example), but not always.
* Control flow. `list.forEach(y -> {if (y < 0) return y;});` does not work.
So, keep in mind, you really have only 2 options:
* Continually retrain yourself to not think in terms of such control flow. You find `orElseGet` 'not as nice'. I concur, but if you really want to blanket apply functional to as many places as you can possibly apply it, the whole notion of control flow out of a lambda needs not be your go-to plan, and you definitely can't keep thinking 'this code is not particularly nice because it would be simpler if I could control flow out', you're going to be depressed all day programming in this style. The day you never even think about it anymore is the day you have succeeded in retraining yourself to 'think more functional', so to speak.
* Stop thinking that 'functional is always better'. Given that there are so many situations where their downsides are so significant, perhaps it is not a good idea to pre-suppose that the lambda/methodref based solution must somehow be superior. Apply what seems correct. That should often be "Actually just a plain old for loop is fine. Better than fine; it's the right, most elegant1 answer here".
[1] "This code is elegant" is, of course, a non-falsifiable statement. It's like saying "The Mona Lisa is a pretty painting". You can't make a logical argument to prove this and it is insanity to try. "This code is elegant" boils down to saying "*I* think it is prettier", it cannot boil down to an objective fact. That also means in team situations there's no point in debating such things. Either everybody gets to decide what 'elegant' is (hold a poll, maybe?), or you install a dictator that decrees what elegance is. If you want to fix that and have meaningful debate, the term 'elegant' needs to be defined in terms of objective, falsifiable statements. I would posit that things like:
* in face of expectable future change requests, this style is easier to modify
* A casual glance at code leaves a first impression. Whichever style has the property that this first impression is accurate - is better (in other words, code that confuses or misleads the casual glancer is bad). Said even more differently: Code that really needs comments to avoid confusion is worse than code that is self-evident.
* this code looks familiar to a wide array of java programmers
* this code consists of fewer AST nodes (the more accurate from of 'fewer lines = better')
* this code has simpler semantic hierarchy (i.e. fewer indents)
Those are the kinds of things that should *define* 'elegance'. Under almost all of those definitions, 'an `if` statement' is as good or better in this specific case! | There is `Optional#ifPresentOrElse` with an extra `Runnable` for the *else* case. Since java 9.
```
public Void traverseQuickestRoute() { // Void return-type from interface
findShortCutThroughWoods()
.map(WoodsShortCut::getTerrainDifficulty)
.ifPresentOrElse(this::walkThroughForestPath,
this::alternative);
return null;
}
private void alternative() {
if (isBikePresent()) {
return cycleQuickestRoute()
}
...
}
```
I would split the method as above. Though for short code `() -> { ... }` might be readable. |
17,429,280 | I want to detect the edges on the serial data signal (din). I have written the following code in VHDL which is running successfully but the edges are detected with one clock period delay i.e change output is generated with one clk\_50mhz period delay at each edge. Could anyone please help me to detect edges without delay. Thank you.
```
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if (rst = '0') then
shift_reg <= (others => '0');
else
shift_reg(1) <= shift_reg(0);
shift_reg(0) <= din;
end if;
end if;
end process;
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if rst = '0' then
change <= '0' ;
elsif(clk_enable_2mhz = '1') then
change <= shift_reg(0) xor shift_reg(1);
end if ;
end if ;
end process ;
```
When I changed my code to following I am able to detect the edges
```
process (clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
if (RST = '0') then
shift_reg <= (others=>'0');
else
shift_reg(1) <= shift_reg(0);
shift_reg(0) <= din;
end if;
end if;
end process;
change <= shift_reg(1) xor din;
``` | 2013/07/02 | [
"https://Stackoverflow.com/questions/17429280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2463272/"
] | Here you go
```
library ieee;
use ieee.std_logic_1164.all;
entity double_edge_detector is
port (
clk_50mhz : in std_logic;
rst : in std_logic;
din : in std_logic;
change : out std_logic
);
end double_edge_detector;
architecture bhv of double_edge_detector is
signal din_delayed1 :std_logic;
begin
process(clk_50mhz)
begin
if rising_edge(clk_50mhz) then
if rst = '1' then
din_delayed1 <= '0';
else
din_delayed1 <= din;
end if;
end if;
end process;
change <= (din_delayed1 xor din); --rising or falling edge (0 -> 1 xor 1 -> 0)
end bhv;
``` | You have to use a combinatorial process to detect the difference without incurring extra clock cycle delays. (You will still need one register to delay the input as well.)
```
DELAY: process(clk_50mhz)
begin
if clk_50mhz'event and clk_50mhz = '1' then
din_reg <= din;
end if;
end process;
change <= din xor din_reg;
``` |
43,979,701 | In preview all good, but when I compiling, there is no image. If problem in source, so why it is showing in preview window?


```
<Grid>
<!-- Grid 4x3 -->
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="0.5*"></RowDefinition>
<RowDefinition Height="0.5*"></RowDefinition>
<RowDefinition Height="0.7*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.2*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="0.2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<!-- Controls -->
<!-- Row №1-->
<Image Grid.Row="0" Grid.Column="1" Source="pack://siteoforigin:,,,/Resources/logo.png"></Image>
<!-- Row №2-3 -->
<StackPanel Grid.Row="1" Grid.Column="1" Grid.RowSpan="2">
<Label Content="Вы заходите как..."></Label>
<ComboBox>
<ComboBoxItem Content="Клиент"></ComboBoxItem>
<ComboBoxItem Content="Сотрудник"></ComboBoxItem>
</ComboBox>
<Label Content="ID"></Label>
<TextBox></TextBox>
<Label Content="Пароль"></Label>
<PasswordBox></PasswordBox>
</StackPanel>
<!-- Row №4 -->
</Grid>
``` | 2017/05/15 | [
"https://Stackoverflow.com/questions/43979701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6677766/"
] | Seems that the image you specified is not copied to the output directory. You can resolve the issue in two ways:
1) In the property grid set Build Action to "None" and Copy to Output Directory to "Copy always" (you need to do this because the siteoforigin URI seeks the resource in the binary file location)
2) Set the Build Action property to "Resource" and use the `pack://application` absolute URI or the relative URI (like this: `<Image Source="Resources/logo.png"/>` ) | Try to set source as this and see if it solve your problem.
```
<Image Source="/MonFitClub;component/Resources/logo.png"/>
```
where if i did see corectly `MonFitClub` is name od your Project. |
47,148,128 | this problem is driving me nuts. I have a test server and a live server. The test server is showing unicode characters retrieved from an Azure sql database correctly. While the live server running identical code accessing the same data is not showing them correctly.
The data in the database is:
Hallo ich heiße Pokémon! Ich würde gerne mal mit einem anderen Kämpfe!
The test servers shows
Hallo ich heiße Pokémon! Ich würde etc...
The live server, which is an Azure web service shows
Hallo ich hei�e Pok�mon! Ich w�rde gerne mal mit einem anderen K�mpfe
Same PHP code, Same database, Same browser, same db connection string,
different web servers, different results.
I do know Azure is running PHP 5.6 and the test server is running PHP 5.3
They are using sqlsrv\_connect
The data field is type varchar.
I tried using "CharacterSet" => "UTF-8" in the connection but this made no difference to the Azure server and screwed up the result on the test server.
I am out of ideas and leads. | 2017/11/07 | [
"https://Stackoverflow.com/questions/47148128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556436/"
] | Edit: After searching stackoverflow, here is a solution you maybe looking for: [MySQL - How to search for exact word match using LIKE?](https://stackoverflow.com/questions/5743177/mysql-how-to-search-for-exact-word-match-using-like)
What‘s you‘r searchquery exactly?
```
SELECT * FROM songs WHERE singers RLIKE '^Gallagher';
``` | If you want to display 'Gallagher only then use SUBSTRING\_INDEX
```
SELECT DISTINCT SUBSTRING_INDEX(singers, " ", -1) FROM songs WHERE singers LIKE '%{$search_string}%' ORDER BY title;
``` |
47,148,128 | this problem is driving me nuts. I have a test server and a live server. The test server is showing unicode characters retrieved from an Azure sql database correctly. While the live server running identical code accessing the same data is not showing them correctly.
The data in the database is:
Hallo ich heiße Pokémon! Ich würde gerne mal mit einem anderen Kämpfe!
The test servers shows
Hallo ich heiße Pokémon! Ich würde etc...
The live server, which is an Azure web service shows
Hallo ich hei�e Pok�mon! Ich w�rde gerne mal mit einem anderen K�mpfe
Same PHP code, Same database, Same browser, same db connection string,
different web servers, different results.
I do know Azure is running PHP 5.6 and the test server is running PHP 5.3
They are using sqlsrv\_connect
The data field is type varchar.
I tried using "CharacterSet" => "UTF-8" in the connection but this made no difference to the Azure server and screwed up the result on the test server.
I am out of ideas and leads. | 2017/11/07 | [
"https://Stackoverflow.com/questions/47148128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556436/"
] | Edit: After searching stackoverflow, here is a solution you maybe looking for: [MySQL - How to search for exact word match using LIKE?](https://stackoverflow.com/questions/5743177/mysql-how-to-search-for-exact-word-match-using-like)
What‘s you‘r searchquery exactly?
```
SELECT * FROM songs WHERE singers RLIKE '^Gallagher';
``` | If you want search single name based on last name (surname) then you need to write below query
```
SELECT * FROM songs WHERE singers LIKE '%Gallagher';
``` |
11,650,228 | So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible? | 2012/07/25 | [
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] | You should not skip test this way. Better do one of following things:
* mark test as ignored via `[Ignore]` attribute
* throw `NotImplementedException` from your test
* write `Assert.Fail()` (otherwise you can forget to complete this test)
* remove this test
Also keep in mind, that your tests should not contain conditional logic. Instead you should create two tests - separate test for each code path (with name, which describes what conditions you are testing). So, instead of writing:
```
[TestMethod]
public void TestFooBar()
{
// Assert foo
if (!bar)
return;
// Assert bar
}
```
Write two tests:
```
[TestMethod]
public void TestFoo()
{
// set bar == false
// Assert foo
}
[Ignore] // you can ignore this test
[TestMethod]
public void TestBar()
{
// set bar == true
// Assert bar
}
``` | You can ignore a test and leave it completely untouched in the code.
```
[TestMethod()]
[Ignore()] //ignores the test below
public void SomeTestCodeTest()
{
//test code here
}
``` |
11,650,228 | So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible? | 2012/07/25 | [
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] | You should not skip test this way. Better do one of following things:
* mark test as ignored via `[Ignore]` attribute
* throw `NotImplementedException` from your test
* write `Assert.Fail()` (otherwise you can forget to complete this test)
* remove this test
Also keep in mind, that your tests should not contain conditional logic. Instead you should create two tests - separate test for each code path (with name, which describes what conditions you are testing). So, instead of writing:
```
[TestMethod]
public void TestFooBar()
{
// Assert foo
if (!bar)
return;
// Assert bar
}
```
Write two tests:
```
[TestMethod]
public void TestFoo()
{
// set bar == false
// Assert foo
}
[Ignore] // you can ignore this test
[TestMethod]
public void TestBar()
{
// set bar == true
// Assert bar
}
``` | There is an `Assert.Inconclusive()` method which you can use to nicely skip the current test. Check the [docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.inconclusive?view=mstest-net-1.2.0). Basically it will throw an exception and will show this method as `Skipped`.
I used this as a programmatic check in my code inside the test method:
```
if (!IsEnvironmentConfigured())
{
Assert.Inconclusive("Some message");
}
```
Here is the result:
```
! ShouldTestThisMethod [31ms]
Test Run Successful.
Total tests: 92
Passed: 91
Skipped: 1
Total time: 1.2518 Seconds
``` |
11,650,228 | So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible? | 2012/07/25 | [
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] | Further to other answers (and as suggested): I'd suggest using `Assert.Inconclusive` over `Assert.Fail`, since the original poster's situation is not an explicit failure case.
Using `Inconclusive` as a result makes it clear that you don't know whether the test succeeded or failed - which is an important distinction. Not proving success doesn't always constitute failure! | You can ignore a test and leave it completely untouched in the code.
```
[TestMethod()]
[Ignore()] //ignores the test below
public void SomeTestCodeTest()
{
//test code here
}
``` |
11,650,228 | So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible? | 2012/07/25 | [
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] | You can ignore a test and leave it completely untouched in the code.
```
[TestMethod()]
[Ignore()] //ignores the test below
public void SomeTestCodeTest()
{
//test code here
}
``` | There is an `Assert.Inconclusive()` method which you can use to nicely skip the current test. Check the [docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.inconclusive?view=mstest-net-1.2.0). Basically it will throw an exception and will show this method as `Skipped`.
I used this as a programmatic check in my code inside the test method:
```
if (!IsEnvironmentConfigured())
{
Assert.Inconclusive("Some message");
}
```
Here is the result:
```
! ShouldTestThisMethod [31ms]
Test Run Successful.
Total tests: 92
Passed: 91
Skipped: 1
Total time: 1.2518 Seconds
``` |
11,650,228 | So I have situation when I need skip current test from test method body.
Simplest way is to write something like this in test method.
```
if (something) return;
```
But I have a lot complicated tests and I need a way to skip test from methods which I invoke in current test method body.
Is it possible? | 2012/07/25 | [
"https://Stackoverflow.com/questions/11650228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/545920/"
] | Further to other answers (and as suggested): I'd suggest using `Assert.Inconclusive` over `Assert.Fail`, since the original poster's situation is not an explicit failure case.
Using `Inconclusive` as a result makes it clear that you don't know whether the test succeeded or failed - which is an important distinction. Not proving success doesn't always constitute failure! | There is an `Assert.Inconclusive()` method which you can use to nicely skip the current test. Check the [docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.inconclusive?view=mstest-net-1.2.0). Basically it will throw an exception and will show this method as `Skipped`.
I used this as a programmatic check in my code inside the test method:
```
if (!IsEnvironmentConfigured())
{
Assert.Inconclusive("Some message");
}
```
Here is the result:
```
! ShouldTestThisMethod [31ms]
Test Run Successful.
Total tests: 92
Passed: 91
Skipped: 1
Total time: 1.2518 Seconds
``` |
19,273,719 | I have a single Crystal Report that I am trying to run via a web site using a Report Viewer and also (using the same .rpt) via a background process that would generate the report straight to a stream or file using the export options.
I am not using a database, but have created an xml schema file and am generating an xml data file to load into the report based on unique user data.
When I created the report I made an ADO.NET(XML) connection to design it and pointed it to my schema file (all within VS 2012).
At run time I use a .net DataSet object and use the ReadXmlSchema and ReadXml methods to get my report data and then just set the datasource of my ReportDocument object.
This all worked great in my web application using Report Viewer. Here is the working code:
```
ReportDocument report = new ReportDocument();
report.Load(reportPath);
DataSet reportData = new DataSet();
reportData.ReadXmlSchema("MySchema.xml");
reportData.ReadXml("SampleData1.xml");
report.SetDataSource(reportData);
CrystalReportViewer1.ReportSource = report;
```
My issue/question is how to run this programmatically with no Report Viewer and have it generate a PDF? Essentially the same code as above minus the Report Viewer piece and adding one of the Export options. I have a long running background process and would like to attach this report as a PDF to an email I generate.
I am able to use the same methodology as the web version, but when I get to the SetDataSource line and try to set it to my DataSet I receive and error saying 'Unknown Database Connection Error...' having to do with not using the SetDatabaseLogon method.
I am trying to understand what Crystal Reports expects in the way of the SetDatabaseLogon method when I am not connecting to a database. If it assumes my original ADO.NET(XML) connection in the .RPT file is a legitimate database connection, then what are the logon parameters? It's just a file. There is no username, password etc.
Is there a better way to do a straight to PDF from an existing Crystal Report without Report Viewer? I have looked at various links but found nothing that does not involve some kind of connection string. If I must use SetDatabaseLogin, what values will work when using XML files only?
Thanks for any information or links!
Edit: In looking at the "Unknown Database Connector Error" (not Connection as I stated earlier) I see that it is actually looking at the .RPT in my Temp folder and not in my Remote location where I thought I was loading it from. Maybe this is the problem? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19273719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2564788/"
] | Have you tried something like this:
```
Report.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("Foldername/Reportname.pdf"));
``` | Try this code:
```
report.ExportOptions.DestinationType = CRExportDestinationType.crEDTDiskFile;
report.ExportOptions.FormatType = CRExportFormatType.crEFTPortableDocFormat;
DiskFileDestinationOptions fileOption = new DiskFileDestinationOptions();
fileOption.DiskFileName = "Test.pdf";
report.ExportOptions.DiskFileName = fileOption.DiskFileName;
report.Export(false);
``` |
19,273,719 | I have a single Crystal Report that I am trying to run via a web site using a Report Viewer and also (using the same .rpt) via a background process that would generate the report straight to a stream or file using the export options.
I am not using a database, but have created an xml schema file and am generating an xml data file to load into the report based on unique user data.
When I created the report I made an ADO.NET(XML) connection to design it and pointed it to my schema file (all within VS 2012).
At run time I use a .net DataSet object and use the ReadXmlSchema and ReadXml methods to get my report data and then just set the datasource of my ReportDocument object.
This all worked great in my web application using Report Viewer. Here is the working code:
```
ReportDocument report = new ReportDocument();
report.Load(reportPath);
DataSet reportData = new DataSet();
reportData.ReadXmlSchema("MySchema.xml");
reportData.ReadXml("SampleData1.xml");
report.SetDataSource(reportData);
CrystalReportViewer1.ReportSource = report;
```
My issue/question is how to run this programmatically with no Report Viewer and have it generate a PDF? Essentially the same code as above minus the Report Viewer piece and adding one of the Export options. I have a long running background process and would like to attach this report as a PDF to an email I generate.
I am able to use the same methodology as the web version, but when I get to the SetDataSource line and try to set it to my DataSet I receive and error saying 'Unknown Database Connection Error...' having to do with not using the SetDatabaseLogon method.
I am trying to understand what Crystal Reports expects in the way of the SetDatabaseLogon method when I am not connecting to a database. If it assumes my original ADO.NET(XML) connection in the .RPT file is a legitimate database connection, then what are the logon parameters? It's just a file. There is no username, password etc.
Is there a better way to do a straight to PDF from an existing Crystal Report without Report Viewer? I have looked at various links but found nothing that does not involve some kind of connection string. If I must use SetDatabaseLogin, what values will work when using XML files only?
Thanks for any information or links!
Edit: In looking at the "Unknown Database Connector Error" (not Connection as I stated earlier) I see that it is actually looking at the .RPT in my Temp folder and not in my Remote location where I thought I was loading it from. Maybe this is the problem? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19273719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2564788/"
] | Have you tried something like this:
```
Report.ExportToDisk(ExportFormatType.PortableDocFormat, Server.MapPath("Foldername/Reportname.pdf"));
``` | You could try this:
```
PageMargins margins = new PageMargins { topMargin = 100, leftMargin = 250, bottomMargin = 100, rightMargin = 100 };
report.PrintOptions.ApplyPageMargins(margins );
Stream str = report.ExportToStream(ExportFormatType.PortableDocFormat);
int length = Convert.ToInt32(str.Length);
byte[] bytes = new byte[length];
str.Read(bytes, 0, length);
str.Close();
File.WriteAllBytes(@"C:\Report.pdf", bytes);
```
I hope it helps. |
28,492,909 | I'm putting together a site which has a protected section where users must be logged in to access. I've done this in Laravel 4 without too much incident. However, for the life of me I cannot figure out why I can't get it to work in Laravel 5(L5).
In L5 middleware was/were introduced. This changes the route file to:
```
Route::get('foo/bar', ['middleware'=>'auth','FooController@index']);
Route::get('foo/bar/{id}', ['middleware'=>'auth','FooController@show']);
```
The route works fine as long as the middleware is not included.
When the route is accessed with the middleware however the result is not so much fun.
>
> Whoops, looks like something went wrong.
>
>
> ReflectionException in Route.php line 150:
>
>
> Function () does not exist
>
>
>
Any insight, help, and/or assistance is very appreciated. I've done the Google circuit and couldn't find anything relevant to my current plight. Thanks in advance. | 2015/02/13 | [
"https://Stackoverflow.com/questions/28492909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3265547/"
] | you forgot the `uses` key :
```
Route::get('foo/bar/{id}', ['middleware'=>'auth', 'uses'=>'FooController@show']);
``` | If you add anything more than your controller method into your routes you need to add `uses` as key of the array for your controller, so for example if I don't haw any middleware it's enough to write:
```
Route::get('foo/bar', 'FooController@index');
Route::get('foo/bar/{id}', 'FooController@show');
```
However if you want to add middleware you need to write:
```
Route::get('foo/bar', ['middleware'=>'auth','uses' => 'FooController@index']);
Route::get('foo/bar/{id}', ['middleware'=>'auth','uses' => 'FooController@show']);
``` |
28,492,909 | I'm putting together a site which has a protected section where users must be logged in to access. I've done this in Laravel 4 without too much incident. However, for the life of me I cannot figure out why I can't get it to work in Laravel 5(L5).
In L5 middleware was/were introduced. This changes the route file to:
```
Route::get('foo/bar', ['middleware'=>'auth','FooController@index']);
Route::get('foo/bar/{id}', ['middleware'=>'auth','FooController@show']);
```
The route works fine as long as the middleware is not included.
When the route is accessed with the middleware however the result is not so much fun.
>
> Whoops, looks like something went wrong.
>
>
> ReflectionException in Route.php line 150:
>
>
> Function () does not exist
>
>
>
Any insight, help, and/or assistance is very appreciated. I've done the Google circuit and couldn't find anything relevant to my current plight. Thanks in advance. | 2015/02/13 | [
"https://Stackoverflow.com/questions/28492909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3265547/"
] | you forgot the `uses` key :
```
Route::get('foo/bar/{id}', ['middleware'=>'auth', 'uses'=>'FooController@show']);
``` | In case you don't use a controller for your view and you just want to display the view, you should do this:
```
Route::get('foo/bar', ['middleware' => 'auth', function () {
return View::make('path.to.your.page');
}]);
``` |
40,313,389 | I am attempting to extract IP Address from a MySQL database using REGEX ina a SELECT statement. When i run the Query in the MySQL console it returns the expected results:
```
SELECT * FROM database.table WHERE field3 REGEXP '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';
```
When I run the same query through a python script it returns results that are not IP Addresses.
```
query = ("SELECT * FROM database.table WHERE field3 REGEXP '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$';")
```
Where am I going wrong? | 2016/10/28 | [
"https://Stackoverflow.com/questions/40313389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6744297/"
] | To answer how to add the `avx` flag into compiler options.
In your case the f77 complier is being picked `gfortran:f77: ./distance.f` < That is the key line.
You could try specifying `--f77flags=-mavx` | In the comments Warren Weckesser explained that Fortran arrays are stored transposed with regards to the C ones. However, one important implication was not mentioned. To traverse the array in the right order, you have to switch the order of the loops. In C the first index is the outer loop, in Fortran the first index should be the inner loop. You are indexing as `dist(i,j)` so your loops are in wrong order.
But because your `j` loop depends on the `i` loop value, you may have to switch the role of the indexes in your array (transpose it).
Some compilers are able to correct some simple loop ordering for you with high enough level of optimizations.
BTW the `-funroll-loops` is known to be often too aggressive and actually detrimental. Some limits usually should be set. |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | You replace the value each time in the loop, so the output is only the result of the last iteration: 4\*4.
Not exactly what calculation you want to do that will give you 24, but maybe you want to add the result to the previous value of y, or multiple it? | x = i+i will get executed for each of the values and the print the last one...
so will print 8 for the add and 16 for multiplication. |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | You replace the value each time in the loop, so the output is only the result of the last iteration: 4\*4.
Not exactly what calculation you want to do that will give you 24, but maybe you want to add the result to the previous value of y, or multiple it? | your code doesn't work correctly because you are only returning the result of the last element in the list
simplest implementation without sum():
```
nums = [1,2,3,4]
def add():
x = 0
for i in nums :
x += i
return x
def multiple():
y = 1
for i in nums :
y *= i
return y
print add()
print multiple()
```
note you don't need to use index you can simply iterate the numbers in both
notice that x and y need to be initalized (and for addition its 0 and multiplication its 1) |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | You only add/multiply the last line
So is X=4\*4 = 16 for mulitply and
X=4+4 = 8 for add
the previous attempts are overwritten in the for-loop | x = i+i will get executed for each of the values and the print the last one...
so will print 8 for the add and 16 for multiplication. |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | **Here you go:**
```
nums = [1,2,3,4]
def add():
return sum(nums)
def multiple():
result = 1
for num in nums:
result *= num
return result
print add()
print multiple()
```
**Output:**
```
10
24
```
>
> If you don't want to use **`sum`** built-in function then you can use this function:
>
>
>
```
def add():
sum_result = 0
for num in nums:
sum_result += num
return sum_result
``` | x = i+i will get executed for each of the values and the print the last one...
so will print 8 for the add and 16 for multiplication. |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | your code doesn't work correctly because you are only returning the result of the last element in the list
simplest implementation without sum():
```
nums = [1,2,3,4]
def add():
x = 0
for i in nums :
x += i
return x
def multiple():
y = 1
for i in nums :
y *= i
return y
print add()
print multiple()
```
note you don't need to use index you can simply iterate the numbers in both
notice that x and y need to be initalized (and for addition its 0 and multiplication its 1) | x = i+i will get executed for each of the values and the print the last one...
so will print 8 for the add and 16 for multiplication. |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | You only add/multiply the last line
So is X=4\*4 = 16 for mulitply and
X=4+4 = 8 for add
the previous attempts are overwritten in the for-loop | your code doesn't work correctly because you are only returning the result of the last element in the list
simplest implementation without sum():
```
nums = [1,2,3,4]
def add():
x = 0
for i in nums :
x += i
return x
def multiple():
y = 1
for i in nums :
y *= i
return y
print add()
print multiple()
```
note you don't need to use index you can simply iterate the numbers in both
notice that x and y need to be initalized (and for addition its 0 and multiplication its 1) |
33,806,541 | I got this homework assignment, cant figure it out.
I need to ask the user how many town names he wants to enter. For example 5.
Then, he enters the 5 town names.
Afterwards, we need to find the average length of the names and show him the names which have less letters than the average length. Thanks for your shared time :)
My code so far:
```
static void Main(string[] args)
{
int n;
Console.WriteLine("How many town names would you like to enter:");
n = int.Parse(Console.ReadLine());
string[] TownNames = new string[n];
Console.Clear();
Console.WriteLine("Enter {0} town names:", n);
for (int i = 0; i < n; i++)
{
Console.Write("Enter number {0}: ", i + 1);
TownNames[i] = Convert.ToString(Console.ReadLine());
}
Console.ReadKey(true);
}
static void Average(double[] TownNames, int n)
{
}
``` | 2015/11/19 | [
"https://Stackoverflow.com/questions/33806541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5581685/"
] | **Here you go:**
```
nums = [1,2,3,4]
def add():
return sum(nums)
def multiple():
result = 1
for num in nums:
result *= num
return result
print add()
print multiple()
```
**Output:**
```
10
24
```
>
> If you don't want to use **`sum`** built-in function then you can use this function:
>
>
>
```
def add():
sum_result = 0
for num in nums:
sum_result += num
return sum_result
``` | your code doesn't work correctly because you are only returning the result of the last element in the list
simplest implementation without sum():
```
nums = [1,2,3,4]
def add():
x = 0
for i in nums :
x += i
return x
def multiple():
y = 1
for i in nums :
y *= i
return y
print add()
print multiple()
```
note you don't need to use index you can simply iterate the numbers in both
notice that x and y need to be initalized (and for addition its 0 and multiplication its 1) |
2,029,257 | By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)? | 2016/11/24 | [
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Let $x,y,z'$ be normally distributed, with $0$ mean. Define $$z=\begin{cases} z' & xyz'\ge 0\\ -z' & xyz'<0\end{cases}$$
The resulting $x,y,z$ will always satisfy $xyz\ge 0$, but be pairwise independent. | An [answer of mine on stats.SE](https://stats.stackexchange.com/a/180727/6633) gives essentially the same answer as the one given by vadim123.
Consider three *standard
normal random variables* $X,Y,Z$ whose joint probability
density function
$f\_{X,Y,Z}(x,y,z)$ is **not** $\phi(x)\phi(y)\phi(z)$ where
$\phi(\cdot)$ is the standard normal density, but rather
$$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z)
& ~~~~\text{if}~ x \geq 0, y\geq 0, z \geq 0,\\
& \text{or if}~ x < 0, y < 0, z \geq 0,\\
& \text{or if}~ x < 0, y\geq 0, z < 0,\\
& \text{or if}~ x \geq 0, y< 0, z < 0,\\
0 & \text{otherwise.}
\end{cases}\tag{1}$$
We can calculate the joint density of any *pair* of the random variables,
(say $X$ and $Z$) by integrating out the joint density with respect to
the unwanted variable, that is,
$$f\_{X,Z}(x,z) = \int\_{-\infty}^\infty f\_{X,Y,Z}(x,y,z)\,\mathrm dy.
\tag{2}$$
* If $x \geq 0, z \geq 0$ or if $x < 0, z < 0$, then
$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z), & y \geq 0,\\
0, & y < 0,\end{cases}$ and so $(2)$ reduces to
$$f\_{X,Z}(x,z) = \phi(x)\phi(z)\int\_{0}^\infty 2\phi(y)\,\mathrm dy =
\phi(x)\phi(z).
\tag{3}$$
* If $x \geq 0, z < 0$ or if $x < 0, z \geq 0$, then
$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z), & y < 0,\\
0, & y \geq 0,\end{cases}$ and so $(2)$ reduces to
$$f\_{X,Z}(x,z) = \phi(x)\phi(z)\int\_{-\infty}^0 2\phi(y)\,\mathrm dy =
\phi(x)\phi(z).
\tag{4}$$
In short, $(3)$ and $(4)$ show that $f\_{X,Z}(x,z) = \phi(x)\phi(z)$ for *all*
$x, z \in (-\infty,\infty)$ and so $X$ and $Z$ are
(*pairwise*) independent standard normal random variables. Similar
calculations (left as an exercise for the bemused
reader) show that $X$ and $Y$ are
(*pairwise*) independent standard normal random variables, and
$Y$ and $Z$ also are
(*pairwise*) independent standard normal random variables. **But**
$X,Y,Z$ are **not** mutually independent normal random variables.
Indeed, their *joint* density $f\_{X,Y,Z}(x,y,z)$
does not equal the product $\phi(x)\phi(y)\phi(z)$ of
their marginal densities for *any* choice of
$x, y, z \in (-\infty,\infty)$ |
2,029,257 | By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)? | 2016/11/24 | [
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Let $x,y,z'$ be normally distributed, with $0$ mean. Define $$z=\begin{cases} z' & xyz'\ge 0\\ -z' & xyz'<0\end{cases}$$
The resulting $x,y,z$ will always satisfy $xyz\ge 0$, but be pairwise independent. | The continuous analog of the Bernstein example: Divide up the unit cube into eight congruent subcubes of side length $1/2$. Select four of these cubes: Subcube #1 has one vertex at $(x,y,z)=(1,0,0)$, subcube #2 has one vertex at $(0,1,0)$, subcube #3 has one vertex at $(0,0,1)$, and subcube #4 has one vertex at $(1,1,1)$. (To visualize this, you have two layers of cubes: the bottom layer has two cubes in a diagonal formation, and the top layer has two cubes in the opposite diagonal formation.)
Now let $(X,Y,Z)$ be uniform over these four cubes. Clearly $X, Y, Z$ are not mutually independent, but every pair of variables $(X,Y)$, $(X,Z)$, $(Y,Z)$ is uniform over the unit square (and hence independent). |
2,029,257 | By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)? | 2016/11/24 | [
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Let $x,y,z'$ be normally distributed, with $0$ mean. Define $$z=\begin{cases} z' & xyz'\ge 0\\ -z' & xyz'<0\end{cases}$$
The resulting $x,y,z$ will always satisfy $xyz\ge 0$, but be pairwise independent. | Here's a potentially very simple construction for $k$-wise independent random variables, uniformly distributed on $[0, 1]$ (though admittedly I didn't work it out very carefully so hopefully the condition checks out)? There is a standard way of constructing discrete $k$-wise independent random variables: let $X\_1,\ldots, X\_{k}$ be uniform independent rvs drawn from $F$, $F$ a finite field of order $q$ ($q$ sufficiently larger than $k$, of course). Then, for $u\in F$, let $Y\_u = X\_1 + uX\_2+\cdots + u^{k-1}X\_k$. Then, the random variables $\{Y\_u : u\in F\}$ are $k$-wise independent.
Now, just divide $[0, 1]$ into $q$ evenly spaced subintervals. Let $Z\_u$ be uniform from the $Y\_u$th subinterval. The rvs $\{Z\_u : u\in F\}$ are $k$-wise independent (their joint CDF would decompose as the product of the individual CDFs, since the $\{Y\_u\}$ are $k$-wise independent), and are uniform over $[0, 1]$ since each $Y\_u$ is uniform over $F$. |
2,029,257 | By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)? | 2016/11/24 | [
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | An [answer of mine on stats.SE](https://stats.stackexchange.com/a/180727/6633) gives essentially the same answer as the one given by vadim123.
Consider three *standard
normal random variables* $X,Y,Z$ whose joint probability
density function
$f\_{X,Y,Z}(x,y,z)$ is **not** $\phi(x)\phi(y)\phi(z)$ where
$\phi(\cdot)$ is the standard normal density, but rather
$$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z)
& ~~~~\text{if}~ x \geq 0, y\geq 0, z \geq 0,\\
& \text{or if}~ x < 0, y < 0, z \geq 0,\\
& \text{or if}~ x < 0, y\geq 0, z < 0,\\
& \text{or if}~ x \geq 0, y< 0, z < 0,\\
0 & \text{otherwise.}
\end{cases}\tag{1}$$
We can calculate the joint density of any *pair* of the random variables,
(say $X$ and $Z$) by integrating out the joint density with respect to
the unwanted variable, that is,
$$f\_{X,Z}(x,z) = \int\_{-\infty}^\infty f\_{X,Y,Z}(x,y,z)\,\mathrm dy.
\tag{2}$$
* If $x \geq 0, z \geq 0$ or if $x < 0, z < 0$, then
$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z), & y \geq 0,\\
0, & y < 0,\end{cases}$ and so $(2)$ reduces to
$$f\_{X,Z}(x,z) = \phi(x)\phi(z)\int\_{0}^\infty 2\phi(y)\,\mathrm dy =
\phi(x)\phi(z).
\tag{3}$$
* If $x \geq 0, z < 0$ or if $x < 0, z \geq 0$, then
$f\_{X,Y,Z}(x,y,z) = \begin{cases} 2\phi(x)\phi(y)\phi(z), & y < 0,\\
0, & y \geq 0,\end{cases}$ and so $(2)$ reduces to
$$f\_{X,Z}(x,z) = \phi(x)\phi(z)\int\_{-\infty}^0 2\phi(y)\,\mathrm dy =
\phi(x)\phi(z).
\tag{4}$$
In short, $(3)$ and $(4)$ show that $f\_{X,Z}(x,z) = \phi(x)\phi(z)$ for *all*
$x, z \in (-\infty,\infty)$ and so $X$ and $Z$ are
(*pairwise*) independent standard normal random variables. Similar
calculations (left as an exercise for the bemused
reader) show that $X$ and $Y$ are
(*pairwise*) independent standard normal random variables, and
$Y$ and $Z$ also are
(*pairwise*) independent standard normal random variables. **But**
$X,Y,Z$ are **not** mutually independent normal random variables.
Indeed, their *joint* density $f\_{X,Y,Z}(x,y,z)$
does not equal the product $\phi(x)\phi(y)\phi(z)$ of
their marginal densities for *any* choice of
$x, y, z \in (-\infty,\infty)$ | Here's a potentially very simple construction for $k$-wise independent random variables, uniformly distributed on $[0, 1]$ (though admittedly I didn't work it out very carefully so hopefully the condition checks out)? There is a standard way of constructing discrete $k$-wise independent random variables: let $X\_1,\ldots, X\_{k}$ be uniform independent rvs drawn from $F$, $F$ a finite field of order $q$ ($q$ sufficiently larger than $k$, of course). Then, for $u\in F$, let $Y\_u = X\_1 + uX\_2+\cdots + u^{k-1}X\_k$. Then, the random variables $\{Y\_u : u\in F\}$ are $k$-wise independent.
Now, just divide $[0, 1]$ into $q$ evenly spaced subintervals. Let $Z\_u$ be uniform from the $Y\_u$th subinterval. The rvs $\{Z\_u : u\in F\}$ are $k$-wise independent (their joint CDF would decompose as the product of the individual CDFs, since the $\{Y\_u\}$ are $k$-wise independent), and are uniform over $[0, 1]$ since each $Y\_u$ is uniform over $F$. |
2,029,257 | By considering the set $\{1,2,3,4\}$, one can easily come up with an [example](https://en.wikipedia.org/wiki/Pairwise_independence) (attributed to S. Bernstein) of pairwise independent but not independent random variables.
Counld anybody give an example with [continuous random variables](https://en.wikipedia.org/wiki/Probability_distribution#Continuous_probability_distribution)? | 2016/11/24 | [
"https://math.stackexchange.com/questions/2029257",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | The continuous analog of the Bernstein example: Divide up the unit cube into eight congruent subcubes of side length $1/2$. Select four of these cubes: Subcube #1 has one vertex at $(x,y,z)=(1,0,0)$, subcube #2 has one vertex at $(0,1,0)$, subcube #3 has one vertex at $(0,0,1)$, and subcube #4 has one vertex at $(1,1,1)$. (To visualize this, you have two layers of cubes: the bottom layer has two cubes in a diagonal formation, and the top layer has two cubes in the opposite diagonal formation.)
Now let $(X,Y,Z)$ be uniform over these four cubes. Clearly $X, Y, Z$ are not mutually independent, but every pair of variables $(X,Y)$, $(X,Z)$, $(Y,Z)$ is uniform over the unit square (and hence independent). | Here's a potentially very simple construction for $k$-wise independent random variables, uniformly distributed on $[0, 1]$ (though admittedly I didn't work it out very carefully so hopefully the condition checks out)? There is a standard way of constructing discrete $k$-wise independent random variables: let $X\_1,\ldots, X\_{k}$ be uniform independent rvs drawn from $F$, $F$ a finite field of order $q$ ($q$ sufficiently larger than $k$, of course). Then, for $u\in F$, let $Y\_u = X\_1 + uX\_2+\cdots + u^{k-1}X\_k$. Then, the random variables $\{Y\_u : u\in F\}$ are $k$-wise independent.
Now, just divide $[0, 1]$ into $q$ evenly spaced subintervals. Let $Z\_u$ be uniform from the $Y\_u$th subinterval. The rvs $\{Z\_u : u\in F\}$ are $k$-wise independent (their joint CDF would decompose as the product of the individual CDFs, since the $\{Y\_u\}$ are $k$-wise independent), and are uniform over $[0, 1]$ since each $Y\_u$ is uniform over $F$. |
31,670 | I have an 8 year old son who refuses to use the restroom. He does #1 in toilet but not #2. This has been going on for less than a year, I'd say about 8 months now. Before that, his potty routine was normal. Out of nowhere he started refusing to go. I've asked him if there's any reason to why he doesn't use the toilet and he responds with "I don't know, there's no reason"
He stays with his grandfather every weekend and he does it there as well. He doesn't do it at school at all, I guess he waits till he's at home where he's most "comfortable" because he doesn't want "kids to smell him".
What can I do to make him use the restroom like he used to? I'm tired of having to wash his underwear as often as I do and having talks with him about the need of toilets. | 2017/09/08 | [
"https://parenting.stackexchange.com/questions/31670",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/29589/"
] | >
> What can I do to make him use the restroom like he used to?
>
>
>
My son went through something similar when he was young, and in my case it was just a battle of wills. I said to him you need to **poopy in the potty**. I would repeat this phrase over and over again. I would sit with him in the bathroom until he did use the bath room. ( Not for hours on end, but 10 min ever hour or so )
The other part of this is I had him hand wash the majority of the mess every single time, be it on just his underwear, or his clothes.
Once he started falling back in line, I provided rewards for doing the right thing, such as allowing him to watch his TV show, or an extra sweet.
Be patient he will come around.
**NOTE:** In writing this answer, I am assuming that **medical conditions** have been eliminated. Have your doctor examine him if this is a concern. | I don't know if this will help you but I must share my experience as what we did HELPED!!! 1. We had NO idea our (completely healthy)teen child was having issues with what I NOW know is called soiling/encopresis. I had no idea it was a thing or that my poor child had been dealing with it for YEARS. THEY didn't even know they were struggling with
It. We knew they had issues with regular/harder bowel movements and were making them drink more water, consume more fruits/veggies in hopes to alleviate it 2. They had had minor soiling in underwear for years but we just reduced it to poor cleaning or not making it to restroom in time. 3.BUT then their bowel movements became so heinous we suspected something was going on internally. 4. My poor child was starting to smell like horrible poo ALL THE TIME! We'd talk and talk about showering, better hygiene, proper cleaning methods ect. But they would be so frustrated with it all because according to them, they WERE doing all the right things with no explanation for the still smelling/soiling problem. The soiling got worse over time and we had had enough! Last year I spent tons of time researching the issue, still not knowing what it was we were dealing with. I came across this site with others who were struggling with the same issues. Thankfully, we now had a name for the issue and secondly we were not the only ones. But we still didn't have a solution. Our child isn't developmentally challenged, hasn't gone through any traumatic events or anything else that could possibly explain what was happening. We spoke with a dr who suggested the typical treatment for this, which meant OTC drugs/stool softener. But I read about the side affects and there were too many families who noticed a negative change in their children's behavior, ie. Depression, mood swings, rage ect. The softener is only meant for adults and for short periods. We were being advised to take for 6mos + as those parents. I was NOT willing to take a gamble. So we did NOT take the medicine as advised.
I researched more looking for an alternative....I came across a post on a blog about some behavioral issues/tendencies. It spoke so much about what my child had been displaying in other areas of their life: low energy, lack of effort in most areas, lack of focus, easily sidetracked or distracted, that I kept reading to see what their solution was. Its main purpose was to bring attention to our children who have an unhealthy gut and an imbalanced level of serotonin which affects so much.
www.homeschool-your-boys.com/focusing-attention-sensoryissues/
It was such a blessing to see this article and how adding a few healthy supplements/vitamins can truly make a difference.
I was SO desperate for my child I was willing to give it a try as it mentioned digestive issues as a side affect of low serotonin. It proposes the use of a prebiotic and grapefruit extract seed for 3 months to help build good bacteria and fight the bad. So I ordered enough for 3 months on Amazon.
Well let me tell you in just 2 MONTHS of daily doses 3x a day + regular water intake, fruit/veggie comsumption, regular potty breaks AND checking their stool daily for softer stools and comfirm that they had indeed used the restroom,, my child's mood improved, their focus improved AND the bowel issue was almost resolved!! This was at the beginning of Feb 2017, by May we could see a significant difference in our child and buy the 3rd month it was completely resolved. No more heinous stench in the bathroom just the typical poo smell, no more soiled clothes, better overall mood/behavior and a confidence we hadn't seen in years got restored. My child had suffered without ever speaking a word to us out of fear/embarrassment. We continued the supplements for another 3 months just to keep them on track and they have not had the issue again! I pray something you read here is helpful and even more what you read on the blog. They suggest behavioral training with the supplements BUT we didn't use the training just the supplements. We continue to monitor our child just in case but to this day Jan 1 2018 they do not have the issue any more! |
31,670 | I have an 8 year old son who refuses to use the restroom. He does #1 in toilet but not #2. This has been going on for less than a year, I'd say about 8 months now. Before that, his potty routine was normal. Out of nowhere he started refusing to go. I've asked him if there's any reason to why he doesn't use the toilet and he responds with "I don't know, there's no reason"
He stays with his grandfather every weekend and he does it there as well. He doesn't do it at school at all, I guess he waits till he's at home where he's most "comfortable" because he doesn't want "kids to smell him".
What can I do to make him use the restroom like he used to? I'm tired of having to wash his underwear as often as I do and having talks with him about the need of toilets. | 2017/09/08 | [
"https://parenting.stackexchange.com/questions/31670",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/29589/"
] | The first thing which needs to be done is that the child needs to see a pediatrician who specializes in *encopresis*, or a pediatric gastroenterologist. Once a child past the age of 4 starts soiling their pants, it might be a medical problem. (There are medical conditions that start earlier, but they are usually recognized as such.)
This can start insidiously with just constipation then a painful BM. The painful BM makes the child afraid to go again, which results in their holding it in, having a harder stool, maybe larger, and again painful, so it becomes a self-reinforcing problem.
[Boston's Children's Hospital](http://www.childrenshospital.org/conditions-and-treatments/conditions/encopresis/symptoms-and-causes) describes it like this:
>
> How does encopresis happen?
>
>
> Constipated children have fewer bowel movements than normal, and their bowel movements can be hard, dry, difficult to pass and so large that they can often even block up the toilet. Here are some examples why:
>
>
> -Your child's stool can become impacted (packed into her rectum and large intestine).
>
> -Her rectum and intestine become enlarged due to the retained stool.
>
> -Eventually, her rectum and intestine have problems sensing the presence of stool, and the anal sphincter (the muscle at the end of the digestive tract that helps hold stool in) becomes dilated, losing its strength.
>
> -Stool can start to leak around the impacted stool, soiling your child's clothing.
>
> -As more and more stool collects, your child will be less and less able to hold it in, leading to accidents. Because of decreased sensitivity in your child’s rectum due to its larger size, she may not even be aware she’s had an accident until after it has occurred.
>
>
>
This is why "I don't know" is the most common answer parents get when they ask their child, "Why didn't you tell me you needed to go?" The colon and sphincter do not give them the signals they need to feel to evacuate 'properly'.
The approach initially will be medical: a dietary change, a bowel evacuation, laxatives, liquids, fiber, etc. With luck (it's still early), your child will respond and this will be a thing of the past.
Often, however, the treatment of longer episodes of encopresis require a multidiciplinary approach: doctor, dietician, and therapist.
Read reputable sites on encopresis. Many parents have gone through this; there are even online encopresis support groups you can join. Good luck! | I don't know if this will help you but I must share my experience as what we did HELPED!!! 1. We had NO idea our (completely healthy)teen child was having issues with what I NOW know is called soiling/encopresis. I had no idea it was a thing or that my poor child had been dealing with it for YEARS. THEY didn't even know they were struggling with
It. We knew they had issues with regular/harder bowel movements and were making them drink more water, consume more fruits/veggies in hopes to alleviate it 2. They had had minor soiling in underwear for years but we just reduced it to poor cleaning or not making it to restroom in time. 3.BUT then their bowel movements became so heinous we suspected something was going on internally. 4. My poor child was starting to smell like horrible poo ALL THE TIME! We'd talk and talk about showering, better hygiene, proper cleaning methods ect. But they would be so frustrated with it all because according to them, they WERE doing all the right things with no explanation for the still smelling/soiling problem. The soiling got worse over time and we had had enough! Last year I spent tons of time researching the issue, still not knowing what it was we were dealing with. I came across this site with others who were struggling with the same issues. Thankfully, we now had a name for the issue and secondly we were not the only ones. But we still didn't have a solution. Our child isn't developmentally challenged, hasn't gone through any traumatic events or anything else that could possibly explain what was happening. We spoke with a dr who suggested the typical treatment for this, which meant OTC drugs/stool softener. But I read about the side affects and there were too many families who noticed a negative change in their children's behavior, ie. Depression, mood swings, rage ect. The softener is only meant for adults and for short periods. We were being advised to take for 6mos + as those parents. I was NOT willing to take a gamble. So we did NOT take the medicine as advised.
I researched more looking for an alternative....I came across a post on a blog about some behavioral issues/tendencies. It spoke so much about what my child had been displaying in other areas of their life: low energy, lack of effort in most areas, lack of focus, easily sidetracked or distracted, that I kept reading to see what their solution was. Its main purpose was to bring attention to our children who have an unhealthy gut and an imbalanced level of serotonin which affects so much.
www.homeschool-your-boys.com/focusing-attention-sensoryissues/
It was such a blessing to see this article and how adding a few healthy supplements/vitamins can truly make a difference.
I was SO desperate for my child I was willing to give it a try as it mentioned digestive issues as a side affect of low serotonin. It proposes the use of a prebiotic and grapefruit extract seed for 3 months to help build good bacteria and fight the bad. So I ordered enough for 3 months on Amazon.
Well let me tell you in just 2 MONTHS of daily doses 3x a day + regular water intake, fruit/veggie comsumption, regular potty breaks AND checking their stool daily for softer stools and comfirm that they had indeed used the restroom,, my child's mood improved, their focus improved AND the bowel issue was almost resolved!! This was at the beginning of Feb 2017, by May we could see a significant difference in our child and buy the 3rd month it was completely resolved. No more heinous stench in the bathroom just the typical poo smell, no more soiled clothes, better overall mood/behavior and a confidence we hadn't seen in years got restored. My child had suffered without ever speaking a word to us out of fear/embarrassment. We continued the supplements for another 3 months just to keep them on track and they have not had the issue again! I pray something you read here is helpful and even more what you read on the blog. They suggest behavioral training with the supplements BUT we didn't use the training just the supplements. We continue to monitor our child just in case but to this day Jan 1 2018 they do not have the issue any more! |
51,415,248 | I got two dictionaries and both of them have same keys ,i am trying to access the second dictionary using the key as input of first dictionary like below
```
Players = {0: "Quit",
1: "Player 1",
2: "Player 2",
3: "Player 3",
4: "Player 4",
5: "Player 5"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} }
avabilablePlayer =",".join(list(Players.values()))
print (avabilablePlayer)
direction = input("Available Players are " + avabilablePlayer + " ").upper()
if direction in exits:
dict_key=exits.get(direction)
print(dict_key)
```
The above code is not returning the values from the second dictionary, how to fix this without using any methods and functions? | 2018/07/19 | [
"https://Stackoverflow.com/questions/51415248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9775079/"
] | Use `font-size: 0;` to `ul` and `font-size: 15px;` to `li`
```css
ul {
display: block;
columns: 2;
font-size: 0;
}
li {
border-top: 1px solid black;
list-style: none;
font-size: 15px;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` | Try to use `column-gap: 0;`. If I understood you correctly, this is what you need.
```css
ul {
display: block;
columns: 2;
column-gap: 0;
}
li {
border-top: 1px solid #e9e9e9;
list-style: none;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` |
51,415,248 | I got two dictionaries and both of them have same keys ,i am trying to access the second dictionary using the key as input of first dictionary like below
```
Players = {0: "Quit",
1: "Player 1",
2: "Player 2",
3: "Player 3",
4: "Player 4",
5: "Player 5"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} }
avabilablePlayer =",".join(list(Players.values()))
print (avabilablePlayer)
direction = input("Available Players are " + avabilablePlayer + " ").upper()
if direction in exits:
dict_key=exits.get(direction)
print(dict_key)
```
The above code is not returning the values from the second dictionary, how to fix this without using any methods and functions? | 2018/07/19 | [
"https://Stackoverflow.com/questions/51415248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9775079/"
] | Use `font-size: 0;` to `ul` and `font-size: 15px;` to `li`
```css
ul {
display: block;
columns: 2;
font-size: 0;
}
li {
border-top: 1px solid black;
list-style: none;
font-size: 15px;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` | **You Can Try Another Way to use flex box**
```css
ul {
display:flex;
flex-wrap:wrap;
box-sizing: border-box;
}
li {
width:50%;
padding: 5px 15px 5px 5px;
border-top: 1px solid black;
list-style: none;
font-size: 15px;
box-sizing: border-box;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` |
51,415,248 | I got two dictionaries and both of them have same keys ,i am trying to access the second dictionary using the key as input of first dictionary like below
```
Players = {0: "Quit",
1: "Player 1",
2: "Player 2",
3: "Player 3",
4: "Player 4",
5: "Player 5"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} }
avabilablePlayer =",".join(list(Players.values()))
print (avabilablePlayer)
direction = input("Available Players are " + avabilablePlayer + " ").upper()
if direction in exits:
dict_key=exits.get(direction)
print(dict_key)
```
The above code is not returning the values from the second dictionary, how to fix this without using any methods and functions? | 2018/07/19 | [
"https://Stackoverflow.com/questions/51415248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9775079/"
] | You can just use `column-gap: 0;` to your `ul`
```css
ul {
display: block;
-webkit-columns: 2;
/* Chrome, Safari, Opera */
-moz-columns: 2;
/* Firefox */
columns: 2;
-webkit-column-gap: 0;
/* Chrome, Safari, Opera */
-moz-column-gap: 0;
/* Firefox */
column-gap: 0;
}
li {
border-top: 1px solid #e9e9e9;
list-style: none;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
```
>
> **Always use Webkit prefixs with the new CSS styles for better support**
>
>
>
Hope this was helpfull. | Try to use `column-gap: 0;`. If I understood you correctly, this is what you need.
```css
ul {
display: block;
columns: 2;
column-gap: 0;
}
li {
border-top: 1px solid #e9e9e9;
list-style: none;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` |
51,415,248 | I got two dictionaries and both of them have same keys ,i am trying to access the second dictionary using the key as input of first dictionary like below
```
Players = {0: "Quit",
1: "Player 1",
2: "Player 2",
3: "Player 3",
4: "Player 4",
5: "Player 5"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0} }
avabilablePlayer =",".join(list(Players.values()))
print (avabilablePlayer)
direction = input("Available Players are " + avabilablePlayer + " ").upper()
if direction in exits:
dict_key=exits.get(direction)
print(dict_key)
```
The above code is not returning the values from the second dictionary, how to fix this without using any methods and functions? | 2018/07/19 | [
"https://Stackoverflow.com/questions/51415248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9775079/"
] | You can just use `column-gap: 0;` to your `ul`
```css
ul {
display: block;
-webkit-columns: 2;
/* Chrome, Safari, Opera */
-moz-columns: 2;
/* Firefox */
columns: 2;
-webkit-column-gap: 0;
/* Chrome, Safari, Opera */
-moz-column-gap: 0;
/* Firefox */
column-gap: 0;
}
li {
border-top: 1px solid #e9e9e9;
list-style: none;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
```
>
> **Always use Webkit prefixs with the new CSS styles for better support**
>
>
>
Hope this was helpfull. | **You Can Try Another Way to use flex box**
```css
ul {
display:flex;
flex-wrap:wrap;
box-sizing: border-box;
}
li {
width:50%;
padding: 5px 15px 5px 5px;
border-top: 1px solid black;
list-style: none;
font-size: 15px;
box-sizing: border-box;
}
```
```html
<ul>
<li>TEST 1</li>
<li>TEST 2</li>
<li>TEST 3</li>
<li>TEST 4</li>
<li>TEST 5</li>
<li>TEST 6</li>
<li>TEST 7</li>
<li>TEST 8</li>
</ul>
``` |
18,331,189 | I have form like this:
```
<%= simple_form_for @category do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :parent_id, collection: @board.subtree, include_blank: false %>
<%= f.button :submit %>
<% end %>
```
`@category` is instance of `Board` so this `:submit` tries to run `create` action from `BoardsController`. Instead of it, I'd like to run `create` action from `CategoriesController`.
How can I do this? | 2013/08/20 | [
"https://Stackoverflow.com/questions/18331189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654940/"
] | Just add the `url` option.
```
<%= simple_form_for @category, url: category_path(@category) do |f| %>
``` | This might help:
<https://stackoverflow.com/a/7136142/2128691>
so yours would look like:
```
<%= simple_form_for @category, :url => category_path, do |f| %>
...
<% end
``` |
34,990,495 | Is there a way to use an event to call a function when the JSON.Parse() has parsed all the objects from a file? | 2016/01/25 | [
"https://Stackoverflow.com/questions/34990495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5685815/"
] | `JSON.parse` is synchronous. it returns the object corresponding to the given JSON text.
More about it from [mozilla](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
now a good way of doing JSON.parse is shown below (inside a try-catch)
```
try {
var data = JSON.parse(string);
//data is the object,
//convert to object is completed here. you can call a function here passing created object
}
catch (err) {
//mark this error ?
}
```
Now there are discussions, about why `JSON.parse` is not async, like the [ONE HERE](https://www.reddit.com/r/javascript/comments/2uc7gv/its_2015_why_the_hell_is_jsonparse_synchronous/) | **EDIT: Since question was changed.**
JSON.parse() is a synchronous method, meaning that once it's called it will execute fully, before code execution continues.
```
var obj= JSON.parse(jsonString);
obj.prop; // obj is already accessible.
```
---
JSON.parse, doesn't actually load any files. It's also synchronous, meaning that code execution resume, after it has finished it's function, which is to parse a valid JSON string, to a JavaScript object.
If you want to execute a callback after a file has loaded, you'd need to look into requests, and ajax to be more precise. Here's a simple example using jQuery.
```
$.ajax({
url: 'url/to/file.json',
dataType: 'json'
}).done(yourCallback);
``` |
157,005 | I have this tree shape artwork and i want to trim hole (which are spotted with black color). I tried with all the trim options, Did not work.
How can i trim. Any other way or option
[File](https://drive.google.com/file/d/1qjEp-3dyvqJSyAC8ivlnk8bKEl6zmx6F/view?usp=sharing)
[](https://i.stack.imgur.com/kT6CK.jpg) | 2022/05/04 | [
"https://graphicdesign.stackexchange.com/questions/157005",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/173783/"
] | Assuming the circles are on top of everything else...
* Select all the circles
* Choose `Object > Compound Path > Make` from the menu. This forces Illustrator to see the circles as one, singular object, rather than a collection of objects.
* Change the **Fill** of the circles to be either 100C100M100Y100K or 0R0G0B, depending upon the color mode you are working in. (Yes, 100% of all inks in CMYK - it's for a *mask* not printed objects.)
* Select all the artwork (trees and circles)
* On the **Transparency Panel** (`Window > Transparency`) click the `Make Mask` button
* **Untick** the `Clip` button on the **Transparency Panel**
This will give you an **Opacity Mask** which will "punch" out the holes in the underlying artwork.
[](https://i.stack.imgur.com/yqLwC.png)
More on opacity masks...
* [Opacity Mask With Multiple Images (Illustrator CS5)](https://graphicdesign.stackexchange.com/questions/6436/opacity-mask-with-multiple-images-illustrator-cs5)
* [Using the Opacity Mask on Illustrator](https://graphicdesign.stackexchange.com/questions/126822/using-the-opacity-mask-on-illustrator)
* [Why doesn't my opacity mask fully hide my object?](https://graphicdesign.stackexchange.com/questions/64083/why-doesnt-my-opacity-mask-fully-hide-my-object)
* [Illustrator: Opacity Mask is not moving/resizing along with object it masks, if the masked object is a Mesh object](https://graphicdesign.stackexchange.com/questions/137123/illustrator-opacity-mask-is-not-moving-resizing-along-with-object-it-masks-if)
* [How to create a gradient opacity mask in Illustrator](https://graphicdesign.stackexchange.com/questions/71406/how-to-create-a-gradient-opacity-mask-in-illustrator)
* [Feather Clipping Mask in Adobe Illustrator](https://graphicdesign.stackexchange.com/questions/153943/feather-clipping-mask-in-adobe-illustrator)
* [illustrator cs6 when exporting to PDF and print - the black area of masks shown in a low opacity also in PDF preview](https://graphicdesign.stackexchange.com/questions/54367/illustrator-cs6-when-exporting-to-pdf-and-print-the-black-area-of-masks-shown) | Definitely what Scott said, but depending on your end purpose, it may actually be easier and quicker to just edit the circles from a black fill, to a white fill. |
91,269 | I want to test a video IP core that reads a block of memory and writes to it again. The IP core is using the VFBC. My idea for testing was to write a core that looks like the VFBC, but just uses a simple 32Meg RAM as back-end.
It is allocated like this:
```
memory_size : NATURAL := ((2 * 2048) * 2048)
type memory_array is array (0 to (memory_size - 1)) of std_logic_vector(31 downto 0);
signal memory : memory_array;
```
ISim is crashing claiming that it needs more than 2 gig of ram, and questasim is allocating 12gig in the process of compilation for simulation.
**Note: I don't want to synthesize this. It is for simulation only!**
So the question is: how can I simulate such an RAM efficiently in VHDL? | 2013/11/20 | [
"https://electronics.stackexchange.com/questions/91269",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/25263/"
] | If the memory you are simulating can fit into the ram of the workstation then using a fixed-size storage is the easiest to use. But as you have seen, signals are much more expensive compared to variables. This difference is related to the *discrete event simulation* model that VHDL is based on. A signal assignment schedules a transaction at a given point in time, but a variable assignment is strictly a sequential statement that execute in zero simulation time. The difference can be seen in the memory usage of the two different models. The results are obtained by running the example code below in Riviera PRO.
Memory allocation when using a signal for data storage:
```
Allocation: Simulator allocated 891567 kB (elbread=1023 elab2=890389 kernel=154 sdf=0)
```
Memory allocation when using a variable for data storage:
```
Allocation: Simulator allocated 39599 kB (elbread=1023 elab2=38421 kernel=154 sdf=0)
```
Example code
------------
```
library ieee;
use ieee.std_logic_1164.all;
use std.env;
entity memtest is
end;
architecture sim of memtest is
signal clk : std_logic := '0';
signal we : std_logic;
signal writedata, q : integer;
signal addr : natural;
-- Uncomment or comment to switch between variable or signal for memory storage.
--signal mem : integer_vector(0 to 2 * 2048**2-1);
begin
clk <= not clk after 10 ns;
-----------------------------------
stimulus :
-----------------------------------
process
begin
for n in 0 to 100 loop
wait until falling_edge(clk);
we <= '1' ;
writedata <= n;
addr <= n;
end loop;
env.stop;
end process;
-----------------------------------
memory :
-----------------------------------
process ( clk )
-- Uncomment or comment to switch between variable or signal for memory storage.
variable mem : integer_vector(0 to 2 * 2048**2-1);
begin
if rising_edge(clk) then
q <= mem(addr);
if we = '1' then
-- Remember to modify assignment operator when switching data storage.
mem(addr) := writedata;
end if;
end if;
end process;
end;
``` | Are you needing to use all of that memory?
Could you get away with simulating a sparse memory...
Using some data structure like a dictionary (I have an [AVL tree](http://en.wikipedia.org/wiki/AVL_tree) - in my 'made-at-work' library, so i can't share it I'm afraid :( ) you can store just the values which have been written and the addresses they were written to. If your simulation only touches a small fraction of the array, you can save a lot!
Micron's memory models used to do this kind of thing, they would use `new` to allocate a row at a time as they were accessed. See if you can dig up their old single-data-rate synchronous DRAM models, they were quite instructive as I recall. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | You want to use a refactoring that replaces a conditional using a polymorphic class. For [example](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
Or here's another [example](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
====
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
```
function doWork(object x)
{
if (x is a type of Apple)
{
x.Eat();
} else if (x is a type of Orange)
{
x.Peel();
x.Eat();
}
}
```
Here you can refactor the switch into some new method that each fruit will handle.
Edit
====
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
```
class FruitFactory
{
Fruit GetMeMoreFruit(typeOfFruit)
{
switch (typeOfFruit)
...
...
}
}
```
The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an [Abstract Factory](http://en.wikipedia.org/wiki/Abstract_factory_pattern). You could also dynamically create the Fruit if your platform supports it. You could also use something like the [Provider Pattern](http://en.wikipedia.org/wiki/Provider_pattern). Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically. | You don't say what language you're using, but if you are using an OO language such as C++, C# or Java, you can often use **virtual functions** to solve the same problem as you are currently solving with a `switch` statement, and in a more extensible way. In the case of C++, compare:
```
class X {
public:
int get_type(); /* Or an enum return type or similar */
...
};
void eat(X& x) {
switch (x.get_type()) {
TYPE_A: eat_A(x); break;
TYPE_B: eat_B(x); break;
TYPE_C: eat_C(x); break;
}
}
void drink(X& x) {
switch (x.get_type()) {
TYPE_A: drink_A(x); break;
TYPE_B: drink_B(x); break;
TYPE_C: drink_C(x); break;
}
}
void be_merry(X& x) {
switch (x.get_type()) {
TYPE_A: be_merry_A(x); break;
TYPE_B: be_merry_B(x); break;
TYPE_C: be_merry_C(x); break;
}
}
```
with
```
class Base {
virtual void eat() = 0;
virtual void drink() = 0;
virtual void be_merry() = 0;
...
};
class A : public Base {
public:
virtual void eat() { /* Eat A-specific stuff */ }
virtual void drink() { /* Drink A-specific stuff */ }
virtual void be_merry() { /* Be merry in an A-specific way */ }
};
class B : public Base {
public:
virtual void eat() { /* Eat B-specific stuff */ }
virtual void drink() { /* Drink B-specific stuff */ }
virtual void be_merry() { /* Be merry in an B-specific way */ }
};
class C : public Base {
public:
virtual void eat() { /* Eat C-specific stuff */ }
virtual void drink() { /* Drink C-specific stuff */ }
virtual void be_merry() { /* Be merry in a C-specific way */ }
};
```
The advantage is that you can add new `Base`-derived classes `D`, `E`, `F` and so on without having to touch any code that only deals with pointers or references to `Base`, so there is nothing that can get out of date the way that a `switch` statement can in the original solution. (The transformation looks very similar in Java, where methods are virtual by default, and I'm sure it looks similar in C# too.) On a large project, this is a *huge* maintainability win. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | You want to use a refactoring that replaces a conditional using a polymorphic class. For [example](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
Or here's another [example](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
====
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
```
function doWork(object x)
{
if (x is a type of Apple)
{
x.Eat();
} else if (x is a type of Orange)
{
x.Peel();
x.Eat();
}
}
```
Here you can refactor the switch into some new method that each fruit will handle.
Edit
====
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
```
class FruitFactory
{
Fruit GetMeMoreFruit(typeOfFruit)
{
switch (typeOfFruit)
...
...
}
}
```
The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an [Abstract Factory](http://en.wikipedia.org/wiki/Abstract_factory_pattern). You could also dynamically create the Fruit if your platform supports it. You could also use something like the [Provider Pattern](http://en.wikipedia.org/wiki/Provider_pattern). Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically. | I actually wrote about how to solve this issues in my blog in April of 2008. Take a look [here](http://adotnetdude.blogspot.com/2008/03/refactoring-code-with-too-many.html) and let me know what you think.
I recommend you:
1. Use polymorphism to get the correct run-time behavior you need without conditional statements.
2. Take all your conditional statements, and move them into some sort of "factory" which will hand you the appropriate type at run-time.
3. You're done. Wasn't that easy? :)
If you want to see some actual code sample on how transform your code, head over to my blog.
*P.S. This is not a cheap attempt at self promotion; I've been a SO user for a long time now, and this is the first time I've linked to my blog - and I've only done so because I think it's relevant.* |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | Were you thinking of Google's "[The Clean Code Talks -- Inheritance, Polymorphism, & Testing](http://www.youtube.com/watch?v=4F72VULWFvc)" video? It discusses approaches to using Object Oriented techniques to remove if/switch conditionals. | How about:
```
/* Code Block 1... */
if(/* result of some condition or function call */)
{
/* Code Block 2... */
if(/* result of some condition or function call */)
{
/* Code Block 3... */
if(/* result of some condition or function call */)
{
/* Code Block 4... */
}
}
}
```
Becomes this:
```
/* Code Block 1... */
IsOk = /* result of some condition or function call */
if(IsOK)
{
/* Code Block 2... */
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 3...*/
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 4...*/
IsOk = /* result of some condition or function call */
}
/* And so on... */
```
You can of course return if ever IsOk becomes false, if appropriate. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | Have you read [this](http://www.codinghorror.com/blog/archives/000486.html) on flattening arrow code from Coding Horror?
You can replace throw with return or goto if you're using a language without exceptions. | I actually wrote about how to solve this issues in my blog in April of 2008. Take a look [here](http://adotnetdude.blogspot.com/2008/03/refactoring-code-with-too-many.html) and let me know what you think.
I recommend you:
1. Use polymorphism to get the correct run-time behavior you need without conditional statements.
2. Take all your conditional statements, and move them into some sort of "factory" which will hand you the appropriate type at run-time.
3. You're done. Wasn't that easy? :)
If you want to see some actual code sample on how transform your code, head over to my blog.
*P.S. This is not a cheap attempt at self promotion; I've been a SO user for a long time now, and this is the first time I've linked to my blog - and I've only done so because I think it's relevant.* |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | You want to use a refactoring that replaces a conditional using a polymorphic class. For [example](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
Or here's another [example](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
====
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
```
function doWork(object x)
{
if (x is a type of Apple)
{
x.Eat();
} else if (x is a type of Orange)
{
x.Peel();
x.Eat();
}
}
```
Here you can refactor the switch into some new method that each fruit will handle.
Edit
====
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
```
class FruitFactory
{
Fruit GetMeMoreFruit(typeOfFruit)
{
switch (typeOfFruit)
...
...
}
}
```
The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an [Abstract Factory](http://en.wikipedia.org/wiki/Abstract_factory_pattern). You could also dynamically create the Fruit if your platform supports it. You could also use something like the [Provider Pattern](http://en.wikipedia.org/wiki/Provider_pattern). Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically. | Have you read [this](http://www.codinghorror.com/blog/archives/000486.html) on flattening arrow code from Coding Horror?
You can replace throw with return or goto if you're using a language without exceptions. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | You don't say what language you're using, but if you are using an OO language such as C++, C# or Java, you can often use **virtual functions** to solve the same problem as you are currently solving with a `switch` statement, and in a more extensible way. In the case of C++, compare:
```
class X {
public:
int get_type(); /* Or an enum return type or similar */
...
};
void eat(X& x) {
switch (x.get_type()) {
TYPE_A: eat_A(x); break;
TYPE_B: eat_B(x); break;
TYPE_C: eat_C(x); break;
}
}
void drink(X& x) {
switch (x.get_type()) {
TYPE_A: drink_A(x); break;
TYPE_B: drink_B(x); break;
TYPE_C: drink_C(x); break;
}
}
void be_merry(X& x) {
switch (x.get_type()) {
TYPE_A: be_merry_A(x); break;
TYPE_B: be_merry_B(x); break;
TYPE_C: be_merry_C(x); break;
}
}
```
with
```
class Base {
virtual void eat() = 0;
virtual void drink() = 0;
virtual void be_merry() = 0;
...
};
class A : public Base {
public:
virtual void eat() { /* Eat A-specific stuff */ }
virtual void drink() { /* Drink A-specific stuff */ }
virtual void be_merry() { /* Be merry in an A-specific way */ }
};
class B : public Base {
public:
virtual void eat() { /* Eat B-specific stuff */ }
virtual void drink() { /* Drink B-specific stuff */ }
virtual void be_merry() { /* Be merry in an B-specific way */ }
};
class C : public Base {
public:
virtual void eat() { /* Eat C-specific stuff */ }
virtual void drink() { /* Drink C-specific stuff */ }
virtual void be_merry() { /* Be merry in a C-specific way */ }
};
```
The advantage is that you can add new `Base`-derived classes `D`, `E`, `F` and so on without having to touch any code that only deals with pointers or references to `Base`, so there is nothing that can get out of date the way that a `switch` statement can in the original solution. (The transformation looks very similar in Java, where methods are virtual by default, and I'm sure it looks similar in C# too.) On a large project, this is a *huge* maintainability win. | How about:
```
/* Code Block 1... */
if(/* result of some condition or function call */)
{
/* Code Block 2... */
if(/* result of some condition or function call */)
{
/* Code Block 3... */
if(/* result of some condition or function call */)
{
/* Code Block 4... */
}
}
}
```
Becomes this:
```
/* Code Block 1... */
IsOk = /* result of some condition or function call */
if(IsOK)
{
/* Code Block 2... */
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 3...*/
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 4...*/
IsOk = /* result of some condition or function call */
}
/* And so on... */
```
You can of course return if ever IsOk becomes false, if appropriate. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | I actually wrote about how to solve this issues in my blog in April of 2008. Take a look [here](http://adotnetdude.blogspot.com/2008/03/refactoring-code-with-too-many.html) and let me know what you think.
I recommend you:
1. Use polymorphism to get the correct run-time behavior you need without conditional statements.
2. Take all your conditional statements, and move them into some sort of "factory" which will hand you the appropriate type at run-time.
3. You're done. Wasn't that easy? :)
If you want to see some actual code sample on how transform your code, head over to my blog.
*P.S. This is not a cheap attempt at self promotion; I've been a SO user for a long time now, and this is the first time I've linked to my blog - and I've only done so because I think it's relevant.* | You don't say what language you're using, but if you are using an OO language such as C++, C# or Java, you can often use **virtual functions** to solve the same problem as you are currently solving with a `switch` statement, and in a more extensible way. In the case of C++, compare:
```
class X {
public:
int get_type(); /* Or an enum return type or similar */
...
};
void eat(X& x) {
switch (x.get_type()) {
TYPE_A: eat_A(x); break;
TYPE_B: eat_B(x); break;
TYPE_C: eat_C(x); break;
}
}
void drink(X& x) {
switch (x.get_type()) {
TYPE_A: drink_A(x); break;
TYPE_B: drink_B(x); break;
TYPE_C: drink_C(x); break;
}
}
void be_merry(X& x) {
switch (x.get_type()) {
TYPE_A: be_merry_A(x); break;
TYPE_B: be_merry_B(x); break;
TYPE_C: be_merry_C(x); break;
}
}
```
with
```
class Base {
virtual void eat() = 0;
virtual void drink() = 0;
virtual void be_merry() = 0;
...
};
class A : public Base {
public:
virtual void eat() { /* Eat A-specific stuff */ }
virtual void drink() { /* Drink A-specific stuff */ }
virtual void be_merry() { /* Be merry in an A-specific way */ }
};
class B : public Base {
public:
virtual void eat() { /* Eat B-specific stuff */ }
virtual void drink() { /* Drink B-specific stuff */ }
virtual void be_merry() { /* Be merry in an B-specific way */ }
};
class C : public Base {
public:
virtual void eat() { /* Eat C-specific stuff */ }
virtual void drink() { /* Drink C-specific stuff */ }
virtual void be_merry() { /* Be merry in a C-specific way */ }
};
```
The advantage is that you can add new `Base`-derived classes `D`, `E`, `F` and so on without having to touch any code that only deals with pointers or references to `Base`, so there is nothing that can get out of date the way that a `switch` statement can in the original solution. (The transformation looks very similar in Java, where methods are virtual by default, and I'm sure it looks similar in C# too.) On a large project, this is a *huge* maintainability win. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | Have you read [this](http://www.codinghorror.com/blog/archives/000486.html) on flattening arrow code from Coding Horror?
You can replace throw with return or goto if you're using a language without exceptions. | You might want to look at the [Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern), wherein instead of putting a long chain of ifs with linked conditions, you abstract each condition to a different object, each one defining what its specific behavior.
The class that defines those objects will implement an Interface which will be called by the parent object. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | Have you read [this](http://www.codinghorror.com/blog/archives/000486.html) on flattening arrow code from Coding Horror?
You can replace throw with return or goto if you're using a language without exceptions. | Were you thinking of Google's "[The Clean Code Talks -- Inheritance, Polymorphism, & Testing](http://www.youtube.com/watch?v=4F72VULWFvc)" video? It discusses approaches to using Object Oriented techniques to remove if/switch conditionals. |
494,506 | Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?
I remember coming across some methods used by the Google folks listed in a Google code blog post. Can’t seem to find it now though | 2009/01/30 | [
"https://Stackoverflow.com/questions/494506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22039/"
] | You want to use a refactoring that replaces a conditional using a polymorphic class. For [example](http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html).
Or here's another [example](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)
Essentially the ideal is very simple you create an object heirarchy, and move the various behaviors into an overriden method. You will still need a method to create the right class but this can be done using a factory pattern.
Edit
====
Let me add that this is not a perfect solution in every case. As (I forgot your name sorry) pointed in my comments, some times this can be a pain especially if you have to create an object model just to do this. This refactoring excells if you have this:
```
function doWork(object x)
{
if (x is a type of Apple)
{
x.Eat();
} else if (x is a type of Orange)
{
x.Peel();
x.Eat();
}
}
```
Here you can refactor the switch into some new method that each fruit will handle.
Edit
====
As someone pointed out how do you create the right type to go into doWork, there are more ways to solve this problem then I could probally list so some basic ways. The first and most straight forward (and yes goes against the grain of this question) is a switch:
```
class FruitFactory
{
Fruit GetMeMoreFruit(typeOfFruit)
{
switch (typeOfFruit)
...
...
}
}
```
The nice thing about this approach is it's easy to write, and is usually the first method I use. While you still have a switch statement its isolated to one area of code and is very basic all it returns is a n object. If you only have a couple of objects and they;re not changing this works very well.
Other more compelx patterns you can look into is an [Abstract Factory](http://en.wikipedia.org/wiki/Abstract_factory_pattern). You could also dynamically create the Fruit if your platform supports it. You could also use something like the [Provider Pattern](http://en.wikipedia.org/wiki/Provider_pattern). Which essentially to me means you configure your object and then you have a factory which based on the configuration and a key you give the factory creates the right class dynamically. | How about:
```
/* Code Block 1... */
if(/* result of some condition or function call */)
{
/* Code Block 2... */
if(/* result of some condition or function call */)
{
/* Code Block 3... */
if(/* result of some condition or function call */)
{
/* Code Block 4... */
}
}
}
```
Becomes this:
```
/* Code Block 1... */
IsOk = /* result of some condition or function call */
if(IsOK)
{
/* Code Block 2... */
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 3...*/
IsOk = /* result of some condition or function call */
}
if(IsOK)
{
/* Code Block 4...*/
IsOk = /* result of some condition or function call */
}
/* And so on... */
```
You can of course return if ever IsOk becomes false, if appropriate. |
38,116,133 | I have a nodejs + expressjs app that needs to be converted to an android. A quick solution that we are thinking of is to use phonegap. The issue I am stuck with is all my files under view folder of the web app are ejs files.
When I try to upload my app to phonegap it says no index.html found in my .zip folder.
My question here is:
1. Should I separate the front end files from the node app? using html and pure js?
2. Is there a way I can render ejs files on to html files (something like import) so that I can convert existing web app into an android app?
3. Is there an option in phonegap to use ejs files instead of html files?
I am using <https://build.phonegap.com/> for converting the app. Someone please help as I am stuck with this for a long time. | 2016/06/30 | [
"https://Stackoverflow.com/questions/38116133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3467302/"
] | As per our discussion discussion , below solution comes:-
1.Need to install `CURL` on your system by the command :-
```
sudo apt-get install php7.0-curl
```
2.Regarding second error i got this link:- [utf8\_(en|de)code removed from php7?](https://stackoverflow.com/questions/35701730/utf8-endecode-removed-from-php7)
It states that `utf8_encode/decode` is function related to `php xml extension` which you have to install your system by below command:-
```
sudo apt-get install php7.0-xml
```
***Important Note:-*** after install of these library packages ***restart*** your ***server*** so that ***changes will reflect***. Thanks. | `utf8_encode()` is a function under the `php xml extension`, and `curl` of-course under the `curl extension`.
Solved by
```
sudo apt-get install php7.0-curl
```
and
```
sudo apt-get install php7.0-xml
``` |
59,444,161 | I am getting really frustrated already. I have tried so many variations and searched for an answer in all existing stackoverflow questions, but it didn't help.
All I need is to get **ALL the text** (**without the @class name 'menu' or without the @id name 'menu'**)
I have tried already these commands:
```
//*[not(descendant-or-self::*[(contains(@id, 'menu')) or (contains(@class, 'menu'))])]/text()[normalize-space()]
```
But whatever I try, I always get back the **all the text even with the elements that I excluded**.
Ps: I am using Scrapy which uses XPATH 1.0
```html
<body>
<div id="top">
<div class="topHeader">
<div class="topHeaderContent">
<a class="headerLogo" href="/Site/Home.de.html"></a>
<a class="headerText" href="/Site/Home.de.html"></a>
<div id="menuSwitch"></div>
</div>
</div>
<div class="topContent">
<div id="menuWrapper">
<nav>
<ul class="" id="menu"><li class="firstChild"><a class="topItem" href="/Site/Home.de.html">Home</a> </li>
<li class="hasChild"><span class="topItem">Produkte</span><ul class=" menuItems"><li class=""><a href="/Site/Managed_Services.de.html">Managed Services</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">VideoServices</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Mobile Publishing</a> </li>
<li class=""><a href="/Site/Broadcasting.de.html">Broadcasting</a> </li>
<li class=""><a href="/Site/Content_Management.de.html">Content Management</a> </li>
</ul>
</li>
<li class="hasChild"><span class="topItem">Digital Media Base</span><ul class=" menuItems"><li class=""><a href="/Site.de.html">About DMB</a> </li>
<li class=""><a href="/Site/DMB/Quellen.de.html">Quellen</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">Video</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Apps</a> </li>
<li class=""><a href="/Site/DMB/Web.de.html">Web</a> </li>
<li class=""><a href="/Site/DMB/Archiv.de.html">Archiv</a> </li>
<li class=""><a href="/Site/DMB/Social_Media.de.html">Social Media</a> </li>
<li class=""><a href="/Site/DMB/statistik.de.html">Statistik</a> </li>
<li class=""><a href="/Site/DMB/Payment.de.html">Payment</a> </li>
</ul>
</li>
<li class="activeMenu "><a class="topItem" href="/Site/Karriere.de.html">Karriere</a> </li>
<li class="hasChild"><span class="topItem">Fake-IT</span><ul class=" menuItems"><li class=""><a href="/Site/About.de.html">About</a> </li>
<li class=""><a href="/Site/Management.de.html">Management</a> </li>
<li class=""><a href="/Site/Mission_Statement.de.html">Mission Statement</a> </li>
<li class=""><a href="/Site/Pressemeldungen.de.html">Pressemeldungen</a> </li>
<li class=""><a href="/Site/Referenzen.de.html">Kunden</a> </li>
</ul>
</li>
</ul>
</nav>
<div class="topSearch">
<div class="topSearch">
<form action="/Site/Suchergebnis.html" method="get">
<form action="/Site/Suchergebnis.html" method="get">
<input class="searchText" onblur="processSearch(this, "Suchbegriff", "blur")" onfocus="processSearch(this,"Suchbegriff")" type="text" value="Suchbegriff" name="searchTerm" id="searchTerm" />
<input class="searchSubmit" id="js_searchSubmit" type="submit" name="yt0" />
<div class="stopFloat">
</div>
</form>
</div>
</div>
</div>
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</body>
```
**I always get this back:**
```
['Home',
'Produkte',
'Managed Services',
'VideoServices',
'Mobile Publishing',
'Broadcasting',
'Content Management',
'Digital Media Base',
'About DMB',
'Quellen',
'Video',
'Apps',
'Web',
'Archiv',
'Social Media',
'Statistik',
'Payment',
'Karriere',
'Fake-IT',
'About',
'Management',
'Mission Statement',
'Pressemeldungen',
'Kunden',
' I want to have this text here! ',
' I want to have this text here! ']
```
**But I need it like that:**
```
[' I want to have this text here! ',
' I want to have this text here! ']
``` | 2019/12/22 | [
"https://Stackoverflow.com/questions/59444161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7513730/"
] | This very convoluted xpath 1.0 expression works on your sample html. It would be somewhat simpler in xpath 2.0 and above. But try it on your actual code:
```
//*[not(descendant-or-self::*[contains(@class,'menu')])]
[not(descendant-or-self::*[contains(@id,'menu')])]
[not(ancestor-or-self::*[contains(@class,'menu')])]
[not(ancestor-or-self::*[contains(@id,'menu')])]//text()
``` | Well, if you consider the element
`<li class=""><a href="/Site/DMB/Video.de.html">VideoServices</a> </li>`
it's a descendant-or-self of something, and it doesn't have the relevant id or class attribute, so of course it gets selected.
Perhaps you want `//*[not(ancestor-or-self::*[@id='menu' or @class='menu']]`
You wrote "contains" but I'm not sure if you really meant it. A lot of people use `contains()` when they should be using "=". |
59,444,161 | I am getting really frustrated already. I have tried so many variations and searched for an answer in all existing stackoverflow questions, but it didn't help.
All I need is to get **ALL the text** (**without the @class name 'menu' or without the @id name 'menu'**)
I have tried already these commands:
```
//*[not(descendant-or-self::*[(contains(@id, 'menu')) or (contains(@class, 'menu'))])]/text()[normalize-space()]
```
But whatever I try, I always get back the **all the text even with the elements that I excluded**.
Ps: I am using Scrapy which uses XPATH 1.0
```html
<body>
<div id="top">
<div class="topHeader">
<div class="topHeaderContent">
<a class="headerLogo" href="/Site/Home.de.html"></a>
<a class="headerText" href="/Site/Home.de.html"></a>
<div id="menuSwitch"></div>
</div>
</div>
<div class="topContent">
<div id="menuWrapper">
<nav>
<ul class="" id="menu"><li class="firstChild"><a class="topItem" href="/Site/Home.de.html">Home</a> </li>
<li class="hasChild"><span class="topItem">Produkte</span><ul class=" menuItems"><li class=""><a href="/Site/Managed_Services.de.html">Managed Services</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">VideoServices</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Mobile Publishing</a> </li>
<li class=""><a href="/Site/Broadcasting.de.html">Broadcasting</a> </li>
<li class=""><a href="/Site/Content_Management.de.html">Content Management</a> </li>
</ul>
</li>
<li class="hasChild"><span class="topItem">Digital Media Base</span><ul class=" menuItems"><li class=""><a href="/Site.de.html">About DMB</a> </li>
<li class=""><a href="/Site/DMB/Quellen.de.html">Quellen</a> </li>
<li class=""><a href="/Site/DMB/Video.de.html">Video</a> </li>
<li class=""><a href="/Site/DMB/Apps.de.html">Apps</a> </li>
<li class=""><a href="/Site/DMB/Web.de.html">Web</a> </li>
<li class=""><a href="/Site/DMB/Archiv.de.html">Archiv</a> </li>
<li class=""><a href="/Site/DMB/Social_Media.de.html">Social Media</a> </li>
<li class=""><a href="/Site/DMB/statistik.de.html">Statistik</a> </li>
<li class=""><a href="/Site/DMB/Payment.de.html">Payment</a> </li>
</ul>
</li>
<li class="activeMenu "><a class="topItem" href="/Site/Karriere.de.html">Karriere</a> </li>
<li class="hasChild"><span class="topItem">Fake-IT</span><ul class=" menuItems"><li class=""><a href="/Site/About.de.html">About</a> </li>
<li class=""><a href="/Site/Management.de.html">Management</a> </li>
<li class=""><a href="/Site/Mission_Statement.de.html">Mission Statement</a> </li>
<li class=""><a href="/Site/Pressemeldungen.de.html">Pressemeldungen</a> </li>
<li class=""><a href="/Site/Referenzen.de.html">Kunden</a> </li>
</ul>
</li>
</ul>
</nav>
<div class="topSearch">
<div class="topSearch">
<form action="/Site/Suchergebnis.html" method="get">
<form action="/Site/Suchergebnis.html" method="get">
<input class="searchText" onblur="processSearch(this, "Suchbegriff", "blur")" onfocus="processSearch(this,"Suchbegriff")" type="text" value="Suchbegriff" name="searchTerm" id="searchTerm" />
<input class="searchSubmit" id="js_searchSubmit" type="submit" name="yt0" />
<div class="stopFloat">
</div>
</form>
</div>
</div>
</div>
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</div>
<p> I want to have this text here! </p>
.
.
More elements
.
.
</body>
```
**I always get this back:**
```
['Home',
'Produkte',
'Managed Services',
'VideoServices',
'Mobile Publishing',
'Broadcasting',
'Content Management',
'Digital Media Base',
'About DMB',
'Quellen',
'Video',
'Apps',
'Web',
'Archiv',
'Social Media',
'Statistik',
'Payment',
'Karriere',
'Fake-IT',
'About',
'Management',
'Mission Statement',
'Pressemeldungen',
'Kunden',
' I want to have this text here! ',
' I want to have this text here! ']
```
**But I need it like that:**
```
[' I want to have this text here! ',
' I want to have this text here! ']
``` | 2019/12/22 | [
"https://Stackoverflow.com/questions/59444161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7513730/"
] | This very convoluted xpath 1.0 expression works on your sample html. It would be somewhat simpler in xpath 2.0 and above. But try it on your actual code:
```
//*[not(descendant-or-self::*[contains(@class,'menu')])]
[not(descendant-or-self::*[contains(@id,'menu')])]
[not(ancestor-or-self::*[contains(@class,'menu')])]
[not(ancestor-or-self::*[contains(@id,'menu')])]//text()
``` | You can iterate tags through scrapy lxml tree directly as it in this code sample:
```
result = []
for tag in response.css("*"):
if 'id' not in tag.attrib and 'class' not in tag.attrib and 'href' not in tag.attrib:
text = tag.css("::text").extract_first("").strip("\n ")
if text:
result.append(tag.css("::text").extract_first())
```
As You can see I also excluded tags with`href` attribute as `<a>` tags like this:
`<a href="/Site/DMB/Video.de.html">VideoServices</a>`
dont have `class` and `id` attribute and they technically don't violate your Xpath expression.
So if you are planning to use Xpath selectors - you need to exclude tags with `href` attribute too. |
60,140,614 | So I have a wordlist containing 3 words:
```
Apple
Christmas Tree
Shopping Bag
```
And I know only certain characters in the word and the length of the word, for instance:
>
> *???i???as ?r??*
>
>
>
where the **?** means it's an unknown character and I want to type it into the console and get an output of ALL the words in the word list containing these characters in these places and with this amount of characters.
Is there any way I can achieve this? I want my program to function in the same way *<https://onelook.com/>* works. | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123677/"
] | You can turn your expression into a regex and try matching with that:
```
import re
words = [
'Apple',
'Christmas Tree',
'Shopping Bag'
]
match = '???i???as ?r??'
regex = '^' + match.replace('?', '.') + '$' # turn your expression into a proper regex
for word in words: # go through each word
if re.match(regex, word): # does the word match the regex?
print(word)
```
Output:
```
Christmas Tree
``` | Try If `str` is in list.
```
IF "str" IN [list]
``` |
60,140,614 | So I have a wordlist containing 3 words:
```
Apple
Christmas Tree
Shopping Bag
```
And I know only certain characters in the word and the length of the word, for instance:
>
> *???i???as ?r??*
>
>
>
where the **?** means it's an unknown character and I want to type it into the console and get an output of ALL the words in the word list containing these characters in these places and with this amount of characters.
Is there any way I can achieve this? I want my program to function in the same way *<https://onelook.com/>* works. | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123677/"
] | You can turn your expression into a regex and try matching with that:
```
import re
words = [
'Apple',
'Christmas Tree',
'Shopping Bag'
]
match = '???i???as ?r??'
regex = '^' + match.replace('?', '.') + '$' # turn your expression into a proper regex
for word in words: # go through each word
if re.match(regex, word): # does the word match the regex?
print(word)
```
Output:
```
Christmas Tree
``` | If you have a *small* word list, then you can run a regex scan on the whole word list. Convert the query string into a regex and you're good to go.
Otherwise, you can organize the word list in chunks, e.g. the equivalent of splitting it into several files in different directories:
```
Appl => [ Apple ]
Chri => [ Christchurch, Christmas Tree, ... ]
Shop => [ Shopper, Shopping Bag, Shopkeeper, ]
```
(You can have several levels).
Since your search query seems to be *anchored*, i.e. you know it starts at the word's beginning, when you look for "???i???as ?r??" you see that "???i" will only match "Chri", and only look in that sub-list.
(Actually if you have to do this a lot of times, you'll better build a recursive search and organize the list as a [n- or "m-ary" tree](https://en.wikipedia.org/wiki/M-ary_tree) - here are some [examples](https://www.ics.uci.edu/~brgallar/week6_3.html)). |
60,140,614 | So I have a wordlist containing 3 words:
```
Apple
Christmas Tree
Shopping Bag
```
And I know only certain characters in the word and the length of the word, for instance:
>
> *???i???as ?r??*
>
>
>
where the **?** means it's an unknown character and I want to type it into the console and get an output of ALL the words in the word list containing these characters in these places and with this amount of characters.
Is there any way I can achieve this? I want my program to function in the same way *<https://onelook.com/>* works. | 2020/02/09 | [
"https://Stackoverflow.com/questions/60140614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10123677/"
] | If you have a *small* word list, then you can run a regex scan on the whole word list. Convert the query string into a regex and you're good to go.
Otherwise, you can organize the word list in chunks, e.g. the equivalent of splitting it into several files in different directories:
```
Appl => [ Apple ]
Chri => [ Christchurch, Christmas Tree, ... ]
Shop => [ Shopper, Shopping Bag, Shopkeeper, ]
```
(You can have several levels).
Since your search query seems to be *anchored*, i.e. you know it starts at the word's beginning, when you look for "???i???as ?r??" you see that "???i" will only match "Chri", and only look in that sub-list.
(Actually if you have to do this a lot of times, you'll better build a recursive search and organize the list as a [n- or "m-ary" tree](https://en.wikipedia.org/wiki/M-ary_tree) - here are some [examples](https://www.ics.uci.edu/~brgallar/week6_3.html)). | Try If `str` is in list.
```
IF "str" IN [list]
``` |
54,828,044 | I'm trying to reference an object that I'm matching for.
```
import re
list = ["abc","b","c"]
if any(re.search(r"a",i) for i in list):
print("yes")
print(i)
```
This works, just not the last `print` command.
Is there any way to do what I'm trying do to here? | 2019/02/22 | [
"https://Stackoverflow.com/questions/54828044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9599075/"
] | This solution will scale worse for *large arrays*, for such cases the other proposed answers will perform better.
---
Here's one way taking advantage of [`broadcasting`](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html):
```
(coo[:,None] == targets).all(2).any(1)
# array([False, True, True, False])
```
---
**Details**
Check for every row in `coo` whether or not it matches another in `target` by direct comparisson having added a first axis to `coo` so it becomes broadcastable against `targets`:
```
(coo[:,None] == targets)
array([[[False, False],
[ True, False]],
[[False, False],
[ True, True]],
[[ True, True],
[False, False]],
[[False, False],
[False, True]]])
```
Then check which `ndarrays` along the second axis have [`all`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html) values to `True`:
```
(coo[:,None] == targets).all(2)
array([[False, False],
[False, True],
[ True, False],
[False, False]])
```
And finally use [`any`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html) to check which rows have at least one `True`. | Here is a simple and intuitive solution that actually uses `numpy.isin()`, to **match tuples**, rather than match individual numbers:
```
# View as a 1d array of tuples
coo_view = coo.view(dtype='i,i').reshape((-1,))
targets_view = targets.view(dtype='i,i').reshape((-1,))
result = np.isin(coo_view, targets_view)
print (result)
print(result.nonzero()[0])
```
**Output:**
```
[False True True False]
[1 2]
```
**Notes:**
1. The creation of these [views](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ndarray.view.html) does not involve any copying of data.
2. The `dtype='i,i'` specifies that we want each element of the view to be a tuple of two integers |
54,828,044 | I'm trying to reference an object that I'm matching for.
```
import re
list = ["abc","b","c"]
if any(re.search(r"a",i) for i in list):
print("yes")
print(i)
```
This works, just not the last `print` command.
Is there any way to do what I'm trying do to here? | 2019/02/22 | [
"https://Stackoverflow.com/questions/54828044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9599075/"
] | This solution will scale worse for *large arrays*, for such cases the other proposed answers will perform better.
---
Here's one way taking advantage of [`broadcasting`](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html):
```
(coo[:,None] == targets).all(2).any(1)
# array([False, True, True, False])
```
---
**Details**
Check for every row in `coo` whether or not it matches another in `target` by direct comparisson having added a first axis to `coo` so it becomes broadcastable against `targets`:
```
(coo[:,None] == targets)
array([[[False, False],
[ True, False]],
[[False, False],
[ True, True]],
[[ True, True],
[False, False]],
[[False, False],
[False, True]]])
```
Then check which `ndarrays` along the second axis have [`all`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html) values to `True`:
```
(coo[:,None] == targets).all(2)
array([[False, False],
[False, True],
[ True, False],
[False, False]])
```
And finally use [`any`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html) to check which rows have at least one `True`. | The [numpy\_indexed](https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/master/numpy_indexed/arraysetops.py#L86) package implements functionality of this type in a vectorized manner (disclaimer: I am its author). Sadly numpy lacks a lot of this functionality out of the box; I started numpy\_indexed with the intention of having it merged into numpy, but there are some backwards compatibility concerns, and big packages like that tend to move slowly. So that hasnt happened in the last 3 years; but the python packaging ecosystem works so well nowadays that just adding one more package to your environment is just as simple, really.
```
import numpy_indexed as npi
bools = npi.in_(targets, coo)
```
This will have a time-complexity similar to that of the solution posted by @fountainhead (logarithmic rather than linear, as per the currently accepted answer), but also the npi library will give you the safety of automated tests, and a lot of other convenient options, should you decide to approach the problem from a slightly different angle. |
1,393,216 | I have an strange problem.
This is Microsoft Office 365 under Windows 10 and I don't remember when, but every time I start the computer, Excel is opened with a blank workbook.
I looked at startup tab in task manager and it is not there.. I also saw in Settings -> Applications -> Startup and it is not there two.
Do you have an advice to avoid this?
Thanks
Jaime
---
Well I did just as you said to do unfortunately though now I **can't get past the windows log in screen because it disabled my fingerprint reader and my pin code**.
*Can you tell me how to set it back to a normal boot up so that I can log back into my computer please.* | 2019/01/11 | [
"https://superuser.com/questions/1393216",
"https://superuser.com",
"https://superuser.com/users/524721/"
] | It turns out that this may be caused by a so-called feature of Microsoft.
Short answer:
Windows Settings->Accounts->Sign-In Options->Privacy->Off
Longer answer:
<https://answers.microsoft.com/en-us/msoffice/forum/all/microsoft-word-and-excel-2016-automatically-opens/8d5869df-0212-4f04-9fac-c7e99256a005> | The issue might be from a startup application or service which is opening excel at startup.
Run msconfig from the run dialog(Windows Key + R) to open the System Configuration. From the General Tab choose Selective StartUp, uncheck Load startup items(this will disable all startup items seen in the Task Manager). Apply and reboot your computer. See if it still pops up. If it does, then try also disabling the services by unchecking Load system services in the Selective startup section.
If it doesn't pop up, then you can set your computer back to Normal Startup in the system configuration, and then one by one disabling the Startup apps from the Task Manager to find out which app is causing the issue. |
58,140,603 | How can i make single select statement that combine both Select statements on the basis of only common 'PO' and 'Style Number' column

 | 2019/09/27 | [
"https://Stackoverflow.com/questions/58140603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571211/"
] | [ASP.NET Core 3.0 not currently available for Azure App Service.](https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#aspnet-core-30-not-currently-available-for-azure-app-service) [Microsoft Docs]
The [preview versions of .NET Core 3.0](https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/azure-apps/index?view=aspnetcore-3.0&tabs=visual-studio#deploy-aspnet-core-preview-release-to-azure-app-service) [Microsoft Docs] are available on the Azure service. | Change this in web.config:
```xml
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
```
to this:
```xml
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
```
I removed `V2` from this `modules="AspNetCoreModuleV2"` and it works. |
58,140,603 | How can i make single select statement that combine both Select statements on the basis of only common 'PO' and 'Style Number' column

 | 2019/09/27 | [
"https://Stackoverflow.com/questions/58140603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571211/"
] | The current [picture](https://aspnetcoreon.azurewebsites.net/) is that ASP.NET Core 3.0 is available everywhere (but not the SDK).
Despite this fact, I (seemingly randomly) got a
```
HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
```
until I realized that activating logging in `web.config` by setting `stdoutLogEnabled` to `true` *without* adjusting the `stdoutLogFile` to `\\?\%home%\LogFiles\stdout` (as suggested in [Troubleshoot ASP.NET Core on Azure App Service and IIS](https://learn.microsoft.com/en-us/aspnet/core/test/troubleshoot-azure-iis?view=aspnetcore-3.0)) was the cause of this error message.
Took me some hours to realize this causality. | Change this in web.config:
```xml
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
```
to this:
```xml
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
```
I removed `V2` from this `modules="AspNetCoreModuleV2"` and it works. |
22,098,456 | I have in my MainPage() the following line of code:
```
string str = tbx1.Text;
```
Then I have a slider that changes this TextBox:
```
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
tbx1.Text = slider1.Value.ToString();
}
```
When I run the app the default value of `tbx1` is read in, and it can be changed with the slider. But how do I read in the new value of `tbx1` into `str`? It seems that only the default value is kept in `str`. | 2014/02/28 | [
"https://Stackoverflow.com/questions/22098456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189952/"
] | If string is accessable you can do the following
```
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
tbx1.Text = slider1.Value.ToString();
str = slider1.Value.ToString();
}
``` | if you want to change str when `tbx1.Text` you can do that :
youcan declare your value in your class
```
private string _str
```
then you have to make your code : (you have to add Leave function to your textbox)
```
private void tbx1_Leave(object sender, EventArgs e)
{
_str = tbx1.Text;
}
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
_str = tbx1.Text = slider1.Value.ToString();
}
``` |
22,098,456 | I have in my MainPage() the following line of code:
```
string str = tbx1.Text;
```
Then I have a slider that changes this TextBox:
```
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
tbx1.Text = slider1.Value.ToString();
}
```
When I run the app the default value of `tbx1` is read in, and it can be changed with the slider. But how do I read in the new value of `tbx1` into `str`? It seems that only the default value is kept in `str`. | 2014/02/28 | [
"https://Stackoverflow.com/questions/22098456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189952/"
] | You can wrap the string in a property and access it dynamically:
```
string Str
{
get { return tbx1.Text; }
set { tbx1.Text = value; }
}
```
If you only need to read the string then you can drop the setter:
```
string Str
{
get { return tbx1.Text; }
}
```
Use the property `Str` instead of the variable `str`. This will always yield the actual value (example):
```
string result = Str;
```
---
**UPDATE**
Alternatively you could directly get the value from the slider.
```
string Str
{
get { return slider1.Value.ToString(); }
}
``` | if you want to change str when `tbx1.Text` you can do that :
youcan declare your value in your class
```
private string _str
```
then you have to make your code : (you have to add Leave function to your textbox)
```
private void tbx1_Leave(object sender, EventArgs e)
{
_str = tbx1.Text;
}
private void Slider_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider1 = sender as Slider;
_str = tbx1.Text = slider1.Value.ToString();
}
``` |
1,921,621 | I have this problem for a long time, and can't find a solution.
I guess this might be something everybodys faced using Sphinx, but I cnanot get any
usefull information.
I have one index, and a delta.
I queried in a php module both indexes, and then show the results.
For each ID in the result, I create an object for the model, and dsiplay main data for
that model.
I delete one document from the database, phisically.
When I query the index, the ID for this deleted document is still there (in the sphinx
result set).
Maybe I can detect this by code, and avoid showing it, but the result set sphinx gaves me
as result is wrong. xxx total\_found, when really is xxx-1.
For example, Sphinx gaves me the first 20 results, but one of this 20 results doesn't
exists anymore, so I have to show only 19 results.
I re-index the main index once per day, and the delta index, each 5 minutes.
Is there a solution for this??
Thanks in advance!! | 2009/12/17 | [
"https://Stackoverflow.com/questions/1921621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170915/"
] | Maybe this fits better to my needs, but involves changing the database.
<http://sphinxsearch.com/docs/current.html#conf-sql-query-killlist> | I suppose you could ask for maybe 25 results from sphinx and then when you get the full data from your DB just have a `limit 20` on the query. |
1,921,621 | I have this problem for a long time, and can't find a solution.
I guess this might be something everybodys faced using Sphinx, but I cnanot get any
usefull information.
I have one index, and a delta.
I queried in a php module both indexes, and then show the results.
For each ID in the result, I create an object for the model, and dsiplay main data for
that model.
I delete one document from the database, phisically.
When I query the index, the ID for this deleted document is still there (in the sphinx
result set).
Maybe I can detect this by code, and avoid showing it, but the result set sphinx gaves me
as result is wrong. xxx total\_found, when really is xxx-1.
For example, Sphinx gaves me the first 20 results, but one of this 20 results doesn't
exists anymore, so I have to show only 19 results.
I re-index the main index once per day, and the delta index, each 5 minutes.
Is there a solution for this??
Thanks in advance!! | 2009/12/17 | [
"https://Stackoverflow.com/questions/1921621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170915/"
] | What I've done in my Ruby Sphinx adapter, Thinking Sphinx, is to track when records are deleted, and update a boolean attribute for the records in the main index (I call it `sphinx_deleted`). Then, whenever I search, I filter on values where `sphinx_deleted` is 0. In the sql\_query configuration, I have the explicit attribute as follows:
```
SELECT fields, more_fields, 0 as sphinx_deleted FROM table
```
And of course there's the attribute definition as well.
```
sql_attr_bool = sphinx_deleted
```
Keep in mind that these updates to attributes (using the Sphinx API) are only stored in memory - the underlying index files aren't changed, so if you restart Sphinx, you'll lose this knowledge, unless you do a full index as well.
This is a bit of work, but it will ensure your result count and pagination will work neatly. | I suppose you could ask for maybe 25 results from sphinx and then when you get the full data from your DB just have a `limit 20` on the query. |
1,921,621 | I have this problem for a long time, and can't find a solution.
I guess this might be something everybodys faced using Sphinx, but I cnanot get any
usefull information.
I have one index, and a delta.
I queried in a php module both indexes, and then show the results.
For each ID in the result, I create an object for the model, and dsiplay main data for
that model.
I delete one document from the database, phisically.
When I query the index, the ID for this deleted document is still there (in the sphinx
result set).
Maybe I can detect this by code, and avoid showing it, but the result set sphinx gaves me
as result is wrong. xxx total\_found, when really is xxx-1.
For example, Sphinx gaves me the first 20 results, but one of this 20 results doesn't
exists anymore, so I have to show only 19 results.
I re-index the main index once per day, and the delta index, each 5 minutes.
Is there a solution for this??
Thanks in advance!! | 2009/12/17 | [
"https://Stackoverflow.com/questions/1921621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/170915/"
] | What I've done in my Ruby Sphinx adapter, Thinking Sphinx, is to track when records are deleted, and update a boolean attribute for the records in the main index (I call it `sphinx_deleted`). Then, whenever I search, I filter on values where `sphinx_deleted` is 0. In the sql\_query configuration, I have the explicit attribute as follows:
```
SELECT fields, more_fields, 0 as sphinx_deleted FROM table
```
And of course there's the attribute definition as well.
```
sql_attr_bool = sphinx_deleted
```
Keep in mind that these updates to attributes (using the Sphinx API) are only stored in memory - the underlying index files aren't changed, so if you restart Sphinx, you'll lose this knowledge, unless you do a full index as well.
This is a bit of work, but it will ensure your result count and pagination will work neatly. | Maybe this fits better to my needs, but involves changing the database.
<http://sphinxsearch.com/docs/current.html#conf-sql-query-killlist> |
54,145,150 | I am trying to automate a pretty trivial scenario where I have to get the text inside multiple `li` child elements of a `ul` elements and compare it against a given array. I am using Protractor with Cucumber JS and using `async/await` to manage promises.
My scenario HTML looks something like this
```
<div class="some-class">
<ul class="some-ul-class">
<li>
<span>Heading1: </span>
<span class="some-span-class> Value of Heading 1</span>
</li>
<li>
<span>Heading2: </span>
<span class="some-span-class> Value of Heading 2</span>
</li>
<li>
<span>Heading3: </span>
<span class="some-span-class> Value of Heading 3</span>
</li>
<li>
<span>Heading4: </span>
<span class="some-span-class> Value of Heading 4</span>
</li>
<li>
<span>Heading5: </span>
<span class="some-span-class> Value of Heading 5</span>
</li>
```
I need to get the values of the first span element i.e the `Heading1`, `Heading2` texts. I saw a lot of approaches in SO, but none of them have resulted in a solution. Most of the solutions do not have `async/await` implemented and if I try them, the code doesn't do what it is intended to do.
Examples I've referred : [Protractor Tests get Values of Table entries](https://stackoverflow.com/questions/34135713/protractor-tests-get-values-of-table-entries)
[Protractor : Read Table contents](https://stackoverflow.com/questions/29501976/protractor-read-table-contents)
If I try using the `map` function inside the `async` block, but that resulted in a `ECONNREFUSED` error, and hence has been suggested not to do so [here](https://github.com/angular/protractor/issues/4706).
Would appreciate if someone can guide me towards a solution on this one. | 2019/01/11 | [
"https://Stackoverflow.com/questions/54145150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1728790/"
] | ```js
(function ($) {
$.fn.formNavigation = function () {
$(this).each(function () {
// Events triggered on keydown (repeatable when holding the key)
$(this).find('input').on('keydown', function(e) {
// Vertical navigation using tab as OP wanted
if (e.which === 13 && !e.shiftKey) {
// navigate forward
if ($(this).closest('tr').next().find('input').length>0) {
// when there is another row below
e.preventDefault();
$(this).closest('tr').next().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').length>0) {
// when last row reached
e.preventDefault();
$(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').focus();
}
} else if (e.which === 13 && e.shiftKey) {
// navigate backward
if ($(this).closest('tr').prev().find('input').length>0) {
// when there is another row above
e.preventDefault();
$(this).closest('tr').prev().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').length>0) {
// when first row reached
e.preventDefault();
$(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').focus();
}
}
});
});
};
})(jQuery);
// usage
$('.gridexample').formNavigation();
```
```html
<!DOCTYPE html>
<html>
<body>
<table class="gridexample">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</tbody>
<table>
<!-- jQuery needed for this solution -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</body>
</html>
``` | Try tabIndex
[TabIndex MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex)
```
<table>
<tr>
<td><input tabindex="0" class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input tabindex="2" class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<tr>
<td><input tabindex="1" class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input tabindex="3" class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<table>
``` |
19,680 | I mean through out the whole show cars are depicted almost exactly the same as cars from our time, except for the lack of wheels. You would think that people 1000 years more advanced than us would be able to come up with a new design. | 2012/06/29 | [
"https://scifi.stackexchange.com/questions/19680",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/7446/"
] | I say it's nostalgia and marketing...As evidence for this I reference the existence of New New York, Mom's Friendly Robot Company ads and just human nature in general. For every viewpoint, you can use nostalgia to sell it! That, I believe, is the simple, unadorned reason that cars look the same in the year 3000. | The requirements for a car in 3000AD are probably very similar to those of cars today i.e. get people around comfortably, safely and cheaply, so they'll end up with broadly similar designs. Certainly demands of fashion will affect the decorative bits that car designers add to distinguish their models, but until material wealth becomes irrelevant I suspect cars will look broadly similar. |
32,517,452 | Can someone help me? I would like to do something like this on a textarea to set the maxlength attribute:
```
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att);
}
</script>
</body>
</html>
```
My code is:
```
<!DOCTYPE html>
<html>
<head>
<style>
</head>
<body>
<textarea>Hello World</textarea>
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text.setAttributeNode(att);
}
</script>
</body>
</html>
```
And if I run the script by clicking the button the console says:
>
> Uncaught TypeError: h1.setAttribute is not a function.
>
>
>
Ps: i'm new at stackoverflow :) | 2015/09/11 | [
"https://Stackoverflow.com/questions/32517452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324123/"
] | Firstly, you forgot the textarea:
```
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Hello World</h1>
<button onclick="myFunction()">change max length</button>
<textarea></textarea>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text[0].setAttributeNode(att);
}
</script>
</body>
</html>
```
And also document.getElementsByTagName returns you an array so you get 'h1.setAttribute is not a function.' mistake. | You have two problems:
You have to work on an element not a collection
===============================================
Compare (specifically the last few characters of each line):
```
var h1 = document.getElementsByTagName("H1")[0];
var text = document.getElementsByTagName("textarea");
```
In the first case you are trying to work on the first H1 in the document. In the second, you are trying to work on the collection of all the textareas.
Collections are not elements and don't have all the methods that elements do.
You have to work on an element that exists
==========================================
You have no textarea in the second set of code. |
32,517,452 | Can someone help me? I would like to do something like this on a textarea to set the maxlength attribute:
```
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att);
}
</script>
</body>
</html>
```
My code is:
```
<!DOCTYPE html>
<html>
<head>
<style>
</head>
<body>
<textarea>Hello World</textarea>
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text.setAttributeNode(att);
}
</script>
</body>
</html>
```
And if I run the script by clicking the button the console says:
>
> Uncaught TypeError: h1.setAttribute is not a function.
>
>
>
Ps: i'm new at stackoverflow :) | 2015/09/11 | [
"https://Stackoverflow.com/questions/32517452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324123/"
] | You have some errors in your code. Check out this simplified one:
[jsFiddle](http://jsfiddle.net/kmsdev/cmkhosx6/)
```
<h1>Hello World</h1>
<textarea rows="10" cols="40"></textarea><br />
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea")[0];
text.setAttribute("maxlength", 100);
}
</script>
``` | You have two problems:
You have to work on an element not a collection
===============================================
Compare (specifically the last few characters of each line):
```
var h1 = document.getElementsByTagName("H1")[0];
var text = document.getElementsByTagName("textarea");
```
In the first case you are trying to work on the first H1 in the document. In the second, you are trying to work on the collection of all the textareas.
Collections are not elements and don't have all the methods that elements do.
You have to work on an element that exists
==========================================
You have no textarea in the second set of code. |
32,517,452 | Can someone help me? I would like to do something like this on a textarea to set the maxlength attribute:
```
<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var h1 = document.getElementsByTagName("H1")[0];
var att = document.createAttribute("class");
att.value = "democlass";
h1.setAttributeNode(att);
}
</script>
</body>
</html>
```
My code is:
```
<!DOCTYPE html>
<html>
<head>
<style>
</head>
<body>
<textarea>Hello World</textarea>
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text.setAttributeNode(att);
}
</script>
</body>
</html>
```
And if I run the script by clicking the button the console says:
>
> Uncaught TypeError: h1.setAttribute is not a function.
>
>
>
Ps: i'm new at stackoverflow :) | 2015/09/11 | [
"https://Stackoverflow.com/questions/32517452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324123/"
] | You have some errors in your code. Check out this simplified one:
[jsFiddle](http://jsfiddle.net/kmsdev/cmkhosx6/)
```
<h1>Hello World</h1>
<textarea rows="10" cols="40"></textarea><br />
<button onclick="myFunction()">change max length</button>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea")[0];
text.setAttribute("maxlength", 100);
}
</script>
``` | Firstly, you forgot the textarea:
```
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<h1>Hello World</h1>
<button onclick="myFunction()">change max length</button>
<textarea></textarea>
<script>
function myFunction() {
var text = document.getElementsByTagName("textarea");
var att = document.createAttribute("maxlength");
att.value = "100";
text[0].setAttributeNode(att);
}
</script>
</body>
</html>
```
And also document.getElementsByTagName returns you an array so you get 'h1.setAttribute is not a function.' mistake. |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | >
> Is this possible?
>
>
>
It definetely is. You could just check which `Activity` is hosting your `Fragment` instance:
```
private void button1OnClick(){
/* could also use instanceof, BUT: if you have something like ActivityC extends ActivityA
then instanceof would evaluate to true for both */
if(getActivity().getClass().equals(ActivityA.class)) {
// do stuff
} else if(getActivity().getClass().equals(ActivityB.class)) {
// do another stuff
}
}
```
>
> Is this the right way?
>
>
>
(*attention opinionated answer*)
It depends. If you have a complex and unique layout/functionality, I'd use different `Fragments`. If you have a simple layout with some buttons that just need to act differently in different `Activities` it is a good idea to reuse an existing `Fragment` class. | Yes you can!
```
if(getActivity() instanceOf ActivityA) {
//do stuff related to ActivityA
} else if(getActivity() instanceOf ActivityB) {
//do stuff related to ActivityB
}
``` |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | >
> Is this possible?
>
>
>
It definetely is. You could just check which `Activity` is hosting your `Fragment` instance:
```
private void button1OnClick(){
/* could also use instanceof, BUT: if you have something like ActivityC extends ActivityA
then instanceof would evaluate to true for both */
if(getActivity().getClass().equals(ActivityA.class)) {
// do stuff
} else if(getActivity().getClass().equals(ActivityB.class)) {
// do another stuff
}
}
```
>
> Is this the right way?
>
>
>
(*attention opinionated answer*)
It depends. If you have a complex and unique layout/functionality, I'd use different `Fragments`. If you have a simple layout with some buttons that just need to act differently in different `Activities` it is a good idea to reuse an existing `Fragment` class. | Your activities have different logic, you can define the button logic in each of them and share the views in this way. You can use a fragment to accomplish this however you can be more direct by sharing a partial layout.
Create a partial layout called three\_buttons.xml
three\_buttons.xml
```
<LinearLayout>
<BUtton android:text="button 1"/>
<BUtton android:text="button 2"/>
<BUtton android:text="button 3"/>
</LinearLayout>
```
activity\_a.xml
```
<LinearLayout>
<TextView android:text="I am A"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
```
activity\_b.xml
```
<LinearLayout>
<TextView android:text="I am B"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
``` |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Of course you can. Just create an interface for the Fragment, let's say `FragmentCallback`, with your desired callback method, `onButtonClick()` for instance. In the `onAttached()` of your Fragment, cast the Activity to your new interface and store it in a variable `private FragmentCallback callback;`. Each Activity using this Fragment must implement this callback interface. Then call the callbacks `onButtonClick()` method in your Fragments `onButtonClick()` method. That's it - a very common pattern. | >
> Is this possible?
>
>
>
It definetely is. You could just check which `Activity` is hosting your `Fragment` instance:
```
private void button1OnClick(){
/* could also use instanceof, BUT: if you have something like ActivityC extends ActivityA
then instanceof would evaluate to true for both */
if(getActivity().getClass().equals(ActivityA.class)) {
// do stuff
} else if(getActivity().getClass().equals(ActivityB.class)) {
// do another stuff
}
}
```
>
> Is this the right way?
>
>
>
(*attention opinionated answer*)
It depends. If you have a complex and unique layout/functionality, I'd use different `Fragments`. If you have a simple layout with some buttons that just need to act differently in different `Activities` it is a good idea to reuse an existing `Fragment` class. |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
I don't recommend to do that, maybe you could reuse your layouts. | Yes you can!
```
if(getActivity() instanceOf ActivityA) {
//do stuff related to ActivityA
} else if(getActivity() instanceOf ActivityB) {
//do stuff related to ActivityB
}
``` |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
I don't recommend to do that, maybe you could reuse your layouts. | Your activities have different logic, you can define the button logic in each of them and share the views in this way. You can use a fragment to accomplish this however you can be more direct by sharing a partial layout.
Create a partial layout called three\_buttons.xml
three\_buttons.xml
```
<LinearLayout>
<BUtton android:text="button 1"/>
<BUtton android:text="button 2"/>
<BUtton android:text="button 3"/>
</LinearLayout>
```
activity\_a.xml
```
<LinearLayout>
<TextView android:text="I am A"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
```
activity\_b.xml
```
<LinearLayout>
<TextView android:text="I am B"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
``` |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Of course you can. Just create an interface for the Fragment, let's say `FragmentCallback`, with your desired callback method, `onButtonClick()` for instance. In the `onAttached()` of your Fragment, cast the Activity to your new interface and store it in a variable `private FragmentCallback callback;`. Each Activity using this Fragment must implement this callback interface. Then call the callbacks `onButtonClick()` method in your Fragments `onButtonClick()` method. That's it - a very common pattern. | Yes you can, but you have to add more logic to your fragments and add some interfaces for each activity.
I don't recommend to do that, maybe you could reuse your layouts. |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Of course you can. Just create an interface for the Fragment, let's say `FragmentCallback`, with your desired callback method, `onButtonClick()` for instance. In the `onAttached()` of your Fragment, cast the Activity to your new interface and store it in a variable `private FragmentCallback callback;`. Each Activity using this Fragment must implement this callback interface. Then call the callbacks `onButtonClick()` method in your Fragments `onButtonClick()` method. That's it - a very common pattern. | Yes you can!
```
if(getActivity() instanceOf ActivityA) {
//do stuff related to ActivityA
} else if(getActivity() instanceOf ActivityB) {
//do stuff related to ActivityB
}
``` |
47,318,912 | I am being passed inconsistent data. The problem is the individual rows of `$data_array` are not consistently in the same sequence but each has a reliable "text:" preceding the value.
Each row contains about 120 elements of data. I only need 24 of those elements.
It's also possible one of the elements I need could be missing, such as "cost".
(I'm using php version 5.4)
-- Task:
Using $order\_array, create a new $data\_array\_new by reordering the data in each "row" into the same sequence as $order\_array.
If an elements is missing from a row insert "NA".
Once the elements are in the correct sequence the "text" is no longer required.
```
$order_array = array("price", "cost", "vol", "eps")
$data_array = Array (
$one = Array ("cost":43.40, "vol":44000, "eps":1.27, "price":65.00),
$two = Array ("eps":5.14, "price":33.14, "vol":657000),
$thr = Array ("vol":650000, "cost":66.67, "eps":1.33, "price":44.31),
);
```
The resulting ouput should appear with the data in this order: ("price", "cost", "vol", "eps")
```
$data_array_new = Array (
$one = Array (65.00,43.40,44000,1.27),
$two = Array (33.14,"NA",657000,5.14),
$thr = Array (44.31,66.67,650000,1.33),
);
``` | 2017/11/15 | [
"https://Stackoverflow.com/questions/47318912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7174910/"
] | Of course you can. Just create an interface for the Fragment, let's say `FragmentCallback`, with your desired callback method, `onButtonClick()` for instance. In the `onAttached()` of your Fragment, cast the Activity to your new interface and store it in a variable `private FragmentCallback callback;`. Each Activity using this Fragment must implement this callback interface. Then call the callbacks `onButtonClick()` method in your Fragments `onButtonClick()` method. That's it - a very common pattern. | Your activities have different logic, you can define the button logic in each of them and share the views in this way. You can use a fragment to accomplish this however you can be more direct by sharing a partial layout.
Create a partial layout called three\_buttons.xml
three\_buttons.xml
```
<LinearLayout>
<BUtton android:text="button 1"/>
<BUtton android:text="button 2"/>
<BUtton android:text="button 3"/>
</LinearLayout>
```
activity\_a.xml
```
<LinearLayout>
<TextView android:text="I am A"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
```
activity\_b.xml
```
<LinearLayout>
<TextView android:text="I am B"/>
<include
android:id="@+id/three_buttons"
layout="@layout/three_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
``` |
22,720,603 | I'm using `ng-repeat` to create an index of records within a Rails view, on this index I'm trying to implement a button to update a particular record. The problem is I need to pass the correct id through to the Rails controller. I'm getting an error when I attempt to pass the record id through with `'{{swim_record.id}}!'` , using string interpolation via Angular.
```
<tbody>
<tr ng-repeat='swim_record in SwimRecords | orderBy:predicate.value:reverse |
filter:search'>
<td>
<a ng-href='/swim_records/{{swim_record.id}}'>
{{swim_record.last_name}}
</a>
</td>
<td>{{swim_record.first_name}}</td>
<td class = 'hidden-xs'>{{swim_record.check_in | date:'MM/dd/yyyy @ h:mma'}}</td>
<th class = 'hidden-xs'>{{swim_record.lmsc}}</td>
<td>
<%= bootstrap_form_for Swimmer.find_by_id("{{swim_record.id }}!".to_i) do |f| %>
<%= f.hidden_field :last_name, value: "Hat" %>
<%= f.submit 'Check Out', class: "btn btn-danger" %>
<% end %>
</td>
</tr>
</tbody>
```
Any suggestions would be very much appreciated! | 2014/03/28 | [
"https://Stackoverflow.com/questions/22720603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395126/"
] | >
> Why is my function returning before the X,Y variables are set?
>
>
>
[Because JavaScript I/O is asynchronous](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call).
If you want to wait for two promises - you need to hook on the promise's completion. Luckily, promises make this super simple for you with `Promise.all` and `Promise.spread`.
```
Promise.all(getX(rows[0].id,con,mysql),getY(rows[0].id,con,mysql)).spread(function(x,y){
console.log(x,y);//should work;
});
``` | The functions `getX` and `getY` are asynchronous functions. Promise solves the issue of nesting anonymous functions, but it don't make the functions synchronous and blocking.
So `x` and `y` are not set at the moment you create the `ref` object and return this object.
Try something like this:
```
getX(rows[0].id,con,mysql).then(function(data) {
x = data; //x logs the return 7 from the db
getY(rows[0].id,con,mysql).then(function(data) {
y = data; //y logs 45 from the db
console.log(x,y,"line77"); //logs "undefined undefined line77"
ref = new P(rows[0].id,x,y);
});
});
```
Also because your whole function is asynchronous, you have to work with an callback or return a promise, in which you have access to `ref` Object. |
22,720,603 | I'm using `ng-repeat` to create an index of records within a Rails view, on this index I'm trying to implement a button to update a particular record. The problem is I need to pass the correct id through to the Rails controller. I'm getting an error when I attempt to pass the record id through with `'{{swim_record.id}}!'` , using string interpolation via Angular.
```
<tbody>
<tr ng-repeat='swim_record in SwimRecords | orderBy:predicate.value:reverse |
filter:search'>
<td>
<a ng-href='/swim_records/{{swim_record.id}}'>
{{swim_record.last_name}}
</a>
</td>
<td>{{swim_record.first_name}}</td>
<td class = 'hidden-xs'>{{swim_record.check_in | date:'MM/dd/yyyy @ h:mma'}}</td>
<th class = 'hidden-xs'>{{swim_record.lmsc}}</td>
<td>
<%= bootstrap_form_for Swimmer.find_by_id("{{swim_record.id }}!".to_i) do |f| %>
<%= f.hidden_field :last_name, value: "Hat" %>
<%= f.submit 'Check Out', class: "btn btn-danger" %>
<% end %>
</td>
</tr>
</tbody>
```
Any suggestions would be very much appreciated! | 2014/03/28 | [
"https://Stackoverflow.com/questions/22720603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3395126/"
] | Promises don't change the language, it's just a library. It cannot change how function returning works. However, do you want something like this:
```
return con.getConnectionAsync().then(function(connection) {
var x;
var y;
return connection.queryAsync('SELECT password,id FROM player WHERE name='+mysql.escape(req.body.user))
.spread(function(rows, fields) {
if (hash.verify(req.body.pass,rows[0].password)) {
req.session.loggedIn = true;
req.session.user = rows[0].id;
ref = new P(rows[0].id,x,y);
res.send({
"msg":"You have logged in!",
"flag":false,
"title":": Logged In"
});
return Promise.all([
getX(rows[0].id,con,mysql),
getY(rows[0].id,con,mysql)
]).then(function(xy) {
x = xy[0];
y = xy[1];
}).return(ref);
} else {
// Should probably throw a LoginError here or something
// because if we get here, we don't define x and y
// and that will require an annoying check later
res.send({
"msg":"Your username and or password was incorrect.",
"flag":true,
"title":": Login Failed"
});
}
}).then(function() {
// If the login succeeded x and y are defined here.
// However, in the else branch you don't define
// x and y so you will need to check here.
// Had you thrown an error in the else branch
// you would know that x and y are always defined here.
use(x, y);
}).finally(function() {
connection.release();
});
});
``` | The functions `getX` and `getY` are asynchronous functions. Promise solves the issue of nesting anonymous functions, but it don't make the functions synchronous and blocking.
So `x` and `y` are not set at the moment you create the `ref` object and return this object.
Try something like this:
```
getX(rows[0].id,con,mysql).then(function(data) {
x = data; //x logs the return 7 from the db
getY(rows[0].id,con,mysql).then(function(data) {
y = data; //y logs 45 from the db
console.log(x,y,"line77"); //logs "undefined undefined line77"
ref = new P(rows[0].id,x,y);
});
});
```
Also because your whole function is asynchronous, you have to work with an callback or return a promise, in which you have access to `ref` Object. |
41,185,122 | I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.
**Example:**
**range 1 = 1-400**
**range 2 = 200-600**
So when I want to check overlap between these two ranges I should get the answer = 200.
Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.
**Example of Lists:**
List1 : 1-400, 401-800, 801-1200 and so on...
List2 : 10240-10276, 10420 10456, 11646-11682 and so on...
Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.
I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.
**Example formula** :
```
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
```
and if the two ranges are not overlapping at all, then function must return 0.
PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula. | 2016/12/16 | [
"https://Stackoverflow.com/questions/41185122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5305863/"
] | If there is any overlapping range ; it must start from the max lower bound to the min upper bound so just use that "formula"
Then just get the number of item in that range by subtracting it's upper bound to it's lower one and add one (to be all inclusive)
Finally if that amount is negative it means that the range weren't overlapping so just get the max between that amount and 0 to handle that case
**Edit :** Oops C# not VB.Net
```
int FindOverlapping (int start1, int end1, int start2, int end2)
{
return Math.Max (0, Math.Min (end1, end2) - Math.Max (start1, start2) + 1);
}
``` | You can try something like this:
```
void Main()
{
double adStart = 1.501;
double adEnd = 21.83;
double bdStart = 0.871;
double bdEnd = 56.81;
int aiStart = 21;
int aiEnd = 35;
int biStart = 29;
int biEnd = 43;
// 20.239
double dOverlap = FindOverlapping((int)(adStart*1000), (int)(adEnd*1000), (int)(bdStart*1000), (int)(bdEnd*1000))/1000.0;
// 6
int iOverlap = FindOverlapping(aiStart, aiEnd, biStart, biEnd);
// 0
iOverlap = FindOverlapping(20, 25, 26, 30);
// 0
iOverlap = FindOverlapping(20, 25, 25, 30);
}
int FindOverlapping(int aStart, int aEnd, int bStart, int bEnd)
{
int overlap = System.Linq.Enumerable.Range(aStart, aEnd - aStart).Intersect(System.Linq.Enumerable.Range(bStart, bEnd - bStart)).Count();
return overlap;
}
``` |
41,185,122 | I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.
**Example:**
**range 1 = 1-400**
**range 2 = 200-600**
So when I want to check overlap between these two ranges I should get the answer = 200.
Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.
**Example of Lists:**
List1 : 1-400, 401-800, 801-1200 and so on...
List2 : 10240-10276, 10420 10456, 11646-11682 and so on...
Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.
I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.
**Example formula** :
```
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
```
and if the two ranges are not overlapping at all, then function must return 0.
PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula. | 2016/12/16 | [
"https://Stackoverflow.com/questions/41185122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5305863/"
] | If there is any overlapping range ; it must start from the max lower bound to the min upper bound so just use that "formula"
Then just get the number of item in that range by subtracting it's upper bound to it's lower one and add one (to be all inclusive)
Finally if that amount is negative it means that the range weren't overlapping so just get the max between that amount and 0 to handle that case
**Edit :** Oops C# not VB.Net
```
int FindOverlapping (int start1, int end1, int start2, int end2)
{
return Math.Max (0, Math.Min (end1, end2) - Math.Max (start1, start2) + 1);
}
``` | A one-liner formula to use would be this one.
Let's say you have 2 intervals:
(a1, a2) and (b1, b2)
Then the overlapping region would be: max{0, min{a2-b1, b2-a1}} |
41,185,122 | I am making a complex algorithm in C# in which one step is to compare 2 very large lists of ranges and finding out the overlapping region. I have tried a lot of ways to find them, but m not sure if I am covering all possibilities. Also my algo on this step is taking too long with huge lists.
**Example:**
**range 1 = 1-400**
**range 2 = 200-600**
So when I want to check overlap between these two ranges I should get the answer = 200.
Because total 200 numbers are overlapping between these two ranges. So this is how I want the answer, I want the exact number of integers that are overlapping between two ranges.
**Example of Lists:**
List1 : 1-400, 401-800, 801-1200 and so on...
List2 : 10240-10276, 10420 10456, 11646-11682 and so on...
Now I have to compare each range of list1 with each range of list2, and find out if a certain range of list1 overlaps with any of the range of list2 and if yes then what is the overlapping answer? These are just sample values for the purposes of understanding.
I only need a simple and most efficient/fast formula to find out the overlap answer between 2 ranges. I can manage the rest of the loop algorithm.
**Example formula** :
```
var OverlappingValue = FindOverlapping(range1.StartValue, range1.EndValue,range2.StartValue, range2.EndValue);
```
and if the two ranges are not overlapping at all, then function must return 0.
PS: I didn't post my code because it's really complicated with a lot of conditions, I only need one simple formula. | 2016/12/16 | [
"https://Stackoverflow.com/questions/41185122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5305863/"
] | You can try something like this:
```
void Main()
{
double adStart = 1.501;
double adEnd = 21.83;
double bdStart = 0.871;
double bdEnd = 56.81;
int aiStart = 21;
int aiEnd = 35;
int biStart = 29;
int biEnd = 43;
// 20.239
double dOverlap = FindOverlapping((int)(adStart*1000), (int)(adEnd*1000), (int)(bdStart*1000), (int)(bdEnd*1000))/1000.0;
// 6
int iOverlap = FindOverlapping(aiStart, aiEnd, biStart, biEnd);
// 0
iOverlap = FindOverlapping(20, 25, 26, 30);
// 0
iOverlap = FindOverlapping(20, 25, 25, 30);
}
int FindOverlapping(int aStart, int aEnd, int bStart, int bEnd)
{
int overlap = System.Linq.Enumerable.Range(aStart, aEnd - aStart).Intersect(System.Linq.Enumerable.Range(bStart, bEnd - bStart)).Count();
return overlap;
}
``` | A one-liner formula to use would be this one.
Let's say you have 2 intervals:
(a1, a2) and (b1, b2)
Then the overlapping region would be: max{0, min{a2-b1, b2-a1}} |
8,725,594 | At the moment I have:
```
//replace common characters
$search = array('&', '£', '$');
$replace = array('&', '£', '$');
$html= str_replace($search, $replace, $html);
```
The problem with this code is that if the & has been already converted it will try to convert it again. How would I make sure this doesn't happen? | 2012/01/04 | [
"https://Stackoverflow.com/questions/8725594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560287/"
] | I would use the built in functions that PHP has to escape HTML characters:
* [`htmlentities()`](http://php.net/manual/en/function.htmlentities.php)
* [`htmlspecialchars()`](http://www.php.net/manual/en/function.htmlspecialchars.php)
Rather than rolling my own as it is much easier. `htmlentities()` and `htmlspecialchars()` explicitly handle this with the `double_encode` parameter:
>
> When double\_encode is turned off PHP will not encode existing html
> entities. The default is to convert everything.
>
>
> | i give an example but it will work if you have the latter like `' & '` then hope this will work for you:
```
$str = 'India & Aust & New ';
$regex = '/(\s\&\s)/i';
$replace = ' & ';
if(preg_match($regex, $str)){
$new_str = preg_replace($regex, $replace, $str );
echo '<pre>';
echo htmlspecialchars($new_str, ENT_QUOTES);
echo '</pre>';
}
else{
echo 'Not matched!';
}
```
but remember this will work if you have space on both sides of an ampersand or whatever you want. Otherwise follow the @Treffynnon Answer.. |
477,504 | I got a local repository in `/var/www/html/centos/7` directory. In here, all rpm packages from centos are downloaded.
I will create a crontab for updating my local repository every 1 week or sth.
I want to learn that does `repocreate --update` do this? Or should I download all the packages from centos repo again?
If I should download the packages from centos repo, is there a way to skip the downloaded packages (they're in `/centos/7` directory as I mentioned) and download just the new (updated) packages from centos?
UPDATE
I have found the solution but it's not working for me. I created a new directory centos7/repo and download some files to check if the rsync --ignore-existing will work. But whenever I run the below command, I got an error
```
failed to connect to ftp.linux.org.tr (193.140.100.100): Connection timed out (110)
rsync: failed to connect to ftp.linux.org.tr (2001:a98:11::100): Network is unreachable (101)
rsync error: error in socket IO (code 10) at clientserver.c(125) [Receiver=3.1.2]
```
The command is:
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
```
I tried other mirrors as well from <https://centos.org/download/mirrors/> (there are rsync location in this site as well). But none of them worked. Can anybody validate that rsync mirrors does work? Probably I can't go through firewall with port 873.
Is there anyway that I can use this rsync through port 80 or is there another way to accomplish this task? (I tried zsync but it needs a zsync file.) | 2018/10/24 | [
"https://unix.stackexchange.com/questions/477504",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/317026/"
] | If you have problems with rsync, then you can use [reposync](https://linux.die.net/man/1/reposync). It is able to download all packages (or --newest-only| -n) from repo, configured in the system.
So final commands in script looks like:
```
/usr/bin/reposync --repoid=updates --download_path=/var/www/html/centos7/repo/updates --newest-only
/usr/bin/createrepo /var/www/html/centos7/repo/updates
``` | you can try the following mirror which is supporting rsync as well
<http://mirror.nl.leaseweb.net/centos/> |
477,504 | I got a local repository in `/var/www/html/centos/7` directory. In here, all rpm packages from centos are downloaded.
I will create a crontab for updating my local repository every 1 week or sth.
I want to learn that does `repocreate --update` do this? Or should I download all the packages from centos repo again?
If I should download the packages from centos repo, is there a way to skip the downloaded packages (they're in `/centos/7` directory as I mentioned) and download just the new (updated) packages from centos?
UPDATE
I have found the solution but it's not working for me. I created a new directory centos7/repo and download some files to check if the rsync --ignore-existing will work. But whenever I run the below command, I got an error
```
failed to connect to ftp.linux.org.tr (193.140.100.100): Connection timed out (110)
rsync: failed to connect to ftp.linux.org.tr (2001:a98:11::100): Network is unreachable (101)
rsync error: error in socket IO (code 10) at clientserver.c(125) [Receiver=3.1.2]
```
The command is:
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
```
I tried other mirrors as well from <https://centos.org/download/mirrors/> (there are rsync location in this site as well). But none of them worked. Can anybody validate that rsync mirrors does work? Probably I can't go through firewall with port 873.
Is there anyway that I can use this rsync through port 80 or is there another way to accomplish this task? (I tried zsync but it needs a zsync file.) | 2018/10/24 | [
"https://unix.stackexchange.com/questions/477504",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/317026/"
] | repoquery queries every package in repository that you configured for your system and after that give the list to xargs to download all packages (new ones not existing ones)with repotrack to your server.
```
repoquery -a | xargs repotrack -a x86_64 -p .
```
The rsync solution also works if you haven't got any firewall rules that restrict the rsync daemon port.
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
``` | you can try the following mirror which is supporting rsync as well
<http://mirror.nl.leaseweb.net/centos/> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.