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 |
|---|---|---|---|---|---|
59,904,969 | Introduction
============
I want to combine my separate Minecraft worlds into a single world and it seemed like a relatively easy feat, but as I did research it evolved into the need to make a custom program.
The Struggle
------------
I started by shifting the region files and combining them in one region folder, wh... | 2020/01/24 | [
"https://Stackoverflow.com/questions/59904969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12778238/"
] | First of: As far as I know there is no more information about "where the chunks are", stored in the region files. There are 32(x direction)\*32(z-direction)= 1024 Chunks stored within one region file and each of it has its position of data within the file. So the chunks are just numbered within the file itself and the ... | I found an editor!
==================
Now I can *edit*, but I don't know *how* the editing works. I haven't *learned* anything, but I did finally find someone else's editor. Not quite what I wanted because I wanted to know how to do this myself.
**Update:** To fix a region using this software I have to manually edit... |
59,904,969 | Introduction
============
I want to combine my separate Minecraft worlds into a single world and it seemed like a relatively easy feat, but as I did research it evolved into the need to make a custom program.
The Struggle
------------
I started by shifting the region files and combining them in one region folder, wh... | 2020/01/24 | [
"https://Stackoverflow.com/questions/59904969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12778238/"
] | First of: As far as I know there is no more information about "where the chunks are", stored in the region files. There are 32(x direction)\*32(z-direction)= 1024 Chunks stored within one region file and each of it has its position of data within the file. So the chunks are just numbered within the file itself and the ... | This Java library is quite nice for editing .mca and has some examples of doing so in the README
<https://github.com/Querz/NBT>
As for how the compression works, chunks can be individually compressed via either gzip or zlib, but in practice are generally all zlib compressed, which is implemented in Java through [Infl... |
34,344,171 | Getting a strange error. I created a database in MySQL, set the database to use it. Using the right settings in my Django settings.py. But still there's an error that no database has been selected.
**First I tried:**
```
python manage.py syncdb
```
**Got this traceback:**
```
django.db.utils.OperationalError: (104... | 2015/12/17 | [
"https://Stackoverflow.com/questions/34344171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2058553/"
] | Check to make sure your database my\_db exists in your MySQL instance. Log into MySQL and run;
```
show databases;
```
make sure my\_db exists. If it does not, run
```
create database my_db;
``` | GRANT access privileges to the user mentioned in the file
```
GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';
```
You need not grant all privileges. modify accordingly. |
35,189,234 | I am trying to seed an instance of pythons random. However when I run the code below it generates a different answer each time even if user input stays the same.
```
import random
import hashlib
mapSeed = hashlib.sha1(input("Enter seed: ").encode('utf-8'))
rnd = random.Random()
rnd.seed(mapSeed)
print(mapSeed)
print(... | 2016/02/03 | [
"https://Stackoverflow.com/questions/35189234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4831464/"
] | Assuming that the seed remains constant during all executions, it will never change. Look at this:
```
>>> import random
>>> r = random.Random()
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
```
Howeve... | One very important concept regarding "random numbers" is that are not actually random, they are dependent of:
1) Algorithm used to generate the "random" sequence of numbers
2) The seed for the algorithm
The same seed will generate the same sequence of random numbers. Why? Because if you can have the same stream of ran... |
35,189,234 | I am trying to seed an instance of pythons random. However when I run the code below it generates a different answer each time even if user input stays the same.
```
import random
import hashlib
mapSeed = hashlib.sha1(input("Enter seed: ").encode('utf-8'))
rnd = random.Random()
rnd.seed(mapSeed)
print(mapSeed)
print(... | 2016/02/03 | [
"https://Stackoverflow.com/questions/35189234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4831464/"
] | `mapSeed`, as the line `print(mapSeed)`, shows, is not a string, but an SHA1 HASH object. When you pass this to `random.seed`, it likely uses the (randomized) `hash()` of the object, hence the different results.
You need to extract the digest from the hash object before passing it to `random.seed`:
```
rnd.seed(mapSe... | Assuming that the seed remains constant during all executions, it will never change. Look at this:
```
>>> import random
>>> r = random.Random()
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
>>> r.seed(515)
>>> r.random()
0.1646746342919
>>> r.random()
0.9567223584846931
```
Howeve... |
35,189,234 | I am trying to seed an instance of pythons random. However when I run the code below it generates a different answer each time even if user input stays the same.
```
import random
import hashlib
mapSeed = hashlib.sha1(input("Enter seed: ").encode('utf-8'))
rnd = random.Random()
rnd.seed(mapSeed)
print(mapSeed)
print(... | 2016/02/03 | [
"https://Stackoverflow.com/questions/35189234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4831464/"
] | `mapSeed`, as the line `print(mapSeed)`, shows, is not a string, but an SHA1 HASH object. When you pass this to `random.seed`, it likely uses the (randomized) `hash()` of the object, hence the different results.
You need to extract the digest from the hash object before passing it to `random.seed`:
```
rnd.seed(mapSe... | One very important concept regarding "random numbers" is that are not actually random, they are dependent of:
1) Algorithm used to generate the "random" sequence of numbers
2) The seed for the algorithm
The same seed will generate the same sequence of random numbers. Why? Because if you can have the same stream of ran... |
38,772,498 | I am running the command in my django project:-
```
$python manage.py runserver
```
then I am getting the error like:-
```
from django.core.context_processors import csrf
ImportError: No module named context_processors
```
here is results of
```
$ pip freeze
dj-database-url==0.4.1
dj-static==0.0.6
Django==1.10... | 2016/08/04 | [
"https://Stackoverflow.com/questions/38772498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6623406/"
] | The `csrf` module is moved from `django.core.context_processors` to `django.views.decorators` in the latest release. You can refer it [here](https://docs.djangoproject.com/ja/1.9/ref/csrf/) | `context_processors` in Django 1.10 and above has been moved from `core` to `template`.
Replace
```
django.core.context_processors
```
with
```
django.template.context_processors
``` |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In a BASH script, assign an argument to variable but provide a default if it exists:
```
MYVAR=${1:-default}
```
$MYVAR will contain the first argument if one was given else "default". | To remove .svn directories you may also use the combination 'find...-prune...-exec...' (without xargs):
```
# tested on Mac OS X
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -ls # test
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -exec /bin/rm -PRfv '{}' \;
``` |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To remove .svn directories you may also use the combination 'find...-prune...-exec...' (without xargs):
```
# tested on Mac OS X
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -ls # test
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -exec /bin/rm -PRfv '{}' \;
``` | To change all files in **~** which are owned by the group **vboxusers** to be owned by the user group kent instead, I created something. But as it had a weakness in using xargs I'm changing it to the solution proposed in the comment to this answer:
```
$ find ~ -group vboxusers -exec chown kent:kent {} \;
``` |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Found this somewhere on the net a long time ago:
```
function bashtips {
cat <<EOF
DIRECTORIES
-----------
~- Previous working directory
pushd tmp Push tmp && cd tmp
popd Pop && cd
GLOBBING AND OUTPUT SUBSTITUTION
--------------------------------
ls a[b-dx]e Globs abe, ace, ade, axe
ls a{c,bl}e Globs ac... | I love the backtick operator.
```
gcc `pkg-config <package> --cflags` -o foo.o -c foo.c
```
And:
```
hd `whereis -b ls | sed "s/ls: //"` | head
```
Knowing me, I've missed a more efficient way of 'head'ing the hexdump of a binary which you don't know the location of... oh, and as is fairly obvious, "ls" can be sw... |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you like to have your current working directory in your prompt (`$PS1`), are running in a terminal with only 80 columns, and sometimes work in really deep hierarchies, you can end up with a prompt that takes all but about 5 characters of your line. In that case, the following declarations are helpful:
```
PS1='${PW... | An effective (and intuitive) way to get a full canonical file path given a specified file. This would resolve all cases of symbolic links, relative file references, etc.
```
full_path="$(cd $(/usr/bin/dirname "$file"); pwd -P)/$(/usr/bin/basename "$file")"
``` |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Add a space (or other delimiter) only if a variable is set, in order to avoid ugly unnecessary spaces.
```
$ first=Joe
$ last= # last name blank, the following echoes a space before the period
$ echo "Hello, $first $last. Welcome to..."
Hello, Joe . Welcome to...
$ echo "Hello, $first${last:+ $last}. Welcome to.... | I love the backtick operator.
```
gcc `pkg-config <package> --cflags` -o foo.o -c foo.c
```
And:
```
hd `whereis -b ls | sed "s/ls: //"` | head
```
Knowing me, I've missed a more efficient way of 'head'ing the hexdump of a binary which you don't know the location of... oh, and as is fairly obvious, "ls" can be sw... |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you like to have your current working directory in your prompt (`$PS1`), are running in a terminal with only 80 columns, and sometimes work in really deep hierarchies, you can end up with a prompt that takes all but about 5 characters of your line. In that case, the following declarations are helpful:
```
PS1='${PW... | To change all files in **~** which are owned by the group **vboxusers** to be owned by the user group kent instead, I created something. But as it had a weakness in using xargs I'm changing it to the solution proposed in the comment to this answer:
```
$ find ~ -group vboxusers -exec chown kent:kent {} \;
``` |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | To remove .svn directories you may also use the combination 'find...-prune...-exec...' (without xargs):
```
# tested on Mac OS X
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -ls # test
find -x -E . \( -type d -regex '.*/\.svn/*.*' -prune \) -exec /bin/rm -PRfv '{}' \;
``` | I use this one a lot in conjunction with Java development:
```
#!/bin/sh
if [ "$1" == "" ] || [ "$2" == "" ]; then
echo "Usage jarfinder.sh "
exit
fi
SEARCH=`echo $2 | sed -e 's/[\\\/]/./g'`
echo Searching jars and zips in $1 for "$SEARCH"
find $1 -type f -printf "'%p'\n" | egrep "\.(jar|zip)'$" | sed -e "s/... |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In a BASH script, assign an argument to variable but provide a default if it exists:
```
MYVAR=${1:-default}
```
$MYVAR will contain the first argument if one was given else "default". | Add a space (or other delimiter) only if a variable is set, in order to avoid ugly unnecessary spaces.
```
$ first=Joe
$ last= # last name blank, the following echoes a space before the period
$ echo "Hello, $first $last. Welcome to..."
Hello, Joe . Welcome to...
$ echo "Hello, $first${last:+ $last}. Welcome to.... |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | G'day,
My favourite, and it's applicable to other shells that support aliases, is the simple way of temporarily disabling an alias by prepending a backslash to a command.
So:
```
alias rm='rm -i'
```
would always give you interactive mode when entering rm, entering
```
\rm
```
on the command line bypasses the a... | I use this one a lot in conjunction with Java development:
```
#!/bin/sh
if [ "$1" == "" ] || [ "$2" == "" ]; then
echo "Usage jarfinder.sh "
exit
fi
SEARCH=`echo $2 | sed -e 's/[\\\/]/./g'`
echo Searching jars and zips in $1 for "$SEARCH"
find $1 -type f -printf "'%p'\n" | egrep "\.(jar|zip)'$" | sed -e "s/... |
965,663 | We've had these for a lot of other languages. The one for [C/C++](https://stackoverflow.com/questions/469696/what-is-your-most-useful-c-c-snippet) was quite popular, so was the equivalent for [Python](https://stackoverflow.com/questions/691946/short-and-useful-python-snippets). I thought one for BASH would be interesti... | 2009/06/08 | [
"https://Stackoverflow.com/questions/965663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Here is another one:
```
#!/bin/bash
# Shows the full path of files, good for copy pasting and for when
# listing the full paths is necessary.
# Usage: Run in the working directory (no path), otherwise takes the
# same file specification as ls.
for file in $(ls "$@"); do
echo -n $(pwd)
[[ $(pwd) != ... | If you like to have your current working directory in your prompt (`$PS1`), are running in a terminal with only 80 columns, and sometimes work in really deep hierarchies, you can end up with a prompt that takes all but about 5 characters of your line. In that case, the following declarations are helpful:
```
PS1='${PW... |
2,980,031 | I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic.
To iterate over rows, the follwoing syntax is used:
```
cursor = gp.getcursor(table)
row = cursor.next()
while row:
#do something with row
row = cursor.next(... | 2010/06/05 | [
"https://Stackoverflow.com/questions/2980031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103225/"
] | Assuming that one of Next and next is a typo and they're both the same, you can use the not-so-well-known variant of the built-in iter function:
```
for row in iter(cursor.next, None):
<do something>
``` | The best way is to use a Python iterator interface around the `table` object, imho:
```
class Table(object):
def __init__(self, table):
self.table = table
def rows(self):
cursor = gp.get_cursor(self.table)
row = cursor.Next()
while row:
yield row
row =... |
2,980,031 | I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic.
To iterate over rows, the follwoing syntax is used:
```
cursor = gp.getcursor(table)
row = cursor.next()
while row:
#do something with row
row = cursor.next(... | 2010/06/05 | [
"https://Stackoverflow.com/questions/2980031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103225/"
] | Assuming that one of Next and next is a typo and they're both the same, you can use the not-so-well-known variant of the built-in iter function:
```
for row in iter(cursor.next, None):
<do something>
``` | You could create a custom wrapper like:
```
class Table(object):
def __init__(self, gp, table):
self.gp = gp
self.table = table
self.cursor = None
def __iter__(self):
self.cursor = self.gp.getcursor(self.table)
return self
def next(self):
n = self.cursor.next... |
2,980,031 | I am using a module that is part of a commercial software API. The good news is there is a python module - the bad news is that its pretty unpythonic.
To iterate over rows, the follwoing syntax is used:
```
cursor = gp.getcursor(table)
row = cursor.next()
while row:
#do something with row
row = cursor.next(... | 2010/06/05 | [
"https://Stackoverflow.com/questions/2980031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103225/"
] | You could create a custom wrapper like:
```
class Table(object):
def __init__(self, gp, table):
self.gp = gp
self.table = table
self.cursor = None
def __iter__(self):
self.cursor = self.gp.getcursor(self.table)
return self
def next(self):
n = self.cursor.next... | The best way is to use a Python iterator interface around the `table` object, imho:
```
class Table(object):
def __init__(self, table):
self.table = table
def rows(self):
cursor = gp.get_cursor(self.table)
row = cursor.Next()
while row:
yield row
row =... |
74,466,125 | Pyhton is new to me and i'm having a little problem with the for loops,
Im used to for loop in java where you can set integers as you like in the loops but can't get it right in python.
the task i was given is to make a function that return True of False.
the function get 3 integers: short rope amount, long ro... | 2022/11/16 | [
"https://Stackoverflow.com/questions/74466125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20523368/"
] | Use a nested list comprehension:
```
pd.DataFrame([[k1, k2, v]
for k1,d in sample_dict.items()
for k2,v in d.items()],
columns=['job', 'person', 'age'])
```
Output:
```
job person age
0 doctor docter_a 26
1 doctor docter_b 40
2 doctor docter_c ... | You can construct a `zip` of length 3 elements, and feed them to `pd.DataFrame` after reshaping:
```
zip_list = [list(zip([key]*len(sample_dict['doctor']),
sample_dict[key],
sample_dict[key].values()))
for key in sample_dict.keys()]
col_len = len(sample_dict['doctor'])... |
19,551,186 | How do I let the user write text in my python program that will transfer into a file using open "w"?
I only figured out how write text into the seperate document using print. But how is it done if I want input to be written to a file? In short terms: Let the user itself write text to a seperate document.
Here is my c... | 2013/10/23 | [
"https://Stackoverflow.com/questions/19551186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877270/"
] | First off, use raw\_input instead of input. This way you capture the text as a string instead of trying to evaluate it. But to answer your question:
```
with open(name, 'w') as o:
o.write(code)
```
You can also surround that code in a loop that keeps repeating until the user hits a certain key if you would like ... | ```
def main():
print ("This program let you create your own HTML-page")
name = input("Enter the name for your HTML-page (end it with .html): ")
outfile = open(name),'w')
code = input ("Enter your code here: ")
outfile.write(code)
main ()
```
This does not accept multi line code entries. You... |
61,624,276 | I'm looking for a pythonic way to define multiple related constants in a single file to be used in multiple modules. I came up with multiple options, but all of them have downsides.
### Approach 1 - simple global constants
```py
# file resources/resource_ids.py
FOO_RESOURCE = 'foo'
BAR_RESOURCE = 'bar'
BAZ_RESOURCE ... | 2020/05/05 | [
"https://Stackoverflow.com/questions/61624276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/895490/"
] | Use `Enum` and mix in `str`:
```
@unique
class ResourceIds(str, Enum):
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
```
Then you won't need to compare against `.value`:
```
>>> ResourceIds.foo == 'foo'
True
```
And you still get good debugging info:
```
>>> ResourceIds.foo
<ResourceIds.foo: 'f... | A few ways you can do this, I don't really like using enum in python because you dont *really* need them IMO ;)
This is how most packages out there do it AFAIK:
```
# module_name.py
CSV = 'csv'
JSON = 'json'
def save(path, format=CSV):
# do some thing with format
...
# other_module.py
import module_name
mo... |
45,836,369 | I know what iterators and generators are. I know the iteration protocol, and I can create both. I read the following line everywhere: "Every generator is an iterator, but not vice versa." I understand the first part, but I don't understand the "not vice versa" part. What does the generator object have that any simple i... | 2017/08/23 | [
"https://Stackoverflow.com/questions/45836369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5567387/"
] | In python3 an iterator is an object with a `__next__` method. That's all.
For an object to be a generator it needs `__next__` method but it also use a yield statement.
So both object have a `__next__` method and so are iterator but the first object doesn't always have a yield statement so an iterator is not necessari... | It's just that generators are a specific kind of iterators.
Their two particular traits are the lazy evaluation (no value is computed in anticipation of it being requested), and the fact that once exhausted, they cannot be iterated once again.
On the other hand, an iterator is no more than something with a `__next__` ... |
45,836,369 | I know what iterators and generators are. I know the iteration protocol, and I can create both. I read the following line everywhere: "Every generator is an iterator, but not vice versa." I understand the first part, but I don't understand the "not vice versa" part. What does the generator object have that any simple i... | 2017/08/23 | [
"https://Stackoverflow.com/questions/45836369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5567387/"
] | >
> I know what's iterator, what's generator, what's iteration protocol, how to create both.
>
>
>
What's an iterator?
-------------------
Per the glossary, an [iterator](https://docs.python.org/2.7/glossary.html#term-iterator) is "an object representing a stream of data". It has an *\_\_iter\_\_()* method retur... | In python3 an iterator is an object with a `__next__` method. That's all.
For an object to be a generator it needs `__next__` method but it also use a yield statement.
So both object have a `__next__` method and so are iterator but the first object doesn't always have a yield statement so an iterator is not necessari... |
45,836,369 | I know what iterators and generators are. I know the iteration protocol, and I can create both. I read the following line everywhere: "Every generator is an iterator, but not vice versa." I understand the first part, but I don't understand the "not vice versa" part. What does the generator object have that any simple i... | 2017/08/23 | [
"https://Stackoverflow.com/questions/45836369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5567387/"
] | >
> I know what's iterator, what's generator, what's iteration protocol, how to create both.
>
>
>
What's an iterator?
-------------------
Per the glossary, an [iterator](https://docs.python.org/2.7/glossary.html#term-iterator) is "an object representing a stream of data". It has an *\_\_iter\_\_()* method retur... | It's just that generators are a specific kind of iterators.
Their two particular traits are the lazy evaluation (no value is computed in anticipation of it being requested), and the fact that once exhausted, they cannot be iterated once again.
On the other hand, an iterator is no more than something with a `__next__` ... |
51,129,487 | I'm using `django-notification` to create notifications. based on [it's documention](https://github.com/django-notifications/django-notifications) I putted:
```
url(r'^inbox/notifications/', include(notifications.urls, namespace='notifications')),
```
in my `urls.py`. I generate a notification for test by using this... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51129487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454690/"
] | oops! It was my mistake.
I Finally find out what was the problem. `actor_object_id` was the field of `notifications_notification` table, which `User.objects.get(username = 'SirSaleh')` saved in it. It should be `Interger` (`user_id` of actor).
So I dropped previous table changed instance to `User.objects.get(usernam... | This is old, but I happen to know the answer.
In your code, you wrote:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
```
You express that you want `guy` to be your sender However, in `notify.send`, you marked the sender as a generic `User` obj... |
51,129,487 | I'm using `django-notification` to create notifications. based on [it's documention](https://github.com/django-notifications/django-notifications) I putted:
```
url(r'^inbox/notifications/', include(notifications.urls, namespace='notifications')),
```
in my `urls.py`. I generate a notification for test by using this... | 2018/07/02 | [
"https://Stackoverflow.com/questions/51129487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454690/"
] | The actor\_object\_id needs to be a CharField to support UUID based primary keys. | This is old, but I happen to know the answer.
In your code, you wrote:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
```
You express that you want `guy` to be your sender However, in `notify.send`, you marked the sender as a generic `User` obj... |
22,725,990 | I always have a hard time understanding the logic of regex in python.
```
all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring'
```
I want to retrieve the substring that STARTS WITH `#` until the FIRST `\n` THAT COMES RIGHT AFTER the LAST `#` - I.e., `'#hello\n#monica, how re "u?\n#hello#ro... | 2014/03/29 | [
"https://Stackoverflow.com/questions/22725990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205745/"
] | This program matches the pattern you request.
```
#!/usr/bin/python
import re
all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho'
regex = re.compile(
r'''\# # first hash
.* # continues to (note: .* greedy)
\# # last hash
.*?$ # res... | Regular expressions are powerful but sometimes they are overkill. String methods should accomplish what you need with much less thought
```
>>> my_string = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring'
>>> hash_positions = [index for index, c in enumerate(my_string) if c == '#']
>>> hash_position... |
49,126,184 | i've a docker with redis container
configuration of it
docker-compose.yml
```
# Redis
redis:
image: redis:4.0.6
build:
context: .
dockerfile: dockerfile_redis
volumes:
- "./redis.conf:/usr/local/etc/redis/redis.conf"
ports:
- "6379:6379"
```
dockerfile\_redis
```
CMD ["chown", "redis:redis... | 2018/03/06 | [
"https://Stackoverflow.com/questions/49126184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6488529/"
] | Please check this blogpost:
<https://blog.huntingmalware.com/notes/LLMalware>
It is very likely a malware causing the working directory of your redis to change, and redis tries to write RDB file to a directory owned by root, following the commands of a malicious script. As it does not run from root, and write access... | If you do not really need to expose ports, just remove next lines:
```
ports:
- "6379:6379"
``` |
22,932,789 | Hi I just start learning python today and get to apply what I learning on a flash cards program, I want to ask the user for their name, and only accept alphabet without numbers or symbols, I've tried several ways but there is something I am missing in my attempts. Here is what I did so far.
```
yname = raw_input('Your... | 2014/04/08 | [
"https://Stackoverflow.com/questions/22932789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3510177/"
] | >
> The homepage is fine but the images in the footer are missing in the whole website.
>
>
>
Seems, that problem is with `float: left` in `<li>` elements. Try fixing size of blocks or make elements inline; | The problem is compatibility of your css/javascript with upper versions of IE, [This](https://stackoverflow.com/a/19150943/87956) should help you out.
Above is just a work around better way would be to fix your css and javascript/jquery to take care of compatibility issues. |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | *This question may be a duplicate of:*
* [Any way to properly pretty-print ordered dictionaries in Python?](https://stackoverflow.com/questions/4301069/any-way-to-properly-pretty-print-ordered-dictionaries-in-python)
---
Using `pprint.PrettyPrinter`
============================
I looked through the [source of pprin... | Consider using the `pretty` module:
* <http://pypi.python.org/pypi/pretty/0.1> |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | My solution was to replace pprint.PrettyPrinter with a simple wrapper that formats any floats it finds before calling the original printer.
```
from __future__ import division
import pprint
if not hasattr(pprint,'old_printer'):
pprint.old_printer=pprint.PrettyPrinter
class MyPrettyPrinter(pprint.old_printer):
... | *This question may be a duplicate of:*
* [Any way to properly pretty-print ordered dictionaries in Python?](https://stackoverflow.com/questions/4301069/any-way-to-properly-pretty-print-ordered-dictionaries-in-python)
---
Using `pprint.PrettyPrinter`
============================
I looked through the [source of pprin... |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | My solution was to replace pprint.PrettyPrinter with a simple wrapper that formats any floats it finds before calling the original printer.
```
from __future__ import division
import pprint
if not hasattr(pprint,'old_printer'):
pprint.old_printer=pprint.PrettyPrinter
class MyPrettyPrinter(pprint.old_printer):
... | Consider using the `pretty` module:
* <http://pypi.python.org/pypi/pretty/0.1> |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | If you would like to modify the default pretty printer without subclassing, you can use the internal `_dispatch` table on the `pprint.PrettyPrinter` class. You can see how examples of how dispatching is added for internal types like dictionaries and lists [in the source](https://github.com/python/cpython/blob/3.7/Lib/p... | Consider using the `pretty` module:
* <http://pypi.python.org/pypi/pretty/0.1> |
3,258,072 | Customizing `pprint.PrettyPrinter`
==================================
The documentation for the `pprint` module mentions that the method `PrettyPrinter.format` is intended to make it possible to customize formatting.
I gather that it's possible to override this method in a subclass, but this doesn't seem to provide a... | 2010/07/15 | [
"https://Stackoverflow.com/questions/3258072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192812/"
] | My solution was to replace pprint.PrettyPrinter with a simple wrapper that formats any floats it finds before calling the original printer.
```
from __future__ import division
import pprint
if not hasattr(pprint,'old_printer'):
pprint.old_printer=pprint.PrettyPrinter
class MyPrettyPrinter(pprint.old_printer):
... | If you would like to modify the default pretty printer without subclassing, you can use the internal `_dispatch` table on the `pprint.PrettyPrinter` class. You can see how examples of how dispatching is added for internal types like dictionaries and lists [in the source](https://github.com/python/cpython/blob/3.7/Lib/p... |
44,302,426 | In my python package I have a configuration module that reads a yaml file (when creating the instance) at an explicit location, i.e. something like
```
class YamlConfig(object):
def __init__(self):
filename = os.path.join(os.path.expanduser('~'), '.hanzo\\config.yml')
with open(filename) as fs:
... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44302426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2834295/"
] | JSON only supports a limited number of datatypes. If you want to store other types of data as JSON then you need to convert it to something that JSON accepts. The obvious choice for Numpy arrays is to store them as (possibly nested) lists. Fortunately, Numpy arrays have a `.tolist` method which performs the conversion ... | Here is a full working example of an Encoder/Decoder that can deal with NumPy arrays:
```
import numpy
from json import JSONEncoder,JSONDecoder
import json
# ********************************** #
class NumpyArrayEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, numpy.ndarray):
r... |
17,460,215 | I would like to know how I can get my code to not crash if a user types anything other than a number for input. I thought that my else statement would cover it but I get an error.
>
> Traceback (most recent call last): File "C:/Python33/Skechers.py",
> line 22, in
> run\_prog = input() File "", line 1, in NameErro... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17460215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361013/"
] | Contrary to what you think, your script is *not* being run in Python 3.x. Somewhere on your system you have Python 2.x installed and the script is running in that, causing it to use 2.x's insecure/inappropriate `input()` instead. | The error message you showed indicates that `input()` tried to evaluate the string typed as a Python expression. This in turn means you're not actually using Python 3; `input` only does that in 2.x. Anyhow, I strongly recommend you do it this way instead, as it makes explicit the kind of input you want.
```
while time... |
17,460,215 | I would like to know how I can get my code to not crash if a user types anything other than a number for input. I thought that my else statement would cover it but I get an error.
>
> Traceback (most recent call last): File "C:/Python33/Skechers.py",
> line 22, in
> run\_prog = input() File "", line 1, in NameErro... | 2013/07/04 | [
"https://Stackoverflow.com/questions/17460215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361013/"
] | Contrary to what you think, your script is *not* being run in Python 3.x. Somewhere on your system you have Python 2.x installed and the script is running in that, causing it to use 2.x's insecure/inappropriate `input()` instead. | You can do this:
```
while times_run == 0:
print("Would you like to run the calculation?")
print("Press 1 for YES.")
print("Press 2 for NO.")
run_prog = input()
if run_prog == 1:
total()
times_run = 1
elif run_prog == 2:
exit()
elif run_prog not in [1,2]:
print('Please enter a number between... |
62,028,585 | I have an ML model that predicts a target attribute `y` with `5` other attributes namely `Age`, `Sex`, `Satisfaction`, `Height` and `weight`
Let's say that I have a new dataset **but it is short `Age`** so it has only `4` attributes namely `Sex`, `Satisfaction`, `Height` and `weight`
So that new dataset I am going to... | 2020/05/26 | [
"https://Stackoverflow.com/questions/62028585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11433497/"
] | There are some models that can handle NaN (empty) values, life XGBOOST, and some models that can't.
Your best option here will be to re-train a model with only the 4 features.
If you can't you can give multiple values to "age" (like 2-99), predict y each time, and take the average of those predictions.
Again, you wi... | It's possible to predict y using fewer Xs. You need more data to train your model.
Keep in mind that 1st example in machine learning is to predict y using just one x. |
64,734,616 | I have a **Payment** Django model that has a *CheckNumber* attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the **str** method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error messag... | 2020/11/08 | [
"https://Stackoverflow.com/questions/64734616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6815773/"
] | Don't.
You have a form. Treat it as such.
```js
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listNam... | With the help of the `event`, you can catch the pressed `enter` (keycode = 13) key, as in my example.
Was it necessary?
```
$('#btn_createList').keypress(function(event){
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
});
``` |
64,734,616 | I have a **Payment** Django model that has a *CheckNumber* attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the **str** method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error messag... | 2020/11/08 | [
"https://Stackoverflow.com/questions/64734616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6815773/"
] | Don't.
You have a form. Treat it as such.
```js
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listNam... | I think what you want is a check for which key was pressed, correct?
To do that, you simply need to check for
event.keyCode === 13
So your code would be something similar to the following:
```
$('#btn_createList').keypress(function(event){
if (event.keyCode === 13) {
$('.ul_current').append($('<li>', {
... |
64,734,616 | I have a **Payment** Django model that has a *CheckNumber* attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the **str** method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error messag... | 2020/11/08 | [
"https://Stackoverflow.com/questions/64734616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6815773/"
] | Don't.
You have a form. Treat it as such.
```js
document.getElementById('input_listName').addEventListener('submit', function(e) {
e.preventDefault();
const li = document.createElement('li');
li.append(this.listName.value);
document.querySelector(".ul_current").append(li);
// optionally:
// this.listNam... | `<input id="input_listName" /><button id="btn_createList">add</button>` this syntax is technically wrong, your tag is starting with `<input>` and ending with `</button>`. Also you can add a simple check to your function that if user haven't entered anything into the input field that should return nothing.
you can also... |
46,195,187 | I am working on a remote server, say IP: 192.128.0.3. On this server there are two folders: `cgi-bin` & `html`. My python code file is in `cgi-bin` which wants to make data.json file in `html/Rohith/` where Rohith folder is already exists. I use the following code
```
jsonObj = json.dumps(main_func(s));
fileobj = op... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46195187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6816478/"
] | It might be path issues; I suggest to use full path instead. Try the following:
```
import os
jsonObj = json.dumps(main_func(s));
path = '\\'.join(__file__.split('\\')[:-2]) # this will return the parent
# folder of cgi-bin on Windows
out_file = path + '/html/Ronhith/dat... | file.write does not create a directory First you have to create a directory then use file.write() for example
```
if not os.path.exists("../html/Rohith/"):
os.makedirs("../html/Rohith/")
jsonObj = json.dumps(mainfunc(s))
fileobj = open("../html/Rohith/data.json","w+")
fileobj.write(jsonObj)
``` |
46,195,187 | I am working on a remote server, say IP: 192.128.0.3. On this server there are two folders: `cgi-bin` & `html`. My python code file is in `cgi-bin` which wants to make data.json file in `html/Rohith/` where Rohith folder is already exists. I use the following code
```
jsonObj = json.dumps(main_func(s));
fileobj = op... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46195187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6816478/"
] | file.write does not create a directory First you have to create a directory then use file.write() for example
```
if not os.path.exists("../html/Rohith/"):
os.makedirs("../html/Rohith/")
jsonObj = json.dumps(mainfunc(s))
fileobj = open("../html/Rohith/data.json","w+")
fileobj.write(jsonObj)
``` | Thanks to the guy sitting next to me! It works when I change path as a local destination rather than like IP path:
```
fileobj = open("/var/www/html/Rohith/data.json","w+");
``` |
46,195,187 | I am working on a remote server, say IP: 192.128.0.3. On this server there are two folders: `cgi-bin` & `html`. My python code file is in `cgi-bin` which wants to make data.json file in `html/Rohith/` where Rohith folder is already exists. I use the following code
```
jsonObj = json.dumps(main_func(s));
fileobj = op... | 2017/09/13 | [
"https://Stackoverflow.com/questions/46195187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6816478/"
] | It might be path issues; I suggest to use full path instead. Try the following:
```
import os
jsonObj = json.dumps(main_func(s));
path = '\\'.join(__file__.split('\\')[:-2]) # this will return the parent
# folder of cgi-bin on Windows
out_file = path + '/html/Ronhith/dat... | Thanks to the guy sitting next to me! It works when I change path as a local destination rather than like IP path:
```
fileobj = open("/var/www/html/Rohith/data.json","w+");
``` |
30,107,212 | I have a deque in Python that I'm iterating over. Sometimes the deque changes while I'm interating which produces a `RuntimeError: deque mutated during iteration`.
If this were a Python list instead of a deque, I would just iterate over a copy of the list (via a slice like `my_list[:]`, but since slice operations can'... | 2015/05/07 | [
"https://Stackoverflow.com/questions/30107212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3486484/"
] | You can "freeze" it by creating a list. There's no necessity to copy it to a new deque. A list is certainly good enough, since you only need it for iterating.
```
for elem in list(my_deque):
...
```
`list(x)` creates a list from any iterable `x`, including deque, and in most cases is the most pythonic way to do ... | While you can create a list out of the deque, `for elem in list(deque)`, this is not always optimum if it is a frequently used function: there's a performance cost to it esp. if there is a large number of elements in the deque and you're constantly changing it to an `array` structure.
A possible alternative without n... |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: <http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/>. C... | I was inspired by Shawn's article and apps like Hyper Terminal to figure out how to exactly replicate the Windows 10 style look as a seamless title bar, and wrote [this tutorial](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial) *(please note: as of 2022 this tutorial is somewhat outdated in terms of E... |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: <http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/>. C... | I use this in my apps:
```js
const { remote } = require("electron");
var win = remote.BrowserWindow.getFocusedWindow();
var title = document.querySelector("title").innerHTML;
document.querySelector("#titleshown").innerHTML = title;
var minimize = document.querySelector("#minimize");
var maximize = document.querySele... |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: <http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/>. C... | Ran into this problem and my solution was to keep the frame but set the title to blank i.e.
```
document.querySelector("title").innerHTML ="";
```
That solved my problem i.e. I got a window which can be closed, maximized or minimized without a title on it. |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | I was inspired by Shawn's article and apps like Hyper Terminal to figure out how to exactly replicate the Windows 10 style look as a seamless title bar, and wrote [this tutorial](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial) *(please note: as of 2022 this tutorial is somewhat outdated in terms of E... | I use this in my apps:
```js
const { remote } = require("electron");
var win = remote.BrowserWindow.getFocusedWindow();
var title = document.querySelector("title").innerHTML;
document.querySelector("#titleshown").innerHTML = title;
var minimize = document.querySelector("#minimize");
var maximize = document.querySele... |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | I was inspired by Shawn's article and apps like Hyper Terminal to figure out how to exactly replicate the Windows 10 style look as a seamless title bar, and wrote [this tutorial](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial) *(please note: as of 2022 this tutorial is somewhat outdated in terms of E... | Ran into this problem and my solution was to keep the frame but set the title to blank i.e.
```
document.querySelector("title").innerHTML ="";
```
That solved my problem i.e. I got a window which can be closed, maximized or minimized without a title on it. |
35,876,962 | So I think I know what my problem is but I cant seem to figure out how to fix it. I am relatively new to wxPython. I am moving some functionality I have in a terminal script to a GUI and cant seem to get it right. I use anaconda for my python distribution and have added wxPython for the GUI. I want users to be able to ... | 2016/03/08 | [
"https://Stackoverflow.com/questions/35876962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4996129/"
] | I use this in my apps:
```js
const { remote } = require("electron");
var win = remote.BrowserWindow.getFocusedWindow();
var title = document.querySelector("title").innerHTML;
document.querySelector("#titleshown").innerHTML = title;
var minimize = document.querySelector("#minimize");
var maximize = document.querySele... | Ran into this problem and my solution was to keep the frame but set the title to blank i.e.
```
document.querySelector("title").innerHTML ="";
```
That solved my problem i.e. I got a window which can be closed, maximized or minimized without a title on it. |
56,355,248 | Is there anyway to merge npz files in python. In my directory I have output1.npz and output2.npz.
I want a new npz file that merges the arrays from both npz files. | 2019/05/29 | [
"https://Stackoverflow.com/questions/56355248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443944/"
] | use `numpy.load('output1.npz')` and `numpy.load('output2.npz')` to load both files as array a1,a2. Then use `a3 =[*a1,*a2]` to merge them. Finally, output via `numpy.savez('output.npz',a3)` | If you have 3 npz files ('Data\_chunk1.npz', 'Data\_chunk2.npz' and 'Data\_chunk3.npz'), all containing the same number of arrays (in my case 7 different arrays), then you can do
```
import numpy as np
# Load the 3 files
data_1 = np.load('Data_chunk1.npz')
data_2 = np.load('Data_chunk2.npz')
data_3 = np.load('Data_ch... |
56,355,248 | Is there anyway to merge npz files in python. In my directory I have output1.npz and output2.npz.
I want a new npz file that merges the arrays from both npz files. | 2019/05/29 | [
"https://Stackoverflow.com/questions/56355248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443944/"
] | use `numpy.load('output1.npz')` and `numpy.load('output2.npz')` to load both files as array a1,a2. Then use `a3 =[*a1,*a2]` to merge them. Finally, output via `numpy.savez('output.npz',a3)` | You have surely solved the problem by now (1 year and 10 months later...), but I just came across the same problem and found a solution that might be worth sharing here.
In general, if you have a list of .npz files `file_list = ['file_0.npz', 'file_1.npz', ...]`, eventually also with particular naming, i.e. the file w... |
8,165,086 | I'm learning Python using [Learn Python The Hard Way](http://learnpythonthehardway.org/). It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer.
Here is my question:
One of the exercises tell to do this:
```
from sys import argv
script, filename = argv
```
... | 2011/11/17 | [
"https://Stackoverflow.com/questions/8165086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051438/"
] | ```
script, filename = argv
```
This is [unpacking the sequence](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) `argv`. The first element goes into `script`, and the second element goes into `filename`. In general, this can be done with any iterable, as long as there exactly as many variabl... | `Unexpected character after line continuation character` means that you have split a command in two lines using the continuation character `\` (see [this question](https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python)) but added some characters (e.g. a white space) after it.
... |
8,165,086 | I'm learning Python using [Learn Python The Hard Way](http://learnpythonthehardway.org/). It is very good and efficient but at one point I had a crash. I've searched the web but could not find an answer.
Here is my question:
One of the exercises tell to do this:
```
from sys import argv
script, filename = argv
```
... | 2011/11/17 | [
"https://Stackoverflow.com/questions/8165086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051438/"
] | ```
script, filename = argv
```
This is [unpacking the sequence](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences) `argv`. The first element goes into `script`, and the second element goes into `filename`. In general, this can be done with any iterable, as long as there exactly as many variabl... | The code works fine, put the code in the example in the codefile.py and pass a dummydata file to it:
```
$ python codefile.py dummydatafile.txt
We're going to erase 'test1.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm... |
61,833,460 | I am creating a program that calculates the optimum angles to fire a projectile from a range of heights and a set initial velocity. Within the final equation I need to utilise, there is an inverse sec function present that is causing some troubles.
I have imported math and attempted to use asec(whatever) however it se... | 2020/05/16 | [
"https://Stackoverflow.com/questions/61833460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553134/"
] | Let's say we're looking for real number *x* whose arcsecant is angle *θ*. Then we have:
```
θ = arcsec(x)
sec(θ) = x
1 / cos(θ) = x
cos(θ) = 1 / x
θ = arccos(1/x)
```
So with this reasoning, you can write your arcsecant function as:
```
from math import acos
def asec(x):
return acos(1/x)
``` | If you can try of inverse of sec then it will be same as
```
>>>from mpmath import *
>>> asec(-1)
mpf('3.1415926535897931')
```
Here are the link in where you can better understand - [<http://omz-software.com/pythonista/sympy/modules/mpmath/functions/trigonometric.html]> |
61,833,460 | I am creating a program that calculates the optimum angles to fire a projectile from a range of heights and a set initial velocity. Within the final equation I need to utilise, there is an inverse sec function present that is causing some troubles.
I have imported math and attempted to use asec(whatever) however it se... | 2020/05/16 | [
"https://Stackoverflow.com/questions/61833460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553134/"
] | Let's say we're looking for real number *x* whose arcsecant is angle *θ*. Then we have:
```
θ = arcsec(x)
sec(θ) = x
1 / cos(θ) = x
cos(θ) = 1 / x
θ = arccos(1/x)
```
So with this reasoning, you can write your arcsecant function as:
```
from math import acos
def asec(x):
return acos(1/x)
``` | "I also understand that sec(x) = 1/cos(x) but when I sub 1/cos(x) ..." Do you have to use sec or asec ?
Because `sec(x)= 1/cos(x)` and `asec(x) = acos(1/x)`. Be careful the notation ^-1 is ambiguous, `cos^-1(x) = acos(x)` is different of `[cos(x)]^-1`.
```
angle = (math.asec(1+(ran0/float(heights))))/2
```
asec is ... |
61,833,460 | I am creating a program that calculates the optimum angles to fire a projectile from a range of heights and a set initial velocity. Within the final equation I need to utilise, there is an inverse sec function present that is causing some troubles.
I have imported math and attempted to use asec(whatever) however it se... | 2020/05/16 | [
"https://Stackoverflow.com/questions/61833460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13553134/"
] | Let's say we're looking for real number *x* whose arcsecant is angle *θ*. Then we have:
```
θ = arcsec(x)
sec(θ) = x
1 / cos(θ) = x
cos(θ) = 1 / x
θ = arccos(1/x)
```
So with this reasoning, you can write your arcsecant function as:
```
from math import acos
def asec(x):
return acos(1/x)
``` | If `math` is OK for you to import, then you can use:
```
import math
def asec(x):
if x == 0:
return 1j * math.inf
else:
return math.acos(1 / x)
```
For some other ways of of re-writing `asec(x)`, feast your eyes on the relevant [Wikipedia article](https://en.wikipedia.org/wiki/Inverse_trigon... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Using `pytest --log-cli-level=DEBUG` works fine with pytest (tested from 6.2.2 to 7.1.1)
Using `pytest --log-cli-level=DEBUG --capture=tee-sys` will also print `stdtout`. | If you use `vscode`, use following config, assuming you've installed
**Python official plugin** (`ms-python.python`) for your python project.
`./.vscode/setting.json` under your proj
```json
{
....
"python.testing.pytestArgs": ["-s", "src"], //here before discover-path src
"python.testing.unittestEnabled": fals... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Works for me, here's the output I get: [snip -> example was incorrect]
Edit: It seems that you have to pass the `-s` option to py.test so it won't capture stdout. Here (py.test not installed), it was enough to use `python pytest.py -s pyt.py`.
For your code, all you need is to pass `-s` in `args` to `main`:
```
pyt... | To turn logger output on use send `--capture=no` flag from command line.
`--capture=no` will show all outputs from logger and print statements. If you would like to capture outputs from logger and not print statements use `--capture=sys`
```
pytest --capture=no tests/system/test_backoffice.py
```
[Here](https://docs... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | To turn logger output on use send `--capture=no` flag from command line.
`--capture=no` will show all outputs from logger and print statements. If you would like to capture outputs from logger and not print statements use `--capture=sys`
```
pytest --capture=no tests/system/test_backoffice.py
```
[Here](https://docs... | If you want to filter logs with the command line, you can pass **--log-cli-level** (pytest --log-cli-level)
and logs will be shown from the level you specified and above
(e.g. **pytest --log-cli-level=INFO** will show INFO and above logs(WARNING, ERROR, CRITICAL))
note that: default --log-cli-level is a WARNING if yo... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | If you want to filter logs with the command line, you can pass **--log-cli-level** (pytest --log-cli-level)
and logs will be shown from the level you specified and above
(e.g. **pytest --log-cli-level=INFO** will show INFO and above logs(WARNING, ERROR, CRITICAL))
note that: default --log-cli-level is a WARNING if yo... | You can read:
[Documentation for logging in pytest](https://docs.pytest.org/en/6.2.x/logging.html)
Here is simple example that you can run and get log from foo function.
```
#./test_main.py
from main import foo
import logging
def test_foo(caplog):
caplog.set_level(logging.INFO)
logging.getLogger().info('L... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Since version 3.3, `pytest` supports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under [Live Logs](https://docs.pytest.org/en/latest/how-to/logging.html#live-logs) section. Live logging is disabled by default; to enable it, set `... | Using `pytest --log-cli-level=DEBUG` works fine with pytest (tested from 6.2.2 to 7.1.1)
Using `pytest --log-cli-level=DEBUG --capture=tee-sys` will also print `stdtout`. |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Since version 3.3, `pytest` supports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under [Live Logs](https://docs.pytest.org/en/latest/how-to/logging.html#live-logs) section. Live logging is disabled by default; to enable it, set `... | Works for me, here's the output I get: [snip -> example was incorrect]
Edit: It seems that you have to pass the `-s` option to py.test so it won't capture stdout. Here (py.test not installed), it was enough to use `python pytest.py -s pyt.py`.
For your code, all you need is to pass `-s` in `args` to `main`:
```
pyt... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | To turn logger output on use send `--capture=no` flag from command line.
`--capture=no` will show all outputs from logger and print statements. If you would like to capture outputs from logger and not print statements use `--capture=sys`
```
pytest --capture=no tests/system/test_backoffice.py
```
[Here](https://docs... | You can read:
[Documentation for logging in pytest](https://docs.pytest.org/en/6.2.x/logging.html)
Here is simple example that you can run and get log from foo function.
```
#./test_main.py
from main import foo
import logging
def test_foo(caplog):
caplog.set_level(logging.INFO)
logging.getLogger().info('L... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Since version 3.3, `pytest` supports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under [Live Logs](https://docs.pytest.org/en/latest/how-to/logging.html#live-logs) section. Live logging is disabled by default; to enable it, set `... | If you want to filter logs with the command line, you can pass **--log-cli-level** (pytest --log-cli-level)
and logs will be shown from the level you specified and above
(e.g. **pytest --log-cli-level=INFO** will show INFO and above logs(WARNING, ERROR, CRITICAL))
note that: default --log-cli-level is a WARNING if yo... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Since version 3.3, `pytest` supports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under [Live Logs](https://docs.pytest.org/en/latest/how-to/logging.html#live-logs) section. Live logging is disabled by default; to enable it, set `... | If you use `vscode`, use following config, assuming you've installed
**Python official plugin** (`ms-python.python`) for your python project.
`./.vscode/setting.json` under your proj
```json
{
....
"python.testing.pytestArgs": ["-s", "src"], //here before discover-path src
"python.testing.unittestEnabled": fals... |
4,673,373 | I would like to put some logging statements within test function to examine some state variables.
I have the following code snippet:
```
import pytest,os
import logging
logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()
###########################################################################... | 2011/01/12 | [
"https://Stackoverflow.com/questions/4673373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568454/"
] | Using `pytest --log-cli-level=DEBUG` works fine with pytest (tested from 6.2.2 to 7.1.1)
Using `pytest --log-cli-level=DEBUG --capture=tee-sys` will also print `stdtout`. | You can read:
[Documentation for logging in pytest](https://docs.pytest.org/en/6.2.x/logging.html)
Here is simple example that you can run and get log from foo function.
```
#./test_main.py
from main import foo
import logging
def test_foo(caplog):
caplog.set_level(logging.INFO)
logging.getLogger().info('L... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | If you evaluate
```
if count: # and count is zero
break
```
then sure - the loop will break immediately.
But you are evaluating this expression:
```
if count > 10: # 0 > 10
```
which is `False`, so you won't break on the first iteration. | If you changed `while True:` to `while count:`, your assumption would indeed be correct |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | If you evaluate
```
if count: # and count is zero
break
```
then sure - the loop will break immediately.
But you are evaluating this expression:
```
if count > 10: # 0 > 10
```
which is `False`, so you won't break on the first iteration. | A while loop is a loop that will run a portion of code until the condition is False.
**while True** is called infinite loop because True is not a condition and therefore can not change. So the loop will run until it found the break instruction.
Here you have two special elements related to loops :
* continue : go d... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | If you evaluate
```
if count: # and count is zero
break
```
then sure - the loop will break immediately.
But you are evaluating this expression:
```
if count > 10: # 0 > 10
```
which is `False`, so you won't break on the first iteration. | You didn't say `while count:` You said `while True:` Since `True` is always `True`, your loop will run forever unless something inside tells it not to. That could be a line that says `break`, or it could be an exception raised. Your loop will break if `count` is greater than `10`. `count` starts out at zero, but at the... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | in code portion `while True`, the condition will always evaluate to true. Now lets go inside the while loop.
when `count > 10` is evaluated, for count = 0, it is false, so while count < 10, it will not break out of while loop.
If it was `while count:` Yes it would have come out of the loop in the first iteration itse... | If you changed `while True:` to `while count:`, your assumption would indeed be correct |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | If you changed `while True:` to `while count:`, your assumption would indeed be correct | A while loop is a loop that will run a portion of code until the condition is False.
**while True** is called infinite loop because True is not a condition and therefore can not change. So the loop will run until it found the break instruction.
Here you have two special elements related to loops :
* continue : go d... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | in code portion `while True`, the condition will always evaluate to true. Now lets go inside the while loop.
when `count > 10` is evaluated, for count = 0, it is false, so while count < 10, it will not break out of while loop.
If it was `while count:` Yes it would have come out of the loop in the first iteration itse... | A while loop is a loop that will run a portion of code until the condition is False.
**while True** is called infinite loop because True is not a condition and therefore can not change. So the loop will run until it found the break instruction.
Here you have two special elements related to loops :
* continue : go d... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | in code portion `while True`, the condition will always evaluate to true. Now lets go inside the while loop.
when `count > 10` is evaluated, for count = 0, it is false, so while count < 10, it will not break out of while loop.
If it was `while count:` Yes it would have come out of the loop in the first iteration itse... | You didn't say `while count:` You said `while True:` Since `True` is always `True`, your loop will run forever unless something inside tells it not to. That could be a line that says `break`, or it could be an exception raised. Your loop will break if `count` is greater than `10`. `count` starts out at zero, but at the... |
36,261,398 | The following program is from a book of python. In this code, count is first set to 0 and then `while True` is used. In the book I read that zeros and empty strings are evaluated as False while all the other values are evaluated as True. If that is the case then how the program executes the while loop? wouldn't the cou... | 2016/03/28 | [
"https://Stackoverflow.com/questions/36261398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6014533/"
] | You didn't say `while count:` You said `while True:` Since `True` is always `True`, your loop will run forever unless something inside tells it not to. That could be a line that says `break`, or it could be an exception raised. Your loop will break if `count` is greater than `10`. `count` starts out at zero, but at the... | A while loop is a loop that will run a portion of code until the condition is False.
**while True** is called infinite loop because True is not a condition and therefore can not change. So the loop will run until it found the break instruction.
Here you have two special elements related to loops :
* continue : go d... |
2,440,799 | when I use MySQLdb get this message:
```
/var/lib/python-support/python2.6/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet
```
I try filter the warning with
```
import warnings
warnings.filterwarnings("ignore", message="the sets module is deprecated from se... | 2010/03/14 | [
"https://Stackoverflow.com/questions/2440799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348081/"
] | From [python documentation](http://docs.python.org/library/warnings.html#temporarily-suppressing-warnings): you could filter your warning this way, so that if other warnings are caused by an other part of your code, there would still be displayed:
```
import warnings
with warnings.catch_warnings():
warnings.simple... | What release of MySQLdb are you using? I think the current one (1.2.3c1) should have it fixed see [this bug](http://sourceforge.net/tracker/index.php?func=detail&aid=2156977&group_id=22307&atid=374932) (marked as fixed as of Oct 2008, 1.2 branch). |
15,801,447 | I'm building an installation EXE for my project using setuptool's bdist\_wininst. However, I've found that when I actually run said installer on a Win7-64bit machine w/ Python 2.7.3, I get a Runtime Error that looks like this: <http://i.imgur.com/8osT3.jpg>. (only the 64 bit installer against python-2.7 64-bit; the 32-... | 2013/04/04 | [
"https://Stackoverflow.com/questions/15801447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182284/"
] | Maybe you have to create the executable specifically for the x64?
This is the command you would have to run:
```
python setup.py build --plat-name=win-amd64
```
More information can be found here:
<http://docs.python.org/2/distutils/builtdist.html#cross-compiling-on-windows> | Maybe a Visual C++ Redistributable Package is missing or corrupt, try (re)install Microsoft Visual C++ 2008 SP1/2010 Redistributable Package (x64) or any other version. |
51,987,427 | I've got working code below. Currently I'm pulling data from sav files, exporting it to a csv file, and then plotting this data. It looks good, but I'd like to zoom in on it and I'm not entirely sure how to do it. This is because my time is listed in the following format:
```
20141107B205309Y
```
There are both lett... | 2018/08/23 | [
"https://Stackoverflow.com/questions/51987427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10236830/"
] | If your data set is consistent then pandas can trim columns for you. Checkout <https://pandas.pydata.org/pandas-docs/stable/text.html>. You can split using 'B' character. After that convert the column into a date.
You can convert a series to date using [How do I convert dates in a Pandas data frame to a 'date' data typ... | Maybe try converting your s["time"] into a list of datetime objects instead of string.
```
from datetime import datetime
date_list = [datetime.strptime(d, '%Y%m%dB%H%M%SY') for d in s["time"]]
time=np.asarray(date_list)
```
Here str objects are converted into datetime objects using this format '%Y%m%dB%H... |
24,897,145 | I am using pythons mock.patch and would like to change the return value for each call.
Here is the caveat:
the function being patched has no inputs, so I can not change the return value based on the input.
Here is my code for reference.
```
def get_boolean_response():
response = io.prompt('y/n').lower()
while... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24897145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2434234/"
] | You can assign an [*iterable*](https://docs.python.org/3/glossary.html#term-iterable) to `side_effect`, and the mock will return the next value in the sequence each time it is called:
```
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'ba... | You can also use patch for multiple return values:
```
@patch('Function_to_be_patched', return_value=['a', 'b', 'c'])
```
Remember that if you are making use of more than one patch for a method then the order of it will look like this:
```
@patch('a')
@patch('b')
def test(mock_b, mock_a);
pass
```
as you can ... |
24,897,145 | I am using pythons mock.patch and would like to change the return value for each call.
Here is the caveat:
the function being patched has no inputs, so I can not change the return value based on the input.
Here is my code for reference.
```
def get_boolean_response():
response = io.prompt('y/n').lower()
while... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24897145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2434234/"
] | You can assign an [*iterable*](https://docs.python.org/3/glossary.html#term-iterable) to `side_effect`, and the mock will return the next value in the sequence each time it is called:
```
>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'ba... | for multiple return values, we can use **side\_effect** during patch initializing also and pass iterable to it
**sample.py**
```
def hello_world():
pass
```
**test\_sample.py**
```
from unittest.mock import patch
from sample import hello_world
@patch('sample.hello_world', side_effect=[{'a': 1, 'b': 2}, {'a': ... |
24,897,145 | I am using pythons mock.patch and would like to change the return value for each call.
Here is the caveat:
the function being patched has no inputs, so I can not change the return value based on the input.
Here is my code for reference.
```
def get_boolean_response():
response = io.prompt('y/n').lower()
while... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24897145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2434234/"
] | for multiple return values, we can use **side\_effect** during patch initializing also and pass iterable to it
**sample.py**
```
def hello_world():
pass
```
**test\_sample.py**
```
from unittest.mock import patch
from sample import hello_world
@patch('sample.hello_world', side_effect=[{'a': 1, 'b': 2}, {'a': ... | You can also use patch for multiple return values:
```
@patch('Function_to_be_patched', return_value=['a', 'b', 'c'])
```
Remember that if you are making use of more than one patch for a method then the order of it will look like this:
```
@patch('a')
@patch('b')
def test(mock_b, mock_a);
pass
```
as you can ... |
72,221,253 | I was reading python collections's [Counter](https://docs.python.org/3/library/collections.html#counter-objects). It says following:
```
>>> from collections import Counter
>>> Counter({'z': 9,'a':4, 'c':2, 'b':8, 'y':2, 'v':2})
Counter({'z': 9, 'b': 8, 'a': 4, 'c': 2, 'y': 2, 'v': 2})
```
Somehow these printed valu... | 2022/05/12 | [
"https://Stackoverflow.com/questions/72221253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317018/"
] | In terms of the data stored in a `Counter` object: The data is insertion-ordered as of Python 3.7, because `Counter` is a subclass of the built-in `dict`. Prior to Python 3.7, there was no guaranteed order of the data.
However, the behavior you are seeing is coming from `Counter.__repr__`. We can see from the [source ... | The order [depends on the python version](https://docs.python.org/3/library/collections.html#collections.Counter).
For python < 3.7, there is no guaranteed order, since python 3.7 the order is that of insertion.
>
> Changed in version 3.7: As a dict subclass, Counter inherited the
> capability to remember insertion ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Using a `while` loop :
```r
x <- list1
while (inherits(x <- x[[1]], "list")) {}
x
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 ... | **base R solution** I've just got the idea for a pretty simple function. It is a `while` loop that runs until the element is not a list.
```
myfun <- function(mylist){
dig_deeper <- TRUE
while(dig_deeper){
mylist<- my_list[[1]]
dig_deeper <- is.list(mylist)
}
return(mylist)
}
```
It works as expected... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | You can use `rrapply::rrapply`:
```r
library(rrapply)
firstList1 <- rrapply(list1, how = "flatten")[[1]]
firstList2 <- rrapply(list2, how = "flatten")[[1]]
all.equal(firstList1, firstList2)
# [1] TRUE
```
output
```r
> rrapply(list1, how = "flatten")[[1]]
Time Series:
Start = 1
End = 100
Frequency = 1
[1] ... | Another possible solution, using `purrr::pluck` and `purrr::vec_depth`:
```r
library(tidyverse)
pluck(list1, !!!(rep(1, vec_depth(list1)-2) %>% as.list()))
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | You can use `rrapply::rrapply`:
```r
library(rrapply)
firstList1 <- rrapply(list1, how = "flatten")[[1]]
firstList2 <- rrapply(list2, how = "flatten")[[1]]
all.equal(firstList1, firstList2)
# [1] TRUE
```
output
```r
> rrapply(list1, how = "flatten")[[1]]
Time Series:
Start = 1
End = 100
Frequency = 1
[1] ... | **base R solution** I've just got the idea for a pretty simple function. It is a `while` loop that runs until the element is not a list.
```
myfun <- function(mylist){
dig_deeper <- TRUE
while(dig_deeper){
mylist<- my_list[[1]]
dig_deeper <- is.list(mylist)
}
return(mylist)
}
```
It works as expected... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Using a `while` loop :
```r
x <- list1
while (inherits(x <- x[[1]], "list")) {}
x
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 ... | We can combine `while` loop with `purrr::pluck`. This avoids an actual recursive function, which could be a problem with deeply nested lists.
```
library(purrr)
get_list <- function(x){
while(is.list(x)){
x <- pluck(x, 1)
}
x
}
```
We can also set the function to be c... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Another base R solution - you could do this with a recursive function:
```
list1 <- list(ts(1:100),
list(1:19,
factor(letters)))
list2 <- list(list(list(ts(1:100), data.frame(a= rnorm(100))),
matrix(rnorm(10))),
NA)
recursive_fun <- function(my_list) ... | You can use `rrapply::rrapply`:
```r
library(rrapply)
firstList1 <- rrapply(list1, how = "flatten")[[1]]
firstList2 <- rrapply(list2, how = "flatten")[[1]]
all.equal(firstList1, firstList2)
# [1] TRUE
```
output
```r
> rrapply(list1, how = "flatten")[[1]]
Time Series:
Start = 1
End = 100
Frequency = 1
[1] ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Using a `while` loop :
```r
x <- list1
while (inherits(x <- x[[1]], "list")) {}
x
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 ... | Another possible solution, using `purrr::pluck` and `purrr::vec_depth`:
```r
library(tidyverse)
pluck(list1, !!!(rep(1, vec_depth(list1)-2) %>% as.list()))
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Another base R solution - you could do this with a recursive function:
```
list1 <- list(ts(1:100),
list(1:19,
factor(letters)))
list2 <- list(list(list(ts(1:100), data.frame(a= rnorm(100))),
matrix(rnorm(10))),
NA)
recursive_fun <- function(my_list) ... | **base R solution** I've just got the idea for a pretty simple function. It is a `while` loop that runs until the element is not a list.
```
myfun <- function(mylist){
dig_deeper <- TRUE
while(dig_deeper){
mylist<- my_list[[1]]
dig_deeper <- is.list(mylist)
}
return(mylist)
}
```
It works as expected... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Another base R solution - you could do this with a recursive function:
```
list1 <- list(ts(1:100),
list(1:19,
factor(letters)))
list2 <- list(list(list(ts(1:100), data.frame(a= rnorm(100))),
matrix(rnorm(10))),
NA)
recursive_fun <- function(my_list) ... | Using a `while` loop :
```r
x <- list1
while (inherits(x <- x[[1]], "list")) {}
x
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | Another base R solution - you could do this with a recursive function:
```
list1 <- list(ts(1:100),
list(1:19,
factor(letters)))
list2 <- list(list(list(ts(1:100), data.frame(a= rnorm(100))),
matrix(rnorm(10))),
NA)
recursive_fun <- function(my_list) ... | Another possible solution, using `purrr::pluck` and `purrr::vec_depth`:
```r
library(tidyverse)
pluck(list1, !!!(rep(1, vec_depth(list1)-2) %>% as.list()))
#> Time Series:
#> Start = 1
#> End = 100
#> Frequency = 1
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#> [19] 19 20 ... |
70,957,167 | Through Python i'm trying to convert the future date into another format and subtract with current date but it's throwing error.
Python version = Python 3.6.8
```
from datetime import datetime
enddate = 'Thu Jun 02 08:00:00 EDT 2022'
todays = datetime.today()
print ('Tpday =',todays)
Modified_date1 = datetime.strptim... | 2022/02/02 | [
"https://Stackoverflow.com/questions/70957167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9658186/"
] | You can use `rrapply::rrapply`:
```r
library(rrapply)
firstList1 <- rrapply(list1, how = "flatten")[[1]]
firstList2 <- rrapply(list2, how = "flatten")[[1]]
all.equal(firstList1, firstList2)
# [1] TRUE
```
output
```r
> rrapply(list1, how = "flatten")[[1]]
Time Series:
Start = 1
End = 100
Frequency = 1
[1] ... | We can combine `while` loop with `purrr::pluck`. This avoids an actual recursive function, which could be a problem with deeply nested lists.
```
library(purrr)
get_list <- function(x){
while(is.list(x)){
x <- pluck(x, 1)
}
x
}
```
We can also set the function to be c... |
1,922,623 | I am using MySQLdb module of python on FC11 machine. Here, i have an issue. I have the following implementation for one of our requirement:
1. connect to mysqldb and get DB handle,open a cursor, execute a delete statement,commit and then close the cursor.
2. Again using the DB handle above, iam performing a "select" s... | 2009/12/17 | [
"https://Stackoverflow.com/questions/1922623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233901/"
] | I've had the same issue, with the TreeView not scrolling to the selected item.
What I did was, after expanding the tree to the selected TreeViewItem, I called a Dispatcher Helper method to allow the UI to update, and then used the TransformToAncestor on the selected item, to find its position within the ScrollViewer. ... | Jason's ScrollViewer trick is a great way of moving a TreeViewItem to a specific position.
One problem, though: in MVVM you do not have access to the ScrollViewer in the view model. Here is a way to get to it anyway. If you have a TreeViewItem, you can walk up its visual tree until you reach the embedded ScrollViewer:... |
47,043,554 | Suppose we have a dataset like this:
```
X =
6 2 1
-2 4 -1
4 1 -1
1 6 1
2 4 1
6 2 1
```
I would like to get two data from this one having last digit 1 and another having last digit -1.
```
X0 =
-2 4 -1
4 1 -1
```
And,
```
X1 =
6 2 1
1 6 1
2 4 1
6 2 1
```
How can we do this in ... | 2017/10/31 | [
"https://Stackoverflow.com/questions/47043554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Suppose you have an array:
```
>>> arr
array([[ 6, 2, 1],
[-2, 4, -1],
[ 4, 1, -1],
[ 1, 6, 1],
[ 2, 4, 1],
[ 6, 2, 1]])
```
Then simply:
```
>>> mask1 = arr[:, -1] == 1
>>> mask2 = arr[:, -1] == -1
>>> X1 = arr[mask1]
>>> X2 = arr[mask2]
```
Results:
```
>>> X1
array... | You could just use `numpy` and use slicing to access your data e.g.:
```
X[X[:, 2] == 1] # Returns all rows where the third column equals 1
```
or as a complete example:
```
import numpy as np
# Random data set
X = np.zeros((6, 3))
X[:3, 2] = 1
X[3:, 2] = -1
np.random.shuffle(X)
print(X[X[:, 2] == 1])
print('-')... |
47,043,554 | Suppose we have a dataset like this:
```
X =
6 2 1
-2 4 -1
4 1 -1
1 6 1
2 4 1
6 2 1
```
I would like to get two data from this one having last digit 1 and another having last digit -1.
```
X0 =
-2 4 -1
4 1 -1
```
And,
```
X1 =
6 2 1
1 6 1
2 4 1
6 2 1
```
How can we do this in ... | 2017/10/31 | [
"https://Stackoverflow.com/questions/47043554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Suppose you have an array:
```
>>> arr
array([[ 6, 2, 1],
[-2, 4, -1],
[ 4, 1, -1],
[ 1, 6, 1],
[ 2, 4, 1],
[ 6, 2, 1]])
```
Then simply:
```
>>> mask1 = arr[:, -1] == 1
>>> mask2 = arr[:, -1] == -1
>>> X1 = arr[mask1]
>>> X2 = arr[mask2]
```
Results:
```
>>> X1
array... | ```
import numpy as np
x = np.array(x)
x0 = x[np.where(a[:,2]==-1)]
x1 = x[np.where(a[:,2]==1)]
``` |
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was writ... | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | "Python" is the name of the language itself, not of a particular interpreter implementation, just as "C" is the name of a programming language and not of a particular compiler.
"CPython" is an implementation of an interpreter of the Python language written in C. It compiles Python source code to byte code and interpre... | a) Python is a programming language. Interpreters of Python code are implemented using other programming languages like C (PyPy even using Python itself to implement one, I believe).
b) CPython, aka Classic Python, is the reference implementation and is written in C. Jython is a Python interpreter written in Java.
c)... |
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was writ... | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | "Python" is the name of the language itself, not of a particular interpreter implementation, just as "C" is the name of a programming language and not of a particular compiler.
"CPython" is an implementation of an interpreter of the Python language written in C. It compiles Python source code to byte code and interpre... | a) Default and most widely used language implementation is written in c also caled CPython. There is also for instance Python implemented in Python - <http://codespeak.net/pypy/dist/pypy/doc/>
b) CPython is default python implemetation in C. Jython is implemetation in Java.
c) Yes.
d) Jython is implementation of Pyt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.