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, which seemed like the obvious solution and it almost worked. **Note: I've opened the files and it seems entire sectors have their coordinates stored, not entities, hence the terrain itself is spatially mismatched with the region file name.**
That led to quite a bit of lag when I opened the client and the regions failed to render. I read up on the Anvil file format and imagined a scheme for reading NBT files. I figured I could manually read out the bytes and edit them, but in my continued research I got conflicting answers as to whether region files are gzipped.
I finished enough code to read some raw bytes, but the byte values didn't come out as I expected.
According to the info I have on NBT files, they all start with a CompoundTag and a CompoundTag starts as a single byte valued as 10, or x0A.
This is where I got my format information: <https://minecraft.gamepedia.com/NBT_format>
Here's a screenshot of what actually came out:
[](https://i.stack.imgur.com/de1Fe.png)
*Note: The class description in the screenshot is not accurate. I just quickly filled in enough to read the bytes, not flesh out the UI function.*
I assume these bytes coming out as non-sense is a sign that the file is compressed. I found this as a start to the gzip problem:
<http://gnuwin32.sourceforge.net/packages/gzip.htm>
I imagine if I could get this installed it would unzip this .mca file and I could read the bytes as expected, but I don't understand the installation instructions. It says use the "Shell Commands, 'configure', 'make' and 'make install'". To me that sounds like Unix, but the file I downloaded is for Windows? There aren't any exe's, but there are quite a few C files. I don't have a C-compiler. . .
Note: I still have not got the gzip software to work.
### Post Script
I've seen similar questions asked here, but all of them were either old (2016ish) with dead links to software that used to work, or they were recent and unanswered. I found one specific copy of this question asked 5 months ago, but I had to make an account to comment. Here's the link: [How can read Minecraft .mca files so that in python I can extract individual blocks?](https://stackoverflow.com/questions/57397934/how-can-read-minecraft-mca-files-so-that-in-python-i-can-extract-individual-blo) His question is with regard to a Python implementation. He said he found an NBT library for Python, but it was rejecting his MCA files for being *not-gzipped*.
I've got a lead on understanding the problem because I have the NBTExplorer source code (see the answer I posted), but I'll have to update on how that pans out. As far as getting my world fixed, I think I have a viable solution now.
If anyone could point me to a finished Java library, with source code, that opens .mca's or a discussion board related to this topic that'd be cool. I'm still also interested in how file compression works, but that's probably outside this question's scope. I realize this isn't directly bug or error related; it's it was moreso that I didn't know what further steps to take to make a code that accomplishes this task.
Update
------
I found someone else's program to do this and posted it as an answer, but I'd still like to know how the file is converted from bytes to useable info. Using the manual edit method of the answer I posted, I will need at most **241,664 manual edits**, so I still need a better solution.
|
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 first 8192 bytes are just about if there is any data about that specific chunk or not, where its found within the file and when it got last updated. Where the complete region (those 1024 Chunks) are positioned within the world can be worked out within the file name where the regions themself are numbered in x and z direction.
So in your case you should be able to rename your region files in a way they stay togehter as they are in the original worlds and you should be able to merge them together.
Second: The NBT Format is not the first thing to look at when you want to decode the data. First of the Region files have their own structure: <https://minecraft.gamepedia.com/Region_file_format> and when you get to the actual data using Zlib (RFC1950) it's getting complicated...
Anyway if you want further information on how to decode I can give you some information (since the files <https://www.rfc-editor.org/rfc/rfc1950.html> and <https://www.rfc-editor.org/rfc/rfc1951> about Zlib (RFC1950) are written in a hard way to understand - at least it was for me). But theres a point where I myself am struggeling right now which is why I came across this question.
|
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 2 fields, for up to 32x32 chunks, and I have *118 regions* that I need to fix. \*\*That's 241,664 potential manual edits! This solution is not viable on a reasonable timescale, but it's the best I have so far:
I found this page: <https://fileinfo.com/extension/mca>
Which linked to this page: <https://fileinfo.com/software/nbtexplorer/nbtexplorer>
Which linked to this page: <https://github.com/jaquadro/NBTExplorer/releases>
I installed the software and it automatically linked to the .minecraft folder, here's a screenshot of the GUI:
[](https://i.stack.imgur.com/xt7vy.png)
On the bright side, the application download page also has a download link for the source, so I intend to read that! I've opened two files so far to take a glance and they were not commented at all. They're also written in C# which I have never seen before, but I've heard it's very similar to Java, so maybe I'll learn that language too.
|
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, which seemed like the obvious solution and it almost worked. **Note: I've opened the files and it seems entire sectors have their coordinates stored, not entities, hence the terrain itself is spatially mismatched with the region file name.**
That led to quite a bit of lag when I opened the client and the regions failed to render. I read up on the Anvil file format and imagined a scheme for reading NBT files. I figured I could manually read out the bytes and edit them, but in my continued research I got conflicting answers as to whether region files are gzipped.
I finished enough code to read some raw bytes, but the byte values didn't come out as I expected.
According to the info I have on NBT files, they all start with a CompoundTag and a CompoundTag starts as a single byte valued as 10, or x0A.
This is where I got my format information: <https://minecraft.gamepedia.com/NBT_format>
Here's a screenshot of what actually came out:
[](https://i.stack.imgur.com/de1Fe.png)
*Note: The class description in the screenshot is not accurate. I just quickly filled in enough to read the bytes, not flesh out the UI function.*
I assume these bytes coming out as non-sense is a sign that the file is compressed. I found this as a start to the gzip problem:
<http://gnuwin32.sourceforge.net/packages/gzip.htm>
I imagine if I could get this installed it would unzip this .mca file and I could read the bytes as expected, but I don't understand the installation instructions. It says use the "Shell Commands, 'configure', 'make' and 'make install'". To me that sounds like Unix, but the file I downloaded is for Windows? There aren't any exe's, but there are quite a few C files. I don't have a C-compiler. . .
Note: I still have not got the gzip software to work.
### Post Script
I've seen similar questions asked here, but all of them were either old (2016ish) with dead links to software that used to work, or they were recent and unanswered. I found one specific copy of this question asked 5 months ago, but I had to make an account to comment. Here's the link: [How can read Minecraft .mca files so that in python I can extract individual blocks?](https://stackoverflow.com/questions/57397934/how-can-read-minecraft-mca-files-so-that-in-python-i-can-extract-individual-blo) His question is with regard to a Python implementation. He said he found an NBT library for Python, but it was rejecting his MCA files for being *not-gzipped*.
I've got a lead on understanding the problem because I have the NBTExplorer source code (see the answer I posted), but I'll have to update on how that pans out. As far as getting my world fixed, I think I have a viable solution now.
If anyone could point me to a finished Java library, with source code, that opens .mca's or a discussion board related to this topic that'd be cool. I'm still also interested in how file compression works, but that's probably outside this question's scope. I realize this isn't directly bug or error related; it's it was moreso that I didn't know what further steps to take to make a code that accomplishes this task.
Update
------
I found someone else's program to do this and posted it as an answer, but I'd still like to know how the file is converted from bytes to useable info. Using the manual edit method of the answer I posted, I will need at most **241,664 manual edits**, so I still need a better solution.
|
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 first 8192 bytes are just about if there is any data about that specific chunk or not, where its found within the file and when it got last updated. Where the complete region (those 1024 Chunks) are positioned within the world can be worked out within the file name where the regions themself are numbered in x and z direction.
So in your case you should be able to rename your region files in a way they stay togehter as they are in the original worlds and you should be able to merge them together.
Second: The NBT Format is not the first thing to look at when you want to decode the data. First of the Region files have their own structure: <https://minecraft.gamepedia.com/Region_file_format> and when you get to the actual data using Zlib (RFC1950) it's getting complicated...
Anyway if you want further information on how to decode I can give you some information (since the files <https://www.rfc-editor.org/rfc/rfc1950.html> and <https://www.rfc-editor.org/rfc/rfc1951> about Zlib (RFC1950) are written in a hard way to understand - at least it was for me). But theres a point where I myself am struggeling right now which is why I came across this question.
|
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 [Inflater](https://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html) and [Deflater](https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html). One annoying thing about the format for chunk data is it is only prefixed with the size of the compressed buffer, with no info on the size of the uncompressed buffer (so the uncompressed buffer must be estimated to be large enough or multiple buffers can be used to fill until the compressed buffer is completely "inflated").
|
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: (1046, 'No database selected')
```
**settings.py:**
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_db',
'USER': 'username',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
```
What have I missed?
|
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(rnd.random())
```
|
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
```
However, since you develop your seed from a user inputted string, the value will not remain constant. Since the value that is returned by the `Random` object will not have a different value somewhere, you can't rely on it to be constant.
If you want the output to be constant, *the seed can not change.*
|
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 random numbers you can actually test changes in your code using the very same stream of random numbers and check if the final output of your code is caused by changes in your code instead of occurrences of different random stream of numbers. This is very common in simulation processes (queues, traffic simulations, etc.).
So, same seed = same stream of random numbers.
Change the seed to have different streams of random number,
I hope it helps.
|
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(rnd.random())
```
|
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(mapSeed.digest())
```
(You can also just used the user input directly; there's no benefit to doing an SHA1 hash over it first)
|
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
```
However, since you develop your seed from a user inputted string, the value will not remain constant. Since the value that is returned by the `Random` object will not have a different value somewhere, you can't rely on it to be constant.
If you want the output to be constant, *the seed can not change.*
|
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(rnd.random())
```
|
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(mapSeed.digest())
```
(You can also just used the user input directly; there's no benefit to doing an SHA1 hash over it first)
|
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 random numbers you can actually test changes in your code using the very same stream of random numbers and check if the final output of your code is caused by changes in your code instead of occurrences of different random stream of numbers. This is very common in simulation processes (queues, traffic simulations, etc.).
So, same seed = same stream of random numbers.
Change the seed to have different streams of random number,
I hope it helps.
|
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
django-toolbelt==0.0.1
gunicorn==19.6.0
pkg-resources==0.0.0
psycopg2==2.6.2
static3==0.7.0
```
and
```
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
```
I searched for many answers on stackoverflow but not getting the error.
|
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 interesting too.
|
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 interesting too.
|
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 interesting too.
|
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 ace, able
\$(ls) \`ls\` (but nestable!)
HISTORY MANIPULATION
--------------------
!! Last command
!?foo Last command containing \`foo'
^foo^bar^ Last command containing \`foo', but substitute \`bar'
!!:0 Last command word
!!:^ Last command's first argument
!\$ Last command's last argument
!!:* Last command's arguments
!!:x-y Arguments x to y of last command
C-s search forwards in history
C-r search backwards in history
LINE EDITING
------------
M-d kill to end of word
C-w kill to beginning of word
C-k kill to end of line
C-u kill to beginning of line
M-r revert all modifications to current line
C-] search forwards in line
M-C-] search backwards in line
C-t transpose characters
M-t transpose words
M-u uppercase word
M-l lowercase word
M-c capitalize word
COMPLETION
----------
M-/ complete filename
M-~ complete user name
M-@ complete host name
M-\$ complete variable name
M-! complete command name
M-^ complete history
EOF
}
```
|
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 swapped out with a variable so in a script it would go something like:
```
#!/bin/bash
hd `whereis -b $1 | sed "s/$1: //"` | head
```
The practical usefulness of the above is fairly limited but it demonstrates the versatility of the backtick operator (and the bash shell) fairly well, in my humble opinion.
|
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 interesting too.
|
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='${PWD##$PREFIX}$ '
PREFIX='' export PREFIX
prefix () {
PREFIX="$1"
}
prefix '*/'
```
The `prefix '*/'` call will set your prompt to only contain the last directory element of your current working directory (instead of the complete path). If you want to see the entire path, call `prefix` with no arguments.
|
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 interesting too.
|
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..."
Hello, Joe. Welcome to...
$ last=Green
$ echo "Hello, $first${last:+ $last}. Welcome to..."
Hello, Joe Green. 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 swapped out with a variable so in a script it would go something like:
```
#!/bin/bash
hd `whereis -b $1 | sed "s/$1: //"` | head
```
The practical usefulness of the above is fairly limited but it demonstrates the versatility of the backtick operator (and the bash shell) fairly well, in my humble opinion.
|
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 interesting too.
|
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='${PWD##$PREFIX}$ '
PREFIX='' export PREFIX
prefix () {
PREFIX="$1"
}
prefix '*/'
```
The `prefix '*/'` call will set your prompt to only contain the last directory element of your current working directory (instead of the complete path). If you want to see the entire path, call `prefix` with no arguments.
|
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 interesting too.
|
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/\(.*\)/echo \1 ; jar tvf \1 | sed -e 's\/^\/ \/' | grep -i \"$SEARCH\"/" | sh
```
which I keep in my [collection of handy scripts](http://git://github.com/DonBranson/scripts.git).
I also use this one-liner a lot:
```
find . -name "*.java" | xargs grep -li "yadayada"
```
end this one:
```
find . -name "*.java" | sed -e 's+\(.*\)+echo \1 ; yada_cmd \1+' | sh
```
|
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 interesting too.
|
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..."
Hello, Joe. Welcome to...
$ last=Green
$ echo "Hello, $first${last:+ $last}. Welcome to..."
Hello, Joe Green. 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 interesting too.
|
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 alias.
HTH
cheers,
|
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/\(.*\)/echo \1 ; jar tvf \1 | sed -e 's\/^\/ \/' | grep -i \"$SEARCH\"/" | sh
```
which I keep in my [collection of handy scripts](http://git://github.com/DonBranson/scripts.git).
I also use this one-liner a lot:
```
find . -name "*.java" | xargs grep -li "yadayada"
```
end this one:
```
find . -name "*.java" | sed -e 's+\(.*\)+echo \1 ; yada_cmd \1+' | sh
```
|
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 interesting too.
|
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) != "/" ]] && echo -n /
echo $file
done
```
|
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='${PWD##$PREFIX}$ '
PREFIX='' export PREFIX
prefix () {
PREFIX="$1"
}
prefix '*/'
```
The `prefix '*/'` call will set your prompt to only contain the last directory element of your current working directory (instead of the complete path). If you want to see the entire path, call `prefix` with no arguments.
|
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()
```
What is the most pythonic way to deal with this situation? I have considered creating a first class function/generator and wrapping calls to a for loop in it:
```
def cursor_iterator(cursor):
row = cursor.next()
while row:
yield row
row = cursor.next()
[...]
cursor = gp.getcursor(table)
for row in cursor_iterator(cursor):
# do something with row
```
This is an improvement, but feels a little clumsy. Is there a more pythonic approach? Should I create a wrapper class around the `table` type?
|
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 = cursor.next()
```
Now you just call:
```
my_table = Table(t)
for row in my_table.rows():
# do stuff with row
```
It's very readable, in my opinion.
|
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()
```
What is the most pythonic way to deal with this situation? I have considered creating a first class function/generator and wrapping calls to a for loop in it:
```
def cursor_iterator(cursor):
row = cursor.next()
while row:
yield row
row = cursor.next()
[...]
cursor = gp.getcursor(table)
for row in cursor_iterator(cursor):
# do something with row
```
This is an improvement, but feels a little clumsy. Is there a more pythonic approach? Should I create a wrapper class around the `table` type?
|
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()
if not n:
raise StopIteration()
return n
```
and then:
```
for row in Table(gp, table)
```
*See also: [Iterator Types](http://docs.python.org/library/stdtypes.html#typeiter)*
|
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()
```
What is the most pythonic way to deal with this situation? I have considered creating a first class function/generator and wrapping calls to a for loop in it:
```
def cursor_iterator(cursor):
row = cursor.next()
while row:
yield row
row = cursor.next()
[...]
cursor = gp.getcursor(table)
for row in cursor_iterator(cursor):
# do something with row
```
This is an improvement, but feels a little clumsy. Is there a more pythonic approach? Should I create a wrapper class around the `table` type?
|
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()
if not n:
raise StopIteration()
return n
```
and then:
```
for row in Table(gp, table)
```
*See also: [Iterator Types](http://docs.python.org/library/stdtypes.html#typeiter)*
|
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 = cursor.next()
```
Now you just call:
```
my_table = Table(t)
for row in my_table.rows():
# do stuff with row
```
It's very readable, in my opinion.
|
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 rope amount and wanted.
it's known the short rope length is 1 meter and the long rope length is 5 meters.
if the wanted length is in range of the possible lengths of the ropes the function will return True, else false,
for example, 1 short rope and 2 long ropes can get you the following length: [1, 5, 6, 10, 11] and if the wanted length that the function got is in this list of lengths it should return True.
here is my code:
```
def wantedLength(short_amount, long_amount, wanted_length):
short_rope_length = 1
long_rope_length = 5
for i in range(short_amount + 1):
for j in range(long_amount + 1):
my_length = [short_rope_length * i + long_rope_length * j, ", "]
if wanted_length in my_length:
return True
else:
return False
```
but when I run the code I get the following error:
TypeError: argument of type 'int' is not iterable
what am I doing wrong in the for loop statement?
thanks in advance!
I tried to change the for loops with other commands like [short\_amount] and etc
the traceback as requsted:
```
Traceback (most recent call last):
File "C:\Users\barva\PycharmProjects\Giraffe\Ariel-Exc\Exc_2.py", line 89, in <module>
print(wantedLength(a,b,c))
File "C:\Users\barva\PycharmProjects\Giraffe\Ariel-Exc\Exc_2.py", line 73, in wantedLength
if wanted_length in my_length:
TypeError: argument of type 'int' is not iterable
```
|
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 42
3 teacher teacher_x 21
4 teacher teacher_y 45
5 teacher teacher_z 33
```
|
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']) # or use any other valid key
output = pd.DataFrame(np.ravel(zip_list).reshape(col_len**2, col_len))
```
|
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 code so far:
```
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: ")
print ("This is the only thing getting written into the file", file=outfile)
main ()
```
|
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 them to be able to hit enter when typing their html file.
**EDIT:** Example of loop to allow continuous user input:
```
with open(name, 'w') as o:
code = input("blah")
while (code != "exit")
o.write('{0}\n'.format(code))
code = input("blah")
```
That way, the loop will keep running until the user types in "exit" or whatever string you choose. The format line inserts a newline into the file. I'm still on python2 so I'm not completely sure how input handles newlines, but if it includes it, feel free to remove the format line and use it as above.
|
```
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 will need an additional module for that.
|
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 = 'baz'
QUX_RESOURCE = 'qux'
```
```py
# file runtime/bar_handler.py
from resources.resource_ids import BAR_RESOURCE
# ...
def my_code():
value = get_resource(BAR_RESOURCE)
```
This is simple and universal, but has a few downsides:
* `_RESOURCE` has to be appended to all constant names to provide context
* Inspecting the constant name in IDE will not display other constant values
### Approach 2 - enum
```py
# file resources/resource_ids.py
from enum import Enum, unique
@unique
class ResourceIds(Enum):
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
```
```
# file runtime/bar_handler.py
from resources.resource_ids import ResourceIds
# ...
def my_code():
value = get_resource(ResourceIds.bar.value)
```
This solves the problems of the first approach, but the downside of this solution is the need of using `.value` in order to get the string representation (assuming we need the string value and not just a consistent enum value). Failure to append `.value` can result in hard to debug issues in runtime.
### Approach 3 - class variables
```py
# file resources/resource_ids.py
class ResourceIds:
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
```
```
# file runtime/bar_handler.py
from resources.resource_ids import ResourceIds
# ...
def my_code():
value = get_resource(ResourceIds.bar)
```
This approach is my favorite, but it may be misinterpreted - classes are made to be instantiated. And while code correctness wouldn't suffer from using an instance of the class instead of the class itself, I would like to avoid this waste.
Another disadvantage of this approach that the values are not actually constant. Any code client can potentially change them.
Is it possible to prevent a class from being instantiated? Am I missing some idiomatic way of grouping closely related constants?
|
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: 'foo'>
>>> list(ResourceIds.foo.__class__)
[
<ResourceIds.foo: 'foo'>,
<ResourceIds.bar: 'bar'>,
<ResourceIds.baz: 'baz'>,
<ResourceIds.qux: 'qux'>,
]
```
|
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
module_name.save('my_path', fomat=module_name.CSV)
```
another way is like this:
```
# module_name.py
options = {
'csv': some_csv_processing_function
'json': some_json_processing_function
}
def save(path, format=options.['csv']:
# do some thing with format
...
# other_module.py
import module_name
module_name.save('my_path', fomat=module_name.options['csv'])
```
(kinda unrelated) You can also make your dicts classes:
```
class DictClass:
def __init__(self, dict_class):
self.__dict__ = dict_class
options = DictClass({
'csv': some_csv_processing_function
'json': some_json_processing_function
})
```
now you can access your dictionary as an object like: `options.csv`
|
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 iterator object does not?
I read [this question](https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators) but it does not explain why an iterator is not a generator. Is it just the syntax `yield` that explains the difference?
Thanks in advance.
|
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 necessarily a generator.
In fact it means that when you generate a generator all its code is **not** run at once. Meanwhile with a more classical iterator you will run only once the generation code.
|
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__` method, and an `__iter__` method.
So lists, tuples, sets, dictionaries... are iterators.
But those are not generators, because all of the elements they contain are defined and evaluated after the container initialization, and they can be iterated over many times.
Therefore, some iterators are not generators.
|
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 iterator object does not?
I read [this question](https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators) but it does not explain why an iterator is not a generator. Is it just the syntax `yield` that explains the difference?
Thanks in advance.
|
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 returns itself, and it has a *next()* method (which is *\_\_next\_\_()* in Python 3). The next-method is responsible for returning a value, advancing the iterator, and raising *StopIteration* when done.
What is a generator?
--------------------
A generator is a regular Python function containing `yield`. When called it returns a generator-iterator (one of the many kinds of iterator).
Examples of how to create generators and iterators
--------------------------------------------------
**Generator example:**
```
>>> def f(x): # "f" is a generator
yield x
yield x**2
yield x**3
>>> g = f(10) # calling "f" returns a generator-iterator
>>> type(f) # "f" is a regular python function with "yield"
<type 'function'>
>>> type(g)
<type 'generator'>
>>> next(g) # next() gets a value from the generator-iterator
10
>>> next(g)
100
>>> next(g)
1000
>>> next(g) # iterators signal that they are done with an Exception
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
next(g)
StopIteration
>>> dir(g) # generator-iterators have next() and \__iter__
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
```
**Iterator using a class:**
```
>>> class Powers: # "Powers" is a class
def __init__(self, base):
self.base = base
self.exp = 0
def __iter__(self):
return self
def next(self):
self.exp += 1
if self.exp > 3:
raise StopIteration
return self.base ** self.exp
>>> g = Powers(10) # calling "Powers" returns an iterator
>>> type(Powers) # "Power" is a regular python class
<type 'classobj'>
>>> type(g) # "g" is a iterator instance with next() and __iter__()
<type 'instance'>
>>> next(g) # next() gets a value from the iterator
10
>>> next(g)
100
>>> next(g)
1000
>>> next(g) # iterators signal that they are done with an Exception
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
next(g)
StopIteration
```
Iterator from a sequence example:
---------------------------------
```
>>> s = 'cat'
>>> it = iter(s) # creates an "iterator" from a sequence
>>> type(s) # "s" is a string which is "iterable"
<type 'str'>
>>> type(it) # An "iterator" with next() and __iter__()
<type 'iterator'>
>>> next(it)
'c'
>>> next(it)
'a'
>>> next(it)
't'
>>> next(it)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
next(it)
StopIteration
```
Comparison and conclusion
-------------------------
An iterator is an object representing a stream of data. It has an *\_\_iter\_\_()* method and a *next()* method.
There are several ways to make an iterator:
1) Call a generator (a regular python function that uses `yield`)
2) Instantiate a class that has an *\_\_iter\_\_()* method and a *next()* method.
**From this, you can see that a generator is just one of many ways to make an iterator** (there are other ways as well: itertools, iter() on a regular function and a sentinel, etc).
|
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 necessarily a generator.
In fact it means that when you generate a generator all its code is **not** run at once. Meanwhile with a more classical iterator you will run only once the generation code.
|
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 iterator object does not?
I read [this question](https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators) but it does not explain why an iterator is not a generator. Is it just the syntax `yield` that explains the difference?
Thanks in advance.
|
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 returns itself, and it has a *next()* method (which is *\_\_next\_\_()* in Python 3). The next-method is responsible for returning a value, advancing the iterator, and raising *StopIteration* when done.
What is a generator?
--------------------
A generator is a regular Python function containing `yield`. When called it returns a generator-iterator (one of the many kinds of iterator).
Examples of how to create generators and iterators
--------------------------------------------------
**Generator example:**
```
>>> def f(x): # "f" is a generator
yield x
yield x**2
yield x**3
>>> g = f(10) # calling "f" returns a generator-iterator
>>> type(f) # "f" is a regular python function with "yield"
<type 'function'>
>>> type(g)
<type 'generator'>
>>> next(g) # next() gets a value from the generator-iterator
10
>>> next(g)
100
>>> next(g)
1000
>>> next(g) # iterators signal that they are done with an Exception
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
next(g)
StopIteration
>>> dir(g) # generator-iterators have next() and \__iter__
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
```
**Iterator using a class:**
```
>>> class Powers: # "Powers" is a class
def __init__(self, base):
self.base = base
self.exp = 0
def __iter__(self):
return self
def next(self):
self.exp += 1
if self.exp > 3:
raise StopIteration
return self.base ** self.exp
>>> g = Powers(10) # calling "Powers" returns an iterator
>>> type(Powers) # "Power" is a regular python class
<type 'classobj'>
>>> type(g) # "g" is a iterator instance with next() and __iter__()
<type 'instance'>
>>> next(g) # next() gets a value from the iterator
10
>>> next(g)
100
>>> next(g)
1000
>>> next(g) # iterators signal that they are done with an Exception
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
next(g)
StopIteration
```
Iterator from a sequence example:
---------------------------------
```
>>> s = 'cat'
>>> it = iter(s) # creates an "iterator" from a sequence
>>> type(s) # "s" is a string which is "iterable"
<type 'str'>
>>> type(it) # An "iterator" with next() and __iter__()
<type 'iterator'>
>>> next(it)
'c'
>>> next(it)
'a'
>>> next(it)
't'
>>> next(it)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
next(it)
StopIteration
```
Comparison and conclusion
-------------------------
An iterator is an object representing a stream of data. It has an *\_\_iter\_\_()* method and a *next()* method.
There are several ways to make an iterator:
1) Call a generator (a regular python function that uses `yield`)
2) Instantiate a class that has an *\_\_iter\_\_()* method and a *next()* method.
**From this, you can see that a generator is just one of many ways to make an iterator** (there are other ways as well: itertools, iter() on a regular function and a sentinel, etc).
|
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__` method, and an `__iter__` method.
So lists, tuples, sets, dictionaries... are iterators.
But those are not generators, because all of the elements they contain are defined and evaluated after the container initialization, and they can be iterated over many times.
Therefore, some iterators are not generators.
|
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 in my views.py:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
```
and I can easily get the number of unread notification in this url:
```
http://127.0.0.1:8000/inbox/notifications/api/unread_count/
```
it return `{"unread_count": 1}` as I want. but with `/api/unread_list/` I can not to get the list of notifications and I get this error:
```
ValueError at /inbox/notifications/
invalid literal for int() with base 10: '<property object at 0x7fe1b56b6e08>'
```
As I beginner in using `django-notifications` any help will be appreciated.
**Full TraceBack**
>
> Environment:
>
>
> Request Method: GET Request URL:
> <http://127.0.0.1:8000/inbox/notifications/api/unread_list/>
>
>
> Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications:
> ['django.contrib.admin', 'django.contrib.auth',
> 'django.contrib.contenttypes', 'django.contrib.sessions',
> 'django.contrib.messages', 'django.contrib.staticfiles',
> 'django.contrib.sites', 'django.forms', 'rest\_framework',
> 'allauth', 'allauth.account', 'allauth.socialaccount', 'guardian',
> 'axes', 'django\_otp', 'django\_otp.plugins.otp\_static',
> 'django\_otp.plugins.otp\_totp', 'two\_factor', 'invitations',
> 'avatar', 'imagekit', 'import\_export', 'djmoney', 'captcha',
> 'dal', 'dal\_select2', 'widget\_tweaks', 'braces', 'django\_tables2',
> 'phonenumber\_field', 'hitcount', 'el\_pagination',
> 'maintenance\_mode', 'notifications', 'mathfilters',
> 'myproject\_web', 'Order', 'PhotoGallery', 'Search', 'Social',
> 'UserAccount', 'UserAuthentication', 'UserAuthorization',
> 'UserProfile'] Installed Middleware:
> ['django.middleware.security.SecurityMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.locale.LocaleMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> 'django\_otp.middleware.OTPMiddleware',
> 'maintenance\_mode.middleware.MaintenanceModeMiddleware']
>
>
> Traceback:
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/exception.py"
> in inner
> 35. response = get\_response(request)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/base.py"
> in \_get\_response
> 128. response = self.process\_exception\_by\_middleware(e, request)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/base.py"
> in \_get\_response
> 126. response = wrapped\_callback(request, \*callback\_args, \*\*callback\_kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/notifications/views.py"
> in live\_unread\_notification\_list
> 164. if n.actor:
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/contrib/contenttypes/fields.py"
> in **get**
> 253. rel\_obj = ct.get\_object\_for\_this\_type(pk=pk\_val)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/contrib/contenttypes/models.py"
> in get\_object\_for\_this\_type
> 169. return self.model\_class().\_base\_manager.using(self.\_state.db).get(\*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in get
> 394. clone = self.filter(\*args, \*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in filter
> 836. return self.\_filter\_or\_exclude(False, \*args, \*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in \_filter\_or\_exclude
> 854. clone.query.add\_q(Q(\*args, \*\*kwargs))
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in add\_q
> 1253. clause, \_ = self.\_add\_q(q\_object, self.used\_aliases)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in \_add\_q
> 1277. split\_subq=split\_subq,
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in build\_filter
> 1215. condition = self.build\_lookup(lookups, col, value)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in build\_lookup
> 1085. lookup = lookup\_class(lhs, rhs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/lookups.py"
> in **init**
> 18. self.rhs = self.get\_prep\_lookup()
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/lookups.py"
> in get\_prep\_lookup
> 68. return self.lhs.output\_field.get\_prep\_value(self.rhs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/fields/**init**.py"
> in get\_prep\_value
> 947. return int(value)
>
>
> Exception Type: ValueError at /inbox/notifications/api/unread\_list/
> Exception Value: invalid literal for int() with base 10: ''
>
>
>
|
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(username = 'SirSaleh')` to User ID. Problem solved.
**So Why type of `actor_object_id` is CharField (varchar)? (at least I don't know)** ;))
|
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` object, not `guy`.
So, change your code to:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=guy, recipient=guy, verb='you visted the site!')
```
Notifications will take the user object `guy`, extrapolate the ID and store it in the database accordingly.
|
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 in my views.py:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=User, recipient=guy, verb='you visted the site!')
```
and I can easily get the number of unread notification in this url:
```
http://127.0.0.1:8000/inbox/notifications/api/unread_count/
```
it return `{"unread_count": 1}` as I want. but with `/api/unread_list/` I can not to get the list of notifications and I get this error:
```
ValueError at /inbox/notifications/
invalid literal for int() with base 10: '<property object at 0x7fe1b56b6e08>'
```
As I beginner in using `django-notifications` any help will be appreciated.
**Full TraceBack**
>
> Environment:
>
>
> Request Method: GET Request URL:
> <http://127.0.0.1:8000/inbox/notifications/api/unread_list/>
>
>
> Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications:
> ['django.contrib.admin', 'django.contrib.auth',
> 'django.contrib.contenttypes', 'django.contrib.sessions',
> 'django.contrib.messages', 'django.contrib.staticfiles',
> 'django.contrib.sites', 'django.forms', 'rest\_framework',
> 'allauth', 'allauth.account', 'allauth.socialaccount', 'guardian',
> 'axes', 'django\_otp', 'django\_otp.plugins.otp\_static',
> 'django\_otp.plugins.otp\_totp', 'two\_factor', 'invitations',
> 'avatar', 'imagekit', 'import\_export', 'djmoney', 'captcha',
> 'dal', 'dal\_select2', 'widget\_tweaks', 'braces', 'django\_tables2',
> 'phonenumber\_field', 'hitcount', 'el\_pagination',
> 'maintenance\_mode', 'notifications', 'mathfilters',
> 'myproject\_web', 'Order', 'PhotoGallery', 'Search', 'Social',
> 'UserAccount', 'UserAuthentication', 'UserAuthorization',
> 'UserProfile'] Installed Middleware:
> ['django.middleware.security.SecurityMiddleware',
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.locale.LocaleMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> 'django\_otp.middleware.OTPMiddleware',
> 'maintenance\_mode.middleware.MaintenanceModeMiddleware']
>
>
> Traceback:
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/exception.py"
> in inner
> 35. response = get\_response(request)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/base.py"
> in \_get\_response
> 128. response = self.process\_exception\_by\_middleware(e, request)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/core/handlers/base.py"
> in \_get\_response
> 126. response = wrapped\_callback(request, \*callback\_args, \*\*callback\_kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/notifications/views.py"
> in live\_unread\_notification\_list
> 164. if n.actor:
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/contrib/contenttypes/fields.py"
> in **get**
> 253. rel\_obj = ct.get\_object\_for\_this\_type(pk=pk\_val)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/contrib/contenttypes/models.py"
> in get\_object\_for\_this\_type
> 169. return self.model\_class().\_base\_manager.using(self.\_state.db).get(\*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in get
> 394. clone = self.filter(\*args, \*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in filter
> 836. return self.\_filter\_or\_exclude(False, \*args, \*\*kwargs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/query.py"
> in \_filter\_or\_exclude
> 854. clone.query.add\_q(Q(\*args, \*\*kwargs))
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in add\_q
> 1253. clause, \_ = self.\_add\_q(q\_object, self.used\_aliases)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in \_add\_q
> 1277. split\_subq=split\_subq,
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in build\_filter
> 1215. condition = self.build\_lookup(lookups, col, value)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/sql/query.py"
> in build\_lookup
> 1085. lookup = lookup\_class(lhs, rhs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/lookups.py"
> in **init**
> 18. self.rhs = self.get\_prep\_lookup()
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/lookups.py"
> in get\_prep\_lookup
> 68. return self.lhs.output\_field.get\_prep\_value(self.rhs)
>
>
> File
> "/home/saleh/Projects/myproject\_web/lib/python3.5/site-packages/django/db/models/fields/**init**.py"
> in get\_prep\_value
> 947. return int(value)
>
>
> Exception Type: ValueError at /inbox/notifications/api/unread\_list/
> Exception Value: invalid literal for int() with base 10: ''
>
>
>
|
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` object, not `guy`.
So, change your code to:
```
guy = User.objects.get(username = 'SirSaleh')
notify.send(sender=guy, recipient=guy, verb='you visted the site!')
```
Notifications will take the user object `guy`, extrapolate the ID and store it in the database accordingly.
|
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#robert'`
So if I try:
```
>>> all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho'
>>> RE_HARD = re.compile(r'(^#.*\n)')
>>> mo = re.search(RE_HARD, all_lines)
>>> print mo.group(0)
#hello
```
Now, if I hardcode what comes after the first \n after the last #, i.e., I hardcode echo, I get:
```
>>> all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho'
>>> RE_HARD = re.compile(r'(^#.*echo)')
>>> mo = re.search(RE_HARD, all_lines)
>>> print mo.group(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
```
I get an error, no idea why. Seems the same as before.
This is still not want I want since in reality after the first \n that comes after the last # I may have any character/string...
|
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
.*?$ # rest of the line. (note .*? non-greedy)
''',
# Flags:
# DOTALL: Make the '.' match any character at all, including a newline
# VERBOSE: Allow comments in pattern
# MULTILINE: Allow $ to match end of line
re.DOTALL | re.VERBOSE | re.MULTILINE)
print re.search(regex, all_lines).group()
```
Reference: <http://docs.python.org/2/library/re.html>
Demo: <http://ideone.com/aZjjVj>
|
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_positions
[0, 7, 27, 33]
>>> first = hash_positions[0]
>>> last = hash_positions[-1]
>>> new_line_after_last_hash = my_string.index('\n',last)
>>> new_line_after_last_hash
40
>>> new_string = my_string[first:new_line_after_last_hash]
>>> new_string
'#hello\n#monica, how re "u?\n#hello#robert'
```
|
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", "-R", "/etc"]
CMD ["chown", "redis:redis", "-R", "/var/lib"]
CMD ["chown", "redis:redis", "-R", "/run"]
CMD ["sudo", "chmod", "644", "/data/dump.rdb" ]
CMD ["sudo", "chmod", "755", "/etc" ]
CMD ["sudo", "chmod", "770", "/var/lib" ]
CMD ["sudo", "chmod", "777", "/run" ]
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]
```
Also i use django and celery, when celery works 4-6 hours, container of celery stopped, with error:
```
[2018-03-05 17:18:24,516: CRITICAL/MainProcess] Unrecoverable error: ResponseError('MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.',)
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start
self.blueprint.start(self)
File "/usr/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
step.start(parent)
File "/usr/local/lib/python3.4/site-packages/celery/bootsteps.py", line 370, in start
return self.obj.start()
File "/usr/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 320, in start
blueprint.start(self)
File "/usr/local/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start
step.start(parent)
File "/usr/local/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 596, in start
c.loop(*c.loop_args())
File "/usr/local/lib/python3.4/site-packages/celery/worker/loops.py", line 88, in asynloop
next(loop)
File "/usr/local/lib/python3.4/site-packages/kombu/async/hub.py", line 354, in create_loop
cb(*cbargs)
File "/usr/local/lib/python3.4/site-packages/kombu/transport/redis.py", line 1040, in on_readable
self.cycle.on_readable(fileno)
File "/usr/local/lib/python3.4/site-packages/kombu/transport/redis.py", line 337, in on_readable
chan.handlers[type]()
File "/usr/local/lib/python3.4/site-packages/kombu/transport/redis.py", line 714, in _brpop_read
**options)
File "/usr/local/lib/python3.4/site-packages/redis/client.py", line 680, in parse_response
response = connection.read_response()
File "/usr/local/lib/python3.4/site-packages/redis/connection.py", line 629, in read_response
raise response
redis.exceptions.ResponseError: MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.
Import Error
-------------- celery@b17b82a69031 v4.1.0 (latentcall)
---- **** -----
--- * *** * -- Linux-4.4.0-34-generic-x86_64-with-debian-8.9 2018-03-05 07:24:00
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: backend:0x7f19e5745208
- ** ---------- .> transport: redis://redis:6379/0
- ** ---------- .> results: disabled://
- *** --- * --- .> concurrency: 20 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
-------------- [queues]
.> celery exchange=celery(direct) key=celery
[tasks]
. CallbackNotifier
. FB posting
. FB token status
. MD posting
. MD token status
. OK posting
. OK token status
. TW posting
. TW token status
. VK posting
. VK token status
. api.controllers.message.scheduled_message
. backend.celery.debug_task
. stats.views.collect_stats
```
In my redis.conf file i disable snapshots
```
stop-writes-on-bgsave-error no
```
In redis logs:
```
1:M 06 Mar 07:40:04.037 * Background saving started by pid 8228
8228:C 06 Mar 07:40:04.038 # Failed opening the RDB file backupall.db (in server root dir /run) for saving: Permission denied
```
But, when i restart redis container i've get some warnings:
```
1:C 06 Mar 08:12:48.982 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1:C 06 Mar 08:12:48.982 # Redis version=4.0.6, bits=64, commit=00000000, modified=0, pid=1, just started
1:C 06 Mar 08:12:48.982 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
1:M 06 Mar 08:12:48.986 * Running mode=standalone, port=6379.
1:M 06 Mar 08:12:48.986 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128.
1:M 06 Mar 08:12:48.986 # Server initialized
1:M 06 Mar 08:12:48.987 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
1:M 06 Mar 08:12:48.988 * DB loaded from disk: 0.001 seconds
1:M 06 Mar 08:12:48.988 * Ready to accept connections
```
1. Permissions in dockerfile\_redis is correct?
2. How configurate redis with my conf file?
3. What also i need to make the redis work well?
|
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 to /run directory is not granted to user 'redis', the writing fails.
So, do not expose your Redis server port to the Internet and it should fix the issue with malware being able to reach it.
|
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 Name ?: ')
if yname.isdigit():
print ('{0}, can\'t be your name!'.format(yname))
print "Please use alphbetic characters only!."
yname = raw_input("Enter your name:?")
print "Welcome %s !" %yname
```
but I figured in this one is if the user input any character more than one time it will eventually continue...So I did this instead.
```
yname = raw_input("EnterName").isalpha()
while yname == True:
if yname == yname.isalpha():
print "Welcome %s " %(yname)
else:
if yname == yname.isdigit():
print ("Name must be alphabetical only!")
yname = raw_input('Enter Name:').isalpha()
```
This while loop goes on forever, as well as I tried (-) and (+) the raw input variable as I've seen in some tutorials. So I thought of using while loop.
```
name = raw_input("your name"):
while True:
if name > 0 and name.isalpha():
print "Hi %s " %name
elif name < 0 and name.isdigit():
print "Name must be Alphabet characters only!"
try:
name != name.isalpha():
except (ValueError):
print "Something went wrong"
```
|
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 way to have the base class methods apply line wrapping and indentation.
* Am I missing something here?
* Is there a better way to do this (e.g. another module)?
Alternatives?
-------------
I've checked out the [`pretty`](http://pypi.python.org/pypi/pretty/0.1) module, which looks interesting, but doesn't seem to provide a way to customize formatting of classes from other modules without modifying those modules.
I think what I'm looking for is something that would allow me to provide a mapping of types (or maybe functions) that identify types to routines that process a node. The routines that process a node would take a node and return the string representation it, along with a list of child nodes. And so on.
Why I’m looking into pretty-printing
------------------------------------
My end goal is to compactly print custom-formatted sections of a DocBook-formatted `xml.etree.ElementTree`.
(I was surprised to not find more Python support for DocBook. Maybe I missed something there.)
I built some basic functionality into a client called [xmlearn](http://github.com/intuited/xmlearn) that uses [lxml](http://pypi.python.org/pypi/lxml). For example, to dump a Docbook file, you could:
```
xmlearn -i docbook_file.xml dump -f docbook -r book
```
It's pretty half-ass, but it got me the info I was looking for.
[xmlearn](http://github.com/intuited/xmlearn) has other features too, like the ability to build a graph image and do dumps showing the relationships between tags in an XML document. These are pretty much totally unrelated to this question.
You can also perform a dump to an arbitrary depth, or specify an XPath as a set of starting points. The XPath stuff sort of obsoleted the docbook-specific format, so that isn't really well-developed.
This still isn't really an answer for the question. I'm still hoping that there's a readily customizable pretty printer out there somewhere.
|
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 pprint](http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup). It seems to suggest that, in order to enhance `pprint()`, you’d need to:
* subclass `PrettyPrinter`
* override `_format()`
* test for `issubclass()`,
* and (if it's not your class), pass back to `_format()`
Alternative
===========
I think a better approach would be just to have your own `pprint()`, which defers to `pprint.pformat` when it doesn't know what's up.
For example:
```python
'''Extending pprint'''
from pprint import pformat
class CrazyClass: pass
def prettyformat(obj):
if isinstance(obj, CrazyClass):
return "^CrazyFoSho^"
else:
return pformat(obj)
def prettyp(obj):
print(prettyformat(obj))
# test
prettyp([1]*100)
prettyp(CrazyClass())
```
The big upside here is that you don't depend on `pprint` internals. It’s explicit and concise.
The downside is that you’ll have to take care of indentation manually.
|
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 way to have the base class methods apply line wrapping and indentation.
* Am I missing something here?
* Is there a better way to do this (e.g. another module)?
Alternatives?
-------------
I've checked out the [`pretty`](http://pypi.python.org/pypi/pretty/0.1) module, which looks interesting, but doesn't seem to provide a way to customize formatting of classes from other modules without modifying those modules.
I think what I'm looking for is something that would allow me to provide a mapping of types (or maybe functions) that identify types to routines that process a node. The routines that process a node would take a node and return the string representation it, along with a list of child nodes. And so on.
Why I’m looking into pretty-printing
------------------------------------
My end goal is to compactly print custom-formatted sections of a DocBook-formatted `xml.etree.ElementTree`.
(I was surprised to not find more Python support for DocBook. Maybe I missed something there.)
I built some basic functionality into a client called [xmlearn](http://github.com/intuited/xmlearn) that uses [lxml](http://pypi.python.org/pypi/lxml). For example, to dump a Docbook file, you could:
```
xmlearn -i docbook_file.xml dump -f docbook -r book
```
It's pretty half-ass, but it got me the info I was looking for.
[xmlearn](http://github.com/intuited/xmlearn) has other features too, like the ability to build a graph image and do dumps showing the relationships between tags in an XML document. These are pretty much totally unrelated to this question.
You can also perform a dump to an arbitrary depth, or specify an XPath as a set of starting points. The XPath stuff sort of obsoleted the docbook-specific format, so that isn't really well-developed.
This still isn't really an answer for the question. I'm still hoping that there's a readily customizable pretty printer out there somewhere.
|
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):
def _format(self,obj,*args,**kwargs):
if isinstance(obj,float):
obj=round(obj,4)
return pprint.old_printer._format(self,obj,*args,**kwargs)
pprint.PrettyPrinter=MyPrettyPrinter
def pp(obj):
pprint.pprint(obj)
if __name__=='__main__':
x=[1,2,4,6,457,3,8,3,4]
x=[_/17 for _ in x]
pp(x)
```
|
*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 pprint](http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup). It seems to suggest that, in order to enhance `pprint()`, you’d need to:
* subclass `PrettyPrinter`
* override `_format()`
* test for `issubclass()`,
* and (if it's not your class), pass back to `_format()`
Alternative
===========
I think a better approach would be just to have your own `pprint()`, which defers to `pprint.pformat` when it doesn't know what's up.
For example:
```python
'''Extending pprint'''
from pprint import pformat
class CrazyClass: pass
def prettyformat(obj):
if isinstance(obj, CrazyClass):
return "^CrazyFoSho^"
else:
return pformat(obj)
def prettyp(obj):
print(prettyformat(obj))
# test
prettyp([1]*100)
prettyp(CrazyClass())
```
The big upside here is that you don't depend on `pprint` internals. It’s explicit and concise.
The downside is that you’ll have to take care of indentation manually.
|
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 way to have the base class methods apply line wrapping and indentation.
* Am I missing something here?
* Is there a better way to do this (e.g. another module)?
Alternatives?
-------------
I've checked out the [`pretty`](http://pypi.python.org/pypi/pretty/0.1) module, which looks interesting, but doesn't seem to provide a way to customize formatting of classes from other modules without modifying those modules.
I think what I'm looking for is something that would allow me to provide a mapping of types (or maybe functions) that identify types to routines that process a node. The routines that process a node would take a node and return the string representation it, along with a list of child nodes. And so on.
Why I’m looking into pretty-printing
------------------------------------
My end goal is to compactly print custom-formatted sections of a DocBook-formatted `xml.etree.ElementTree`.
(I was surprised to not find more Python support for DocBook. Maybe I missed something there.)
I built some basic functionality into a client called [xmlearn](http://github.com/intuited/xmlearn) that uses [lxml](http://pypi.python.org/pypi/lxml). For example, to dump a Docbook file, you could:
```
xmlearn -i docbook_file.xml dump -f docbook -r book
```
It's pretty half-ass, but it got me the info I was looking for.
[xmlearn](http://github.com/intuited/xmlearn) has other features too, like the ability to build a graph image and do dumps showing the relationships between tags in an XML document. These are pretty much totally unrelated to this question.
You can also perform a dump to an arbitrary depth, or specify an XPath as a set of starting points. The XPath stuff sort of obsoleted the docbook-specific format, so that isn't really well-developed.
This still isn't really an answer for the question. I'm still hoping that there's a readily customizable pretty printer out there somewhere.
|
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):
def _format(self,obj,*args,**kwargs):
if isinstance(obj,float):
obj=round(obj,4)
return pprint.old_printer._format(self,obj,*args,**kwargs)
pprint.PrettyPrinter=MyPrettyPrinter
def pp(obj):
pprint.pprint(obj)
if __name__=='__main__':
x=[1,2,4,6,457,3,8,3,4]
x=[_/17 for _ in x]
pp(x)
```
|
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 way to have the base class methods apply line wrapping and indentation.
* Am I missing something here?
* Is there a better way to do this (e.g. another module)?
Alternatives?
-------------
I've checked out the [`pretty`](http://pypi.python.org/pypi/pretty/0.1) module, which looks interesting, but doesn't seem to provide a way to customize formatting of classes from other modules without modifying those modules.
I think what I'm looking for is something that would allow me to provide a mapping of types (or maybe functions) that identify types to routines that process a node. The routines that process a node would take a node and return the string representation it, along with a list of child nodes. And so on.
Why I’m looking into pretty-printing
------------------------------------
My end goal is to compactly print custom-formatted sections of a DocBook-formatted `xml.etree.ElementTree`.
(I was surprised to not find more Python support for DocBook. Maybe I missed something there.)
I built some basic functionality into a client called [xmlearn](http://github.com/intuited/xmlearn) that uses [lxml](http://pypi.python.org/pypi/lxml). For example, to dump a Docbook file, you could:
```
xmlearn -i docbook_file.xml dump -f docbook -r book
```
It's pretty half-ass, but it got me the info I was looking for.
[xmlearn](http://github.com/intuited/xmlearn) has other features too, like the ability to build a graph image and do dumps showing the relationships between tags in an XML document. These are pretty much totally unrelated to this question.
You can also perform a dump to an arbitrary depth, or specify an XPath as a set of starting points. The XPath stuff sort of obsoleted the docbook-specific format, so that isn't really well-developed.
This still isn't really an answer for the question. I'm still hoping that there's a readily customizable pretty printer out there somewhere.
|
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/pprint.py#L180-L192).
Here is how I added a custom pretty printer for [MatchPy's Operation](https://matchpy.readthedocs.io/en/latest/api/matchpy.expressions.expressions.html#matchpy.expressions.expressions.Operation) type:
```
import pprint
import matchpy
def _pprint_operation(self, object, stream, indent, allowance, context, level):
"""
Modified from pprint dict https://github.com/python/cpython/blob/3.7/Lib/pprint.py#L194
"""
operands = object.operands
if not operands:
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "(")
self._format_items(
operands, stream, indent + len(cls.__name__), allowance + 1, context, level
)
stream.write(")")
pprint.PrettyPrinter._dispatch[matchpy.Operation.__repr__] = _pprint_operation
```
Now if I use `pprint.pprint` on any object that has the same `__repr__` as `matchpy.Operation`, it will use this method to pretty print it. This works on subclasses as well, as long as they don't override the `__repr__`, which makes some sense! If you have the same `__repr__` you have the same pretty printing behavior.
Here is an example of the pretty printing some MatchPy operations now:
```
ReshapeVector(Vector(Scalar('1')),
Vector(Index(Vector(Scalar('0')),
If(Scalar('True'),
Scalar("ReshapeVector(Vector(Scalar('2'), Scalar('2')), Iota(Scalar('10')))"),
Scalar("ReshapeVector(Vector(Scalar('2'), Scalar('2')), Ravel(Iota(Scalar('10'))))")))))
```
|
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 way to have the base class methods apply line wrapping and indentation.
* Am I missing something here?
* Is there a better way to do this (e.g. another module)?
Alternatives?
-------------
I've checked out the [`pretty`](http://pypi.python.org/pypi/pretty/0.1) module, which looks interesting, but doesn't seem to provide a way to customize formatting of classes from other modules without modifying those modules.
I think what I'm looking for is something that would allow me to provide a mapping of types (or maybe functions) that identify types to routines that process a node. The routines that process a node would take a node and return the string representation it, along with a list of child nodes. And so on.
Why I’m looking into pretty-printing
------------------------------------
My end goal is to compactly print custom-formatted sections of a DocBook-formatted `xml.etree.ElementTree`.
(I was surprised to not find more Python support for DocBook. Maybe I missed something there.)
I built some basic functionality into a client called [xmlearn](http://github.com/intuited/xmlearn) that uses [lxml](http://pypi.python.org/pypi/lxml). For example, to dump a Docbook file, you could:
```
xmlearn -i docbook_file.xml dump -f docbook -r book
```
It's pretty half-ass, but it got me the info I was looking for.
[xmlearn](http://github.com/intuited/xmlearn) has other features too, like the ability to build a graph image and do dumps showing the relationships between tags in an XML document. These are pretty much totally unrelated to this question.
You can also perform a dump to an arbitrary depth, or specify an XPath as a set of starting points. The XPath stuff sort of obsoleted the docbook-specific format, so that isn't really well-developed.
This still isn't really an answer for the question. I'm still hoping that there's a readily customizable pretty printer out there somewhere.
|
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):
def _format(self,obj,*args,**kwargs):
if isinstance(obj,float):
obj=round(obj,4)
return pprint.old_printer._format(self,obj,*args,**kwargs)
pprint.PrettyPrinter=MyPrettyPrinter
def pp(obj):
pprint.pprint(obj)
if __name__=='__main__':
x=[1,2,4,6,457,3,8,3,4]
x=[_/17 for _ in x]
pp(x)
```
|
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/pprint.py#L180-L192).
Here is how I added a custom pretty printer for [MatchPy's Operation](https://matchpy.readthedocs.io/en/latest/api/matchpy.expressions.expressions.html#matchpy.expressions.expressions.Operation) type:
```
import pprint
import matchpy
def _pprint_operation(self, object, stream, indent, allowance, context, level):
"""
Modified from pprint dict https://github.com/python/cpython/blob/3.7/Lib/pprint.py#L194
"""
operands = object.operands
if not operands:
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "(")
self._format_items(
operands, stream, indent + len(cls.__name__), allowance + 1, context, level
)
stream.write(")")
pprint.PrettyPrinter._dispatch[matchpy.Operation.__repr__] = _pprint_operation
```
Now if I use `pprint.pprint` on any object that has the same `__repr__` as `matchpy.Operation`, it will use this method to pretty print it. This works on subclasses as well, as long as they don't override the `__repr__`, which makes some sense! If you have the same `__repr__` you have the same pretty printing behavior.
Here is an example of the pretty printing some MatchPy operations now:
```
ReshapeVector(Vector(Scalar('1')),
Vector(Index(Vector(Scalar('0')),
If(Scalar('True'),
Scalar("ReshapeVector(Vector(Scalar('2'), Scalar('2')), Iota(Scalar('10')))"),
Scalar("ReshapeVector(Vector(Scalar('2'), Scalar('2')), Ravel(Iota(Scalar('10'))))")))))
```
|
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:
self.cfg = yaml.load(fs.read())
```
Now what should I do when writing my unit test if I don't want to use the explicitly specified file? Instead I want to create a temporary `config.yml` to be used for testing.
I could simply allow for a specified filename in `__init__()`, but I strongly prefer forcing the filename location. I.e. like this
```
class YamlConfig(object):
def __init__(self, filename=os.path.join(os.path.expanduser('~'), '.hanzo\\config.yml')):
with open(filename) as fs:
self.cfg = yaml.load(fs.read())
```
Is there other ways to solve my issue? I guess it might be possible using `mock` right way? Also feel free to give any comments about upside and downside.
|
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 efficiently.
```
import numpy as np
import json
a = np.array(range(25), dtype=np.uint8).reshape(5, 5)
print(a)
print(json.dumps(a.tolist()))
```
**output**
```
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]
```
`.tolist` will convert the array elements to native Python types (int or float) if it can do so losslessly. If you use other datatypes I suggest you convert them to something portable before calling `.tolist`.
|
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):
return obj.tolist()
return JSONEncoder.default(self, obj)
class NumpyArrayDecoder(JSONDecoder):
def default(self, obj):
if isinstance(obj, list):
return numpy.asarray(obj)
return JSONEncoder.default(self, obj)
# ********************************** #
if __name__ == "__main__":
# TO TEST
numpyArrayOne = numpy.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
numpyArrayTwo = numpy.array([[51, 61, 91], [121 ,118, 127]])
# Serialization
numpyData = {"arrayOne": numpyArrayOne, "arrayTwo": numpyArrayTwo}
print("Original Data: \n")
print(numpyData)
print("\nSerialize NumPy array into JSON and write into a file")
with open("numpyData.json", "w") as write_file:
json.dump(numpyData, write_file, cls=NumpyArrayEncoder)
print("Done writing serialized NumPy array into file")
# Deserialization
print("Started Reading JSON file")
with open("numpyData.json", "r") as read_file:
print("Converting JSON encoded data into Numpy array")
decodedArray = json.load(read_file, cls=NumpyArrayDecoder)
print("Re-Imported Data: \n")
print(decodedArray)
```
|
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 NameError: name 's' is not defined
>
>
>
In this instance I typed the letter "s".
Below is the portion of the code that gives me the issue. The program runs flawlessly other than if you give it letters or symbols.
I want it to print "Invalid input" instead of crashing if possible.
Is there a trick that I have to do with another elif statement and isalpha function?
```
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()
else:
print ("Invalid input")
print(" ")
```
I tried a few variations of this with no success.
```
elif str(run_prog):
print ("Invalid: input")
print(" ")
```
I appreciate any feedback even if it is for me to reference a specific part of the python manual.
Thanks!
|
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 times_run == 0:
sys.stdout.write("Would you like to run the calculation?\n"
"Press 1 for YES.\n"
"Press 2 for NO.\n")
try:
run_prog = int(sys.stdin.readline())
except ValueError:
run_prog = 0
if not (1 <= run_prog <= 2):
sys.stdout.write("Invalid input.\n")
continue
# ... what you have ...
```
|
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 NameError: name 's' is not defined
>
>
>
In this instance I typed the letter "s".
Below is the portion of the code that gives me the issue. The program runs flawlessly other than if you give it letters or symbols.
I want it to print "Invalid input" instead of crashing if possible.
Is there a trick that I have to do with another elif statement and isalpha function?
```
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()
else:
print ("Invalid input")
print(" ")
```
I tried a few variations of this with no success.
```
elif str(run_prog):
print ("Invalid: input")
print(" ")
```
I appreciate any feedback even if it is for me to reference a specific part of the python manual.
Thanks!
|
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 1 and 2.')
```
If the user writes `s` the text `Please enter a number between 1 and 2` will appear
|
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 predict has lost one column (attribute) which is `Age`
Is it still possible to predict the target attribute 'y`?
Note: - I have my model exported with the `pickel` python library and trying to predict the new dataset as folllow:
```
model=pickle.load(open('gaussian.pkl','rb'))
print(model.predict(inputs)) # ----------------> inputs which has now only 4 attributes
```
And this gives an error:
>
> ValueError: operands could not be broadcast together with shapes (100,4) (5,)
>
>
>
How can I tackle this?
|
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 will really be better to re-train your model on the features without age if this is possible.
|
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 message:
```
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
```
this is my code:
```
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
```
I would absolutely love any comments/suggestions about the cause of the error
|
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.listName.value = ""
}, false);
```
```html
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
```
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like `required` to the `<input />` element, and the browser will handle it all for you.
|
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 message:
```
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
```
this is my code:
```
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
```
I would absolutely love any comments/suggestions about the cause of the error
|
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.listName.value = ""
}, false);
```
```html
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
```
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like `required` to the `<input />` element, and the browser will handle it all for you.
|
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>', {
text: $('#input_listName').val()
}));
}
});
```
Hopefully that does the trick!
|
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 message:
```
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
```
this is my code:
```
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
```
I would absolutely love any comments/suggestions about the cause of the error
|
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.listName.value = ""
}, false);
```
```html
<form id="input_listName">
<input type="text" name="listName" />
<button type="submit">add</button>
</form>
<ul class="ul_current"></ul>
```
Making it a form provides all of the benefits that a browser does for you. On desktop, you can press Enter to submit it. On mobile, the virtual keyboard may also provide a quick-access submit button. You could even add validation rules like `required` to the `<input />` element, and the browser will handle it all for you.
|
`<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 have a look at this cheat sheet to know more about keycodes <https://css-tricks.com/snippets/javascript/javascript-keycodes/>
```js
$('#btn_createList').keypress(function(event){
if($('#input_listName').val()) {
if (event.keyCode == 13) {
$('.ul_current').append($('<li>', {
text: $('#input_listName').val()
}));
}
}
});
```
```html
<div id="btn_createList">
<input id="input_listName" type="text">
<ul class="ul_current">
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
```
|
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 = open("http://192.128.0.3/Rohith/data.json","w+");
fileobj.write(jsonObj);
```
But it is not creating the file there although I can create on the same folder (cgi-bin) of my python script. Can anyone tell me why it is not creating the file in the given destination?
|
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/data.json'
fileobj = open(out_file, 'w+') # w+ mode creates the file if its not exists
fileobj.write(jsonObj)
```
If it still not working, try changing the file mode to `a+` from `w+`
>
> **a+** Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. **If the file does not exist, it creates a new file for reading and writing.**
>
>
>
|
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 = open("http://192.128.0.3/Rohith/data.json","w+");
fileobj.write(jsonObj);
```
But it is not creating the file there although I can create on the same folder (cgi-bin) of my python script. Can anyone tell me why it is not creating the file in the given destination?
|
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 = open("http://192.128.0.3/Rohith/data.json","w+");
fileobj.write(jsonObj);
```
But it is not creating the file there although I can create on the same folder (cgi-bin) of my python script. Can anyone tell me why it is not creating the file in the given destination?
|
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/data.json'
fileobj = open(out_file, 'w+') # w+ mode creates the file if its not exists
fileobj.write(jsonObj)
```
If it still not working, try changing the file mode to `a+` from `w+`
>
> **a+** Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. **If the file does not exist, it creates a new file for reading and writing.**
>
>
>
|
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't be used on deques, I wonder what the most pythonic way of handling this is?
My solution is to import the copy module and then iterate over a copy, like `for item in copy(my_deque):` which is fine, but since I searched high and low for this topic I figured I'd post here to ask?
|
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 so.
---
Bare in mind this solution is only valid if the deque is being modified in the same thread (i.e. inside the loop). Else, be aware that `list(my_deque)` is not atomic, and is also iterating over the deque. This means that if another thread alters the deque while it runs, you end up with the same error. If you're in a multithreaded environment, use a lock.
|
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 needing to create a list is to use a `while` loop with some boolean var to control the conditions. This provides for a time complexity of O(1).
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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/>. Code to get you started is also hosted here: <https://github.com/srakowski/ElectronLikeVS>
To summarize, you need to pass frame: false when you create the BrowserWindow:
```
mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
```
Then create and add control buttons for your title bar:
```
<div id="title-bar">
<div id="title">My Life For The Code</div>
<div id="title-bar-btns">
<button id="min-btn">-</button>
<button id="max-btn">+</button>
<button id="close-btn">x</button>
</div>
</div>
```
Bind in the max/min/close functions in js:
```
(function () {
var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
function init() {
document.getElementById("min-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.minimize();
});
document.getElementById("max-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.maximize();
});
document.getElementById("close-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.close();
});
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
init();
}
};
})();
```
Styling the window can be tricky, but the key use to use special properties from webkit. Here is some minimal CSS:
```
body {
padding: 0px;
margin: 0px;
}
#title-bar {
-webkit-app-region: drag;
height: 24px;
background-color: darkviolet;
padding: none;
margin: 0px;
}
#title {
position: fixed;
top: 0px;
left: 6px;
}
#title-bar-btns {
-webkit-app-region: no-drag;
position: fixed;
top: 0px;
right: 6px;
}
```
Note that these are important:
```
-webkit-app-region: drag;
-webkit-app-region: no-drag;
```
-webkit-app-region: drag on your 'title bar' region will make it so that you can drag it around as is common with windows. The no-drag is applied to the buttons so that they do not cause dragging.
|
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 Electron)*.
[](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial)
It includes a fix for the resizing issue Shawn mentioned, and also switches between the maximise and restore buttons, even when e.g. the window is maximised by dragging the it to the top of the screen.
### Quick reference
* Title bar height: `32px`
* Title bar title font-size: `12px`
* Window control buttons: `46px` wide, `32px` high
* Window control button assets from font `Segoe MDL2 Assets` ([docs here](https://learn.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font)), size: `10px`
* Minimise: ``
* Maximise: ``
* Restore: ``
* Close: ``
* Window control button colours: varies between UWP apps, but seems to be
* Dark mode apps (white window controls): `#FFF`
* Light mode apps (black window controls): `#171717`
* Close button colours
* Hover (`:hover`): background `#E81123`, colour `#FFF`
* Pressed (`:active`): background `#F1707A`, colour `#000` or `#171717`
Note: in the tutorial I have switched to PNG icons with different sizes for pixel-perfect scaling, but I leave the Segoe MDL2 Assets font characters above as an alternative
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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/>. Code to get you started is also hosted here: <https://github.com/srakowski/ElectronLikeVS>
To summarize, you need to pass frame: false when you create the BrowserWindow:
```
mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
```
Then create and add control buttons for your title bar:
```
<div id="title-bar">
<div id="title">My Life For The Code</div>
<div id="title-bar-btns">
<button id="min-btn">-</button>
<button id="max-btn">+</button>
<button id="close-btn">x</button>
</div>
</div>
```
Bind in the max/min/close functions in js:
```
(function () {
var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
function init() {
document.getElementById("min-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.minimize();
});
document.getElementById("max-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.maximize();
});
document.getElementById("close-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.close();
});
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
init();
}
};
})();
```
Styling the window can be tricky, but the key use to use special properties from webkit. Here is some minimal CSS:
```
body {
padding: 0px;
margin: 0px;
}
#title-bar {
-webkit-app-region: drag;
height: 24px;
background-color: darkviolet;
padding: none;
margin: 0px;
}
#title {
position: fixed;
top: 0px;
left: 6px;
}
#title-bar-btns {
-webkit-app-region: no-drag;
position: fixed;
top: 0px;
right: 6px;
}
```
Note that these are important:
```
-webkit-app-region: drag;
-webkit-app-region: no-drag;
```
-webkit-app-region: drag on your 'title bar' region will make it so that you can drag it around as is common with windows. The no-drag is applied to the buttons so that they do not cause dragging.
|
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.querySelector("#maximize");
var quit = document.querySelector("#quit");
minimize.addEventListener("click", () => {
win.minimize();
});
maximize.addEventListener("click", () => {
win.setFullScreen(!win.isFullScreen());
});
quit.addEventListener("click", () => {
win.close();
});
```
```css
nav {
display: block;
width: 100%;
height: 30px;
background-color: #333333;
-webkit-app-region: drag;
-webkit-user-select: none;
position: fixed;
z-index: 1;
}
nav #titleshown {
width: 30%;
height: 100%;
line-height: 30px;
color: #f7f7f7;
float: left;
padding: 0 0 0 1em;
}
nav #buttons {
float: right;
width: 150px;
height: 100%;
line-height: 30px;
background-color: #222222;
-webkit-app-region: no-drag;
}
nav #buttons #minimize,
nav #buttons #maximize,
nav #buttons #quit {
float: left;
height: 100%;
width: 33%;
text-align: center;
color: #f7f7f7;
cursor: default;
}
nav #buttons #minimize:hover {
background-color: #333333aa;
}
nav #buttons #maximize:hover {
background-color: #333333aa;
}
nav #buttons #quit:hover {
background-color: #ff0000dd;
}
main {
padding-top: 30px;
overflow: auto;
height: calc(100vh - 30px);
position: absolute;
top: 30px;
left: 0;
padding: 0;
width: 100%;
}
```
```html
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<nav>
<div id="titleshown"></div>
<div id="buttons">
<div id="minimize"><span>‐</span></div>
<div id="maximize"><span>□</span></div>
<div id="quit"><span>×</span></div>
</div>
</nav>
<main>
<div class="container">
<h1>Hello World!</h1>
</div>
</main>
</body>
</html>
```
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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/>. Code to get you started is also hosted here: <https://github.com/srakowski/ElectronLikeVS>
To summarize, you need to pass frame: false when you create the BrowserWindow:
```
mainWindow = new BrowserWindow({width: 800, height: 600, frame: false});
```
Then create and add control buttons for your title bar:
```
<div id="title-bar">
<div id="title">My Life For The Code</div>
<div id="title-bar-btns">
<button id="min-btn">-</button>
<button id="max-btn">+</button>
<button id="close-btn">x</button>
</div>
</div>
```
Bind in the max/min/close functions in js:
```
(function () {
var remote = require('remote');
var BrowserWindow = remote.require('browser-window');
function init() {
document.getElementById("min-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.minimize();
});
document.getElementById("max-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.maximize();
});
document.getElementById("close-btn").addEventListener("click", function (e) {
var window = BrowserWindow.getFocusedWindow();
window.close();
});
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
init();
}
};
})();
```
Styling the window can be tricky, but the key use to use special properties from webkit. Here is some minimal CSS:
```
body {
padding: 0px;
margin: 0px;
}
#title-bar {
-webkit-app-region: drag;
height: 24px;
background-color: darkviolet;
padding: none;
margin: 0px;
}
#title {
position: fixed;
top: 0px;
left: 6px;
}
#title-bar-btns {
-webkit-app-region: no-drag;
position: fixed;
top: 0px;
right: 6px;
}
```
Note that these are important:
```
-webkit-app-region: drag;
-webkit-app-region: no-drag;
```
-webkit-app-region: drag on your 'title bar' region will make it so that you can drag it around as is common with windows. The no-drag is applied to the buttons so that they do not cause dragging.
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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 Electron)*.
[](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial)
It includes a fix for the resizing issue Shawn mentioned, and also switches between the maximise and restore buttons, even when e.g. the window is maximised by dragging the it to the top of the screen.
### Quick reference
* Title bar height: `32px`
* Title bar title font-size: `12px`
* Window control buttons: `46px` wide, `32px` high
* Window control button assets from font `Segoe MDL2 Assets` ([docs here](https://learn.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font)), size: `10px`
* Minimise: ``
* Maximise: ``
* Restore: ``
* Close: ``
* Window control button colours: varies between UWP apps, but seems to be
* Dark mode apps (white window controls): `#FFF`
* Light mode apps (black window controls): `#171717`
* Close button colours
* Hover (`:hover`): background `#E81123`, colour `#FFF`
* Pressed (`:active`): background `#F1707A`, colour `#000` or `#171717`
Note: in the tutorial I have switched to PNG icons with different sizes for pixel-perfect scaling, but I leave the Segoe MDL2 Assets font characters above as an alternative
|
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.querySelector("#maximize");
var quit = document.querySelector("#quit");
minimize.addEventListener("click", () => {
win.minimize();
});
maximize.addEventListener("click", () => {
win.setFullScreen(!win.isFullScreen());
});
quit.addEventListener("click", () => {
win.close();
});
```
```css
nav {
display: block;
width: 100%;
height: 30px;
background-color: #333333;
-webkit-app-region: drag;
-webkit-user-select: none;
position: fixed;
z-index: 1;
}
nav #titleshown {
width: 30%;
height: 100%;
line-height: 30px;
color: #f7f7f7;
float: left;
padding: 0 0 0 1em;
}
nav #buttons {
float: right;
width: 150px;
height: 100%;
line-height: 30px;
background-color: #222222;
-webkit-app-region: no-drag;
}
nav #buttons #minimize,
nav #buttons #maximize,
nav #buttons #quit {
float: left;
height: 100%;
width: 33%;
text-align: center;
color: #f7f7f7;
cursor: default;
}
nav #buttons #minimize:hover {
background-color: #333333aa;
}
nav #buttons #maximize:hover {
background-color: #333333aa;
}
nav #buttons #quit:hover {
background-color: #ff0000dd;
}
main {
padding-top: 30px;
overflow: auto;
height: calc(100vh - 30px);
position: absolute;
top: 30px;
left: 0;
padding: 0;
width: 100%;
}
```
```html
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<nav>
<div id="titleshown"></div>
<div id="buttons">
<div id="minimize"><span>‐</span></div>
<div id="maximize"><span>□</span></div>
<div id="quit"><span>×</span></div>
</div>
</nav>
<main>
<div class="container">
<h1>Hello World!</h1>
</div>
</main>
</body>
</html>
```
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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 Electron)*.
[](https://github.com/binaryfunt/electron-seamless-titlebar-tutorial)
It includes a fix for the resizing issue Shawn mentioned, and also switches between the maximise and restore buttons, even when e.g. the window is maximised by dragging the it to the top of the screen.
### Quick reference
* Title bar height: `32px`
* Title bar title font-size: `12px`
* Window control buttons: `46px` wide, `32px` high
* Window control button assets from font `Segoe MDL2 Assets` ([docs here](https://learn.microsoft.com/en-us/windows/uwp/design/style/segoe-ui-symbol-font)), size: `10px`
* Minimise: ``
* Maximise: ``
* Restore: ``
* Close: ``
* Window control button colours: varies between UWP apps, but seems to be
* Dark mode apps (white window controls): `#FFF`
* Light mode apps (black window controls): `#171717`
* Close button colours
* Hover (`:hover`): background `#E81123`, colour `#FFF`
* Pressed (`:active`): background `#F1707A`, colour `#000` or `#171717`
Note: in the tutorial I have switched to PNG icons with different sizes for pixel-perfect scaling, but I leave the Segoe MDL2 Assets font characters above as an alternative
|
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 drag and drop files into the text controls and then have the file contents imported into dataframes for analysis with pandas. So far everything is happy. Other than the fact that the program will not quit. I think it has to do with how I am defining the window and the frame. I have removed a significant amount of the functionality from the script to help simplify things. Please let me know what I am missing.
Thanks
Tyler
```
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress
class MyFileDropTarget(wx.FileDropTarget):
#----------------------------------------------------------------------
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
#----------------------------------------------------------------------
def OnDropFiles(self, x, y, filenames):
self.window.SetInsertionPointEnd(y)
#self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
# (len(filenames), x, y), y)
for filepath in filenames:
self.window.updateText(filepath + '\n', y)
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
file_drop_target = MyFileDropTarget(self)
self.CreateStatusBar() # A Statusbar in the bottom of the window
# Creating the menubar.
menubar = wx.MenuBar()
fileMenu = wx.Menu()
helpMenu = wx.Menu()
menubar.Append(fileMenu, '&File')
menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
#self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
fileMenu.AppendSeparator()
menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
menubar.Append(helpMenu, '&Help')
menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About"," Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.SetMenuBar(menubar)
#Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
grid = wx.GridBagSizer(hgap=5, vgap=5)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
#Create a button
self.button = wx.Button(self, label="Test")
#self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)
# Radio Boxes
sysList = ['QEXL','QEX10','QEX7']
wlList = ['1100', '1400', '1800']
sys = wx.RadioBox(self, label="What system are you calibrating ?", pos=(20, 40), choices=sysList, majorDimension=3,
style=wx.RA_SPECIFY_COLS)
grid.Add(sys, pos=(1,0), span=(1,3))
WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?", pos=(20, 100), choices=wlList, majorDimension=0,
style=wx.RA_SPECIFY_COLS)
grid.Add(WL, pos=(2,0), span=(1,3))
self.lblname = wx.StaticText(self, label="Cal File 1 :")
grid.Add(self.lblname, pos=(3,0))
self.Cal_1 = wx.TextCtrl(self, name="Cal_1", value="", size=(240,-1))
self.Cal_1.SetDropTarget(file_drop_target)
grid.Add(self.Cal_1, pos=(3,1))
self.lblname = wx.StaticText(self, label="Cal File 2 :")
grid.Add(self.lblname, pos=(4,0))
self.Cal_2 = wx.TextCtrl(self, value="", name="Cal_2", size=(240,-1))
self.Cal_2.SetDropTarget(file_drop_target)
grid.Add(self.Cal_2, pos=(4,1))
self.lblname = wx.StaticText(self, label="Cal File 3 :")
grid.Add(self.lblname, pos=(5,0))
self.Cal_3 = wx.TextCtrl(self, value="", name="Cal_3", size=(240,-1))
self.Cal_3.SetDropTarget(file_drop_target)
grid.Add(self.Cal_3, pos=(5,1))
hSizer.Add(grid, 0, wx.ALL, 5)
mainSizer.Add(hSizer, 0, wx.ALL, 5)
mainSizer.Add(self.button, 0, wx.CENTER)
self.SetSizerAndFit(mainSizer)
self.Show(True)
def OnAbout(self,e):
# A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
dlg.ShowModal() # Show it
dlg.Destroy() # finally destroy it when finished.
def OnExit(self,e):
# Close the frame.
self.Close(True)
def SetInsertionPointEnd(self, y):
if y <= -31:
self.Cal_1.SetInsertionPointEnd()
elif y >= -1:
self.Cal_3.SetInsertionPointEnd()
else:
self.Cal_2.SetInsertionPointEnd()
def updateText(self, text, y):
if y <= -31:
self.Cal_1.WriteText(text)
elif y >= -1:
self.Cal_3.WriteText(text)
else:
self.Cal_2.WriteText(text)
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()
```
|
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.querySelector("#maximize");
var quit = document.querySelector("#quit");
minimize.addEventListener("click", () => {
win.minimize();
});
maximize.addEventListener("click", () => {
win.setFullScreen(!win.isFullScreen());
});
quit.addEventListener("click", () => {
win.close();
});
```
```css
nav {
display: block;
width: 100%;
height: 30px;
background-color: #333333;
-webkit-app-region: drag;
-webkit-user-select: none;
position: fixed;
z-index: 1;
}
nav #titleshown {
width: 30%;
height: 100%;
line-height: 30px;
color: #f7f7f7;
float: left;
padding: 0 0 0 1em;
}
nav #buttons {
float: right;
width: 150px;
height: 100%;
line-height: 30px;
background-color: #222222;
-webkit-app-region: no-drag;
}
nav #buttons #minimize,
nav #buttons #maximize,
nav #buttons #quit {
float: left;
height: 100%;
width: 33%;
text-align: center;
color: #f7f7f7;
cursor: default;
}
nav #buttons #minimize:hover {
background-color: #333333aa;
}
nav #buttons #maximize:hover {
background-color: #333333aa;
}
nav #buttons #quit:hover {
background-color: #ff0000dd;
}
main {
padding-top: 30px;
overflow: auto;
height: calc(100vh - 30px);
position: absolute;
top: 30px;
left: 0;
padding: 0;
width: 100%;
}
```
```html
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<nav>
<div id="titleshown"></div>
<div id="buttons">
<div id="minimize"><span>‐</span></div>
<div id="maximize"><span>□</span></div>
<div id="quit"><span>×</span></div>
</div>
</nav>
<main>
<div class="container">
<h1>Hello World!</h1>
</div>
</main>
</body>
</html>
```
|
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_chunk3.npz')
# Merge each of the 7 arrays of the 3 files
arr_0 = np.concatenate([data_1['arr_0'], data_2['arr_0'], data_3['arr_0']])
arr_1 = np.concatenate([data_1['arr_1'], data_2['arr_1'], data_3['arr_1']])
arr_2 = np.concatenate([data_1['arr_2'], data_2['arr_2'], data_3['arr_2']])
arr_3 = np.concatenate([data_1['arr_3'], data_2['arr_3'], data_3['arr_3']])
arr_4 = np.concatenate([data_1['arr_4'], data_2['arr_4'], data_3['arr_4']])
arr_5 = np.concatenate([data_1['arr_5'], data_2['arr_5'], data_3['arr_5']])
arr_6 = np.concatenate([data_1['arr_6'], data_2['arr_6'], data_3['arr_6']])
# Save the new npz file
np.savez('Data_new.npz', arr_0, arr_1, arr_2, arr_3, arr_4, arr_5, arr_6 )
```
|
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 was created using \*\*kwargs and not simply \*args, one could do the following:
```
import numpy as np
data_all = [np.load(fname) for fname in file_list]
merged_data = {}
for data in data_all:
[merged_data.update({k: v}) for k, v in data.items()]
np.savez('new_file.npz', **merged_data)
```
I was using python 3.7.7 with numpy 1.18.1.
Cheers!
|
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
```
and then it proceeds to doing things that I do understand:
```
print "we are going to erase %r." % filename
print "if you don't want that, hit CTRL-C (^C)."
print "if you do want that, hit RETURN."
raw_input("?")
print "opening the file..."
target = open(filename, 'w')
```
What does the first part mean?
P.S. the error I get is:
>
> syntaxError Unexpected character after line continuation character
>
>
>
|
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 variables on the left-hand-side as are items in the iterable on the right-hand-side.
The code you show seems ok, I don't know why you are getting a syntax-error there.
|
`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.
But I do not see any `\` in your code...
|
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
```
and then it proceeds to doing things that I do understand:
```
print "we are going to erase %r." % filename
print "if you don't want that, hit CTRL-C (^C)."
print "if you do want that, hit RETURN."
raw_input("?")
print "opening the file..."
target = open(filename, 'w')
```
What does the first part mean?
P.S. the error I get is:
>
> syntaxError Unexpected character after line continuation character
>
>
>
|
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 variables on the left-hand-side as are items in the iterable on the right-hand-side.
The code you show seems ok, I don't know why you are getting a syntax-error there.
|
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 going to ask you for three lines.
line 1:
line 2:
line 3:
I'm going to write these to the file.
And finally, we close it.
$
```
This should solve your problem
|
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 seems math can not calculate inverse sec functions? I also understand that sec(x) = 1/cos(x) but when I sub 1/cos(x) into the equation instead and algebraically solve for x it becomes a non real result :/.
The code I have is as follows:
```
print("This program calculates the optimum angles to launch a projectile from a given range of heights and a initial speed.")
x = input("Input file name containing list of heights (m): ")
f = open(x, "r")
for line in f:
heights = line
print("the heights you have selected are : ", heights)
f.close()
speed = float(input("Input your initial speed (m/s): "))
print("The initial speed you have selected is : ", speed)
ran0 = speed*speed/9.8
print(ran0)
f = open(x, "r")
for line in f:
heights = (line)
import math
angle = (math.asec(1+(ran0/float(heights))))/2
print(angle)
f.close()
```
So my main question is, is there any way to find the inverse sec of anything in python without installing and importing something else?
I realise this may be more of a math based problem than a coding problem however any help is appreciated :).
|
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 seems math can not calculate inverse sec functions? I also understand that sec(x) = 1/cos(x) but when I sub 1/cos(x) into the equation instead and algebraically solve for x it becomes a non real result :/.
The code I have is as follows:
```
print("This program calculates the optimum angles to launch a projectile from a given range of heights and a initial speed.")
x = input("Input file name containing list of heights (m): ")
f = open(x, "r")
for line in f:
heights = line
print("the heights you have selected are : ", heights)
f.close()
speed = float(input("Input your initial speed (m/s): "))
print("The initial speed you have selected is : ", speed)
ran0 = speed*speed/9.8
print(ran0)
f = open(x, "r")
for line in f:
heights = (line)
import math
angle = (math.asec(1+(ran0/float(heights))))/2
print(angle)
f.close()
```
So my main question is, is there any way to find the inverse sec of anything in python without installing and importing something else?
I realise this may be more of a math based problem than a coding problem however any help is appreciated :).
|
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 not defined from -1 to 1
If you have a height lower than zero, and so the result of `(ran0/float(heights))` is between -2 and 0, your angle will be non real.
I don't really know if this is what you asked for, but I hope it helps.
|
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 seems math can not calculate inverse sec functions? I also understand that sec(x) = 1/cos(x) but when I sub 1/cos(x) into the equation instead and algebraically solve for x it becomes a non real result :/.
The code I have is as follows:
```
print("This program calculates the optimum angles to launch a projectile from a given range of heights and a initial speed.")
x = input("Input file name containing list of heights (m): ")
f = open(x, "r")
for line in f:
heights = line
print("the heights you have selected are : ", heights)
f.close()
speed = float(input("Input your initial speed (m/s): "))
print("The initial speed you have selected is : ", speed)
ran0 = speed*speed/9.8
print(ran0)
f = open(x, "r")
for line in f:
heights = (line)
import math
angle = (math.asec(1+(ran0/float(heights))))/2
print(angle)
f.close()
```
So my main question is, is there any way to find the inverse sec of anything in python without installing and importing something else?
I realise this may be more of a math based problem than a coding problem however any help is appreciated :).
|
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_trigonometric_functions).
---
Alternatively, you could use [Taylor series](https://en.wikipedia.org/wiki/Taylor_series) expansions, which always come in polynomial form, so, although that is only an approximation in a neighborhood of a given point, it would not require `math`.
For `asec(x)`, its Taylor expansion in a neighborhood of `±∞` (also known as [Laurent series](https://en.wikipedia.org/wiki/Laurent_series)) [is given by](https://www.wolframalpha.com/input/?i=asec%28x%29) (without using `math`):
```
def asec_taylor(x, pi=3.14159265):
if x == 0:
return 1j * float('inf')
else:
return pi / 2 - 1 / x - 1 / (6 * x ** 3) - 3 / (40 * x ** 5)
```
---
You can quickly check that the farther you are from 0, the better the approximation holds:
```
for x in range(-10, 10):
print(x, asec(x), asec_taylor(x))
```
```none
-10 1.6709637479564565 1.670963741666667
-9 1.6821373411358604 1.6821373299281108
-8 1.696124157962962 1.6961241346516926
-7 1.714143895700262 1.7141438389326868
-6 1.7382444060145859 1.7382442416666668
-5 1.7721542475852274 1.7721536583333335
-4 1.8234765819369754 1.823473733854167
-3 1.9106332362490186 1.910611139814815
-2 2.0943951023931957 2.0939734083333335
-1 3.141592653589793 2.8124629916666666
0 (nan+infj) (nan+infj)
1 0 0.32912965833333346
2 1.0471975511965979 1.0476192416666668
3 1.2309594173407747 1.2309815101851853
4 1.318116071652818 1.3181189161458333
5 1.369438406004566 1.3694389916666667
6 1.4033482475752073 1.4033484083333334
7 1.4274487578895312 1.4274488110673134
8 1.4454684956268313 1.4454685153483076
9 1.4594553124539327 1.4594553200718894
```
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true,
...
}
```
P.S. Some plugins work on it, **including but not limited to**:
* **Python Test Explorer for Visual Studio Code** (`littlefoxteam.vscode-python-test-adapter`)
* **Test Explorer for Visual Studio Code**(`hbenl.vscode-test-explorer`)
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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`:
```
pytest.main(args=['-s', os.path.abspath(__file__)])
```
See the py.test documentation on [capturing output](https://docs.pytest.org/en/latest/capture.html).
|
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.pytest.org/en/latest/capture.html) is more information about "Capturing of the stdout/stderr output"
By default logger output level is "WARNING"
To change log output level use `--log-cli-level` flag.
```
pytest --capture=no --log-cli-level=DEBUG tests/system/test_backoffice.py
```
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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.pytest.org/en/latest/capture.html) is more information about "Capturing of the stdout/stderr output"
By default logger output level is "WARNING"
To change log output level use `--log-cli-level` flag.
```
pytest --capture=no --log-cli-level=DEBUG tests/system/test_backoffice.py
```
|
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 you don't specify it (<https://docs.pytest.org/en/6.2.x/logging.html>)
But if you dont want to use **--log-cli-level** every time use pytest,
you can set **log-level**
in your pytest config file (pytest.ini/tox.ini/setup.cfg)
e.g.
put **log-level=INFO** in pytest.ini (or other config files i mentioned)
when you run **pytest**, you only see INFO and above logs
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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 you don't specify it (<https://docs.pytest.org/en/6.2.x/logging.html>)
But if you dont want to use **--log-cli-level** every time use pytest,
you can set **log-level**
in your pytest config file (pytest.ini/tox.ini/setup.cfg)
e.g.
put **log-level=INFO** in pytest.ini (or other config files i mentioned)
when you run **pytest**, you only see INFO and above logs
|
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('Log inside a test function!')
assert foo(1, 2) == 5
/* your test here*/
```
```
# ./main.py
import logging
def foo(a, b):
logging.getLogger().info('a: ' + str(a))
logging.getLogger().info('b: ' + str(b))
return a + b
```
Now you can run pytest and get log info from function that you need.
If you don't have any errors, logs will be omitted.
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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 `log_cli = 1` in the `pyproject.toml`1 or `pytest.ini`2 config. Live logging supports emitting to terminal and file; the relevant options allow records customizing:
### terminal:
* `log_cli_level`
* `log_cli_format`
* `log_cli_date_format`
### file:
* `log_file`
* `log_file_level`
* `log_file_format`
* `log_file_date_format`
As pointed out by [Kévin Barré](https://stackoverflow.com/users/7505103/k%c3%a9vin-barr%c3%a9) in [this comment](https://stackoverflow.com/questions/4673373/logging-within-py-test-tests/51633600?noredirect=1#comment91175953_51633600), overriding `ini` options from command line can be done via:
>
> `-o OVERRIDE_INI, --override-ini=OVERRIDE_INI`
>
> override ini option with "option=value" style, e.g.
>
> `-o xfail_strict=True -o cache_dir=cache`
>
>
>
So instead of declaring `log_cli` in `pytest.ini`, you can simply call:
```
$ pytest -o log_cli=true ...
```
Examples
--------
Simple test file used for demonstrating:
```
# test_spam.py
import logging
LOGGER = logging.getLogger(__name__)
def test_eggs():
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
assert True
```
As you can see, no extra configuration needed; `pytest` will setup the logger automatically, based on options specified in `pytest.ini` or passed from command line.
### Live logging to terminal, `INFO` level, fancy output
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
```
Running the test:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
2018-08-01 14:33:20 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:33:20 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:33:20 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:33:20 [CRITICAL] eggs critical (test_spam.py:10)
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
```
### Live logging to terminal and file, only message & `CRITICAL` level in terminal, fancy output in `pytest.log` file
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "CRITICAL"
log_cli_format = "%(message)s"
log_file = "pytest.log"
log_file_level = "DEBUG"
log_file_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_file_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = CRITICAL
log_cli_format = %(message)s
log_file = pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
```
Test run:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
eggs critical
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
$ cat pytest.log
2018-08-01 14:38:09 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:38:09 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:38:09 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:38:09 [CRITICAL] eggs critical (test_spam.py:10)
```
---
1 `pyproject.toml` supported since version 6.0 and is the best option IMO. See [PEP 518](https://www.python.org/dev/peps/pep-0517/) for the specs.
2 Although you can also configure `pytest` in `setup.cfg` under the `[tool:pytest]` section, don't be tempted to do that when you want to provide custom live logging format. Other tools reading `setup.cfg` might treat stuff like `%(message)s` as string interpolation and fail. The best choice is using `pyproject.toml` anyway, but if you are forced to use the legacy ini-style format, stick to `pytest.ini` to avoid errors.
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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 `log_cli = 1` in the `pyproject.toml`1 or `pytest.ini`2 config. Live logging supports emitting to terminal and file; the relevant options allow records customizing:
### terminal:
* `log_cli_level`
* `log_cli_format`
* `log_cli_date_format`
### file:
* `log_file`
* `log_file_level`
* `log_file_format`
* `log_file_date_format`
As pointed out by [Kévin Barré](https://stackoverflow.com/users/7505103/k%c3%a9vin-barr%c3%a9) in [this comment](https://stackoverflow.com/questions/4673373/logging-within-py-test-tests/51633600?noredirect=1#comment91175953_51633600), overriding `ini` options from command line can be done via:
>
> `-o OVERRIDE_INI, --override-ini=OVERRIDE_INI`
>
> override ini option with "option=value" style, e.g.
>
> `-o xfail_strict=True -o cache_dir=cache`
>
>
>
So instead of declaring `log_cli` in `pytest.ini`, you can simply call:
```
$ pytest -o log_cli=true ...
```
Examples
--------
Simple test file used for demonstrating:
```
# test_spam.py
import logging
LOGGER = logging.getLogger(__name__)
def test_eggs():
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
assert True
```
As you can see, no extra configuration needed; `pytest` will setup the logger automatically, based on options specified in `pytest.ini` or passed from command line.
### Live logging to terminal, `INFO` level, fancy output
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
```
Running the test:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
2018-08-01 14:33:20 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:33:20 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:33:20 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:33:20 [CRITICAL] eggs critical (test_spam.py:10)
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
```
### Live logging to terminal and file, only message & `CRITICAL` level in terminal, fancy output in `pytest.log` file
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "CRITICAL"
log_cli_format = "%(message)s"
log_file = "pytest.log"
log_file_level = "DEBUG"
log_file_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_file_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = CRITICAL
log_cli_format = %(message)s
log_file = pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
```
Test run:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
eggs critical
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
$ cat pytest.log
2018-08-01 14:38:09 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:38:09 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:38:09 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:38:09 [CRITICAL] eggs critical (test_spam.py:10)
```
---
1 `pyproject.toml` supported since version 6.0 and is the best option IMO. See [PEP 518](https://www.python.org/dev/peps/pep-0517/) for the specs.
2 Although you can also configure `pytest` in `setup.cfg` under the `[tool:pytest]` section, don't be tempted to do that when you want to provide custom live logging format. Other tools reading `setup.cfg` might treat stuff like `%(message)s` as string interpolation and fail. The best choice is using `pyproject.toml` anyway, but if you are forced to use the legacy ini-style format, stick to `pytest.ini` to avoid errors.
|
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`:
```
pytest.main(args=['-s', os.path.abspath(__file__)])
```
See the py.test documentation on [capturing output](https://docs.pytest.org/en/latest/capture.html).
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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.pytest.org/en/latest/capture.html) is more information about "Capturing of the stdout/stderr output"
By default logger output level is "WARNING"
To change log output level use `--log-cli-level` flag.
```
pytest --capture=no --log-cli-level=DEBUG tests/system/test_backoffice.py
```
|
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('Log inside a test function!')
assert foo(1, 2) == 5
/* your test here*/
```
```
# ./main.py
import logging
def foo(a, b):
logging.getLogger().info('a: ' + str(a))
logging.getLogger().info('b: ' + str(b))
return a + b
```
Now you can run pytest and get log info from function that you need.
If you don't have any errors, logs will be omitted.
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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 `log_cli = 1` in the `pyproject.toml`1 or `pytest.ini`2 config. Live logging supports emitting to terminal and file; the relevant options allow records customizing:
### terminal:
* `log_cli_level`
* `log_cli_format`
* `log_cli_date_format`
### file:
* `log_file`
* `log_file_level`
* `log_file_format`
* `log_file_date_format`
As pointed out by [Kévin Barré](https://stackoverflow.com/users/7505103/k%c3%a9vin-barr%c3%a9) in [this comment](https://stackoverflow.com/questions/4673373/logging-within-py-test-tests/51633600?noredirect=1#comment91175953_51633600), overriding `ini` options from command line can be done via:
>
> `-o OVERRIDE_INI, --override-ini=OVERRIDE_INI`
>
> override ini option with "option=value" style, e.g.
>
> `-o xfail_strict=True -o cache_dir=cache`
>
>
>
So instead of declaring `log_cli` in `pytest.ini`, you can simply call:
```
$ pytest -o log_cli=true ...
```
Examples
--------
Simple test file used for demonstrating:
```
# test_spam.py
import logging
LOGGER = logging.getLogger(__name__)
def test_eggs():
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
assert True
```
As you can see, no extra configuration needed; `pytest` will setup the logger automatically, based on options specified in `pytest.ini` or passed from command line.
### Live logging to terminal, `INFO` level, fancy output
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
```
Running the test:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
2018-08-01 14:33:20 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:33:20 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:33:20 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:33:20 [CRITICAL] eggs critical (test_spam.py:10)
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
```
### Live logging to terminal and file, only message & `CRITICAL` level in terminal, fancy output in `pytest.log` file
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "CRITICAL"
log_cli_format = "%(message)s"
log_file = "pytest.log"
log_file_level = "DEBUG"
log_file_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_file_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = CRITICAL
log_cli_format = %(message)s
log_file = pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
```
Test run:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
eggs critical
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
$ cat pytest.log
2018-08-01 14:38:09 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:38:09 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:38:09 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:38:09 [CRITICAL] eggs critical (test_spam.py:10)
```
---
1 `pyproject.toml` supported since version 6.0 and is the best option IMO. See [PEP 518](https://www.python.org/dev/peps/pep-0517/) for the specs.
2 Although you can also configure `pytest` in `setup.cfg` under the `[tool:pytest]` section, don't be tempted to do that when you want to provide custom live logging format. Other tools reading `setup.cfg` might treat stuff like `%(message)s` as string interpolation and fail. The best choice is using `pyproject.toml` anyway, but if you are forced to use the legacy ini-style format, stick to `pytest.ini` to avoid errors.
|
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 you don't specify it (<https://docs.pytest.org/en/6.2.x/logging.html>)
But if you dont want to use **--log-cli-level** every time use pytest,
you can set **log-level**
in your pytest config file (pytest.ini/tox.ini/setup.cfg)
e.g.
put **log-level=INFO** in pytest.ini (or other config files i mentioned)
when you run **pytest**, you only see INFO and above logs
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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 `log_cli = 1` in the `pyproject.toml`1 or `pytest.ini`2 config. Live logging supports emitting to terminal and file; the relevant options allow records customizing:
### terminal:
* `log_cli_level`
* `log_cli_format`
* `log_cli_date_format`
### file:
* `log_file`
* `log_file_level`
* `log_file_format`
* `log_file_date_format`
As pointed out by [Kévin Barré](https://stackoverflow.com/users/7505103/k%c3%a9vin-barr%c3%a9) in [this comment](https://stackoverflow.com/questions/4673373/logging-within-py-test-tests/51633600?noredirect=1#comment91175953_51633600), overriding `ini` options from command line can be done via:
>
> `-o OVERRIDE_INI, --override-ini=OVERRIDE_INI`
>
> override ini option with "option=value" style, e.g.
>
> `-o xfail_strict=True -o cache_dir=cache`
>
>
>
So instead of declaring `log_cli` in `pytest.ini`, you can simply call:
```
$ pytest -o log_cli=true ...
```
Examples
--------
Simple test file used for demonstrating:
```
# test_spam.py
import logging
LOGGER = logging.getLogger(__name__)
def test_eggs():
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
assert True
```
As you can see, no extra configuration needed; `pytest` will setup the logger automatically, based on options specified in `pytest.ini` or passed from command line.
### Live logging to terminal, `INFO` level, fancy output
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
```
Running the test:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
2018-08-01 14:33:20 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:33:20 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:33:20 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:33:20 [CRITICAL] eggs critical (test_spam.py:10)
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
```
### Live logging to terminal and file, only message & `CRITICAL` level in terminal, fancy output in `pytest.log` file
Configuration in `pyproject.toml`:
```
[tool.pytest.ini_options]
log_cli = true
log_cli_level = "CRITICAL"
log_cli_format = "%(message)s"
log_file = "pytest.log"
log_file_level = "DEBUG"
log_file_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
log_file_date_format = "%Y-%m-%d %H:%M:%S"
```
The identical configuration in legacy `pytest.ini`:
```
[pytest]
log_cli = 1
log_cli_level = CRITICAL
log_cli_format = %(message)s
log_file = pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
```
Test run:
```
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
eggs critical
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
$ cat pytest.log
2018-08-01 14:38:09 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:38:09 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:38:09 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:38:09 [CRITICAL] eggs critical (test_spam.py:10)
```
---
1 `pyproject.toml` supported since version 6.0 and is the best option IMO. See [PEP 518](https://www.python.org/dev/peps/pep-0517/) for the specs.
2 Although you can also configure `pytest` in `setup.cfg` under the `[tool:pytest]` section, don't be tempted to do that when you want to provide custom live logging format. Other tools reading `setup.cfg` might treat stuff like `%(message)s` as string interpolation and fail. The best choice is using `pyproject.toml` anyway, but if you are forced to use the legacy ini-style format, stick to `pytest.ini` to avoid errors.
|
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": false,
"python.testing.nosetestsEnabled": false,
"python.testing.pytestEnabled": true,
...
}
```
P.S. Some plugins work on it, **including but not limited to**:
* **Python Test Explorer for Visual Studio Code** (`littlefoxteam.vscode-python-test-adapter`)
* **Test Explorer for Visual Studio Code**(`hbenl.vscode-test-explorer`)
|
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()
#############################################################################
def setup_module(module):
''' Setup for the entire module '''
mylogger.info('Inside Setup')
# Do the actual setup stuff here
pass
def setup_function(func):
''' Setup for test functions '''
if func == test_one:
mylogger.info(' Hurray !!')
def test_one():
''' Test One '''
mylogger.info('Inside Test 1')
#assert 0 == 1
pass
def test_two():
''' Test Two '''
mylogger.info('Inside Test 2')
pass
if __name__ == '__main__':
mylogger.info(' About to start the tests ')
pytest.main(args=[os.path.abspath(__file__)])
mylogger.info(' Done executing the tests ')
```
I get the following output:
```
[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items
minitest.py ..
====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests
```
Notice that only the logging messages from the `'__name__ == __main__'` block get transmitted to the console.
Is there a way to force `pytest` to emit logging to console from test methods as well?
|
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('Log inside a test function!')
assert foo(1, 2) == 5
/* your test here*/
```
```
# ./main.py
import logging
def foo(a, b):
logging.getLogger().info('a: ' + str(a))
logging.getLogger().info('b: ' + str(b))
return a + b
```
Now you can run pytest and get log info from function that you need.
If you don't have any errors, logs will be omitted.
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 directly to next iteration
* break : go out of the loop
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 first iteration, `count += 1` happens and `count` is now one. Since `count` is not greater than ten, it does not break. Since `count` is not equal to `5`, it doesn't continue either. All it does is print `1`. At the next iteration, `count` increments again and the same thing happens with the `if` statements. It is the same until eventually, the iteration where `count` is equal to `4` ends. Since `True` is still `True`, the iteration happens again. `count` is incremented and now equals five. The `if count > 10:` statement is `False`, but `if count == 5:` is `True`, so the loop just skips the `print` call and goes back to the beginning of the loop. The first thing it gets to is `count += 1`, so `count` is now equal to six. The next few iterations are quite similar to what happened before `count` was five. Once the iteration where `count` is nine happens, it gets to the beginning of the loop and increments `count`. Now `count` is ten and the loop breaks.
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 itself as `while count:` is equivalent to - `while count != 0`
for condition `count == 5` it continues on to next iteration, and does not print inside the loop.
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 directly to next iteration
* break : go out of the loop
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 itself as `while count:` is equivalent to - `while count != 0`
for condition `count == 5` it continues on to next iteration, and does not print inside the loop.
|
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 directly to next iteration
* break : go out of the loop
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 itself as `while count:` is equivalent to - `while count != 0`
for condition `count == 5` it continues on to next iteration, and does not print inside the loop.
|
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 first iteration, `count += 1` happens and `count` is now one. Since `count` is not greater than ten, it does not break. Since `count` is not equal to `5`, it doesn't continue either. All it does is print `1`. At the next iteration, `count` increments again and the same thing happens with the `if` statements. It is the same until eventually, the iteration where `count` is equal to `4` ends. Since `True` is still `True`, the iteration happens again. `count` is incremented and now equals five. The `if count > 10:` statement is `False`, but `if count == 5:` is `True`, so the loop just skips the `print` call and goes back to the beginning of the loop. The first thing it gets to is `count += 1`, so `count` is now equal to six. The next few iterations are quite similar to what happened before `count` was five. Once the iteration where `count` is nine happens, it gets to the beginning of the loop and increments `count`. Now `count` is ten and the loop breaks.
|
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 count evaluated as False as the count is set to 0?
Could someone please explain this?
```
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True: # while count is True
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
```
|
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 first iteration, `count += 1` happens and `count` is now one. Since `count` is not greater than ten, it does not break. Since `count` is not equal to `5`, it doesn't continue either. All it does is print `1`. At the next iteration, `count` increments again and the same thing happens with the `if` statements. It is the same until eventually, the iteration where `count` is equal to `4` ends. Since `True` is still `True`, the iteration happens again. `count` is incremented and now equals five. The `if count > 10:` statement is `False`, but `if count == 5:` is `True`, so the loop just skips the `print` call and goes back to the beginning of the loop. The first thing it gets to is `count += 1`, so `count` is now equal to six. The next few iterations are quite similar to what happened before `count` was five. Once the iteration where `count` is nine happens, it gets to the beginning of the loop and increments `count`. Now `count` is ten and the loop breaks.
|
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 directly to next iteration
* break : go out of the loop
|
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 sets import ImmutableSet")
```
but, I not get changes.
any suggestion?
Many thanks.
|
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.simplefilter("ignore", DeprecationWarning)
import MySQLdb
[...]
```
but as said by Alex Martelli, the best solution would be to update MySQLdb so that it doesn't use deprecated modules.
|
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-bit one (on python2.7 32-bit) appears fine) I can click OK and the installer finishes, but this certainly looks poor to end-users.
Any ideas how to solve it?
|
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 letters and numbers within the code, so I'm not sure what to do.
I could do this two ways, I suppose:
1. I was considering using python to "trim" the time data so it displays with only the "20141107" in the csv file, which should make it easy to browse.
2. I'm not sure if its possible but if someone knows how I could obviously search the code using "xrange=[]" as I typically would with data.
My code:
```
import scipy.io as spio
import numpy as np
import csv
import pandas as pd
import matplotlib as plt
np.set_printoptions(threshold=np.nan)
onfile='/file'
finalfile='/fileout'
s=spio.readsav(onfile,python_dict=true,verbose=true)
time=np.asarray(s["time"])
data=np.asarray(s["data"])
d=pd.DataFrame({'time':time,'data':data})
d.to_csv(finalfile,sep=' ', encoding='utf-u',header=True)
d.plot(x='time',y='data',kind='line')
```
|
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 type?](https://stackoverflow.com/questions/16852911/how-do-i-convert-dates-in-a-pandas-data-frame-to-a-date-data-type)
|
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%M%SY'
Here
```
%d is the day number
%m is the month number
%b is the month abbreviation
%y is the year last two digits
%Y is the all year
```
|
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 response not in ('y', 'n', 'yes', 'no'):
io.echo('Not a valid input. Try again'])
response = io.prompt('y/n').lower()
return response in ('y', 'yes')
```
My Test code:
```
@mock.patch('io')
def test_get_boolean_response(self, mock_io):
#setup
mock_io.prompt.return_value = ['x','y']
result = operations.get_boolean_response()
#test
self.assertTrue(result)
self.assertEqual(mock_io.prompt.call_count, 2)
```
`io.prompt` is just a platform independent (python 2 and 3) version of "input". So ultimately I am trying to mock out the users input. I have tried using a list for the return value, but that doesn't seam to work.
You can see that if the return value is something invalid, I will just get an infinite loop here. So I need a way to eventually change the return value, so that my test actually finishes.
(another possible way to answer this question could be to explain how I could mimic user input in a unit-test)
---
Not a dup of [this question](https://stackoverflow.com/questions/7665682/python-mock-object-with-method-called-multiple-times) mainly because I do not have the ability to vary the inputs.
One of the comments of the Answer on [this question](https://stackoverflow.com/questions/21927057/mock-patch-os-path-exists-with-multiple-return-values) is along the same lines, but no answer/comment has been provided.
|
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()
'baz'
```
Quoting the [`Mock()` documentation](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock):
>
> If *side\_effect* is an iterable then each call to the mock will return the next value from the iterable.
>
>
>
|
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 see here, it will be reverted. First mentioned patch will be in the last position.
|
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 response not in ('y', 'n', 'yes', 'no'):
io.echo('Not a valid input. Try again'])
response = io.prompt('y/n').lower()
return response in ('y', 'yes')
```
My Test code:
```
@mock.patch('io')
def test_get_boolean_response(self, mock_io):
#setup
mock_io.prompt.return_value = ['x','y']
result = operations.get_boolean_response()
#test
self.assertTrue(result)
self.assertEqual(mock_io.prompt.call_count, 2)
```
`io.prompt` is just a platform independent (python 2 and 3) version of "input". So ultimately I am trying to mock out the users input. I have tried using a list for the return value, but that doesn't seam to work.
You can see that if the return value is something invalid, I will just get an infinite loop here. So I need a way to eventually change the return value, so that my test actually finishes.
(another possible way to answer this question could be to explain how I could mimic user input in a unit-test)
---
Not a dup of [this question](https://stackoverflow.com/questions/7665682/python-mock-object-with-method-called-multiple-times) mainly because I do not have the ability to vary the inputs.
One of the comments of the Answer on [this question](https://stackoverflow.com/questions/21927057/mock-patch-os-path-exists-with-multiple-return-values) is along the same lines, but no answer/comment has been provided.
|
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()
'baz'
```
Quoting the [`Mock()` documentation](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock):
>
> If *side\_effect* is an iterable then each call to the mock will return the next value from the iterable.
>
>
>
|
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': 4, 'b': 5}])
def test_first_test(self, hello_world_patched):
assert hello_world() == {'a': 1, 'b': 2}
assert hello_world() == {'a': 4, 'b': 5}
assert hello_world_patched.call_count == 2
```
|
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 response not in ('y', 'n', 'yes', 'no'):
io.echo('Not a valid input. Try again'])
response = io.prompt('y/n').lower()
return response in ('y', 'yes')
```
My Test code:
```
@mock.patch('io')
def test_get_boolean_response(self, mock_io):
#setup
mock_io.prompt.return_value = ['x','y']
result = operations.get_boolean_response()
#test
self.assertTrue(result)
self.assertEqual(mock_io.prompt.call_count, 2)
```
`io.prompt` is just a platform independent (python 2 and 3) version of "input". So ultimately I am trying to mock out the users input. I have tried using a list for the return value, but that doesn't seam to work.
You can see that if the return value is something invalid, I will just get an infinite loop here. So I need a way to eventually change the return value, so that my test actually finishes.
(another possible way to answer this question could be to explain how I could mimic user input in a unit-test)
---
Not a dup of [this question](https://stackoverflow.com/questions/7665682/python-mock-object-with-method-called-multiple-times) mainly because I do not have the ability to vary the inputs.
One of the comments of the Answer on [this question](https://stackoverflow.com/questions/21927057/mock-patch-os-path-exists-with-multiple-return-values) is along the same lines, but no answer/comment has been provided.
|
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': 4, 'b': 5}])
def test_first_test(self, hello_world_patched):
assert hello_world() == {'a': 1, 'b': 2}
assert hello_world() == {'a': 4, 'b': 5}
assert hello_world_patched.call_count == 2
```
|
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 see here, it will be reverted. First mentioned patch will be in the last position.
|
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 values are printed in descending order (9 > 8 > 4 > 2). Why is it so? Does `Counter` store values sorted?
PS: Am on python 3.7.7
|
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 code](https://github.com/python/cpython/blob/a834e2d8e1230c17193c19b425e83e0bf736179e/Lib/collections/__init__.py#L731) that it will first try to display using the [`Counter.most_common`](https://docs.python.org/3/library/collections.html#collections.Counter.most_common) method, which sorts by value in descending order. If that fails because the values are not sortable, it will fall back to the `dict` representation, which, again, is insertion-ordered.
|
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 order. Math operations on Counter
> objects also preserve order. Results are ordered according to when an
> element is first encountered in the left operand and then by the order
> encountered in the right operand.
>
>
>
Example on python 3.8 (3.8.10 [GCC 9.4.0]):
```
from collections import Counter
Counter({'z': 9,'a':4, 'c':2, 'b':8, 'y':2, 'v':2})
```
Output:
```
Counter({'z': 9, 'a': 4, 'c': 2, 'b': 8, 'y': 2, 'v': 2})
```
#### how to check that `Counter` doesn't sort by count
As `__str__` in `Counter` return the `most_common`, it is not a reliable way to check the order.
Convert to `dict`, the `__str__` representation will be faithful.
```
c = Counter({'z': 9,'a':4, 'c':2, 'b':8, 'y':2, 'v':2})
print(dict(c))
# {'z': 9, 'a': 4, 'c': 2, 'b': 8, 'y': 2, 'v': 2}
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
x <- list2
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
**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
```
> myfun(list1)
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 20 21 22 23 24
[25] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
[49] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
[97] 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
[27] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
[53] 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
[79] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
```
|
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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
pluck(list2, !!!(rep(1, vec_depth(list2)-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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
[27] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
[53] 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
[79] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
```
|
**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
```
> myfun(list1)
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 20 21 22 23 24
[25] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
[49] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
[97] 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
x <- list2
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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 called 'recursively' until it finds a "ts" class object:
```
get_list <- function(x){
while(!is(x, 'ts')){
x <- pluck(x, 1)
}
x
}
```
**output**
```
get_list(list2)
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 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
[46] 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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) {
if (inherits(my_list, 'list')) {
Recall(my_list[[1]])
} else {
my_list
}
}
```
Output:
```
> recursive_fun(list1)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
> recursive_fun(list2)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
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] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
[27] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
[53] 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
[79] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
x <- list2
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
pluck(list2, !!!(rep(1, vec_depth(list2)-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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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) {
if (inherits(my_list, 'list')) {
Recall(my_list[[1]])
} else {
my_list
}
}
```
Output:
```
> recursive_fun(list1)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
> recursive_fun(list2)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
**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
```
> myfun(list1)
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 20 21 22 23 24
[25] 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
[49] 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
[97] 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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) {
if (inherits(my_list, 'list')) {
Recall(my_list[[1]])
} else {
my_list
}
}
```
Output:
```
> recursive_fun(list1)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
> recursive_fun(list2)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
x <- list2
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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) {
if (inherits(my_list, 'list')) {
Recall(my_list[[1]])
} else {
my_list
}
}
```
Output:
```
> recursive_fun(list1)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
> recursive_fun(list2)
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 20 21 22 23 24 25 26 27 28 29 30
[31] 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
[61] 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
pluck(list2, !!!(rep(1, vec_depth(list2)-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 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#> [37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#> [55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#> [73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#> [91] 91 92 93 94 95 96 97 98 99 100
```
|
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.strptime(enddate, ' %a %b %d %H:%M:%S %Z %Y')
subtract_days= Modified_date1 - todays
print (subtract_days.days)
```
***Output***
```
Today = 2022-02-02 08:06:53.687342
Traceback (most recent call last):
File "1.py", line 106, in trusstore_output
Modified_date1 = datetime.strptime(enddate1, ' %a %b %d %H:%M:%S %Z %Y')
File "/usr/lib64/python3.6/_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib64/python3.6/_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data ' Thu Jun 02 08:00:00 EDT 2022' does not match format ' %a %b %d %H:%M:%S %Z %Y'
During handling of the above exception, another exception occurred:
```
**Linux server date**
```
$ date
Wed Feb 2 08:08:36 CST 2022
```
|
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] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
[27] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
[53] 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
[79] 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
```
|
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 called 'recursively' until it finds a "ts" class object:
```
get_list <- function(x){
while(!is(x, 'ts')){
x <- pluck(x, 1)
}
x
}
```
**output**
```
get_list(list2)
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 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
[46] 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
```
|
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" statement one some different table using the cursor way as described above.
I was able to delete few records using Step1, but step2 select is not working. It simply gives no records for step2 though there are some records available under DB.
But, when i comment step1 and execute step2, i could see that step2 works fine. Why this is so?
Though there are records, why the above sequence is failing to do so?
Any ideas would be appreciated.
Thanks!
|
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. Here is the code:
```
// Allow UI Rendering to Refresh
DispatcherHelper.WaitForPriority();
// Scroll to selected Item
TreeViewItem tvi = myTreeView.SelectedItem as TreeViewItem;
Point offset = tvi.TransformToAncestor(myScroll).Transform(new Point(0, 0));
myScroll.ScrollToVerticalOffset(offset.Y);
```
Here is the DispatcherHelper code:
```
public class DispatcherHelper
{
private static readonly DispatcherOperationCallback exitFrameCallback = ExitFrame;
/// <summary>
/// Processes all UI messages currently in the message queue.
/// </summary>
public static void WaitForPriority()
{
// Create new nested message pump.
DispatcherFrame nestedFrame = new DispatcherFrame();
// Dispatch a callback to the current message queue, when getting called,
// this callback will end the nested message loop.
// The priority of this callback should be lower than that of event message you want to process.
DispatcherOperation exitOperation = Dispatcher.CurrentDispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle, exitFrameCallback, nestedFrame);
// pump the nested message loop, the nested message loop will immediately
// process the messages left inside the message queue.
Dispatcher.PushFrame(nestedFrame);
// If the "exitFrame" callback is not finished, abort it.
if (exitOperation.Status != DispatcherOperationStatus.Completed)
{
exitOperation.Abort();
}
}
private static Object ExitFrame(Object state)
{
DispatcherFrame frame = state as DispatcherFrame;
// Exit the nested message loop.
frame.Continue = false;
return null;
}
}
```
|
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:
```
// Get the TreeView's ScrollViewer
DependencyObject parent = VisualTreeHelper.GetParent(selectedTreeViewItem);
while (parent != null && !(parent is ScrollViewer))
{
parent = VisualTreeHelper.GetParent(parent);
}
```
|
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 numpy efficiently?
In simple python, I could do this like this:
```
dataset = np.loadtxt('data.txt')
X0, X1 = [], []
for i in range(len(X)):
if X[i][-1] == 1:
X0.append(X[i])
else:
X1.append(X[i])
```
This is slow and cumbersome, Numpy is fast and easy so, I would appreciate if there is easier way in numpy. Thanks.
|
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([[6, 2, 1],
[1, 6, 1],
[2, 4, 1],
[6, 2, 1]])
>>> X2
array([[-2, 4, -1],
[ 4, 1, -1]])
```
|
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('-')
print(X[X[:, 2] == -1])
```
|
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 numpy efficiently?
In simple python, I could do this like this:
```
dataset = np.loadtxt('data.txt')
X0, X1 = [], []
for i in range(len(X)):
if X[i][-1] == 1:
X0.append(X[i])
else:
X1.append(X[i])
```
This is slow and cumbersome, Numpy is fast and easy so, I would appreciate if there is easier way in numpy. Thanks.
|
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([[6, 2, 1],
[1, 6, 1],
[2, 4, 1],
[6, 2, 1]])
>>> X2
array([[-2, 4, -1],
[ 4, 1, -1]])
```
|
```
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 written in C or does the interpreter convert Python source code into C?
2. CPython is nothing but the original Python & the term was just coined to later distinguish it from Jython - true or false?
3. Now that Python is implemented in C (not really sure what that means), but does that mean python can be seamlessly integrated with any C code.
4. Is Jython like a new programming language or does its syntax & other programming constructs look exactly similar to the original python? or is it just python which can be integrated with java code?
5. If none of my above questions answer the difference between Python & Jython, what is it?
|
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 interprets the byte code. It's the oldest and reference implementation of the Python language.
"Jython" is another implementation of the Python language. It translates Python code to Java byte code, which can be executed on a Java virtual machine.
|
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) Using C libraries in Python is pretty easy, e.g. using the ctypes module.
d) see b.
e) see a and b.
|
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 written in C or does the interpreter convert Python source code into C?
2. CPython is nothing but the original Python & the term was just coined to later distinguish it from Jython - true or false?
3. Now that Python is implemented in C (not really sure what that means), but does that mean python can be seamlessly integrated with any C code.
4. Is Jython like a new programming language or does its syntax & other programming constructs look exactly similar to the original python? or is it just python which can be integrated with java code?
5. If none of my above questions answer the difference between Python & Jython, what is it?
|
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 interprets the byte code. It's the oldest and reference implementation of the Python language.
"Jython" is another implementation of the Python language. It translates Python code to Java byte code, which can be executed on a Java virtual machine.
|
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 Python language writen in Java.
e) CPython is easly integrated whit C, Jython is easly integrated whit Java.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.