qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
51,268,745 | How can I create a permutation mapping of two lists in python?
For example I have two lists `[1,2,3]` and `['A','B','C']`
Then my code should generate a list of 6 dictionaries
```
[ {1:'A',2:'B',3:'C'},
{1:'A',2:'C',3:'B'},
{1:'B',2:'A',3:'C'},
{1:'B',2:'C',3:'A'},
{1:'C',2:'A',3:'B'},
{1:'C',2:'B',3:'A'} ... | 2018/07/10 | [
"https://Stackoverflow.com/questions/51268745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8272518/"
] | Using [`zip`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) in a list comprehension:
```
>>> from itertools import permutations
>>> L1 = [1,2,3]
>>> L2 = ['A','B','C']
>>> [dict(zip(L1, p)) for p in permutat... | You seem to permutate only the values of the dicts, so you could do something like
```
from itertools import permutations
dicts = []
keys = [1, 2, 3]
for values in permutations(['A', 'B', 'C']):
new_dict = dict(zip(keys, values))
dicts.append(new_dict)
``` |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant).
`str` is actually a class, so `str(whatever)` is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has ... | I believe short strings that can be evaluated at compile time, will be interned automatically. In the last examples, the result can't be evaluated at compile time because `str` or `join` might be redefined. |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | In terms of language specification, any compliant Python compiler and runtime is fully allowed, for any instance of an immutable type, to make a new instance OR find an existing instance of the same type that's equal to the required value and use a new reference to that same instance. This means it's always incorrect t... | I believe short strings that can be evaluated at compile time, will be interned automatically. In the last examples, the result can't be evaluated at compile time because `str` or `join` might be redefined. |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | In terms of language specification, any compliant Python compiler and runtime is fully allowed, for any instance of an immutable type, to make a new instance OR find an existing instance of the same type that's equal to the required value and use a new reference to that same instance. This means it's always incorrect t... | Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant).
`str` is actually a class, so `str(whatever)` is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has ... |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | Python is allowed to inline string constants; A,B,C,D are actually the same literals (if Python sees a constant expression, it treats it as a constant).
`str` is actually a class, so `str(whatever)` is calling this class' constructor, which should yield a fresh object. This explains E,F,G (note that each of these has ... | in answer to S.Lott's suggestion of examining the byte code:
```
import dis
def moo():
A = "10000"
B = "10000"
C = "100" + "00"
D = "%i"%10000
E = str(10000)
F = str(10000)
G = "1000"+str(0)
H = "0".join(("10","00"))
I = str("10000")
for obj in (A,B,C,D,E,F,G,H, I):
pri... |
1,150,765 | I was trying to figure out which integers python only instantiates once (-6 to 256 it seems), and in the process stumbled on some string behaviour I can't see the pattern in. Sometimes, equal strings created in different ways share the same id, sometimes not. This code:
```
A = "10000"
B = "10000"
C = "100" + "00"
D =... | 2009/07/19 | [
"https://Stackoverflow.com/questions/1150765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/125185/"
] | In terms of language specification, any compliant Python compiler and runtime is fully allowed, for any instance of an immutable type, to make a new instance OR find an existing instance of the same type that's equal to the required value and use a new reference to that same instance. This means it's always incorrect t... | in answer to S.Lott's suggestion of examining the byte code:
```
import dis
def moo():
A = "10000"
B = "10000"
C = "100" + "00"
D = "%i"%10000
E = str(10000)
F = str(10000)
G = "1000"+str(0)
H = "0".join(("10","00"))
I = str("10000")
for obj in (A,B,C,D,E,F,G,H, I):
pri... |
20,448,734 | ```
#!/bin/sh
echo "Hello from sh"
```
---
When I run this program (hello.sh) I get a command not found error. I'm using cygwin on Windows and I looked at cy's FAQ. It said to change the permissions to 755. I already did that and still no luck. I get the same error with these other two programs.
```
#!/usr/bin/env ... | 2013/12/08 | [
"https://Stackoverflow.com/questions/20448734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As has already been said, you need to add the Cygwin binaries to your path. To do so, right click on "My Computer", click "Properties", then "Advanced", then "Environment Variables".
Create a new environment variable with name `CYGWIN_HOME` and value `C:\cygwin` (or wherever you installed cygwin. The default location ... | I was getting the "command not found" error on a Perl script. That script has the shebang line: "#!/usr/bin/env perl" as the first line and my user is the owner who has execute permissions. I was trying to run the script using the command line "ppminstall.pl ?" (the script is set up to display documentation for using t... |
20,448,734 | ```
#!/bin/sh
echo "Hello from sh"
```
---
When I run this program (hello.sh) I get a command not found error. I'm using cygwin on Windows and I looked at cy's FAQ. It said to change the permissions to 755. I already did that and still no luck. I get the same error with these other two programs.
```
#!/usr/bin/env ... | 2013/12/08 | [
"https://Stackoverflow.com/questions/20448734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | As has already been said, you need to add the Cygwin binaries to your path. To do so, right click on "My Computer", click "Properties", then "Advanced", then "Environment Variables".
Create a new environment variable with name `CYGWIN_HOME` and value `C:\cygwin` (or wherever you installed cygwin. The default location ... | Maybe caused by the wrong line break?
Open this shell in Notepad++, and then check if the line break is `UNIX(LF)` in the lower right corner.
If not, click the text `Windows (CR LF)` and then click `Convert to UNIX(LF)`.
This works for me. |
67,698,235 | I wonder that is there anyway to speed up python3/numpy's `np.where` operation? I have a minimal working example as follows:
```
from time import time
import numpy as np
a = np.random.randint(0, 4, (768, 512, 512))
b = a.copy().astype(np.uint8)
c = b.copy()
print(a.shape)
ts = time()
a[a > 0] = 1
print(f'normalize i... | 2021/05/26 | [
"https://Stackoverflow.com/questions/67698235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15424596/"
] | The best way to accomplish your operation is to convert the matrix to the boolean datatype and then back to integer, especially if 8-bit integers are used:
```
import numpy as np
import timeit
a = np.random.randint(0, 4, (768, 512, 512))
a_short = a.astype(np.uint8)
# Time to initialize
%timeit b=a.copy()
201 ms ... | You could try with `numexpr`:
```
import numpy as np
import numexpr as ne
# for timing reference
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a[a > 0] = 1
```
782 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
```
a = np.random.randint(0, 4, (768, 512, 512))
%timeit a = ne.evaluate("where(... |
66,730 | I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object. | 2008/09/15 | [
"https://Stackoverflow.com/questions/66730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8453/"
] | You can also define signals inside the class definition:
```
class MyGObjectClass(gobject.GObject):
__gsignals__ = {
"some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
```
The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`. | Here is how:
```
import gobject
class MyGObjectClass(gobject.GObject):
...
gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,
None, (str, int))
```
Where the second to last argument is the return type and the last argument is a tuple of argument types. |
66,730 | I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object. | 2008/09/15 | [
"https://Stackoverflow.com/questions/66730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8453/"
] | You can also define signals inside the class definition:
```
class MyGObjectClass(gobject.GObject):
__gsignals__ = {
"some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
```
The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`. | If you use kiwi available [here](http://kiwi.async.com.br/) you can just do:
```
from kiwi.utils import gsignal
class MyObject(gobject.GObject):
gsignal('signal-name')
``` |
73,069,374 | I have this table
| Stars |
| --- |
| 3 stars |
| Stars 20 |
| 901stars |
| 8 |
I'm using python to filter the table but I'm not sure of the regex to reject 8. `[^0-9]` will flag `3 stars, 901stars` as errors too but I just want to flag that 8 is incorrect based on the regex.
The regex I need would only flag out the... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73069374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16125533/"
] | I'd suggest `\d+$` to match 1 or more digits at the end of the line. (or even `^\d+$` to search from beginning of line).
disclaimer: I don't have a clue wrt Python, but if has a standard rx library, this should work. | Here is a way without using regex.
```
pd.to_numeric(df['Stars'],errors = 'coerce').isna()
``` |
2,587,709 | I was wondering if there is a way to automatically run commands on entering the python shell as you would with the .bash\_profile or .profile scripts with bash. I would like to automatically import some modules so I don't have to type the whole shebang everytime I hop into the shell.
Thanks, | 2010/04/06 | [
"https://Stackoverflow.com/questions/2587709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278205/"
] | Yup you can use the `PYTHONSTARTUP` environment variable to do this as outlined [here](http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file) | Also consider using [ipython](http://ipython.scipy.org/) if you're doing a lot of interactive work. Your options for this kind of automation expand significantly. |
56,902,458 | I am trying to use this example code from the PyTorch [website](https://pytorch.org/tutorials/advanced/cpp_export.html) to convert a python model for use in the PyTorch c++ api (LibTorch).
```
Converting to Torch Script via Tracing
To convert a PyTorch model to Torch Script via tracing, you must pass an instance of yo... | 2019/07/05 | [
"https://Stackoverflow.com/questions/56902458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4402282/"
] | (from pytorch forums)
trace only supports modules that have tensor or tuple of tensor as output.
According to deeplabv3 implementation, its output is OrderedDict. That is a problem.
To solve this, make a wrapper module
```
class wrapper(torch.nn.Module):
def __init__(self, model):
super(wrapper, self).__i... | Your problem originates in the BatchNorm layer. If it requires *more than one value per channel*, then your model is in training mode. Could you invoke <https://pytorch.org/cppdocs/api/classtorch_1_1nn_1_1_module.html#_CPPv4N5torch2nn6Module4evalEv> on the model and see if there's an improvement?
Otherwise you could ... |
14,425,833 | What I'm trying to do seems rather simple, but I can't find a way to do it.
Imagine somebody sends you a link for a dropbox folder. You can go to that URL and see all the files in the folder.
I'm trying to write a script in either python, php, or javascript to get all the download links in that folder from that URL.
... | 2013/01/20 | [
"https://Stackoverflow.com/questions/14425833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706798/"
] | In absence of suffixes, sufficiently small numbers have `int` or `double` types
```
a = 42; /* 42 has type int */
b = 42.0; /* 42.0 has type double */
```
You can use suffixes to specify the type of the literal
```
c = 42U; /* unsigned int */
d = 42.0f; /* float */
e = 42.0L; /* long double */
f = 42ULL; /* unsigne... | >
> Will I need to cast one of the operands to (float) to make this
> condition true?
>
>
>
Yes, because integral literals are of type `int` and a division between two `int` types returns also an `int`, meaning that the fraction is omitted.
>
> Has the situation now changed, because the compiler notices one of ... |
14,425,833 | What I'm trying to do seems rather simple, but I can't find a way to do it.
Imagine somebody sends you a link for a dropbox folder. You can go to that URL and see all the files in the folder.
I'm trying to write a script in either python, php, or javascript to get all the download links in that folder from that URL.
... | 2013/01/20 | [
"https://Stackoverflow.com/questions/14425833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706798/"
] | >
> Will I need to cast one of the operands to (float) to make this
> condition true?
>
>
>
Yes, because integral literals are of type `int` and a division between two `int` types returns also an `int`, meaning that the fraction is omitted.
>
> Has the situation now changed, because the compiler notices one of ... | "1", "3", "0" are all integers.
while "1.0" is a double.
what's different between the to situations is that double/integer is a double while integer/integer is an integer. |
14,425,833 | What I'm trying to do seems rather simple, but I can't find a way to do it.
Imagine somebody sends you a link for a dropbox folder. You can go to that URL and see all the files in the folder.
I'm trying to write a script in either python, php, or javascript to get all the download links in that folder from that URL.
... | 2013/01/20 | [
"https://Stackoverflow.com/questions/14425833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706798/"
] | In absence of suffixes, sufficiently small numbers have `int` or `double` types
```
a = 42; /* 42 has type int */
b = 42.0; /* 42.0 has type double */
```
You can use suffixes to specify the type of the literal
```
c = 42U; /* unsigned int */
d = 42.0f; /* float */
e = 42.0L; /* long double */
f = 42ULL; /* unsigne... | "1", "3", "0" are all integers.
while "1.0" is a double.
what's different between the to situations is that double/integer is a double while integer/integer is an integer. |
58,464,713 | `H4sIAAAAAAAAAO1aT3PbSHaHrPHYkj1j73gn2doku3B2N7PJLjz4T0BVqQpFQiQ4BCCBoCjiomoADRIk/mhBUBT5AXJL5ZbkkqocUqVrDvkE+ijzFXJNJXkNSjLHpjyyx95JuWQfRHSjG6/f+/V7v/e6tylqi9qItimKYu5R96Jg4x82qPu1bJoWG9vUZoEGW9QnOPWHFPm3SW01owDvxWgwgcf/2aa2O+NpHFuzFOcPqXt6QP06CESZD8KAYVUkMUJFDhkk4goTYB7xvuf7LO/BuP08O8F5EeHJFvWwwGfFNMcTIsbGQ+r+IYqnmPp... | 2019/10/19 | [
"https://Stackoverflow.com/questions/58464713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989704/"
] | There are no quotes in your string; it's simply made up of two identical base64 encoded strings, each of which can be decoded fine after a small fix: it appears that what has happened is that the trailing `==` in the first string have become `\u003d\u003d`. Replace `\u003d\u003d` with `==` and use the first string, or ... | You can use triple quotes like so :
```
my_var = """My text with quotes ' " is stored in a variable this way"""
```
You could also use ''' instead of """ if you prefer.
```
my_var = '''My text with quotes ' " is also stored in a variable this way'''
```
See : <https://docs.python.org/3/tutorial/introduction.html#... |
28,654,590 | Our security team asked me to not submit `plain text` passwords in my log in page, we use HTTPS though. so I thought that I need to do client side encryption before submit, I searched for solution and decided to implement [jCryption](http://www.jcryption.org/).
However the example presented there is PHP/python, aft... | 2015/02/22 | [
"https://Stackoverflow.com/questions/28654590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/735839/"
] | Your understanding about the second function is correct.
You may want to store actual nodes in the `edges` slot instead of node numbers. Then, instead of binding local variables to the node list inside of the two nodes that you want to connect, though, you can bind them to the nodes themselves, which would also look b... | Instead of:
```
(setf (slot-value (nth begin-node node-list) 'edges)
(cons end-node (slot-value (nth begin-node node-list) 'edges)))
```
You can write:
```
(push end-node (slot-value (nth begin-node node-list) 'edges))
```
Why is the following not working as expected?
```
(let ((begin-node-lst (slot-value ... |
40,712,568 | This python script returns a value of `90.0`:
```
import itertools
a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]
def TestFunction (a, b, c):
result = a + b/c
return result
Params=itertools.product(a, b, c)
x = 2
print(TestFunction(*list(Params)[x]))
```
However, I would like to evaluate my funct... | 2016/11/21 | [
"https://Stackoverflow.com/questions/40712568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7098896/"
] | ```
for x in range (5):
print(TestFunction(*list(Params)[x]))
```
`Params` is an iterator. The first time through the loop, you consume it entirely by converting it to a list. Therefore on the second iteration there's nothing in it and converting it to a list yields `[]`, the empty list, and trying get index 1 of... | Because calling `list()` on the iterator exhausts the iterator. Thus it can be called once only:
```
>>> Params=itertools.product(a, b, c)
>>> Params
<itertools.product object at 0x7f5ed3da5870>
>>> list(Params)
[(12, 234, 1), (12, 234, 2)..., (234, 1, 4)]
>>> list(Params)
[]
```
You can see that the second call to ... |
40,712,568 | This python script returns a value of `90.0`:
```
import itertools
a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]
def TestFunction (a, b, c):
result = a + b/c
return result
Params=itertools.product(a, b, c)
x = 2
print(TestFunction(*list(Params)[x]))
```
However, I would like to evaluate my funct... | 2016/11/21 | [
"https://Stackoverflow.com/questions/40712568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7098896/"
] | ```
for x in range (5):
print(TestFunction(*list(Params)[x]))
```
`Params` is an iterator. The first time through the loop, you consume it entirely by converting it to a list. Therefore on the second iteration there's nothing in it and converting it to a list yields `[]`, the empty list, and trying get index 1 of... | Because `Params` is an iterator and converting it to a list consumes it entirely.
There are 2 methods to handle your case:
1. Convert the iterator to a list outside of loop:
```
Params = list(itertools.product(a, b, c))
```
2. Use `copy.copy`:
```
from copy import copy
print(TestFunction(*list(copy(Params))[x]))
... |
40,712,568 | This python script returns a value of `90.0`:
```
import itertools
a=[12,345,1423,65,234]
b=[234,12,34,1,1,1]
c=[1,2,3,4]
def TestFunction (a, b, c):
result = a + b/c
return result
Params=itertools.product(a, b, c)
x = 2
print(TestFunction(*list(Params)[x]))
```
However, I would like to evaluate my funct... | 2016/11/21 | [
"https://Stackoverflow.com/questions/40712568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7098896/"
] | Because calling `list()` on the iterator exhausts the iterator. Thus it can be called once only:
```
>>> Params=itertools.product(a, b, c)
>>> Params
<itertools.product object at 0x7f5ed3da5870>
>>> list(Params)
[(12, 234, 1), (12, 234, 2)..., (234, 1, 4)]
>>> list(Params)
[]
```
You can see that the second call to ... | Because `Params` is an iterator and converting it to a list consumes it entirely.
There are 2 methods to handle your case:
1. Convert the iterator to a list outside of loop:
```
Params = list(itertools.product(a, b, c))
```
2. Use `copy.copy`:
```
from copy import copy
print(TestFunction(*list(copy(Params))[x]))
... |
68,650,493 | I have some experience starting starting up Apache Airflow but I have now an error when I try to `airflow db init` command. The error is as below. I am running Airflow on virtual env with Python 3.8. Any help would appreciated. I am not sure to understand this error as I managed to init the db without importing any `_c... | 2021/08/04 | [
"https://Stackoverflow.com/questions/68650493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8867871/"
] | Use `CROSS JOIN` to build all combinations and top up with a `LEFT JOIN`:
```
SELECT p.product_id, s.status, COUNT(t.any_not_null_column)
FROM (SELECT DISTINCT product_id FROM t) AS p
CROSS JOIN (SELECT DISTINCT status FROM t) AS s
LEFT JOIN t ON p.product_id = t.product_id AND s.status = t.status
GROUP BY p.product_i... | The following is a Postgres solution (a database I strongly recommend over MS Access). The idea is to generate all the rows and then use `left join` and `group by` to get the counts you want:
```
select p.product_id, s.status, count(d.product_id)
from (select distinct product_id from details) p cross join
(values... |
42,881,650 | I have a list e.g. `l1 = [1,2,3,4]` and another list: `l2 = [1,2,3,4,5,6,7,1,2,3,4]`.
I would like to check if `l1` is a subset in `l2` and if it is, then I want to delete these elements from `l2` such that `l2` would become `[5,6,7,1,2,3,4]`, where indexes 0-3 have been removed.
Is there a pythonic way of doing thi... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42881650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Well, here is a brute-force way. There are probably more efficient ways. If you expect to encounter a matching sublist early, the performance shouldn't be terrible.
```
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> for i in range(0, len(l2), len(l1)):
... if l2[i:len(l1)] == l1:
... del l2[i:len(... | I'm not proud of this, and it's not pythonic, but I thought it might be a bit of fun to write. I've annotated the code to make it a little more obvious what's happening.
```
>>> import re
>>> from ast import literal_eval
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> literal_eval( # convert the strin... |
42,890,951 | I have anaconda installed in my Mac. I am trying to install python-igraph.
I tried the following commands to install it:
```
$ brew install igraph
$ pip install python-igraph
```
My python setup:
```
Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (cl... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42890951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2529269/"
] | I found exactly what I was looking for, [SwipeCellKit](https://github.com/jerkoch/SwipeCellKit), by jerkoch. This library performs the same exact actions as the stock iOS Mail app does when swiping to the left. No need to deal with different `UIViews` and `UIButtons`.
To use, simply conform to the `SwipeTableViewCellD... | I would take a look at the [SWTableViewCell](https://github.com/CEWendel/SWTableViewCell) by CEWendel. It looks like it has exactly what you're looking for. |
42,890,951 | I have anaconda installed in my Mac. I am trying to install python-igraph.
I tried the following commands to install it:
```
$ brew install igraph
$ pip install python-igraph
```
My python setup:
```
Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (cl... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42890951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2529269/"
] | I would take a look at the [SWTableViewCell](https://github.com/CEWendel/SWTableViewCell) by CEWendel. It looks like it has exactly what you're looking for. | May be late to answer this, but in case anyone else is looking - consider this read to answer the question: <https://www.raywenderlich.com/62435/make-swipeable-table-view-cell-actions-without-going-nuts-scroll-views> |
42,890,951 | I have anaconda installed in my Mac. I am trying to install python-igraph.
I tried the following commands to install it:
```
$ brew install igraph
$ pip install python-igraph
```
My python setup:
```
Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (cl... | 2017/03/19 | [
"https://Stackoverflow.com/questions/42890951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2529269/"
] | I found exactly what I was looking for, [SwipeCellKit](https://github.com/jerkoch/SwipeCellKit), by jerkoch. This library performs the same exact actions as the stock iOS Mail app does when swiping to the left. No need to deal with different `UIViews` and `UIButtons`.
To use, simply conform to the `SwipeTableViewCellD... | May be late to answer this, but in case anyone else is looking - consider this read to answer the question: <https://www.raywenderlich.com/62435/make-swipeable-table-view-cell-actions-without-going-nuts-scroll-views> |
49,132,008 | I have next method:
```
public void callPython() throws IOException {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python -c \"from test import read_and_show; read_and_show()\" src/main/python");
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49132008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5417750/"
] | When executing other programs from java, I've found it's easier to keep it as simple as possible in java and instead execute a batch file
```
Runtime.getRuntime().exec("chrome.exe www.google.com");
```
Would instead become
```
Runtime.getRuntime().exec("openChrome.bat");
```
and openChrome.bat:
```
chrome.exe ww... | You're missing the shebang statement that states where the python interpreter is. It should be line #1
```
#!/usr/bin/python
``` |
49,132,008 | I have next method:
```
public void callPython() throws IOException {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("python -c \"from test import read_and_show; read_and_show()\" src/main/python");
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49132008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5417750/"
] | When executing other programs from java, I've found it's easier to keep it as simple as possible in java and instead execute a batch file
```
Runtime.getRuntime().exec("chrome.exe www.google.com");
```
Would instead become
```
Runtime.getRuntime().exec("openChrome.bat");
```
and openChrome.bat:
```
chrome.exe ww... | Runtime.exec is obsolete. It was replaced by the [ProcessBuilder class](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessBuilder.html) a long time ago:
```
ProcessBuilder builder = new ProcessBuilder(
"python", "-c", "from test import read_and_show; read_and_show()", "src/main/python");
builder.redirectI... |
33,560,877 | I would like to convert my list(items) from string to int, therefore I can calculate the numbers in it. However, the python showed up the invalid literal for int() with base 10 error, and I've no idea what's wrong with it. (list: in one line only, separate by comma and no space before and after comma.)
list:
```
51,2... | 2015/11/06 | [
"https://Stackoverflow.com/questions/33560877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532342/"
] | I modified according to your code. Please have try.
```
def main():
file = str(input("Please enter the full name of the desired file (with extension) at the prompt below: \n"))
parseCSV(file)
def parseCSV(file):
file_open = open(file)
print (file_open.read())
with open(file) as rd:
lines... | To answer your question, *'What's wrong with it?'*:
You are reading in your whole csv to a list containing one item that is the whole file as a long string. Even if your csv only contains integers the way you are parsing in all of the lines will not work. |
33,560,877 | I would like to convert my list(items) from string to int, therefore I can calculate the numbers in it. However, the python showed up the invalid literal for int() with base 10 error, and I've no idea what's wrong with it. (list: in one line only, separate by comma and no space before and after comma.)
list:
```
51,2... | 2015/11/06 | [
"https://Stackoverflow.com/questions/33560877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532342/"
] | You are trying to convert this to an integer:
```
'51,2,2,49,15,2,1,14'
```
The error message is pretty explicit in showing you what it is you are trying to typecast to an `int`.
The data in your file is most likely comma separated, and you are reading it in as a list with a single string entry that is comma sepa... | I modified according to your code. Please have try.
```
def main():
file = str(input("Please enter the full name of the desired file (with extension) at the prompt below: \n"))
parseCSV(file)
def parseCSV(file):
file_open = open(file)
print (file_open.read())
with open(file) as rd:
lines... |
33,560,877 | I would like to convert my list(items) from string to int, therefore I can calculate the numbers in it. However, the python showed up the invalid literal for int() with base 10 error, and I've no idea what's wrong with it. (list: in one line only, separate by comma and no space before and after comma.)
list:
```
51,2... | 2015/11/06 | [
"https://Stackoverflow.com/questions/33560877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5532342/"
] | You are trying to convert this to an integer:
```
'51,2,2,49,15,2,1,14'
```
The error message is pretty explicit in showing you what it is you are trying to typecast to an `int`.
The data in your file is most likely comma separated, and you are reading it in as a list with a single string entry that is comma sepa... | To answer your question, *'What's wrong with it?'*:
You are reading in your whole csv to a list containing one item that is the whole file as a long string. Even if your csv only contains integers the way you are parsing in all of the lines will not work. |
22,023,184 | I tried to subclass NSThread in order to operate a thread with some data. I want to simulate the join() in python, according to the doc:
>
> join(): Wait until the thread terminates. This blocks the calling thread until
> the thread whose join() method is called terminates
>
>
>
So I think using performSelector... | 2014/02/25 | [
"https://Stackoverflow.com/questions/22023184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014948/"
] | From Apple's documentation on `performSelector:onThread:withObject:waitUntilDone:`:
>
> This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target threa... | You're basically in a deadlock condition.
```
-(void)join
{
[self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}
```
`join` is waiting for `myRun` to finish (waitUntilDone flag), but `myRun` is enqueued on the same thread as `join`, so it's also waiting for `join` to finish.
... |
56,143,264 | i upgrade pip. But after the upgrade have some syntax error.
i try install python 3.x but not fixed.
Traceback (most recent call last):
```
File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
File "/usr/lib/python2.6/site-packages/pip/_internal/__init__.py", line 19, in <module>
from pi... | 2019/05/15 | [
"https://Stackoverflow.com/questions/56143264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7571523/"
] | python2.6 is not supported anymore, try to change you SYS PATH to point for new python and pip
check this : [Python ENV](https://www.tutorialspoint.com/python/python_environment.htm)
alternatively you can use the following:
```
/path/to/pip3 install ....
/path/to/python3 <NAME_OF_THE_SCRIPT>
``` | ----------UPDATE----------------
i try to install python36u i got some errors
```
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: liblzma.so.5(XZ_5.0)(64bit)
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: libgdbm_compat.so.4()(64bit)
Error: Package: p... |
56,143,264 | i upgrade pip. But after the upgrade have some syntax error.
i try install python 3.x but not fixed.
Traceback (most recent call last):
```
File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
File "/usr/lib/python2.6/site-packages/pip/_internal/__init__.py", line 19, in <module>
from pi... | 2019/05/15 | [
"https://Stackoverflow.com/questions/56143264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7571523/"
] | Change your Default python version using this link [Change default python version](https://stackoverflow.com/questions/45542690/linux-centos-7-how-to-set-python3-5-2-as-default-python-version)
you have installed pyopenssl for python2 environment. so first uninstall it.
check version: python3.6 -V, pip3 -V etc
While ... | ----------UPDATE----------------
i try to install python36u i got some errors
```
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: liblzma.so.5(XZ_5.0)(64bit)
Error: Package: python36u-libs-3.6.8-1.el7.ius.x86_64 (ius)
Requires: libgdbm_compat.so.4()(64bit)
Error: Package: p... |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | We can use `melt` with `xtabs` in `R`
```
library(reshape2)
xtabs(value~L1 + L2, melt(values))
# L2
#L1 a b c d
# 1 1 10 0 0
# 2 0 0 1 99
# 3 0 1 0 4
``` | Here's a solution with `plyr` package:
```
ldply(values, data.frame)
a b d c
1 1 10 NA NA
2 NA NA 99 1
3 NA 1 4 NA
# mutate each to replace NA with 0
ldply(values, data.frame) %>%
mutate_each(funs(replace(., is.na(.), 0)))
a b d c
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | We can use `melt` with `xtabs` in `R`
```
library(reshape2)
xtabs(value~L1 + L2, melt(values))
# L2
#L1 a b c d
# 1 1 10 0 0
# 2 0 0 1 99
# 3 0 1 0 4
``` | Using base R to construct a matrix, you could do the following.
first, the set up
```
# flatten list to pull out info for matrix construction
flat <- unlist(values)
# build a 0 matrix with correct dimensions and column names
myMat <- matrix(0, nrow=length(values), ncol=length(unique(names(flat))),
dim... |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | With `dplyr` you could do it like this:
```
library(dplyr)
values %>% bind_rows() %>% mutate_all(function(x) coalesce(x, 0))
# A tibble: 3 × 4
a b d c
<dbl> <dbl> <dbl> <dbl>
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` | Here's a solution with `plyr` package:
```
ldply(values, data.frame)
a b d c
1 1 10 NA NA
2 NA NA 99 1
3 NA 1 4 NA
# mutate each to replace NA with 0
ldply(values, data.frame) %>%
mutate_each(funs(replace(., is.na(.), 0)))
a b d c
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | Here's a solution with `plyr` package:
```
ldply(values, data.frame)
a b d c
1 1 10 NA NA
2 NA NA 99 1
3 NA 1 4 NA
# mutate each to replace NA with 0
ldply(values, data.frame) %>%
mutate_each(funs(replace(., is.na(.), 0)))
a b d c
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` | Using base R to construct a matrix, you could do the following.
first, the set up
```
# flatten list to pull out info for matrix construction
flat <- unlist(values)
# build a 0 matrix with correct dimensions and column names
myMat <- matrix(0, nrow=length(values), ncol=length(unique(names(flat))),
dim... |
43,773,802 | Using python and pandas I can easily construct a sparse DataFrame from a list of dictionary objects. The following code snippet shows how this can be done in pandas:
```
In [1]: import pandas as pd; (pd.DataFrame([{'a':1, 'b':10},
{'d':99, 'c':1},
... | 2017/05/04 | [
"https://Stackoverflow.com/questions/43773802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4862483/"
] | With `dplyr` you could do it like this:
```
library(dplyr)
values %>% bind_rows() %>% mutate_all(function(x) coalesce(x, 0))
# A tibble: 3 × 4
a b d c
<dbl> <dbl> <dbl> <dbl>
1 1 10 0 0
2 0 0 99 1
3 0 1 4 0
``` | Using base R to construct a matrix, you could do the following.
first, the set up
```
# flatten list to pull out info for matrix construction
flat <- unlist(values)
# build a 0 matrix with correct dimensions and column names
myMat <- matrix(0, nrow=length(values), ncol=length(unique(names(flat))),
dim... |
18,942,318 | I try to upload the data into datastore use remote\_api at my dev server, but I got the following error, the SDK version is 1.8.4. Is there anyone has the same error? It looks like the new datastore version 4 cause this?
```
Traceback (most recent call last):
File "D:\python-lib\google_appengine\appcfg.py", line 1... | 2013/09/22 | [
"https://Stackoverflow.com/questions/18942318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2345755/"
] | What about this?
```
MyBase * base = dynamic_cast<MyBase *>(clicked_shape);
base->SetText("too");
```
You might want to check for `base` being null, if the Shape you get isn't actually one of yours.
`MyBase` needs at least one virtual function for this - the destructor would do. | Shape class is a base class hence it provides an interface that can be overridden. E.g. there could be `draw()` method which is called to draw a shape. That one would be a good candidate to be overridden in your new class with text box. For example:
```
class SquareWithText: public Square {
void draw() {
Square:... |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | Try this,
I believe this serves your purpose. I won't call it much pythonic. More like PyQt override.
#minor code edit
```
from PyQt4 import QtGui
import sys
#===============================================================================
# MyEditableTextBox-
#=======================================================... | Hey i know i am kind of late, but I hope this might help some one else like me who spent some time searching for this
**Mycase:**
I was trying to convert only the first letter to capital and this is what i ended up with and it worked (just a beginner in python so if you can make this more pythonic please let me know)
... |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | Try this,
I believe this serves your purpose. I won't call it much pythonic. More like PyQt override.
#minor code edit
```
from PyQt4 import QtGui
import sys
#===============================================================================
# MyEditableTextBox-
#=======================================================... | I am also late but after contemplating on this question I think this is some sort of pythonic way of accomplishing it in PyQt5:
```
class CustomInput(QLineEdit):
def __init__(self):
super().__init__()
self.textChanged.connect(self.text_changed)
def text_changed(self):
if self.text().is... |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | The simplest way would be to use a [validator](http://qt-project.org/doc/qt-4.8/qvalidator.html).
This will immediately uppercase anything the user types, or pastes, into the line-edit:
```
from PyQt4 import QtCore, QtGui
class Validator(QtGui.QValidator):
def validate(self, string, pos):
return QtGui.QV... | Hey i know i am kind of late, but I hope this might help some one else like me who spent some time searching for this
**Mycase:**
I was trying to convert only the first letter to capital and this is what i ended up with and it worked (just a beginner in python so if you can make this more pythonic please let me know)
... |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | The simplest way would be to use a [validator](http://qt-project.org/doc/qt-4.8/qvalidator.html).
This will immediately uppercase anything the user types, or pastes, into the line-edit:
```
from PyQt4 import QtCore, QtGui
class Validator(QtGui.QValidator):
def validate(self, string, pos):
return QtGui.QV... | I am also late but after contemplating on this question I think this is some sort of pythonic way of accomplishing it in PyQt5:
```
class CustomInput(QLineEdit):
def __init__(self):
super().__init__()
self.textChanged.connect(self.text_changed)
def text_changed(self):
if self.text().is... |
28,962,266 | I had drawn up an UI using the QT Designer but found out that there are no parameters for me to set QLineEdit inputs to be uppercase.
After doing some online searching, I have only seen a very few handful of results that cater to my needs, however all are coded in Qt. Example, this [link](http://www.qtforum.org/articl... | 2015/03/10 | [
"https://Stackoverflow.com/questions/28962266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3212246/"
] | Hey i know i am kind of late, but I hope this might help some one else like me who spent some time searching for this
**Mycase:**
I was trying to convert only the first letter to capital and this is what i ended up with and it worked (just a beginner in python so if you can make this more pythonic please let me know)
... | I am also late but after contemplating on this question I think this is some sort of pythonic way of accomplishing it in PyQt5:
```
class CustomInput(QLineEdit):
def __init__(self):
super().__init__()
self.textChanged.connect(self.text_changed)
def text_changed(self):
if self.text().is... |
42,683,602 | I am writing a new Python application that I intend to distribute to several colleagues. Instead of my normal carefree attitude of just having everything self contained and run inside a folder in my home directory, this time I would like to broaden my horizon and actually try to utilize the Linux directory structure as... | 2017/03/08 | [
"https://Stackoverflow.com/questions/42683602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272450/"
] | You could use the `map()` feature of the stream to convert each `User` instance in your list to a `UserWithAge` instance.
```
List<User> userList = ... // your list
List<UserWithAge> usersWithAgeList = userList.stream()
.map(user -> {
// create UserWithAge instance and copy user name
... | While you could do this, You should not do like this.
```
List<UserWithAge> userWithAgeList = new ArrayList<UserWithAge>();
userList.stream().forEach(user -> {
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
... |
42,683,602 | I am writing a new Python application that I intend to distribute to several colleagues. Instead of my normal carefree attitude of just having everything self contained and run inside a folder in my home directory, this time I would like to broaden my horizon and actually try to utilize the Linux directory structure as... | 2017/03/08 | [
"https://Stackoverflow.com/questions/42683602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272450/"
] | You could use the `map()` feature of the stream to convert each `User` instance in your list to a `UserWithAge` instance.
```
List<User> userList = ... // your list
List<UserWithAge> usersWithAgeList = userList.stream()
.map(user -> {
// create UserWithAge instance and copy user name
... | ```
public class ListIteratorExp {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
Person p1 = new Person();
p1.setName("foo");
Person p2 = new Person();
p2.setName("bee");
list.add(p1);
list.add(p2);
list.stream().f... |
42,683,602 | I am writing a new Python application that I intend to distribute to several colleagues. Instead of my normal carefree attitude of just having everything self contained and run inside a folder in my home directory, this time I would like to broaden my horizon and actually try to utilize the Linux directory structure as... | 2017/03/08 | [
"https://Stackoverflow.com/questions/42683602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272450/"
] | While you could do this, You should not do like this.
```
List<UserWithAge> userWithAgeList = new ArrayList<UserWithAge>();
userList.stream().forEach(user -> {
UserWithAge userWithAge = new UserWithAge();
userWithAge.setName(user.getName());
userWithAge.setAge(27);
... | ```
public class ListIteratorExp {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
Person p1 = new Person();
p1.setName("foo");
Person p2 = new Person();
p2.setName("bee");
list.add(p1);
list.add(p2);
list.stream().f... |
70,600,154 | How can I implement a selection based on selecting the first 3n+1 elements from a tag in it's path? For example, let's say I have the following xpath:
```
//div[@class='ResultsSectionContainer-sc-gdhf14-0 kteggz']/div[@class='Wrapper-sc-11673k2-0 gIBPSk']//div/div/a
```
Taken from this url:
```
https://www.jobsite.... | 2022/01/05 | [
"https://Stackoverflow.com/questions/70600154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15675231/"
] | The XPath filter predicate `[position() mod 3 = 1]` selects all elements whose 1-based position is 3n+1 for some integer n. | All you need here is to use a **correct** locator.
I guess you are trying to get all the job links?
If so, instead of this
`//div[@class='ResultsSectionContainer-sc-gdhf14-0 kteggz']/div[@class='Wrapper-sc-11673k2-0 gIBPSk']//div/div/a`
very long, complex and fragile XPath you can use this XPath:
```py
//a[@d... |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | Replace call with check\_output.
```
from subprocess import check_output
a = check_output(["lsb_release", "-si"])
``` | You can also try subprocess.check\_output.
Based on docs: "Run command with arguments and return its output as a byte string." Docs: <https://docs.python.org/2/library/subprocess.html>
Code:
```
a = subprocess.check_output(["lsb_release", "-si"])
```
In my case, output was:
```
'Ubuntu\n'
``` |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | The 'a' is just the exit status, try:
```
from subprocess import Popen, PIPE, STDOUT
cmd = "lsb_release -si"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
``` | As you can see from the link I linked to in the 2nd answer : <https://github.com/easybuilders/easybuild/wiki/OS_flavor_name_version>
you notice that platform.dist is a way better method of determining the current linux platform, however this is deprecated in python 3.5 and is gone in 3.8. It seems like there hardly i... |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | The 'a' is just the exit status, try:
```
from subprocess import Popen, PIPE, STDOUT
cmd = "lsb_release -si"
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
``` | What about `open("/etc/issue","r").read()`? |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | Replace call with check\_output.
```
from subprocess import check_output
a = check_output(["lsb_release", "-si"])
``` | As you can see from the link I linked to in the 2nd answer : <https://github.com/easybuilders/easybuild/wiki/OS_flavor_name_version>
you notice that platform.dist is a way better method of determining the current linux platform, however this is deprecated in python 3.5 and is gone in 3.8. It seems like there hardly i... |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | What about `open("/etc/issue","r").read()`? | You can also try subprocess.check\_output.
Based on docs: "Run command with arguments and return its output as a byte string." Docs: <https://docs.python.org/2/library/subprocess.html>
Code:
```
a = subprocess.check_output(["lsb_release", "-si"])
```
In my case, output was:
```
'Ubuntu\n'
``` |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | ```
In [24]: open('/etc/lsb-release').readline().strip().split('=')[-1]
Out[24]: 'LinuxMint'
``` | What about `open("/etc/issue","r").read()`? |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | Replace call with check\_output.
```
from subprocess import check_output
a = check_output(["lsb_release", "-si"])
``` | What about `open("/etc/issue","r").read()`? |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | ```
In [24]: open('/etc/lsb-release').readline().strip().split('=')[-1]
Out[24]: 'LinuxMint'
``` | You can also try subprocess.check\_output.
Based on docs: "Run command with arguments and return its output as a byte string." Docs: <https://docs.python.org/2/library/subprocess.html>
Code:
```
a = subprocess.check_output(["lsb_release", "-si"])
```
In my case, output was:
```
'Ubuntu\n'
``` |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | What about `open("/etc/issue","r").read()`? | As you can see from the link I linked to in the 2nd answer : <https://github.com/easybuilders/easybuild/wiki/OS_flavor_name_version>
you notice that platform.dist is a way better method of determining the current linux platform, however this is deprecated in python 3.5 and is gone in 3.8. It seems like there hardly i... |
34,791,797 | I would like to know how to determine the precise Linux distribution I am on (excluding version numbers), from within a Python script and define a variable as equal to it. Now, I should clarify and say that I have seen these two questions:
* [Python: What OS am I running on?](https://stackoverflow.com/questions/1854/p... | 2016/01/14 | [
"https://Stackoverflow.com/questions/34791797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876983/"
] | ```
In [24]: open('/etc/lsb-release').readline().strip().split('=')[-1]
Out[24]: 'LinuxMint'
``` | As you can see from the link I linked to in the 2nd answer : <https://github.com/easybuilders/easybuild/wiki/OS_flavor_name_version>
you notice that platform.dist is a way better method of determining the current linux platform, however this is deprecated in python 3.5 and is gone in 3.8. It seems like there hardly i... |
49,105,070 | I'm a python newbie. I created a calculator program that will accept 2 number and a type of operation from user. I already have a working code for this but I want to further simplify the code by exploring and using function.
Here's the portion of the code:
```
def addition(num1,num2):
sum = num1 + num2
print('... | 2018/03/05 | [
"https://Stackoverflow.com/questions/49105070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9404668/"
] | You should write something like that.. the ?? is so that if it can't convert the argument into Int it will add 0 to your variable myInt..
```
let myInt:Int = Int("1234") ?? 0
``` | You can do it like this by creating an extension of String:
```
extension String {
var toInt: Int {
return Int(self) ?? 0
}
}
```
and use it like this
```
let preparationTimeInt = preparationTime.toInt
``` |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I have faced the similar issue in Windows Server 2012 r2. After lot of findings I found that mfplat.dll was missing which is related to Window Media Service.
Hence you have to manually install the features so that you can get dll related to window media service.
1. Turn windows features on or off
2. Skip the roles sc... | I had the same problem on Windows Server 2012 R2 x64. I was creating executable file using PyInstaller and got error in runtime:
```
ImportError: DLL load failed: The specified module could not be found.
```
After installing "Visual C++ redistributable" 2015 and enabling "Media Foundation" feature my problem was res... |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I had the same error (although I compiled OpenCV myself), in my case there were some DLL dependencies missing. You can check that with the program [Dependency Walker](http://dependencywalker.com/).
Download Dependency Walker and run it, and open the file *cv2.pyd* with Dependency Walker, it should be in `C:\Program Fi... | All you need is python 3.6.
I've been looking for solution for last 3 days and my problem was solved when i installed python 3.6.7.
After installing python 3.6 you can simply run `pip install opencv-python`.
Source: <https://www.geeksforgeeks.org/setup-opencv-with-pycharm-environment/> |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | It helps me `pip install opencv-contrib-python` Anaconda Prompt, python 3.7.1 cv2 4.1.1 | Just ran into this problem of cv2 importable from my conda environment but not through the "same" environment in jupyter. The error I was getting was that it couldn't load the dll.
Additionally, I could not get opencv installed through jupyter, even using:
```
import sys
!conda install --yes --prefix {sys.prefix} num... |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I had the same error (although I compiled OpenCV myself), in my case there were some DLL dependencies missing. You can check that with the program [Dependency Walker](http://dependencywalker.com/).
Download Dependency Walker and run it, and open the file *cv2.pyd* with Dependency Walker, it should be in `C:\Program Fi... | Installing Python version 3.6 and then installing `opencv` with the command:
`pip install opencv-python==3.3.0.9` resolved this issue for me |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | i was suffering from the same problem "DLL load failed" after reading tons of answers and articles i got a solution.
i don't know this works for you or not but give it a try.
tools and versions i used: anaconda - 5.3.1, python - 3.7, win 10 (64 bit)
Steps i performed :
**step1**:i installed opencv 3.4.4 from [here]... | All you need is python 3.6.
I've been looking for solution for last 3 days and my problem was solved when i installed python 3.6.7.
After installing python 3.6 you can simply run `pip install opencv-python`.
Source: <https://www.geeksforgeeks.org/setup-opencv-with-pycharm-environment/> |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I was having this problem on Windows. I resolved this error by checking instructions [here](https://pypi.org/project/opencv-python).
Q: Import fails on Windows: ImportError: DLL load failed: The specified module could not be found?
A: If the import fails on Windows, make sure you have
[Visual C++ redistributable 2015... | It helps me `pip install opencv-contrib-python` Anaconda Prompt, python 3.7.1 cv2 4.1.1 |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I was having the same issue. I resolved this error by downgrading open cv.
`pip install opencv-python==3.3.0.9` | I was having this problem on Windows Server 2008R2 fresh install and took almost a day to resolve, as was trying with many hits and trials finally I found solution somewhere in internet (not stackoverflow)
* Installed Windows Media Feature Pack for 2008R2 then installed Server Manager-> Features-> Add Features-> Desk... |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | I was having this problem on Windows. I resolved this error by checking instructions [here](https://pypi.org/project/opencv-python).
Q: Import fails on Windows: ImportError: DLL load failed: The specified module could not be found?
A: If the import fails on Windows, make sure you have
[Visual C++ redistributable 2015... | **its worked well for me.\***
Answer is Need to put cv2.pyd file to your virtual environment.
need to put under two folder of envs,
* **first** is under DLLS folder and
**Second** is under Lib/site-packages
To get cv2.pyd > download from this link <https://sourceforge.net/projects/opencvlibrary/> and then extract t... |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | After 15 days of brain storming, This solution worked for me. And I am sure that it will work for you too. I installed anaconda to use OpenCV 3.1.0. I followed following Steps:
1) I have installed anaconda-5.3 64-bit installer (614.3 MB) which uses python 3.7. You can download anaconda from link: <https://www.anaconda... | I was having the same issue. I resolved this error by downgrading open cv.
`pip install opencv-python==3.3.0.9` |
52,349,669 | In [windows server 2012 R2 x64, python 3.7 64x]
```
pip install opencv-contrib-python
```
installed without any error .
and when I try to import it
```
import cv2
```
show me this error :
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import cv2
File "C:\Program Files\Pyth... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52349669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7407809/"
] | Can you try uninstalling opencv and installing it using a wheel file instead? [Here](https://www.lfd.uci.edu/~gohlke/pythonlibs/) is a website that has many versions of OpenCV compiled for windows, search for the one you need and simply install it with `pip` command.
So if you have Python 3.6 (64 Bit) and wish to inst... | It helps me `pip install opencv-contrib-python` Anaconda Prompt, python 3.7.1 cv2 4.1.1 |
24,944,627 | I'm using the Canopy distribution and when I try to install pymatbridge using 'pip install pymatbridge' I get an error saying that pymatbridge does not work on win32. I've got the 64-bit version of Canopy so I don't understand what that means.
<http://arokem.github.io/python-matlab-bridge/>
```
Downloading/unpacking ... | 2014/07/24 | [
"https://Stackoverflow.com/questions/24944627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/334059/"
] | I am the developer of this software. This should work now (since version 0.4), but I don't have a Windows machine to test this one. I have had help from Windows users in developing the patches to make this Windows-functional. Though, I am not always able to solve issues, I am happy to receive suggestions/complaints/pra... | "Win32" in this context means Windows 32- or 64-bit, as distinct from Cygwin.
The developer of pymatbridge introduced this explicit restriction in May 2014:
<https://github.com/arokem/python-matlab-bridge/commit/a6fd3cc3adf5ef2b5e3d9b83a8050d783c76d48f>
I don't know why. Perhaps, like many small developers, he found ... |
60,119,580 | I am building HR app using python with Django framework, I am having issue to calculation retirement year of an employee, for example if an employee enters his/her date of birth let the system calculate his/her retirement year or how many years remaining to retire. staff retire at 60 years
Am getting this error:
```
... | 2020/02/07 | [
"https://Stackoverflow.com/questions/60119580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860292/"
] | Here's a full working example of what you want to achieve:
```
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
df_1 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_2 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_3 = pd.Da... | I figured out the solution for this, hope it will be helpful to others. Since the input is list of dataframe, it is easier to do as follow:
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from itertools import cycle
df1, df2 = list_of_df[0], list_of_df[1]
colors=cm.tab10(np.linspace(0, 1,len(df1... |
60,119,580 | I am building HR app using python with Django framework, I am having issue to calculation retirement year of an employee, for example if an employee enters his/her date of birth let the system calculate his/her retirement year or how many years remaining to retire. staff retire at 60 years
Am getting this error:
```
... | 2020/02/07 | [
"https://Stackoverflow.com/questions/60119580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860292/"
] | Here's a full working example of what you want to achieve:
```
import pandas as pd
import matplotlib.pyplot as plt
import pandas as pd
df_1 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_2 = pd.DataFrame({'2010':[10,11,12,13],'2011':[14,18,14,15],'2012':[12,13,14,13]})
df_3 = pd.Da... | ```
import pandas as pd
import matplotlib.pyplot as plt
df_1 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_2 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_3 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
list_df = [df_1,df_2,df_3]
for i,... |
60,119,580 | I am building HR app using python with Django framework, I am having issue to calculation retirement year of an employee, for example if an employee enters his/her date of birth let the system calculate his/her retirement year or how many years remaining to retire. staff retire at 60 years
Am getting this error:
```
... | 2020/02/07 | [
"https://Stackoverflow.com/questions/60119580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860292/"
] | I figured out the solution for this, hope it will be helpful to others. Since the input is list of dataframe, it is easier to do as follow:
```
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
from itertools import cycle
df1, df2 = list_of_df[0], list_of_df[1]
colors=cm.tab10(np.linspace(0, 1,len(df1... | ```
import pandas as pd
import matplotlib.pyplot as plt
df_1 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_2 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
df_3 = pd.DataFrame({'A':[15,16,17,20],'B':[21,22,23,24],'C':[25,26,27,28]})
list_df = [df_1,df_2,df_3]
for i,... |
59,207,859 | I've found related question, mine about GitLab, those about GitHub: [How to remove extra line space on GitHub markdown bullets/lists?](https://stackoverflow.com/questions/45113083/how-to-remove-extra-line-space-on-github-markdown-bullets-lists) and one answer is to use 4 spaces and another:
>
> You cannot do this ...... | 2019/12/06 | [
"https://Stackoverflow.com/questions/59207859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5499118/"
] | I found that alternating between the `+` and `-` unordered list indicators produces the desired result.
```
- Item 1
- SubItem 1
- SubItem 2
+ Item 2
+ SubItem 1
+ SubItem 2
- Item 3
- SubItem 1
- SubItem 2
``` | Small mistake: should have put `<br/>` on same level as secondary list (indent with 4 spaces) - then extra line is seen in GUI. |
8,673,035 | I know feature hashing (hashing-trick) is used to reduce the dimensionality and handle sparsity of bit vectors but I don't understand how it really works. Can anyone explain this to me.Is there any python library available to do feature hashing?
Thank you. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8673035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/585329/"
] | On Pandas, you could use something like this:
```
import pandas as pd
import numpy as np
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
data = pd.DataFrame(data)
def hash_col(df, col, N):
cols = [col + "_" ... | [Here](http://metaoptimize.com/qa/questions/6943/what-is-the-hashing-trick#6945) (sorry I cannot add this as a comment for some reason.) Also, the first page of [Feature Hashing for Large Scale Multitask Learning](http://arxiv.org/pdf/0902.2206) explains it nicely. |
8,673,035 | I know feature hashing (hashing-trick) is used to reduce the dimensionality and handle sparsity of bit vectors but I don't understand how it really works. Can anyone explain this to me.Is there any python library available to do feature hashing?
Thank you. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8673035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/585329/"
] | [Here](http://metaoptimize.com/qa/questions/6943/what-is-the-hashing-trick#6945) (sorry I cannot add this as a comment for some reason.) Also, the first page of [Feature Hashing for Large Scale Multitask Learning](http://arxiv.org/pdf/0902.2206) explains it nicely. | Large sparse feature can be derivate from interaction, U as user and X as email, so the dimension of U x X is memory intensive. Usually, task like spam filtering has time limitation as well.
Hash trick like other hash function store binary bits (index) which make large scale training feasible. In theory, more hashed l... |
8,673,035 | I know feature hashing (hashing-trick) is used to reduce the dimensionality and handle sparsity of bit vectors but I don't understand how it really works. Can anyone explain this to me.Is there any python library available to do feature hashing?
Thank you. | 2011/12/29 | [
"https://Stackoverflow.com/questions/8673035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/585329/"
] | On Pandas, you could use something like this:
```
import pandas as pd
import numpy as np
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
data = pd.DataFrame(data)
def hash_col(df, col, N):
cols = [col + "_" ... | Large sparse feature can be derivate from interaction, U as user and X as email, so the dimension of U x X is memory intensive. Usually, task like spam filtering has time limitation as well.
Hash trick like other hash function store binary bits (index) which make large scale training feasible. In theory, more hashed l... |
11,511,080 | I am a beginner at python (one week). Here I am trying print the list of all the prime factor of 60. But for line 19, I am getting following error:
*TypeError: unsupported operand type(s) for %: 'float' and 'list'*
The code:
```
whylist = []
factor = []
boom = []
primefactor = []
n = 60
j = (list(range(1, n, 1)))
fo... | 2012/07/16 | [
"https://Stackoverflow.com/questions/11511080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526409/"
] | To apply a math operation to every element in a list you can use a list-comprehension:
```
new_list = [ x%num for x in old_list]
```
There are other ways to do it as well. Sometimes people will use `map`
```
new_list = map(lambda x: x%num, old_list)
```
but most people prefer the first form which is generally mo... | Another option is to use numpy arrays instead of lists.
```
import numpy as np
j = np.arange(1,n,1)
rem = np.mod(j,num)
```
and numpy will take care of broadcasting operations for you. It should also be faster than list comprehensions or map. |
55,235,230 | I get this warning most of the time when i define a model using Keras. It seems to somehow come from tensorflow though:
```
WARNING:tensorflow:From C:\Users\lenik\AppData\Local\Programs\Python\Python37\lib\site-packages\keras\backend\tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with ... | 2019/03/19 | [
"https://Stackoverflow.com/questions/55235230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8104036/"
] | This depreciation warning is due to the Dropout layer in `tf.keras.layers.Dropout`.
To avoid this warning, you need to clearly specify `rate=` in Dropout as: `Dropout(rate=0.2)`.
Earlier it was `keep_prob` and it is now deprecated to `rate` i.e. rate = 1-keep\_prob.
For more, you can check out this tensorflow [doc... | Tensorflow is telling you that the argument `keep_prob` is deprecated and that it has been replaced by the argument `rate`.
Now, to achieve the same behavior you have now and remove the warning, you need to replace every occurrence of the `keep_prob` argument with `rate` argument, and pass the value `1-keep_prob`. |
4,341,206 | When trying to authenticate via OAuth in Django Piston, the following exception is thrown:
```
Environment:
Request Method: GET
Request URL: http://localhost:8000/api/oauth/request_token/?oauth_nonce=32921052&oauth_timestamp=1291331173&oauth_consumer_key=ghof7av2vu8hal2hek&oauth_signature_method=HMAC-SHA1&oauth_versi... | 2010/12/02 | [
"https://Stackoverflow.com/questions/4341206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186101/"
] | This is a piston problem that comes from an encoding problem of the key/secret of the consumer.
The solution is to force the encoding of the key/secret returned from the database to ASCII.
In the `store.py` file of Piston, modify the `lookup_consumer` so it look like this:
```
def lookup_consumer(self, key):
try:... | This problem also occurs inside Piston's "oauth.py" module's "build\_signature()" method if a unicode key value is passed in. I discovered this issue while using the clemesha/django-piston-oauth-example client code mentioned above because it kept failing after the prompt for the "PIN Code".
The underlying problem is d... |
62,555,213 | I am having two dicts, one in list:
```
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = {'21':"yes"},{'24':"yes"}
```
I need to compare var\_a and var\_b with the key from var\_b with the number value in var\_a.
I have tried this and got the output:
```
for key, value in var_b.iteritems(... | 2020/06/24 | [
"https://Stackoverflow.com/questions/62555213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741562/"
] | You can use `map` to create a keys set from `var_b` keys and then loop only over `var_a` to check if the number value exists in the `var_b` keys set
```
var_a = [{'name':"John",'number':21},{'name':"Kevin",'number':23}]
var_b = [{'21':"yes"},{'23':"no"}]
keys_set = set(map(lambda x: int(list(x.keys())[0]), var_b))
fo... | I think you need to use the lambda function with one for-loop:
```
for key, value in var_b.iteritems():
result = filter(lambda d: d['id'] == key, var_a)
```
The result will give you the output for sure. |
35,823,709 | I have read the article "Ubuntu Installation --Guide for Ubuntu 14.04 with a 64 bit processor." from Github website (<https://github.com/tiangolo/caffe/blob/ubuntu-tutorial-b/docs/install_apt2.md>).
And now, I open IPython to test that PyCaffe is working. I input "ipython" command, and enter to the ipython page.
Then,... | 2016/03/06 | [
"https://Stackoverflow.com/questions/35823709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4159177/"
] | I found this:
<https://groups.google.com/forum/#!topic/caffe-users/C_air48cISU>
Claiming that this is a non-error, cause by mis-matched versions of Boost. You can safely ignore it. They've promised to clean up the warning (at some point not yet specified) | You can edit /caffe/python/caffe/\_caffe.cpp . There are four places need to change,like this
```
bp::register_ptr_to_python<shared_ptr<Layer<Dtype> > >();
```
to
```
const boost::python::type_info cinfo = boost::python::type_id<shared_ptr<Blob<Dtype> > >();
const boost::python::converter::registration* creg = boos... |
49,963,862 | I have a dictionary that has tuple keys and numpy array values. I tried saving it using h5 and pickle but I get error messages. what is the best way to save this object to file?
```
import numpy as np
from collections import defaultdict
Q =defaultdict(lambda: np.zeros(2))
Q[(1,2,False)] = np.array([1,2])
Q[(1,3,True)]... | 2018/04/22 | [
"https://Stackoverflow.com/questions/49963862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7091646/"
] | How about saving it as a plain dictionary? You don't need the `defaultdict` behavior during saving.
```
In [126]: from collections import defaultdict
In [127]: Q =defaultdict(lambda: np.zeros(2))
...: Q[(1,2,False)] = np.array([1,2])
...: Q[(1,3,True)] = np.array([3,4])
...: Q[(3,4,False)]
...:
Ou... | I don't see any problems using `pickle`
```
import pickle
import numpy as np
x = {(1,2,False): np.array([1,4]), (1,3,False): np.array([4,5])}
with open('filename.pickle', 'wb') as handle:
pickle.dump(x, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open('filename.pickle', 'rb') as handle:
y = pickle.load(ha... |
55,647,936 | I am porting the application from python 2 to python 3 and encountered the following problem: `random.randint` returns different result according to used Python version. So
```
import random
random.seed(1)
result = random.randint(1, 100)
```
On Python 2.x result will be 14 and on Python 3.x: 18
Unfortunately, I nee... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55647936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542977/"
] | The difference is caused by two things:
1. You should use `random.seed(42, version=1)`
2. In python 3.2 there was a change to `random.randrange`, which is called by `random.randint` and probably add to above [issue](https://docs.python.org/3/library/random.html#random.randrange).
So use something like:
```
try: rand... | You can specify which version to use for the seed: `random.seed(1, version=1)`. However, as stated by Sparky05, you are probably better off using `numpy.random` instead. |
55,647,936 | I am porting the application from python 2 to python 3 and encountered the following problem: `random.randint` returns different result according to used Python version. So
```
import random
random.seed(1)
result = random.randint(1, 100)
```
On Python 2.x result will be 14 and on Python 3.x: 18
Unfortunately, I nee... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55647936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542977/"
] | The difference is caused by two things:
1. You should use `random.seed(42, version=1)`
2. In python 3.2 there was a change to `random.randrange`, which is called by `random.randint` and probably add to above [issue](https://docs.python.org/3/library/random.html#random.randrange).
So use something like:
```
try: rand... | Functions which emulate `random.seed(a=None)` and `random.randint(a, b)` for `python 3` and `python 2`:
```python
import random
def seed(a=None):
try: # Python3
random.seed(a, version=1)
except TypeError: # Python2
random.seed(a)
def randint(a, b):
return int(random.random() * (b - a + ... |
55,647,936 | I am porting the application from python 2 to python 3 and encountered the following problem: `random.randint` returns different result according to used Python version. So
```
import random
random.seed(1)
result = random.randint(1, 100)
```
On Python 2.x result will be 14 and on Python 3.x: 18
Unfortunately, I nee... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55647936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542977/"
] | Finally found the answer!
Sparky05 give interesting idea and was near with `int(1+99*random.random())`.
But the right answer is
```
random.seed(seed, version=1)
int(random.random() * 100) + 1
```
in Python 3.x
Works in the same way like
```
random.seed(seed)
random.randint(1, 100)
```
in Python 2.x | You can specify which version to use for the seed: `random.seed(1, version=1)`. However, as stated by Sparky05, you are probably better off using `numpy.random` instead. |
55,647,936 | I am porting the application from python 2 to python 3 and encountered the following problem: `random.randint` returns different result according to used Python version. So
```
import random
random.seed(1)
result = random.randint(1, 100)
```
On Python 2.x result will be 14 and on Python 3.x: 18
Unfortunately, I nee... | 2019/04/12 | [
"https://Stackoverflow.com/questions/55647936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542977/"
] | Finally found the answer!
Sparky05 give interesting idea and was near with `int(1+99*random.random())`.
But the right answer is
```
random.seed(seed, version=1)
int(random.random() * 100) + 1
```
in Python 3.x
Works in the same way like
```
random.seed(seed)
random.randint(1, 100)
```
in Python 2.x | Functions which emulate `random.seed(a=None)` and `random.randint(a, b)` for `python 3` and `python 2`:
```python
import random
def seed(a=None):
try: # Python3
random.seed(a, version=1)
except TypeError: # Python2
random.seed(a)
def randint(a, b):
return int(random.random() * (b - a + ... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead. | This:
```
let snackName = favoriteSnacks[person] ?? "Candy Bar"
```
Is equals this:
```
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
```
Explaining in words, if the `let` statement fail to grab `person` from `favoriteSnacks` it will a... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead. | One addition to @Icaro's answer you can declare values without initialize them. In my opinion this is better:
```
func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String
if let favoriteSnackName = favoriteSnacks[person] {
snackNa... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead. | ```
let something = a ?? b
```
means
```
let something = a != nil ? a! : b
``` |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | It is "nil coalescing operator" (also called "default operator"). `a ?? b` is value of `a` (i.e. `a!`), unless `a` is `nil`, in which case it yields `b`. I.e. if `favouriteSnacks[person]` is missing, return assign `"Candy Bar"` in its stead. | The nil-coalescing operator `a ?? b` is a shortcut for `a != nil ? a! : b` |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | This:
```
let snackName = favoriteSnacks[person] ?? "Candy Bar"
```
Is equals this:
```
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
```
Explaining in words, if the `let` statement fail to grab `person` from `favoriteSnacks` it will a... | One addition to @Icaro's answer you can declare values without initialize them. In my opinion this is better:
```
func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String
if let favoriteSnackName = favoriteSnacks[person] {
snackNa... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | This:
```
let snackName = favoriteSnacks[person] ?? "Candy Bar"
```
Is equals this:
```
if favoriteSnacks[person] != nil {
let snackName = favoriteSnacks[person]
} else {
let snackName = "Candy Bar"
}
```
Explaining in words, if the `let` statement fail to grab `person` from `favoriteSnacks` it will a... | The nil-coalescing operator `a ?? b` is a shortcut for `a != nil ? a! : b` |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | ```
let something = a ?? b
```
means
```
let something = a != nil ? a! : b
``` | One addition to @Icaro's answer you can declare values without initialize them. In my opinion this is better:
```
func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String
if let favoriteSnackName = favoriteSnacks[person] {
snackNa... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | The nil-coalescing operator `a ?? b` is a shortcut for `a != nil ? a! : b` | One addition to @Icaro's answer you can declare values without initialize them. In my opinion this is better:
```
func buyFavoriteSnack(person:String) throws {
// let snackName = favoriteSnacks[person] ?? "Candy Bar"
let snackName: String
if let favoriteSnackName = favoriteSnacks[person] {
snackNa... |
30,772,068 | I have the following string object (its json) in Java (its pretty printed so it is legible):
```
{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}
```
I have an array with 100 people with the same structure.
What is the best way to go throu... | 2015/06/11 | [
"https://Stackoverflow.com/questions/30772068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971888/"
] | ```
let something = a ?? b
```
means
```
let something = a != nil ? a! : b
``` | The nil-coalescing operator `a ?? b` is a shortcut for `a != nil ? a! : b` |
54,064,946 | I am working in jupyter with python in order to clean a set of data that I have retrieved from an analysis software and I would like to have an equal number of samples that pass and fail. Basically my dataframe in pandas looks like this:
```
grade section area_steel Nx Myy utilisation Accceptable
0 C16/20 STD ... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54064946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10876004/"
] | Using formatting string and assuming that `optimal_system` is your dictionary:
```
with open('output.txt', 'w') as f:
for k in optimal_system.keys():
f.write("{}: {}\n".format(k, optimal_system[k]))
```
**EDIT**
As pointed by @wwii, the code above can be also written as:
```
with open('output.txt', 'w'... | You can use json.dumps() to do this with the indent parameter. For example:
```
import json
dictionary_variable = {'employee_01': {'fname': 'John', 'lname': 'Doe'},
'employee_02': {'fname': 'Jane', 'lname': 'Doe'}}
with open('output.txt', 'w') as f:
f.write(json.dumps(dictionary_variable, ... |
54,064,946 | I am working in jupyter with python in order to clean a set of data that I have retrieved from an analysis software and I would like to have an equal number of samples that pass and fail. Basically my dataframe in pandas looks like this:
```
grade section area_steel Nx Myy utilisation Accceptable
0 C16/20 STD ... | 2019/01/06 | [
"https://Stackoverflow.com/questions/54064946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10876004/"
] | You can use the [`pprint` module](https://docs.python.org/3/library/pprint.html) -- it also works for all other data structures.
To force every entry on a new line, set the `width` argument to something low. The `stream` argument lets you directly write to the file.
```
import pprint
mydata = {'Optimal Temperature (K)... | You can use json.dumps() to do this with the indent parameter. For example:
```
import json
dictionary_variable = {'employee_01': {'fname': 'John', 'lname': 'Doe'},
'employee_02': {'fname': 'Jane', 'lname': 'Doe'}}
with open('output.txt', 'w') as f:
f.write(json.dumps(dictionary_variable, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.