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 |
|---|---|---|---|---|---|
21,869,675 | ```
list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
item1 = 1
item2 = 'c'
#hypothetical:
assert list_.index_by_first_value(item1) == 0
assert list_.index_by_second_value(item2) == 2
```
What would be the fastest way to emulate the `index_by_first/second_value` method in python?
If you don't understand what's going on; if you... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21869675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002473/"
] | At first, I thought along [the same lines as Nick T](https://stackoverflow.com/a/21869852/418413). Your method is fine if the number of tuples (N) is short. But of course a linear search is O(N). As the number of tuples increases, the time increases directly with it. You can get O(1) lookup time with a dict mapping the... | **What is fastest?** *It depends on how many times you need to use it, and if you are able to create an index dictionary from the very beginning.*
As the others have mentioned, dictionary is much faster once you have it, but it is costly to transform the list into a dictionary. I'm going to show what I get on my compu... |
21,869,675 | ```
list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
item1 = 1
item2 = 'c'
#hypothetical:
assert list_.index_by_first_value(item1) == 0
assert list_.index_by_second_value(item2) == 2
```
What would be the fastest way to emulate the `index_by_first/second_value` method in python?
If you don't understand what's going on; if you... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21869675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002473/"
] | EDIT: Just kidding. As the lists grow longer it looks like the manual `for` loop takes less time. Updated to generate random lists via kojiro's method:
Just some timing tests for your information while maintaining lists. The good thing about preserving list form versus a dictionary is that it's expansible to include t... | @Nick T
I think some time is wasted enumerating the list and then converting it to a dictionary, so even if it is an O(1) lookup for a dict, creating the dict in the first place is too costly to consider it a viable option for large lists.
This is the test I used to determine it:
```
import time
l = [(i, chr(i)) for... |
21,869,675 | ```
list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
item1 = 1
item2 = 'c'
#hypothetical:
assert list_.index_by_first_value(item1) == 0
assert list_.index_by_second_value(item2) == 2
```
What would be the fastest way to emulate the `index_by_first/second_value` method in python?
If you don't understand what's going on; if you... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21869675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002473/"
] | **What is fastest?** *It depends on how many times you need to use it, and if you are able to create an index dictionary from the very beginning.*
As the others have mentioned, dictionary is much faster once you have it, but it is costly to transform the list into a dictionary. I'm going to show what I get on my compu... | @Nick T
I think some time is wasted enumerating the list and then converting it to a dictionary, so even if it is an O(1) lookup for a dict, creating the dict in the first place is too costly to consider it a viable option for large lists.
This is the test I used to determine it:
```
import time
l = [(i, chr(i)) for... |
21,869,675 | ```
list_ = [(1, 'a'), (2, 'b'), (3, 'c')]
item1 = 1
item2 = 'c'
#hypothetical:
assert list_.index_by_first_value(item1) == 0
assert list_.index_by_second_value(item2) == 2
```
What would be the fastest way to emulate the `index_by_first/second_value` method in python?
If you don't understand what's going on; if you... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21869675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002473/"
] | EDIT: Just kidding. As the lists grow longer it looks like the manual `for` loop takes less time. Updated to generate random lists via kojiro's method:
Just some timing tests for your information while maintaining lists. The good thing about preserving list form versus a dictionary is that it's expansible to include t... | **What is fastest?** *It depends on how many times you need to use it, and if you are able to create an index dictionary from the very beginning.*
As the others have mentioned, dictionary is much faster once you have it, but it is costly to transform the list into a dictionary. I'm going to show what I get on my compu... |
36,584,975 | I've a little problem with my code.
I tried to rewrite code from python to java.
In Python it's:
```
data = bytearray(filesize)
f.readinto(data)
```
Then I tried to write it in java like this:
```
try {
data = Files.readAllBytes(file.toPath());
} catch (IOException ex) {
Logger.getLogger(Encryp... | 2016/04/12 | [
"https://Stackoverflow.com/questions/36584975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6195753/"
] | Since `@metrics` is an array, it doesn't look like you're calling any code on your model at all so your model code isn't actually doing anything.
This code your controller will generate the output you're looking for:
```
CSV.generate do |csv|
@metrics.each { |item| csv << [item] }
end
``` | This is just a guess, but try formatting `@metrics` as an array of arrays: so each element of `@metrics` is its own array. It seems likely that `to_csv` treats an array like a row, so you need an array of arrays to generate new lines.
```
[["Group Name,1"], ["25"], ["44,2,5"]]
```
**UPDATE**
Looking at your code ag... |
31,767,709 | What's a good command from term to render all images in a dir into one browser window?
Looking for something like this:
`python -m SimpleHTTPServer 8080`
But instead of a list ...
... Would like to see **all the images rendered in a single browser window**, just flowed naturally, at natural dimensions, just scroll ... | 2015/08/02 | [
"https://Stackoverflow.com/questions/31767709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1618304/"
] | I found a perl CGI script to do this:
```
#!/usr/bin/perl -wT
# myscript.pl
use strict;
use CGI;
use Image::Size;
my $q = new CGI;
my $imageDir = "./";
my @images;
opendir DIR, "$imageDir" or die "Can't open $imageDir $!";
@images = grep { /\.(?:png|gif|jpg)$/i } readdir DIR;
# @images = grep { /\.(?:png|g... | This is quite easy, you can program something like this in a couple of minutes.
Just create an array of all the images in ./ create a var s = '' and appen for each img in ./ '>
' and send it to the webbrowser the server->google is your friend |
41,708,458 | I have many bash scripts to help set my current session environment variables. I need the env variables set so I can use the subprocess module to run commands in my python scripts. This is how I execute the bash scripts:
```
. ./file1.sh
```
Below is the beginning of the bash script:
```
echo "Setting Environment V... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41708458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259469/"
] | ### Using `shell=True` With Your Existing Script
First, in terms of the *very simplest thing* -- if you're using `shell=True`, you can tell the shell that starts to run the contents of your preexisting script unmodified.
That is to say -- if you were initially doing this:
```
subprocess.Popen(['your-command', 'arg1'... | You should consider the Python builtin `os` [module](https://docs.python.org/2/library/os.html). The attribute
`os.environ` is a dictionary of environment variables that you can *read*, e.g.
```
import os
os.environ["USER"]
```
You cannot, however, *write* bash environment variables from the child process (see e.g.,... |
41,708,458 | I have many bash scripts to help set my current session environment variables. I need the env variables set so I can use the subprocess module to run commands in my python scripts. This is how I execute the bash scripts:
```
. ./file1.sh
```
Below is the beginning of the bash script:
```
echo "Setting Environment V... | 2017/01/17 | [
"https://Stackoverflow.com/questions/41708458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7259469/"
] | ### Using `shell=True` With Your Existing Script
First, in terms of the *very simplest thing* -- if you're using `shell=True`, you can tell the shell that starts to run the contents of your preexisting script unmodified.
That is to say -- if you were initially doing this:
```
subprocess.Popen(['your-command', 'arg1'... | Both of your questions are answered before.
You can execute bash scripts from python with something like;
```
import subprocess
subprocess.Popen("cwm --rdf test.rdf --ntriples > test.nt")
```
See this question [running bash commands in python](https://stackoverflow.com/q/4256107/1916158)
Better set the environment ... |
58,225,904 | I have a multiline string in python that looks like this
```
"""1234 dog list some words 1432 cat line 2 1789 cat line3 1348 dog line 4 1678 dog line 5 1733 fish line 6 1093 cat more words"""
```
I want to be able to group specific lines by the animals in python. So my output would look like
```
dog
1234 dog list ... | 2019/10/03 | [
"https://Stackoverflow.com/questions/58225904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476376/"
] | >
> Or maybe there is a simpler way of archiving this?
>
>
>
Consider *option would be to have a function for each type* that is called by *the same function*.
```
void testVariableInput_int(const int *a, const int *b, int *out, int m) {
while (m > 0) {
m--;
out[m] = a[m] + b[m];
}
}
// Like-wise for... | >
> Or maybe there is a simpler way of achieving this?
>
>
>
I like function pointers. Here we can pass a function pointer that adds two elements. That way we can separate the logic of the function from the abstraction that handles the types.
```
#include <stdlib.h>
#include <stdio.h>
void add_floats(const void ... |
64,771,870 | I am using a colab pro TPU instance for the purpose of patch image classification.
i'm using tensorflow version 2.3.0.
When calling model.fit I get the following error: `InvalidArgumentError: Unable to find the relevant tensor remote_handle: Op ID: 14738, Output num: 0` with the following trace:
```
--------
InvalidA... | 2020/11/10 | [
"https://Stackoverflow.com/questions/64771870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8777119/"
] | @Pooya448
I know this is quite late, but this may be useful for anyone stuck here.
Following is the function I use to connect to TPUs.
```py
def connect_to_tpu(tpu_address: str = None):
if tpu_address is not None: # When using GCP
cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver(
... | I actually tried all the methods that are suggested in git and stackoverflow none of them worked for me. But what worked is I created a new notebook and connected it to the TPU and trained the model. It worked fine, so may be this is related to the problem of the notebook at the time when we created it. |
32,017,621 | I would like to connect and receive http response from a specific web site link.
I have many Python codes :
```
import urllib.request
import os,sys,re,datetime
fp = urllib.request.urlopen("http://www.python.org")
mybytes = fp.read()
mystr = mybytes.decode(encoding=sys.stdout.encoding)
fp.close()
```
when I pass th... | 2015/08/14 | [
"https://Stackoverflow.com/questions/32017621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5228214/"
] | first of all: <https://docs.python.org/2/tutorial/classes.html#inheritance>
At any rate...
```
GParent.testmethod(self) <-- calling a method before it is defined
class GParent(): <-- always inherit object on your base class to ensure you are using new style classes
def testmethod(self):
print "This is te... | You cannot call GParent's `testmethod` without an instance of `GParent` as its first argument.
**Inheritance**
```
class GParent(object):
def testmethod(self):
print "I'm a grandpa"
class Parent(GParent):
# implicitly inherit __init__() ... |
56,711,890 | If I had a function that had three or four optional keyword arguments is it best to use \*\*kwargs or to specify them in the function definition?
I feel as
`def foo(required, option1=False, option2=False, option3=True)`
is much more clumsy looking than
`def foo(required, **kwargs)`.
However if I need to use these ke... | 2019/06/22 | [
"https://Stackoverflow.com/questions/56711890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10206378/"
] | If the function is only using the parameters in its own operation, you should list them all explicitly. This will allow Python to detect if an invalid argument was provided in a call to your function.
You use `**kwargs` when you need to accept dynamic parameters, often because you're passing them along to other functi... | One easy way to pass in several optional parameters while keeping your function definition clean is to use a dictionary that contains all the parameters. That way your function becomes
```py
def foo(required, params):
print(required)
if 'true' in params and params['true']:
print(params['true'])
```
Y... |
26,625,845 | I work on a project in which I need a python web server. This project is hosted on Amazon EC2 (ubuntu).
I have made two unsuccessful attempts so far:
1. run `python -m SimpleHTTPServer 8080`. It works if I launch a browser on the EC2 instance and head to localhost:8080 or <*ec2-public-IP*>:8080. However I can't acces... | 2014/10/29 | [
"https://Stackoverflow.com/questions/26625845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3592547/"
] | you should open the 8080 port and ip limitation in security croups, such as:
All TCP TCP 0 - 65535 0.0.0.0/0
the last item means this server will accept every request from any ip and port, you also | You passble need to `IAM` in `AWS`.
`Aws` set security permission that need to open up port so you only `localhost` links your webservice
[aws link](http://aws.amazon.com/) |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | You can build a new dictionary in the shape you want like this:
```
...
data = {
element["Name"]: {
key: value for key, value in element.items() if key != "Name"
}
for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...
```
Result:
```
{
"Memory": {
"SensorType": "... | ```
x="""[
{
"Name": "Memory 1",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Load",
"Value": 53.3276978
}]"""
json_obj=json.loads(x)
new_list=[]
for item in json_obj:
name=item.pop('Name')
new_list.append({name:item})
print(json.dumps(n... |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | You can build a new dictionary in the shape you want like this:
```
...
data = {
element["Name"]: {
key: value for key, value in element.items() if key != "Name"
}
for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...
```
Result:
```
{
"Memory": {
"SensorType": "... | How about this?
```
import json
orig_list = json.load(<filename>)
new_dict = { l['Name']:{k:v for k,v in l.items() if k!='Name'} for l in orig_list}
json.dumps(new_dict, <filename>)
```
This way, you won't have to `del` items from the `dict`s that you load from the file. |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | Assuming you need to keep the values if key already exists:
```
import json
data = [
{
"Name": "Memory",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Temperature",
"Value": 69
},
{
"Name": "Used Space",
"SensorType": "Load",
"Value": 93.12801
... | You can build a new dictionary in the shape you want like this:
```
...
data = {
element["Name"]: {
key: value for key, value in element.items() if key != "Name"
}
for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...
```
Result:
```
{
"Memory": {
"SensorType": "... |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | You can build a new dictionary in the shape you want like this:
```
...
data = {
element["Name"]: {
key: value for key, value in element.items() if key != "Name"
}
for element in json.loads(output)
}
fdata = json.dumps(data, indent=4)
...
```
Result:
```
{
"Memory": {
"SensorType": "... | You can just replace
```
for mNull in data:
del mNull['Scope']
del mNull['Path']
del mNull['Options']
del mNull['ClassPath']
del mNull['Properties']
del mNull['SystemProperties']
del mNull['Qualifiers']
del mNull['Site']
del mNull['Container']
del mNull['PSComputerName']
del... |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | Assuming you need to keep the values if key already exists:
```
import json
data = [
{
"Name": "Memory",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Temperature",
"Value": 69
},
{
"Name": "Used Space",
"SensorType": "Load",
"Value": 93.12801
... | ```
x="""[
{
"Name": "Memory 1",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Load",
"Value": 53.3276978
}]"""
json_obj=json.loads(x)
new_list=[]
for item in json_obj:
name=item.pop('Name')
new_list.append({name:item})
print(json.dumps(n... |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | Assuming you need to keep the values if key already exists:
```
import json
data = [
{
"Name": "Memory",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Temperature",
"Value": 69
},
{
"Name": "Used Space",
"SensorType": "Load",
"Value": 93.12801
... | How about this?
```
import json
orig_list = json.load(<filename>)
new_dict = { l['Name']:{k:v for k,v in l.items() if k!='Name'} for l in orig_list}
json.dumps(new_dict, <filename>)
```
This way, you won't have to `del` items from the `dict`s that you load from the file. |
51,733,698 | I have a program that right now grabs data like temperature and loads using a powershell script and the WMI. It outputs the data as a JSON file. Now let me preface this by saying this is my first time every working with JSON's and im not very familiar with the JSON python library. Here is the code to my program:
```
i... | 2018/08/07 | [
"https://Stackoverflow.com/questions/51733698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9801535/"
] | Assuming you need to keep the values if key already exists:
```
import json
data = [
{
"Name": "Memory",
"SensorType": "Load",
"Value": 53.3276978
},
{
"Name": "CPU Core #2",
"SensorType": "Temperature",
"Value": 69
},
{
"Name": "Used Space",
"SensorType": "Load",
"Value": 93.12801
... | You can just replace
```
for mNull in data:
del mNull['Scope']
del mNull['Path']
del mNull['Options']
del mNull['ClassPath']
del mNull['Properties']
del mNull['SystemProperties']
del mNull['Qualifiers']
del mNull['Site']
del mNull['Container']
del mNull['PSComputerName']
del... |
24,888,691 | Well, I finally got cocos2d-x into the IDE, and now I can make minor changes like change the label text.
But when trying to add a sprite, the app crashes on my phone (Galaxy Ace 2), and I can't make sense of the debug output.
I followed [THIS](http://youtu.be/2LI1IrRp_0w) video to set up my IDE, and i've literally ju... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24888691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3863962/"
] | ```
var new= "\"" + string.Join( "\",\"", keys) + "\"";
```
To include a double quote in a string, you escape it with a backslash character, thus "\"" is a string consisting of a single double quote character, and "\", \"" is a string containing a double quote, a comma, a space, and another double quote. | If performance is the key, you can always use a `StringBuilder` to concatenate everything.
[Here's a fiddle](https://dotnetfiddle.net/nptVEH) to see it in action, but the main part can be summarized as:
```
// these look like snails, but they are actually pretty fast
using @_____ = System.Collections.Generic.IEnumera... |
24,888,691 | Well, I finally got cocos2d-x into the IDE, and now I can make minor changes like change the label text.
But when trying to add a sprite, the app crashes on my phone (Galaxy Ace 2), and I can't make sense of the debug output.
I followed [THIS](http://youtu.be/2LI1IrRp_0w) video to set up my IDE, and i've literally ju... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24888691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3863962/"
] | Please give a try to this.
```
var keys = new object[] { "test1", "hello", "world", null, "", "oops"};
var csv = string.Join(",", keys.Select(k => string.Format("\"{0}\"", k)));
```
Because you have an `object[]` array, `string.Format` can deal with null as well as other types than strings. This solutions also work... | If performance is the key, you can always use a `StringBuilder` to concatenate everything.
[Here's a fiddle](https://dotnetfiddle.net/nptVEH) to see it in action, but the main part can be summarized as:
```
// these look like snails, but they are actually pretty fast
using @_____ = System.Collections.Generic.IEnumera... |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:
```
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this... | I'm geting the camera with OpenCV
```
from opencv import cv
from opencv import highgui
from opencv import adaptors
def get_image()
cam = highgui.cvCreateCameraCapture(0)
im = highgui.cvQueryFrame(cam)
# Add the line below if you need it (Ubuntu 8.04+)
#im = opencv.cvGetMat(im)
return im
``` |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:
```
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this... | Anthony, one of the SimpleCV developers here.
Also instead of using image.save(), this function writes the file/video to disk, you instead probably want to use image.show(). You can save if you want, but you need to specify a file path like image.save("/tmp/blah.png")
So you want to do:
```
img = mycam.getImage()
im... |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | since the error raised from Camera.py of SimpleCV, you need to debug the getImage() method. If you can edit it:
```
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this... | Also I should mention, which I didn't realize, is that OpenCV less than 2.3 is broken with webcams on Ubuntu 11.04 and up. I didn't realize this as I was running Ubuntu 10.10 before, by the looks of your output you are using python 2.7 which makes me think you are on Ubuntu 11.04 or higher. Anyway, we have a fix for th... |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | To answer my own question...
I bought a Logitech C210 today and the problem disappeared.
I'm now getting warnings:
`Corrupt JPEG data: X extraneous bytes before marker 0xYY`.
However, I am able to successfully push a video stream to my web-browser via `JpegStreamer()`. If I cannot solve this error, I'll open a new ... | I'm geting the camera with OpenCV
```
from opencv import cv
from opencv import highgui
from opencv import adaptors
def get_image()
cam = highgui.cvCreateCameraCapture(0)
im = highgui.cvQueryFrame(cam)
# Add the line below if you need it (Ubuntu 8.04+)
#im = opencv.cvGetMat(im)
return im
``` |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | To answer my own question...
I bought a Logitech C210 today and the problem disappeared.
I'm now getting warnings:
`Corrupt JPEG data: X extraneous bytes before marker 0xYY`.
However, I am able to successfully push a video stream to my web-browser via `JpegStreamer()`. If I cannot solve this error, I'll open a new ... | Anthony, one of the SimpleCV developers here.
Also instead of using image.save(), this function writes the file/video to disk, you instead probably want to use image.show(). You can save if you want, but you need to specify a file path like image.save("/tmp/blah.png")
So you want to do:
```
img = mycam.getImage()
im... |
6,990,760 | I wrapped opencv today with simplecv python interface. After going through the official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-and-saving-images), and [Manipulate](http://simplecv.org/doc/cookbook.html#image-manipu... | 2011/08/09 | [
"https://Stackoverflow.com/questions/6990760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568884/"
] | To answer my own question...
I bought a Logitech C210 today and the problem disappeared.
I'm now getting warnings:
`Corrupt JPEG data: X extraneous bytes before marker 0xYY`.
However, I am able to successfully push a video stream to my web-browser via `JpegStreamer()`. If I cannot solve this error, I'll open a new ... | Also I should mention, which I didn't realize, is that OpenCV less than 2.3 is broken with webcams on Ubuntu 11.04 and up. I didn't realize this as I was running Ubuntu 10.10 before, by the looks of your output you are using python 2.7 which makes me think you are on Ubuntu 11.04 or higher. Anyway, we have a fix for th... |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | ```
let newFavorites = favorites;
```
This assigns newFavorites to point to favorites
```
newFavorites.push(newFav);
```
Because newFavorites points to favorites, which is an array in `state`, you can't push anything onto it and have that change render.
What you need to do, is populate a new array `newFavorites` ... | I would make some changes in your addFavourite function:
function addFavorite(name, id) {
let newFav = {name, id};
```
setFavorites([…favourites, newFav]);
```
}
This way, everytime you click favourite, you ensure a new array is being created with spread operator |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | ```
let newFavorites = favorites;
```
This assigns newFavorites to point to favorites
```
newFavorites.push(newFav);
```
Because newFavorites points to favorites, which is an array in `state`, you can't push anything onto it and have that change render.
What you need to do, is populate a new array `newFavorites` ... | Its not working because use are mutating the existing state.
The list is updating but it won't render as useState only renders when the parameter passed to it is different from previous one but in your case though you are changing the list items still the reference is not altering.
To make it work you can use spread o... |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | ```
let newFavorites = favorites;
```
This assigns newFavorites to point to favorites
```
newFavorites.push(newFav);
```
Because newFavorites points to favorites, which is an array in `state`, you can't push anything onto it and have that change render.
What you need to do, is populate a new array `newFavorites` ... | For changing array state, you should use:
```
function addFavorite(name, id) {
let newFav = { name: name, id: id };
setFavorites((favorites) => [...favorites, newFav]);
}
``` |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | I would make some changes in your addFavourite function:
function addFavorite(name, id) {
let newFav = {name, id};
```
setFavorites([…favourites, newFav]);
```
}
This way, everytime you click favourite, you ensure a new array is being created with spread operator | Its not working because use are mutating the existing state.
The list is updating but it won't render as useState only renders when the parameter passed to it is different from previous one but in your case though you are changing the list items still the reference is not altering.
To make it work you can use spread o... |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | I would make some changes in your addFavourite function:
function addFavorite(name, id) {
let newFav = {name, id};
```
setFavorites([…favourites, newFav]);
```
}
This way, everytime you click favourite, you ensure a new array is being created with spread operator | For changing array state, you should use:
```
function addFavorite(name, id) {
let newFav = { name: name, id: id };
setFavorites((favorites) => [...favorites, newFav]);
}
``` |
69,383,255 | I am trying to calculate the distance between 2 points in python using this code :
```
import math
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Point({0}, {1})".format(self.x, self.y)
def __sub__(self, other):
return Point(... | 2021/09/29 | [
"https://Stackoverflow.com/questions/69383255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16743649/"
] | Its not working because use are mutating the existing state.
The list is updating but it won't render as useState only renders when the parameter passed to it is different from previous one but in your case though you are changing the list items still the reference is not altering.
To make it work you can use spread o... | For changing array state, you should use:
```
function addFavorite(name, id) {
let newFav = { name: name, id: id };
setFavorites((favorites) => [...favorites, newFav]);
}
``` |
40,634,826 | I'm using Swig 3.0.7 to create python 2.7-callable versions of C functions that define constants in this manner:
```c
#define MYCONST 5.0
```
In previous versions of swig these would be available to python transparently:
```py
import mymodule
x = 3. * mymodule.MYCONST
```
But now this generates a message
```no... | 2016/11/16 | [
"https://Stackoverflow.com/questions/40634826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263972/"
] | You can use [`split`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html), then cast column `year` to `int` and if necessary add `Q` to column `q`:
```
df = pd.DataFrame({'date':['2015Q1','2015Q2']})
print (df)
date
0 2015Q1
1 2015Q2
df[['year','q']] = df.date.str.split('Q', exp... | You could also construct a datetimeIndex and call year and quarter on it.
```
df.index = pd.to_datetime(df.date)
df['year'] = df.index.year
df['quarter'] = df.index.quarter
date year quarter
date
2015-01-01 2015Q1 2015 1
2015-04-01 2015Q2 2015 2
```
Not... |
51,567,959 | I am sort of new to python. I can open files in Windows with but am having trouble in Mac. I can open webbrowsers but I am unsure as to how I open other programs or word documents.
Thanks | 2018/07/28 | [
"https://Stackoverflow.com/questions/51567959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10147138/"
] | use this class `col-md-auto` to make width auto and `d-inline-block` to display column inline block (bootstrap 4)
```
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-md-auto col-lg-auto d-inline-block">
<label for="name">Com... | I think that you can see the example below,this may satisfy your need. Also,you can set the col-x-x property to place more that 3 input in one row.
[row-col example](http://%20https://v3.bootcss.com/components/#input-groups-buttons) |
63,627,160 | 1. I am trying to get a students attendance record set up in python. I have most of it figured out. I am stuck on one section and it is the attendane section. I am trying to use a table format (tksheets) to keep record of students names and their attendance. The issue I am having is working with tksheets. I can't seem ... | 2020/08/28 | [
"https://Stackoverflow.com/questions/63627160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4049491/"
] | Try Something like this-
```
';SELECT text
FROM notes
WHERE username = 'alice
``` | SQL Injection can be implemented by concatenating the SQL statement with the input parameters. For example, the following statement is vulnerable to SQL Injection:
```
String statement = "SELECT ID FROM USERS WHERE USERNAME = '" + inputUsername + "' AND PASSWORD = '" + hashedPassword + "'";
```
An attacker would en... |
63,283,368 | I've got the problem during setting up deploying using cloudbuild and dockerfile.
My `Dockerfile`:
```
FROM python:3.8
ARG ENV
ARG NUM_WORKERS
ENV PORT=8080
ENV NUM_WORKERS=$NUM_WORKERS
RUN pip install poetry
COPY pyproject.toml poetry.lock ./
RUN poetry config virtualenvs.create false && \
poetry install --no... | 2020/08/06 | [
"https://Stackoverflow.com/questions/63283368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11993534/"
] | Here is a working example of how you would attach the value of a configuration trait to another pallet's storage item.
Pallet 1
--------
Here is `pallet_1` which has the storage item we want to use.
>
> NOTE: This storage is marked `pub` so it is accessible outside the pallet.
>
>
>
```rust
use frame_support::{... | It is actually as creating a trait impl the struct and then in the runtime pass the struct to the receiver (by using the trait), what I did to learn this is to look at all of the pallets that are already there and see how the pass information
for instance this trait in authorship
<https://github.com/paritytech/substra... |
30,902,443 | I'm using vincent a data visualization package. One of the inputs it takes is path to data.
(from the documentation)
```
`geo_data` needs to be passed as a list of dicts with the following
| format:
| {
| name: data name
| url: path_to_data,
| feature: TopoJSON object s... | 2015/06/17 | [
"https://Stackoverflow.com/questions/30902443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4682755/"
] | It seems that you're using it in Jupyter Notebook. If no, my reply is irrelevant for your case.
AFAIK, vincent needs this topojson file to be available through web server (so javascript from your browser will be able to download it to build the map). If the topojson file is somewhere in the Jupyter root dir then it's ... | I know that this post is old, hopefully this helps someone. I am not sure what map you are looking for, but here is the URL for the world map
```
world_topo="https://raw.githubusercontent.com/wrobstory/vincent_map_data/master/world-countries.topo.json"
```
and the USA state maps
```
state_topo = "https://raw.github... |
17,975,795 | I'm sure this must be simple, but I'm a python noob, so I need some help.
I have a list that looks the following way:
```
foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]
```
Notice that every word has 1 or 2 numbers to it. I want to substr... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17975795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001008/"
] | `''` cannot be converted to string.
```
bar = []
for a,b,c in foo:
d = float(a or 0) - float(b or 0)
bar.append((c,d))
```
However, that will not make a dictionary. For that you want:
```
bar = {}
for a,b,c in foo:
d = float(a or 0)-float(b or 0)
bar[c] = d
```
Or a shorter way using dictionary co... | Add a condition to verify if the string is empty like that '' and convert it to 0 |
17,975,795 | I'm sure this must be simple, but I'm a python noob, so I need some help.
I have a list that looks the following way:
```
foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]
```
Notice that every word has 1 or 2 numbers to it. I want to substr... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17975795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001008/"
] | `''` cannot be converted to string.
```
bar = []
for a,b,c in foo:
d = float(a or 0) - float(b or 0)
bar.append((c,d))
```
However, that will not make a dictionary. For that you want:
```
bar = {}
for a,b,c in foo:
d = float(a or 0)-float(b or 0)
bar[c] = d
```
Or a shorter way using dictionary co... | `float('')` doesn't work. Assuming you want `0` in that case, I recommend a helper function:
```
def safefloat(s):
if not s:
return 0.0
return float(s)
res = {}
for a, b, c in foo:
res[c] = safefloat(a) - safefloat(b)
```
Note you can make the dictionary in one line with a comprehension:
```
r... |
17,975,795 | I'm sure this must be simple, but I'm a python noob, so I need some help.
I have a list that looks the following way:
```
foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]
```
Notice that every word has 1 or 2 numbers to it. I want to substr... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17975795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001008/"
] | `''` cannot be converted to string.
```
bar = []
for a,b,c in foo:
d = float(a or 0) - float(b or 0)
bar.append((c,d))
```
However, that will not make a dictionary. For that you want:
```
bar = {}
for a,b,c in foo:
d = float(a or 0)-float(b or 0)
bar[c] = d
```
Or a shorter way using dictionary co... | that happens because in some cases their is an empty string
you could write
```
d = float(a or '0') - float(b or '0')
``` |
17,975,795 | I'm sure this must be simple, but I'm a python noob, so I need some help.
I have a list that looks the following way:
```
foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'], ['0', '0', 'dorsal'], ['0', '0', 'ventral'], ['0', '0', 'acroscopic']]
```
Notice that every word has 1 or 2 numbers to it. I want to substr... | 2013/07/31 | [
"https://Stackoverflow.com/questions/17975795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001008/"
] | `''` cannot be converted to string.
```
bar = []
for a,b,c in foo:
d = float(a or 0) - float(b or 0)
bar.append((c,d))
```
However, that will not make a dictionary. For that you want:
```
bar = {}
for a,b,c in foo:
d = float(a or 0)-float(b or 0)
bar[c] = d
```
Or a shorter way using dictionary co... | ```
>>> foo = [['0.125', '0', 'able'], ['', '0.75', 'unable'],
['0', '0', 'dorsal'], ['0', '0', 'ventral'],
['0', '0', 'acroscopic']]
>>> dict((i[2], float(i[0] or 0) - float(i[1])) for i in foo)
{'acroscopic': 0.0, 'ventral': 0.0, 'unable': -0.75, 'able': 0.125,
'dorsal': 0.0}
``` |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | To translate you need a table of [codons](http://en.wikipedia.org/wiki/DNA_codon_table), so without dictionary or other data structure seems strange.
Maybe you can look into [biopython](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec26)? And see how they manage it.
You can also translate directly from the c... | You cannot practically do this without either a function or a dictionary. Part 1, converting the sequence into three-character codons, is easy enough as you have already done it.
But Part 2, to convert these into amino acids, you will need to define a mapping, either:
```
mapping = {"NNN": "X", ...}
```
or
```
def... |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | You cannot practically do this without either a function or a dictionary. Part 1, converting the sequence into three-character codons, is easy enough as you have already done it.
But Part 2, to convert these into amino acids, you will need to define a mapping, either:
```
mapping = {"NNN": "X", ...}
```
or
```
def... | you can convert the nucleotide bases in numbers (base 4) and then translate using ordered aa in a string:
```
def translate(seq,frame):
BASES = 'ACGT'
# standard code
AA = 'KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF'
# convert DNA sequence in numbers: A=0; C=1; G=2; T=3
seqn =... |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | To translate you need a table of [codons](http://en.wikipedia.org/wiki/DNA_codon_table), so without dictionary or other data structure seems strange.
Maybe you can look into [biopython](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec26)? And see how they manage it.
You can also translate directly from the c... | You got the amino acid output for the first codon only because you used 'return' inside the 'for loop'. Once the first amino acid is returned, the loop terminates, hence the second codon won't be tested at all.
You can create an empty list to keep the results for the translation of each codon, e.g.
```
aa = []
```
... |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | To translate you need a table of [codons](http://en.wikipedia.org/wiki/DNA_codon_table), so without dictionary or other data structure seems strange.
Maybe you can look into [biopython](http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec26)? And see how they manage it.
You can also translate directly from the c... | you can convert the nucleotide bases in numbers (base 4) and then translate using ordered aa in a string:
```
def translate(seq,frame):
BASES = 'ACGT'
# standard code
AA = 'KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF'
# convert DNA sequence in numbers: A=0; C=1; G=2; T=3
seqn =... |
21,188,579 | I'm stuck in a exercice in python where I need to convert a DNA sequence into its corresponding amino acids. So far, I have:
```
seq1 = "AATAGGCATAACTTCCTGTTCTGAACAGTTTGA"
for i in range(0, len(seq), 3):
print seq[i:i+3]
```
I need to do this without using dictionaries, and I was going for replace, but it seems... | 2014/01/17 | [
"https://Stackoverflow.com/questions/21188579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884400/"
] | You got the amino acid output for the first codon only because you used 'return' inside the 'for loop'. Once the first amino acid is returned, the loop terminates, hence the second codon won't be tested at all.
You can create an empty list to keep the results for the translation of each codon, e.g.
```
aa = []
```
... | you can convert the nucleotide bases in numbers (base 4) and then translate using ordered aa in a string:
```
def translate(seq,frame):
BASES = 'ACGT'
# standard code
AA = 'KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF'
# convert DNA sequence in numbers: A=0; C=1; G=2; T=3
seqn =... |
37,986,367 | How I can overcome an issue with conditionals in python? The issue is that it should show certain text according to certain conditional, but if the input was No, it anyway indicates the data of Yes conditional.
```
def main(y_b,c_y):
ans=input('R u Phil?')
if ans=='Yes' or 'yes':
years=y_b-c_y
... | 2016/06/23 | [
"https://Stackoverflow.com/questions/37986367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6492505/"
] | `or` is inclusive. So the `yes` test will always pass because when `ans != 'Yes'` the other condition `yes` has a truthy value.
```
>>> bool('yes')
True
```
You should instead test with:
```
if ans in ('Yes', 'yeah', 'yes'):
# code
elif ans in ('No', 'Nah', 'no'):
# code
else:
# more code
``` | When you write if statements and you have multiple conditionals, you have to write both conditionals and compare them. This is wrong:
```
if ans == 'Yes' or 'yes':
```
and this is ok:
```
if ans == 'Yes' or ans == 'yes':
``` |
37,986,367 | How I can overcome an issue with conditionals in python? The issue is that it should show certain text according to certain conditional, but if the input was No, it anyway indicates the data of Yes conditional.
```
def main(y_b,c_y):
ans=input('R u Phil?')
if ans=='Yes' or 'yes':
years=y_b-c_y
... | 2016/06/23 | [
"https://Stackoverflow.com/questions/37986367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6492505/"
] | When you write if statements and you have multiple conditionals, you have to write both conditionals and compare them. This is wrong:
```
if ans == 'Yes' or 'yes':
```
and this is ok:
```
if ans == 'Yes' or ans == 'yes':
``` | It's not that different from other languages:
```
def main(y_b,c_y):
ans = input('R u Phil?')
if ans == 'Yes' or ans == 'yes':
years = y_b-c_y
print('U r', abs(years), 'jahre alt')
elif ans == 'No' or ans == 'no':
print("How old r u?")
else:
prin... |
37,986,367 | How I can overcome an issue with conditionals in python? The issue is that it should show certain text according to certain conditional, but if the input was No, it anyway indicates the data of Yes conditional.
```
def main(y_b,c_y):
ans=input('R u Phil?')
if ans=='Yes' or 'yes':
years=y_b-c_y
... | 2016/06/23 | [
"https://Stackoverflow.com/questions/37986367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6492505/"
] | `or` is inclusive. So the `yes` test will always pass because when `ans != 'Yes'` the other condition `yes` has a truthy value.
```
>>> bool('yes')
True
```
You should instead test with:
```
if ans in ('Yes', 'yeah', 'yes'):
# code
elif ans in ('No', 'Nah', 'no'):
# code
else:
# more code
``` | It's not that different from other languages:
```
def main(y_b,c_y):
ans = input('R u Phil?')
if ans == 'Yes' or ans == 'yes':
years = y_b-c_y
print('U r', abs(years), 'jahre alt')
elif ans == 'No' or ans == 'no':
print("How old r u?")
else:
prin... |
49,021,968 | I have a list of filenames in a directory and I'd like to keep only the latest versions. The list looks like:
`['file1-v1.csv', 'file1-v2.csv', 'file2-v1.txt', ...]`.
I'd like to only keep the newest csv files as per the version (part after `-` in the filename) and the txt files.
The output would be `[''file1-v2.... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49021968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771315/"
] | Do this:
```
SELECT * FROM yourTable
WHERE DATE(punch_in_utc_time)=current_date;
```
For testing:
```
SELECT DATE("2018-02-28 09:32:00")=current_date;
```
See [DEMO on SQL Fiddle](http://sqlfiddle.com/#!9/9eecb/17666). | Should be able to do that using Date function, TRUNC timestamp to date then compare with the date field.
```
SELECT DATE("2018-02-28 09:32:00") = "2018-02-28";
```
The above dml will return 1 since the date part is equal. |
49,021,968 | I have a list of filenames in a directory and I'd like to keep only the latest versions. The list looks like:
`['file1-v1.csv', 'file1-v2.csv', 'file2-v1.txt', ...]`.
I'd like to only keep the newest csv files as per the version (part after `-` in the filename) and the txt files.
The output would be `[''file1-v2.... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49021968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771315/"
] | Should be able to do that using Date function, TRUNC timestamp to date then compare with the date field.
```
SELECT DATE("2018-02-28 09:32:00") = "2018-02-28";
```
The above dml will return 1 since the date part is equal. | I am not sure if this is what you wanted:
If you are using earlier version of SQL server use
```
CONVERT
```
(otherwise you might have to use `DATEPART` function instead), do this:
`SELECT CONVERT(punch_in_utc_time)` which will give you date only value.
So in your comparison:
```
SELECT 'TRUE' WHERE Convert(Date... |
49,021,968 | I have a list of filenames in a directory and I'd like to keep only the latest versions. The list looks like:
`['file1-v1.csv', 'file1-v2.csv', 'file2-v1.txt', ...]`.
I'd like to only keep the newest csv files as per the version (part after `-` in the filename) and the txt files.
The output would be `[''file1-v2.... | 2018/02/28 | [
"https://Stackoverflow.com/questions/49021968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2771315/"
] | Do this:
```
SELECT * FROM yourTable
WHERE DATE(punch_in_utc_time)=current_date;
```
For testing:
```
SELECT DATE("2018-02-28 09:32:00")=current_date;
```
See [DEMO on SQL Fiddle](http://sqlfiddle.com/#!9/9eecb/17666). | I am not sure if this is what you wanted:
If you are using earlier version of SQL server use
```
CONVERT
```
(otherwise you might have to use `DATEPART` function instead), do this:
`SELECT CONVERT(punch_in_utc_time)` which will give you date only value.
So in your comparison:
```
SELECT 'TRUE' WHERE Convert(Date... |
56,227,936 | I am getting the following error when I try to see if my object is valid using `full_clean()`.
```sh
django.core.exceptions.ValidationError: {'schedule_date': ["'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]}
```
I have tried all the formats recommended here, but ... | 2019/05/20 | [
"https://Stackoverflow.com/questions/56227936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9633315/"
] | The issue was with the logic of the code. I specified the time range that won't allow even one millionth second difference in the `schedule_date` and `timezone.now()`
After taking a look at the source code of `DateTimeField`, it seems like if I have my validator to throw code="invalid", it will just show the above err... | i solve this problem with this
```
datetime.strptime(request.POST['date'], "%Y-%m-%dT%H:%M")
``` |
64,799,578 | I am working on a python script, where I will be passing a directory, and I need to get all log-files from it. Currently, I have a small script which watches for any changes to these files and then processes that information.
It's working good, but it's just for a single file, and hardcoded file value. How can I pass ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64799578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1510701/"
] | You could use a generic / reusable approach based on the two-queries approach.
One SQL query to retrieve the entities' `IDs` and a second query with an `IN` predicate including the `IDs` from the second query.
Implementing a custom Spring Data JPA Executor:
```
@NoRepositoryBean
public interface AsimioJpaSpecificati... | I found a workaround myself. Based upon this:
[How can I avoid the Warning "firstResult/maxResults specified with collection fetch; applying in memory!" when using Hibernate?](https://stackoverflow.com/questions/11431670/how-can-i-avoid-the-warning-firstresult-maxresults-specified-with-collection-fe/46195656#4619565... |
64,799,578 | I am working on a python script, where I will be passing a directory, and I need to get all log-files from it. Currently, I have a small script which watches for any changes to these files and then processes that information.
It's working good, but it's just for a single file, and hardcoded file value. How can I pass ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64799578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1510701/"
] | You could use a generic / reusable approach based on the two-queries approach.
One SQL query to retrieve the entities' `IDs` and a second query with an `IN` predicate including the `IDs` from the second query.
Implementing a custom Spring Data JPA Executor:
```
@NoRepositoryBean
public interface AsimioJpaSpecificati... | The approach to fetch ids first and then do the main query works but is not very efficient. I think this is a perfect use case for [Blaze-Persistence](https://persistence.blazebit.com/documentation/core/manual/en_US/index.html#anchor-offset-pagination).
Blaze-Persistence is a query builder on top of JPA which supports... |
28,814,455 | I am appending a file via python based on the code that has been input by the user.
```
with open ("markbook.txt", "a") as g:
g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4)
```
`sn`, `sna`, `sg1`, `sg2`, `sg3`, `sg4` have all been entered by the user and when the program is finished a line will be adde... | 2015/03/02 | [
"https://Stackoverflow.com/questions/28814455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4624147/"
] | Add a "\n" to the end of the write line.
So:
```
g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4+"\n")
``` | You're missing the new line character at the end of your string. Also, though string concatenation is completely fine in this case, you should be aware that Python has alternative options for formatting strings.
```
with open('markbook.txt', 'a') as g:
g.write('{},{},{},{},{},{}\n'
.format(s... |
28,814,455 | I am appending a file via python based on the code that has been input by the user.
```
with open ("markbook.txt", "a") as g:
g.write(sn+","+sna+","+sg1+","+sg2+","+sg3+","+sg4)
```
`sn`, `sna`, `sg1`, `sg2`, `sg3`, `sg4` have all been entered by the user and when the program is finished a line will be adde... | 2015/03/02 | [
"https://Stackoverflow.com/questions/28814455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4624147/"
] | You need to write line separators between your your lines:
```
g.write(sn + "," + sna + "," + sg1 + "," + sg2 + "," + sg3 + "," + sg4 + '\n')
```
You appear to be reinventing the CSV wheel, however. Leave separators (line or column) to the [`csv` library](https://docs.python.org/2/library/csv.html) instead:
```
imp... | You're missing the new line character at the end of your string. Also, though string concatenation is completely fine in this case, you should be aware that Python has alternative options for formatting strings.
```
with open('markbook.txt', 'a') as g:
g.write('{},{},{},{},{},{}\n'
.format(s... |
37,518,997 | My question is related to this earlier question - [Python subprocess usage](https://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments)
I am trying to run this command using python
**nccopy -k 4 "<http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysi... | 2016/05/30 | [
"https://Stackoverflow.com/questions/37518997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4033876/"
] | There's two dilemmas here.
One being that subprocess processes your arguments and tries to use `4` as a separate argument.
The other being that system calls still goes under normal shell rules, meaning that parameters and commands will be parsed for [metacharacters](http://www.tutorialspoint.com/unix/unix-quoting-m... | Instead of arg1 = "-k 4", use two arguments instead.
```
import subprocess
url = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis2/pressure/air.2014.nc?air[408:603][2][20:34][26:40]'
outputFile = 'foo.nc'
arg1 = "-k"
arg2 = "4"
arg3 = url
arg4 = outputFile
subprocess.check_call(["nccopy", arg1... |
37,518,997 | My question is related to this earlier question - [Python subprocess usage](https://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments)
I am trying to run this command using python
**nccopy -k 4 "<http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysi... | 2016/05/30 | [
"https://Stackoverflow.com/questions/37518997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4033876/"
] | Instead of arg1 = "-k 4", use two arguments instead.
```
import subprocess
url = 'http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis2/pressure/air.2014.nc?air[408:603][2][20:34][26:40]'
outputFile = 'foo.nc'
arg1 = "-k"
arg2 = "4"
arg3 = url
arg4 = outputFile
subprocess.check_call(["nccopy", arg1... | If you have a working shell command that runs a single program with multiple arguments and you want to parameterized it e.g., to use a variable filename instead of the hardcoded value then you could use `shlex.split()` to create a list of command-line arguments that you could pass to `subprocess` module and replace the... |
37,518,997 | My question is related to this earlier question - [Python subprocess usage](https://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments)
I am trying to run this command using python
**nccopy -k 4 "<http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysi... | 2016/05/30 | [
"https://Stackoverflow.com/questions/37518997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4033876/"
] | There's two dilemmas here.
One being that subprocess processes your arguments and tries to use `4` as a separate argument.
The other being that system calls still goes under normal shell rules, meaning that parameters and commands will be parsed for [metacharacters](http://www.tutorialspoint.com/unix/unix-quoting-m... | If you have a working shell command that runs a single program with multiple arguments and you want to parameterized it e.g., to use a variable filename instead of the hardcoded value then you could use `shlex.split()` to create a list of command-line arguments that you could pass to `subprocess` module and replace the... |
54,677,761 | The following code generates the warning in tensorflow r1.12 python API:
```
#!/usr/bin/python3
import tensorflow as tf
M = tf.keras.models.Sequential();
M.add(tf.keras.layers.Dense(2));
```
The complete warning text is this:
```
WARNING: Logging before flag parsing goes to stderr.
W0213 15:50:07.239809 140701996... | 2019/02/13 | [
"https://Stackoverflow.com/questions/54677761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906266/"
] | You are running tensor flow 2.0 and it looks like VarianceScaling.**init** is deprecated. It might mean that Sequential will need to be more explicitly initialized in the future.
for example:
```py
model = tf.keras.Sequential([
# Adds a densely-connected layer with 64 units to the model:
layers.Dense(64, activation='... | This is just a warning based on the [changes in Tensorflow 2.0](https://www.tensorflow.org/beta/guide/effective_tf2).
If you don't want to see these warnings, upgrade to TensorFlow 2.0. You can install the beta version via pip:
```
pip install tensorflow==2.0.0-beta1
``` |
54,677,761 | The following code generates the warning in tensorflow r1.12 python API:
```
#!/usr/bin/python3
import tensorflow as tf
M = tf.keras.models.Sequential();
M.add(tf.keras.layers.Dense(2));
```
The complete warning text is this:
```
WARNING: Logging before flag parsing goes to stderr.
W0213 15:50:07.239809 140701996... | 2019/02/13 | [
"https://Stackoverflow.com/questions/54677761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7906266/"
] | The warning may be caused upstream by `abseil-py`, a dependency of `tensorflow`.
See the details [here](https://github.com/tensorflow/tensorflow/issues/26691).
An easy fix may be to update `abseil-py` by running:
`pip install --upgrade absl-py`
(In my case, the conflicting version was `0.7.1` and the problem was fixe... | This is just a warning based on the [changes in Tensorflow 2.0](https://www.tensorflow.org/beta/guide/effective_tf2).
If you don't want to see these warnings, upgrade to TensorFlow 2.0. You can install the beta version via pip:
```
pip install tensorflow==2.0.0-beta1
``` |
2,641,665 | I've got a Django app that accepts uploads from [jQuery uploadify](http://www.uploadify.com/), a jQ plugin that uses flash to upload files and give a progress bar.
Files under about 150k work, but bigger files always fail and almost always at around 192k (that's 3 chunks) completed, sometimes at around 160k. The Excep... | 2010/04/14 | [
"https://Stackoverflow.com/questions/2641665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246265/"
] | Html.DropDownList() accepts a SelectList as a parameter which has a SelectedValue property. Specify the selected item when you create the SelectList and pass the SelectList to the Html.DropDownList(). | Here's an example that has 7 drop downs on the page, each with the same 5 options. Each drop down can have a different option selected.
In my view, I have the following code inside my form:
```
<%= Html.DropDownListFor(m => m.ValueForList1, Model.AllItems)%>
<%= Html.DropDownListFor(m => m.ValueForList2, Model.AllIte... |
2,641,665 | I've got a Django app that accepts uploads from [jQuery uploadify](http://www.uploadify.com/), a jQ plugin that uses flash to upload files and give a progress bar.
Files under about 150k work, but bigger files always fail and almost always at around 192k (that's 3 chunks) completed, sometimes at around 160k. The Excep... | 2010/04/14 | [
"https://Stackoverflow.com/questions/2641665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246265/"
] | Html.DropDownList() accepts a SelectList as a parameter which has a SelectedValue property. Specify the selected item when you create the SelectList and pass the SelectList to the Html.DropDownList(). | class 'Item' with properties 'Id' and 'Name'
ViewModel class has a Property 'SelectedItemId'
items = IEnumerable<Item>
```
<%=Html.DropDownList("selectname", items.Select(i => new SelectListItem{ Text = i.Name, Value = i.Id.ToString(), Selected = Model.SelectedItemId.HasValue ? i.Id == Model.SelectedItemId.Value... |
2,641,665 | I've got a Django app that accepts uploads from [jQuery uploadify](http://www.uploadify.com/), a jQ plugin that uses flash to upload files and give a progress bar.
Files under about 150k work, but bigger files always fail and almost always at around 192k (that's 3 chunks) completed, sometimes at around 160k. The Excep... | 2010/04/14 | [
"https://Stackoverflow.com/questions/2641665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246265/"
] | class 'Item' with properties 'Id' and 'Name'
ViewModel class has a Property 'SelectedItemId'
items = IEnumerable<Item>
```
<%=Html.DropDownList("selectname", items.Select(i => new SelectListItem{ Text = i.Name, Value = i.Id.ToString(), Selected = Model.SelectedItemId.HasValue ? i.Id == Model.SelectedItemId.Value... | Here's an example that has 7 drop downs on the page, each with the same 5 options. Each drop down can have a different option selected.
In my view, I have the following code inside my form:
```
<%= Html.DropDownListFor(m => m.ValueForList1, Model.AllItems)%>
<%= Html.DropDownListFor(m => m.ValueForList2, Model.AllIte... |
73,662,597 | I have setup Glue Interactive sessions locally by following <https://docs.aws.amazon.com/glue/latest/dg/interactive-sessions.html>
However, I am not able to add any additional packages like HUDI to the interactive session
There are a few magic commands to use but not sure which one is apt and how to use
```
%addition... | 2022/09/09 | [
"https://Stackoverflow.com/questions/73662597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19958017/"
] | It is a bit hard t understand what problem you are actually facing, as this is very basic SQL.
Use `EXISTS`:
```
select *
from a
where type = 'F'
and exists (select null from b where b.id = a.id and dt >= date '2022-01-01');
```
Or `IN`:
```
select *
from a
where type = 'F'
and id in (select id from b where dt >= ... | ```
SELECT *
FROM A
WHERE type='F'
AND id IN (
SELECT id
FROM B
WHERE DATE>='2022-01-01'; -- '2022' imo should be enough, need to check
);
```
I don't think joining is necessary. |
48,497,092 | I implement multiple linear regression from scratch but I did not find slope and intercept, gradient decent give me nan value.
Here is my code and I also give ipython notebook file.
<https://drive.google.com/file/d/1NMUNL28czJsmoxfgeCMu3KLQUiBGiX1F/view?usp=sharing>
```
import pandas as pd
import numpy as np
import... | 2018/01/29 | [
"https://Stackoverflow.com/questions/48497092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5107898/"
] | This is not a programming issue, but an issue of your function. [Numpy can use different data types](https://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html). In your case it uses float64. You can check the largest number, you can represent with this data format:
```
>>>sys.float_info
>>>sys.float_info(max=1.79... | try scaling your x
```py
def scale(x):
for j in range(x.shape[1]):
mean_x = 0
for i in range(len(x)):
mean_x += x[i,j]
mean_x = mean_x / len(x)
sum_of_sq = 0
for i in range(len(x)):
sum_of_sq += (x[i,j] - mean_x)**2
stdev = sum_of_sq / (x.shap... |
70,964,456 | I had an issue like this on my Nano:
```
profiles = [ SERIAL_PORT_PROFILE ],
File "/usr/lib/python2.7/site-packages/bluetooth/bluez.py", line 176, in advertise_service
raise BluetoothError (str (e))
bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')
```
I tried adding compatibility mode in the... | 2022/02/03 | [
"https://Stackoverflow.com/questions/70964456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18104741/"
] | You might want to have a look at the following article which shows how to do the connection with core Python Socket library
<https://blog.kevindoran.co/bluetooth-programming-with-python-3/>.
The way BlueZ does this now is with the [Profile](https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/profile-api.txt) A... | The solution was in the path of the bluetooth configuration file (inspired from this <https://developer.nvidia.com/embedded/learn/tutorials/connecting-bluetooth-audio>)
this answer : [bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')](https://stackoverflow.com/questions/36675931/bluetooth-btcommon-bl... |
24,879,641 | I've been looking everywhere for a step-by-step explanation for how to set up the following on an EC2 instance. For a new user I want things to be clean and correct but all of the 'guides' have different information and are really confusing.
My first thought is that I need to do the following
* Upgrade to latest vers... | 2014/07/22 | [
"https://Stackoverflow.com/questions/24879641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3195487/"
] | I assume you may be unfamiliar with EC2, so I suggest going through this [FAQ](https://wiki.debian.org/Amazon/EC2/FAQ) before continuing with deploying an EC2 instance to run your Python2.7 application.
Anyway, now that you are somewhat more familiar with that, here's how I normally deploy a one-off instance through t... | A script to build python in case the version you need is not in an available repo:
<https://gist.github.com/AvnerCohen/3e5cbe09bc40231869578ce7cbcbe9cc>
```
#!/bin/bash -e
NEW_VERSION="2.7.13"
CURRENT_VERSION="$(python -V 2>&1)"
if [[ "$CURRENT_VERSION" == "Python $NEW_VERSION" ]]; then
echo "Python $NEW_V... |
40,145,127 | I'm trying to construct a URL based on what I get from a initial URL.
Example:
*URL1:*
```
http://some-url/rest/ids?configuration_path=project/Main/10-deploy
```
**Response here is** 123
*URL2:*
```
http://abc-bld/download/{RESPONSE_FROM_URL1_HERE}.latest_successful/artifacts/build-info.props
```
so my final U... | 2016/10/20 | [
"https://Stackoverflow.com/questions/40145127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5622743/"
] | First how you can import your variable without modifying extra.py, if really want too,
You would have to take help of sys module for getting reference to foo in extra module.
```
import sys
from extra import *
print('1. Foo in globals ? {0}'.format('foo' in globals()))
setfoo()
print('2. Foo in globals ? {0}'.format... | Modules have namespaces which are variable names bound to objects. When you do `from extra import *`, you take the objects found in `extra`'s namespace and bind them to new variables in the new module. If `setfoo` has never been called, then `extra` doesn't have a variable called `foo` and there is nothing to bind in t... |
40,145,127 | I'm trying to construct a URL based on what I get from a initial URL.
Example:
*URL1:*
```
http://some-url/rest/ids?configuration_path=project/Main/10-deploy
```
**Response here is** 123
*URL2:*
```
http://abc-bld/download/{RESPONSE_FROM_URL1_HERE}.latest_successful/artifacts/build-info.props
```
so my final U... | 2016/10/20 | [
"https://Stackoverflow.com/questions/40145127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5622743/"
] | First how you can import your variable without modifying extra.py, if really want too,
You would have to take help of sys module for getting reference to foo in extra module.
```
import sys
from extra import *
print('1. Foo in globals ? {0}'.format('foo' in globals()))
setfoo()
print('2. Foo in globals ? {0}'.format... | Without knowing details, one possible solution would be to return `foo` in `extra.py setfoo()` function instead of declaring as a global variable.
Then declare global `foo` in main.py and feed in value from external function `setfoo()`
Here is the setup
```
#extra.py
def setfoo(): # sets "foo" to 5 even if it is ... |
25,585,785 | I'm using python 3.3. Consider this function:
```
def foo(action, log=False,*args) :
print(action)
print(log)
print(args)
print()
```
The following call works as expected:
```
foo("A",True,"C","D","E")
A
True
('C', 'D', 'E')
```
But this one doesn't.
```
foo("A",log=True,"C","D","E")
SyntaxErro... | 2014/08/30 | [
"https://Stackoverflow.com/questions/25585785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888862/"
] | Consider the following:
```
def foo(bar="baz", bat=False, *args):
...
```
Now if I call
```
foo(bat=True, "bar")
```
Where does "bar" go? Either:
* `bar = "bar", bat = True, args = ()`, or
* `bar = "baz", bat = True, args = ("bar",)`, or even
* `bar = "baz", bat = "bar", args = ()`
and there's no obvious ch... | The function of keyword arguments is twofold:
1. To provide an interface to functions that does not rely on the order of the parameters.
2. To provide a way to reduce ambiguity when passing parameters to a function.
Providing a mixture of keyword and ordered arguments is only a problem when you provide the keyword ar... |
53,965,764 | Hi I'm learning to code in python and thought it would be cool to automate a task I usually do for my room mates. I write out a list of names and the date for each month so that everyone knows whos turn it is for dishes.
Here's my code:
```
def dish_day_cycle(month, days):
print('Dish Cycle For %s:' % month)
... | 2018/12/29 | [
"https://Stackoverflow.com/questions/53965764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10844873/"
] | You used a nested for loop, therefore for every day - each of the names is printed along with that day. Use only the outer loop, and calculate who's turn it is. should be something like:
```
for day in range(1, days):
print('%s %s : %s' % (month, day, dish_list[day % len(dish_list)]))
```
assuming your roomates ... | You can loop through both lists together and repeating the shorter with `itertools.cycle`:
```
import itertools
for day, person in zip(range(1, days), itertools.cycle(dish_list)):
print('{} {} : {}'.format(month, day, person))
```
Update:
`zip` will pair elements in the two iterables--`range` object of days an... |
53,965,764 | Hi I'm learning to code in python and thought it would be cool to automate a task I usually do for my room mates. I write out a list of names and the date for each month so that everyone knows whos turn it is for dishes.
Here's my code:
```
def dish_day_cycle(month, days):
print('Dish Cycle For %s:' % month)
... | 2018/12/29 | [
"https://Stackoverflow.com/questions/53965764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10844873/"
] | You used a nested for loop, therefore for every day - each of the names is printed along with that day. Use only the outer loop, and calculate who's turn it is. should be something like:
```
for day in range(1, days):
print('%s %s : %s' % (month, day, dish_list[day % len(dish_list)]))
```
assuming your roomates ... | The problem is that you're iterating over the days and then for over the list of names. Imagine running line by line because a for loop only repeats after it has gotten to the end of an item. So you've said in your function, for each day each person has to do the dishes which is why you have all this repetition.
Much ... |
44,861,989 | I have an xlsx file, with columns with various coloring.
I want to read only the white columns of this excel in python using pandas, but I have no clues on hot to do this.
I am able to read the full excel into a dataframe, but then I miss the information about the coloring of the columns and I don't know which colum... | 2017/07/01 | [
"https://Stackoverflow.com/questions/44861989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4402942/"
] | **(Disclosure: I'm one of the authors of the library I'm going to suggest)**
With [StyleFrame](https://github.com/DeepSpace2/StyleFrame) (that wraps pandas) you can read an excel file into a dataframe without loosing the style data.
Consider the following sheet:
[ and save the results
3. Create pa... |
51,165,672 | When I execute the code below, is there anyway to keep python compiler running the code without error messages popping up?
Since I don't know how to differentiate integers and strings,
when `int(result)` executes and `result` contains letters, it spits out an error message that stops the program.
Is there anyway a... | 2018/07/04 | [
"https://Stackoverflow.com/questions/51165672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029884/"
] | Actually, with Python and many other languages, you can differentiate types.
When you execute `int(result)`, the `int` builtin assumes the parameter value is able to be turned into an integer. If not, say the string is `abc123`, it can not turn that string into an integer and will raise an exception.
An easy way arou... | You can put everything that might throw an error, in a try block, and have an except block that keeps the flow of the program.
btw I think, in your code it should be, `isinstance(result,int)` not `isinstance(result,str)`
In your case,
```
result = input('Type in your number,type y when finished.\n')
try:
result ... |
51,165,672 | When I execute the code below, is there anyway to keep python compiler running the code without error messages popping up?
Since I don't know how to differentiate integers and strings,
when `int(result)` executes and `result` contains letters, it spits out an error message that stops the program.
Is there anyway a... | 2018/07/04 | [
"https://Stackoverflow.com/questions/51165672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029884/"
] | Let's look at your code:
```
int(result)
```
All that will do is raise an exception if `result` cannot be converted to an `int`. It does **not** change `result`. Why not? Because in python string (and int) objects cannot be changed, they are *immutable*. So:
```
if isinstance(result,str):
print('finished')
```... | Actually, with Python and many other languages, you can differentiate types.
When you execute `int(result)`, the `int` builtin assumes the parameter value is able to be turned into an integer. If not, say the string is `abc123`, it can not turn that string into an integer and will raise an exception.
An easy way arou... |
51,165,672 | When I execute the code below, is there anyway to keep python compiler running the code without error messages popping up?
Since I don't know how to differentiate integers and strings,
when `int(result)` executes and `result` contains letters, it spits out an error message that stops the program.
Is there anyway a... | 2018/07/04 | [
"https://Stackoverflow.com/questions/51165672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029884/"
] | Let's look at your code:
```
int(result)
```
All that will do is raise an exception if `result` cannot be converted to an `int`. It does **not** change `result`. Why not? Because in python string (and int) objects cannot be changed, they are *immutable*. So:
```
if isinstance(result,str):
print('finished')
```... | You can put everything that might throw an error, in a try block, and have an except block that keeps the flow of the program.
btw I think, in your code it should be, `isinstance(result,int)` not `isinstance(result,str)`
In your case,
```
result = input('Type in your number,type y when finished.\n')
try:
result ... |
69,216,484 | Hello I'm trying to sort my microscpoy images.
I'm using python 3.7
File names' are like this. t0, t1, t2
```
S18_b0s17t0c0x62672-1792y6689-1024.tif
S18_b0s17t1c0x62672-1792y6689-1024.tif
S18_b0s17t2c0x62672-1792y6689-1024.tif
.
.
.
S18_b0s17t145c0x62672-1792y6689-1024
```
I tried "sorted" the list but it was like t... | 2021/09/17 | [
"https://Stackoverflow.com/questions/69216484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16075554/"
] | **Updated answer for your updated question:**
**The simple answer to your question is that you can use [string.Split](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0) to separate that string at the commas.** But the fact that you have to do this is indicative of a larger problem with your... | I'm editing the answer based on the new information.
I'd still consider using my Dapper wrapper package.
<https://www.nuget.org/packages/Cworth.DapperExtensions/#>
Create a model class that matches the filed returned in your select.
```
public class MyModel
{
public string Command { get; set; }
public string... |
59,126,742 | i am playing with wxPython and try to set position of frame:
```
import wx
app = wx.App()
p = wx.Point(200, 200)
frame = wx.Frame(None, title = 'test position', pos = p)
frame.Show(True)
print('frame position: ', frame.GetPosition())
app.MainLoop()
```
even though `print('frame position: ', frame.GetPosition())` ... | 2019/12/01 | [
"https://Stackoverflow.com/questions/59126742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3455890/"
] | I had the same problem under Windows and played around with the style flags. With wxICONIZE sytle set active the window finally used the positioning information | The position is provided to the window manager as a "hint". It is totally up to the window manager whether it will actually honor the hint or not. Check the openbox settings or preferences and see if there is anything relevant that can be changed. |
56,451,482 | Within my main window I have a table of class QTreeView. The second column contains subjects of mails. With a click of a push button I want to search for a specific character, let's say "Y". Now I want the table to jump to the first found subject beginning with the letter "Y".
See the following example.
[![enter imag... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56451482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10598535/"
] | You have to do the following:
* Use the [`match()`](https://doc.qt.io/qt-5/qabstractitemmodel.html#match) method of view to find the QModelIndex given the text.
* Use the [`scrollTo()`](https://doc.qt.io/qt-5/qabstractitemview.html#scrollTo) method of view to scroll to QModelIndex
* Use the [`select()`](https://doc.qt... | I'll be honnest, I don't use GUI with python but here is how you could do by replacing my arbitrary functions by the needed ones with PyQT
```py
mostWantedChar = 'Y'
foundElements = []
for element in dataView.listElements():
if element[0] == mostWantedChar:
foundElements.Append(element + '@' + element.Lin... |
4,089,843 | I'm looking to implement a SOAP web service in python on top of IIS. Is there a recommended library that would take a given Python class and expose its functions as web methods? It would be great if said library would also auto-generate a WSDL file based on the interface. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4089843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
] | There is an article by Doug Hellmann that evaluates various SOAP Tools
* <http://doughellmann.com/2009/09/01/evaluating-tools-for-developing-with-soap-in-python.html>
Other ref:
* <http://wiki.python.org/moin/WebServices>
* <http://pywebsvcs.sourceforge.net/> | Take a look at SOAPpy (<http://pywebsvcs.sourceforge.net/>). It allows you to expose your functions as web methods, but you have to add a line of code (manually) to register your function with the exposed web service. It is fairly easy to do. Also, it doesn't auto generate wsdl for you.
Here's an example of how to crea... |
4,089,843 | I'm looking to implement a SOAP web service in python on top of IIS. Is there a recommended library that would take a given Python class and expose its functions as web methods? It would be great if said library would also auto-generate a WSDL file based on the interface. | 2010/11/03 | [
"https://Stackoverflow.com/questions/4089843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11208/"
] | You might want to take a look at <https://github.com/stepank/pyws>, it can expose python functions as SOAP methods and provides WSDL description. I've just released version 1.0, it's interoperability was tested on several clients, so it seems to be quite friendly. | Take a look at SOAPpy (<http://pywebsvcs.sourceforge.net/>). It allows you to expose your functions as web methods, but you have to add a line of code (manually) to register your function with the exposed web service. It is fairly easy to do. Also, it doesn't auto generate wsdl for you.
Here's an example of how to crea... |
11,387,575 | The [python sample source code](https://developers.google.com/drive/examples/python#complete_source_code) goes thru the details of authentication/etc. I am looking for a simple upload to the Google Drive folder that has public writable permissions. (Plan to implement authorization at a later point).
I want to replace... | 2012/07/08 | [
"https://Stackoverflow.com/questions/11387575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055761/"
] | You can't. All requests to the Drive API need authentication (source: <http://developers.google.com/drive/about_auth>) | As Wooble said, you cannot do this without authentication. You can use this service + file-upload widget to let your website visitors upload files to your Google Drive folder: <https://github.com/cloudwok/file-upload-embed/> |
32,341,972 | I'm creating a small python program that iterates through a folder structure and performs a task on every audio file that it finds.
I need to identify which files are audio and which are 'other' (e.g. jpegs of the album cover) that I want the process to ignore and just move onto the next file.
From searching on Stack... | 2015/09/01 | [
"https://Stackoverflow.com/questions/32341972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1701514/"
] | This is likely happening because you are drawing your screenshot in your `Activity#onCreate()`. At this point, your View has not measured its dimensions, so `View#getDrawingCache()` will return null because width and height of the view will be 0.
You can move your screenshot code away from `onCreate()` or you could us... | got the solution from @ugo's suggestion
put this in a your onCreate function
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_share );
//
...
///
myLayout.getViewTreeObserv... |
60,410,173 | I have a pip requirements file that includes specific cpu-only versions of torch and torchvision. I can use the following pip command to successfully install my requirements.
```bash
pip install --requirement azure-pipelines-requirements.txt --find-links https://download.pytorch.org/whl/torch_stable.html
```
My requ... | 2020/02/26 | [
"https://Stackoverflow.com/questions/60410173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/575530/"
] | [This example](https://github.com/conda/conda/blob/54e4a91d0da4d659a67e3097040764d3a2f6aa16/tests/conda_env/support/advanced-pip/environment.yml) shows how to specify options for pip
Specify the global pip option first:
```
name: build
dependencies:
- python=3.6
- pip
- pip:
- --find-links https://d... | Found the answer in the pip documentation [here](https://pip.pypa.io/en/stable/reference/pip_install/#requirement-specifiers). I can add the `find-links` option to my requirements file, so my conda environment yaml file becomes
```yaml
name: build
dependencies:
- python=3.6
- pip
- pip:
- --requirement azure... |
45,894,208 | I'm using Spyder to do some small projects with Keras, and every now and then (I haven't pinned down what it is in the code that makes it appear) I get this message:
```
File "~/.local/lib/python3.5/site-packages/google/protobuf/descriptor_pb2.py", line 1771, in <module>
__module__ = 'google.protobuf.descriptor_... | 2017/08/26 | [
"https://Stackoverflow.com/questions/45894208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718331/"
] | Ok, I found the cause: interrupting the execution before Keras fully loads.
As said before restarting Spyder (or just the console) solves it. | I had the same problem with Spyder, which happened when it was trying to reload modules that were already loaded. I solved it by disabling the UMR (User Module Reloader) option in "preferences -> python interpreter" . |
45,894,208 | I'm using Spyder to do some small projects with Keras, and every now and then (I haven't pinned down what it is in the code that makes it appear) I get this message:
```
File "~/.local/lib/python3.5/site-packages/google/protobuf/descriptor_pb2.py", line 1771, in <module>
__module__ = 'google.protobuf.descriptor_... | 2017/08/26 | [
"https://Stackoverflow.com/questions/45894208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718331/"
] | Ok, I found the cause: interrupting the execution before Keras fully loads.
As said before restarting Spyder (or just the console) solves it. | Restarting Sypder works or run your script using console only.
Don't forget to use at the top:
```
from google.cloud import bigquery
from google.oauth2 import service_account
from google.auth.transport import requests
``` |
45,894,208 | I'm using Spyder to do some small projects with Keras, and every now and then (I haven't pinned down what it is in the code that makes it appear) I get this message:
```
File "~/.local/lib/python3.5/site-packages/google/protobuf/descriptor_pb2.py", line 1771, in <module>
__module__ = 'google.protobuf.descriptor_... | 2017/08/26 | [
"https://Stackoverflow.com/questions/45894208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1718331/"
] | I had the same problem with Spyder, which happened when it was trying to reload modules that were already loaded. I solved it by disabling the UMR (User Module Reloader) option in "preferences -> python interpreter" . | Restarting Sypder works or run your script using console only.
Don't forget to use at the top:
```
from google.cloud import bigquery
from google.oauth2 import service_account
from google.auth.transport import requests
``` |
65,266,224 | I'm new to python so please kindly help, I don't know much.
I'm working on a project which asks for a command, if the command is = to "help" then it will say how to use the program. I can't seem to do this, every time I try to use the if statement, it still prints the help section wether the command exists or not.
**... | 2020/12/12 | [
"https://Stackoverflow.com/questions/65266224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14759499/"
] | If you are using gnu-efi, use `uefi_call_wrapper()` to call UEFI functions.
```c
RT->GetTime(time, NULL); // Program hangs
uefi_call_wrapper(RT->GetTime, 2, time, NULL); // Okay
```
The reason is the different calling convention between UEFI (which uses Microsoft x64 calling convention) and Linux (which uses Syste... | I think you missed to initialize RT.
```
RT = SystemTable->RuntimeServices;
```
Your code is very similar to one of the examples (the one at section 4.7.1) of the Unified Extensible Firmware Interface Specification 2.6. I doubth you haven't read it, but just in case.
<https://www.uefi.org/sites/default/files/resour... |
25,310,746 | I've large set of images. I wan't to chage their background to specific color. Lets say green. All of the images have transparent background. Is there a way to perform this action using python-fu scripting in Gimp. Or some other tool available to do this specific task in automated fashion. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25310746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811502/"
] | The fact is that when you query a model (via a QuerySet method, or indirectly via a ForeignKey) **you get non-polymorphic instances** - in contrast to SQLAlchemy, where you get polymorphic instances.
This is because the fetched data corresponds only to the data you're accessing (and it's ancestors since they are known... | According to Django Documentation:
`If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using the lower-case version of the model name:`
```
p = Place.objects.get(id=12)
p.restaurant
```
Further to that:
>
> **However, if p in the above example was not a Re... |
25,310,746 | I've large set of images. I wan't to chage their background to specific color. Lets say green. All of the images have transparent background. Is there a way to perform this action using python-fu scripting in Gimp. Or some other tool available to do this specific task in automated fashion. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25310746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/811502/"
] | The fact is that when you query a model (via a QuerySet method, or indirectly via a ForeignKey) **you get non-polymorphic instances** - in contrast to SQLAlchemy, where you get polymorphic instances.
This is because the fetched data corresponds only to the data you're accessing (and it's ancestors since they are known... | As another workaround, I wrote this function that can be used for the same purpose without the need of `django-polymorphic` :
```
def is_model_instance(object, model):
'''
`object` is expected to be a subclass of models.Model
`model` should be a string containing the name of a models.Model subclass
R... |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | You can wrap it in a [io.TextIOWrapper](http://docs.python.org/library/io.html#io.TextIOWrapper).
```
items_file = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
```
Should work. | [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) is on the right track (Thanks, Lennart, I voted up your answer) and it **almost** works:
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.Z... |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | I just noticed that [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) didn't work with Python **3.1**, but it **does** work with [Python **3.2**](http://www.python.org/download/releases/3.2/). They've enhanced [`zipfile.ZipExt... | You can wrap it in a [io.TextIOWrapper](http://docs.python.org/library/io.html#io.TextIOWrapper).
```
items_file = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
```
Should work. |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | You can wrap it in a [io.TextIOWrapper](http://docs.python.org/library/io.html#io.TextIOWrapper).
```
items_file = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
```
Should work. | And if you just like to read a file into a string:
```
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
eggs = myfile.read().decode('UTF-8'))
``` |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | You can wrap it in a [io.TextIOWrapper](http://docs.python.org/library/io.html#io.TextIOWrapper).
```
items_file = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')
```
Should work. | Starting with Python 3.8, the zipfile module has the [Path object](https://docs.python.org/3.8/library/zipfile.html#path-objects), which we can use with its open() method to get an io.TextIOWrapper object, which can be passed to the csv readers:
```py
import csv, sys, zipfile
# Give a string path to the ZIP archive, ... |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | I just noticed that [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) didn't work with Python **3.1**, but it **does** work with [Python **3.2**](http://www.python.org/download/releases/3.2/). They've enhanced [`zipfile.ZipExt... | [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) is on the right track (Thanks, Lennart, I voted up your answer) and it **almost** works:
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.Z... |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
``... | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | And if you just like to read a file into a string:
```
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
eggs = myfile.read().decode('UTF-8'))
``` | [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) is on the right track (Thanks, Lennart, I voted up your answer) and it **almost** works:
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.Z... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.