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
|
|---|---|---|---|---|---|
63,191,480
|
I wrote a small code with python. But this part of the code doesn't work when game focused on and it doesnt respond back.
`pyautogui.moveRel(-2, 4)`
Also this part works when my cursor appear in menu or etc. too. But when i switched into game (when my cursor disappear and crosshair appeared) it doesn't work (doesn't matter fullscreen or else). These type of keyboard commands are in my code also but they works fine.
`keyboard.is_pressed('Alt')`
It's about mouse or pyautogui ?.. How can i make mouse moves correct ?
|
2020/07/31
|
[
"https://Stackoverflow.com/questions/63191480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027997/"
] |
I tried this code below:
`import win32con`
`import win32api`
`win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, int(10), int(10), 0, 0)`
And it worked in game. I think it relative with win32con. Anyway i got it.
|
This is how PyAutoGui works:
```
0,0 X increases -->
+---------------------------+
| | Y increases
| | |
| 1920 x 1080 screen | |
| | V
| |
| |
+---------------------------+ 1919, 1079
```
So you need to write like this:
```
pyautogui.moveTo(100, 200) # moves mouse to X of 100, Y of 200
```
or
```
pyautogui.moveTo(100, 200, 2) # moves mouse to X of 100, Y of 200 over 2 seconds
```
|
63,191,480
|
I wrote a small code with python. But this part of the code doesn't work when game focused on and it doesnt respond back.
`pyautogui.moveRel(-2, 4)`
Also this part works when my cursor appear in menu or etc. too. But when i switched into game (when my cursor disappear and crosshair appeared) it doesn't work (doesn't matter fullscreen or else). These type of keyboard commands are in my code also but they works fine.
`keyboard.is_pressed('Alt')`
It's about mouse or pyautogui ?.. How can i make mouse moves correct ?
|
2020/07/31
|
[
"https://Stackoverflow.com/questions/63191480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027997/"
] |
I was with the same problem in linux. For me it was wayland. After switching to X, it worked. In `/etc/gdm3/custom.conf` uncomment the line `#WaylandEnable=false`.
|
This is how PyAutoGui works:
```
0,0 X increases -->
+---------------------------+
| | Y increases
| | |
| 1920 x 1080 screen | |
| | V
| |
| |
+---------------------------+ 1919, 1079
```
So you need to write like this:
```
pyautogui.moveTo(100, 200) # moves mouse to X of 100, Y of 200
```
or
```
pyautogui.moveTo(100, 200, 2) # moves mouse to X of 100, Y of 200 over 2 seconds
```
|
22,049,248
|
I would like to develop an app engine application that directly stream data into a BigQuery table.
According to Google's documentation there is a simple way to stream data into bigquery:
* <http://googlecloudplatform.blogspot.co.il/2013/09/google-bigquery-goes-real-time-with-streaming-inserts-time-based-queries-and-more.html>
* <https://developers.google.com/bigquery/streaming-data-into-bigquery#streaminginsertexamples>
(note: in the above link you should select the python tab and not Java)
Here is the sample code snippet on how streaming insert should be coded:
```
body = {"rows":[
{"json": {"column_name":7.7,}}
]}
response = bigquery.tabledata().insertAll(
projectId=PROJECT_ID,
datasetId=DATASET_ID,
tableId=TABLE_ID,
body=body).execute()
```
Although I've downloaded the client api I didn't find any reference to a "bigquery" module/object referenced in the above Google's example.
Where is the the bigquery object (from snippet) should be located?
Can anyone show a more complete way to use this snippet (with the right imports)?
I've Been searching for that a lot and found documentation confusing and partial.
|
2014/02/26
|
[
"https://Stackoverflow.com/questions/22049248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2558486/"
] |
Minimal working (as long as you fill in the right ids for your project) example:
```
import httplib2
from apiclient import discovery
from oauth2client import appengine
_SCOPE = 'https://www.googleapis.com/auth/bigquery'
# Change the following 3 values:
PROJECT_ID = 'your_project'
DATASET_ID = 'your_dataset'
TABLE_ID = 'TestTable'
body = {"rows":[
{"json": {"Col1":7,}}
]}
credentials = appengine.AppAssertionCredentials(scope=_SCOPE)
http = credentials.authorize(httplib2.Http())
bigquery = discovery.build('bigquery', 'v2', http=http)
response = bigquery.tabledata().insertAll(
projectId=PROJECT_ID,
datasetId=DATASET_ID,
tableId=TABLE_ID,
body=body).execute()
print response
```
As Jordan says: "Note that this uses the appengine robot to authenticate with BigQuery, so you'll to add the robot account to the ACL of the dataset. Note that if you also want to use the robot to run queries, not just stream, you need the robot to be a member of the project 'team' so that it is authorized to run jobs."
|
Here is a working code example from an appengine app that streams records to a BigQuery table. It is open source at code.google.com:
<http://code.google.com/p/bigquery-e2e/source/browse/sensors/cloud/src/main.py#124>
To find out where the bigquery object comes from, see
<http://code.google.com/p/bigquery-e2e/source/browse/sensors/cloud/src/config.py>
Note that this uses the appengine robot to authenticate with BigQuery, so you'll to add the robot account to the ACL of the dataset.
Note that if you also want to use the robot to run queries, not just stream, you need to robot to be a member of the project 'team' so that it is authorized to run jobs.
|
39,771,024
|
I made a module and moved it to `/root/Downloads/Python-3.5.2/Lib/site-packages`.
When I run bash command `python3` in this folder to start the ide and import the module it works. However if I run `python3` in any other directory (e.g. `/root/Documents/Python`) it says
```none
ImportError: No module named 'exampleModule'
```
I was under the impression that Python would automatically search for modules in `site-packages` regardless of the directory. How can I fix it so that it will work regardless of where I am?
|
2016/09/29
|
[
"https://Stackoverflow.com/questions/39771024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6726467/"
] |
Instead of moving the module I would suggest you add the location of the module to the `PYTHONPATH` environment variable. If this is set then the python interpreter will know where to look for your module.
e.g. on Linux
```sh
export PYTHONPATH=$PYTHONPATH:<insert module location here>
```
|
**If you are a window user and you are getting import issues from site-packages
then you can add the path of your site-packages to env variable**
[](https://i.stack.imgur.com/fmK0h.png)
C:\Users\hp\AppData\Local\Programs\Python\Python310\Lib\site-packages
(site-package directory)
|
39,771,024
|
I made a module and moved it to `/root/Downloads/Python-3.5.2/Lib/site-packages`.
When I run bash command `python3` in this folder to start the ide and import the module it works. However if I run `python3` in any other directory (e.g. `/root/Documents/Python`) it says
```none
ImportError: No module named 'exampleModule'
```
I was under the impression that Python would automatically search for modules in `site-packages` regardless of the directory. How can I fix it so that it will work regardless of where I am?
|
2016/09/29
|
[
"https://Stackoverflow.com/questions/39771024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6726467/"
] |
There is two ways to make python find your module:
1. add the path where you module reside in your `PYTHONPATH` as suggested by bmat
2. add the path where you module reside in your script like this:
```py
import sys
sys.path.insert(0, '/root/Downloads/Python-3.5.2/Lib/site-packages')
```
|
**If you are a window user and you are getting import issues from site-packages
then you can add the path of your site-packages to env variable**
[](https://i.stack.imgur.com/fmK0h.png)
C:\Users\hp\AppData\Local\Programs\Python\Python310\Lib\site-packages
(site-package directory)
|
8,121,886
|
I'm sure this has been answered somewhere, because it's a very basic question - I can not, however, for the life of me, find the answer on the web. I feel like a complete idiot, but I have to ask so, here goes:
I'm writing a python code that will produce a list of all page addresses on a domain. This is done using selenium 2 - my problem occurs when I try to access the list of all links produced by selenium.
Here's what I have so far:
```
from selenium import webdriver
import time
HovedDomene = 'http://www.example.com'
Listlinker = []
Domenesider = []
Domenesider.append(HovedDomene)
driver = webdriver.Firefox()
for side in Domenesider:
driver.get(side)
time.sleep(10)
Listlinker = driver.find_elements_by_xpath("//a")
for link in Listlinker:
if link in Domenesider:
pass
elif str(HovedDomene) in str(link):
Domenesider.append(side)
print(Domenesider)
driver.close()
```
the `Listlinker` variable does not contain the links found on the page - instead the list contains, (I'm guessing here) selenium specific objects called WebElements. I can not, however, find any WebElement attributes that will give me the links - as a matter of fact I can't find any examples of WebElement attributes being accessed in python (at least not in a manner i can reproduce)
I would really appreciate any help you all could give me
Sincerely
Rookie
|
2011/11/14
|
[
"https://Stackoverflow.com/questions/8121886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1020693/"
] |
I'm familiar with python's api of selenium
but you probably can receive link using `get_attribute(attributename)` method. So it should be something like:
```
linkstr = ""
for link in Listlinker:
linkstr = link.get_attribute("href")
if linkstr in Domenesider:
pass
elif str(HovedDomene) in linkstr:
Domenesider.append(side)
```
|
>
> I've been checking up on your tip to not use time.sleep(10) as a page load wait. From reading different posts itseems to me that waiting for page loading is redundant with selenium 2. Se for example link The reason being that selenium 2 has a implicit wait for load function. Just thought I'd mention it to you, since you took the time to answer my question.
>
>
>
Sometimes selenium behaves in unclear way. And sometimes selenium throws errors which don't interested for us.
```
By byCondition;
T result; // T is IWebElement
const int SELENIUMATTEMPTS = 5;
int timeout = 60 * 1000;
StopWatch watch = new StopWatch();
public T MatchElement<T>() where T : IWebElement
{
try
{
try {
this.result = this.find(WebDriver.Instance, this.byCondition);
}
catch (NoSuchElementException) { }
while (this.watch.ElapsedMilliseconds < this.timeout && !this.ReturnCondMatched)
{
Thread.Sleep(100);
try {
this.result = this.find(WebDriver.Instance, this.byCondition);
}
catch (NoSuchElementException) { }
}
}
catch (Exception ex)
{
if (this.IsKnownError(ex))
{
if (this.seleniumAttempts < SELENIUMATTEMPTS)
{
this.seleniumAttempts++;
return MatchElement();
}
}
else { log.Error(ex); }
}
return this.result;
}
public bool IsKnownError(Exception ex)
{
//if selenium find nothing it throw an exception. This is bad practice to my mind.
bool res = (ex.GetType() == typeof(NoSuchElementException));
//OpenQA.Selenium.StaleElementReferenceException: Element not found in the cache
//issue appears when selenium interact with other plugins.
//this is probably something connected with syncronization
res = res || (ex.GetType() == (typeof(InvalidSelectorException) && ex.Message
.Contains("Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE)" +
"[nsIDOMXPathEvaluator.createNSResolver]"));
//OpenQA.Selenium.StaleElementReferenceException: Element not found in the cache
res = res || (ex.GetType() == typeof(StaleElementReferenceException) &&
ex.Message.Contains("Element not found in the cache"));
return res;
}
```
Sorry for C# but I'm beginner in Python. Code is simplified of course.
|
52,131,675
|
I have list of list of integers as shown below:
```
flst = [[19],
[21, 31],
[22],
[23],
[9, 25],
[26],
[27, 29],
[28],
[27, 29],
[2, 8, 30],
[21, 31],
[5, 11, 32],
[33]]
```
I want to get the list of integers in increasing order as shown below:
```
out = [19, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33]
```
I want to compare every list item with the item/s in next list and get item which is greater than the preceding item:
for ex:
In the list first item is [19] and next list items are [21,31]. Both elements are greater than [19] but [21] is near to [19], so it should be selected.
I'm learning python and tried the following code:
```
for i in range(len(flst)-2):
for j in flst[i+1]:
if j in range(flst[j], flst[j+2]):
print(j)
```
Went through many codes for incremental order in stackoverflow, but unable to find any solution.
|
2018/09/01
|
[
"https://Stackoverflow.com/questions/52131675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017391/"
] |
Sure, you can pass field names as arguments and use `[arg]` accessors as you already do with `[key]`:
```js
function populateClinicRoomSelect(object, valueField, labelField) {
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
value: object[key][valueField],
label: object[key][labelField],
};
selectArray = selectArray.concat(options);
}
}
return selectArray;
}
const object = {
a: {
id: 1,
room: 'first room'
},
b: {
id: 2,
room: 'second room'
}
}
const result = populateClinicRoomSelect(object, 'id', 'room');
console.log(result)
```
|
You mean like this?
```js
function populateClinicRoomSelect(object, value, label) {
value = value || "id"; // defaults value to id
label = label || "RoomName"; // defaults label to RoomName
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
value: object[key][value],
label: object[key][label],
};
selectArray = selectArray.concat(options);
}
}
return selectArray;
}
let obj = { 1: { id:1, RoomName: "Blue Lounge" }, 2: { id:2, RoomName: "Red Lounge" } }
console.log(populateClinicRoomSelect(obj, 'id', 'RoomName'));
```
|
44,456,572
|
Am getting the following error - Missing required dependencies ['numpy']
Standalone and via Django, without Apache2 integration - the code work likes charm, however things start to fall when used with Apache2. It refuses to import pandas or numpy giving one error after another.
I am using Apache2, libapache2-mod-wsgi-py3, Python 3.5 and Anaconda 2.3.0
```
Request Method: GET
Request URL: http://127.0.0.1/api/users/0/
Django Version: 1.10.5
Exception Type: ImportError
Exception Value:
Missing required dependencies ['numpy']
Exception Location: /home/fractaluser/anaconda3/lib/python3.4/site-packages/pandas/__init__.py in <module>, line 18
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/home/fractaluser/anaconda3/lib/python3.4/site-packages',
'/home/fractaluser/anaconda3/lib/python3.4/site-packages/Sphinx-1.3.1-py3.4.egg',
'/home/fractaluser/anaconda3/lib/python3.4/site-packages/setuptools-27.2.0-py3.4.egg',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages',
'/var/www/html/cgmvp']
Server time: Fri, 9 Jun 2017 11:12:37 +0000
```
|
2017/06/09
|
[
"https://Stackoverflow.com/questions/44456572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1759084/"
] |
In your class fields
```
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
```
When the time consuming thread is started
```
// Here start time consuming thread
// Here show the ProgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
```
When the time consuming thread ends
```
progressHandler.removeCallbacks(progressRunnable);
/// Here dismiss the ProgressDialog.
```
**ADDED:**
Instead new Thread(new Runnable) that you probably use for your time consuming code I propose to do this:
To initialize the task :
```
MyTask task = new MyTask();
task.execute();
// Here show the PorgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
```
Add this private class inside your main class:
```
private class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
//Here do your time consuming work
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
// This will be called on the UI thread after doInBackground returns
progressHandler.removeCallbacks(progressRunnable);
progressDialog.dismiss();
}
}
```
|
do something lik this
```
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(prStatus == 100)
prStatus = 0;
}
}
}).start();
```
|
17,056,796
|
I'm trying to send an ascii command over tcp/ip but python (i think) add a header to he string.
if I do a `s.send(bytes('RV\n ', 'ascii'))` I get an eRV rather than RV when I inspect the command going out. Any ideas?
[Previous post](https://stackoverflow.com/questions/16968253/python-3-tcp-ip-ascii-command).
|
2013/06/12
|
[
"https://Stackoverflow.com/questions/17056796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2460673/"
] |
If you want to stay away from SQL you can try with [EntityFramework.Extended](http://weblogs.asp.net/pwelter34/archive/2011/11/29/entity-framework-batch-update-and-future-queries.aspx).
Provides support for writing LINQ like batch delete/update queries. I only tried it once, it worked nice, but not sure if i would use it in production.
|
There are two ways I can think of right off hand to achieve what you are seeking.
1) create a stored procedure and call it from your entity model.
2) Send the raw command text to the db, see this [microsoft article](http://msdn.microsoft.com/en-us/data/jj592907.aspx)
|
17,420,528
|
I am following the book "how to think like a computer scientist" to learn python
and am having some problems understanding the classes and object chapter.
An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by adding dx to the x co-ordinate of corner and dy to the y co-ordinate of corner.
Now, I am not really sure if the code I have written is correct or not.
So, let me tell you what i was trying to do
and you can tell me whether I was doing it right?
first I created a class Rectangle
then I created an instance of it
and entered the details such as
values of co-ordinates x and y
and width and height of the rectangle.
so, this was my code earlier:
```
class Rectangle:
pass
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But when I ran this code it gave me an attribute error
and : class Rectangle has no attribute x
Therefore, I moved the following lines into the moveRect function
```
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
```
and thus the code became:
```
class Rectangle:
pass
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But, this code still gives me an error.
So,what's actually wrong with this code?
At the moment, I feel as if I wrote this code using trial and error,
and changed around the parts when I saw an error. I want to properly understand
how this works.so,please shed some light on this.
The book "how to think like a computer scientist" hasn't introduced init in chapter 12 and therefore I need to do it without using init.
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17420528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297440/"
] |
In your first example, you passed the *class* as an argument instead of the *instance* you created. Because there is no `self.x` in the class `Rectangle`, the error was raised.
You could just put the function in the class:
```
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def moveRect(self, dx, dy):
self.x += dx
self.y += dy
rect = Rectangle(3.0, 4.0, 50, 120)
dx = raw_input("enter dx value:")
dy = raw_input("enter dy value:")
rect.moveRect(float(dx), float(dy))
```
|
Frob instances, not types.
```
moveRect(rect, dx, dy)
```
|
17,420,528
|
I am following the book "how to think like a computer scientist" to learn python
and am having some problems understanding the classes and object chapter.
An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by adding dx to the x co-ordinate of corner and dy to the y co-ordinate of corner.
Now, I am not really sure if the code I have written is correct or not.
So, let me tell you what i was trying to do
and you can tell me whether I was doing it right?
first I created a class Rectangle
then I created an instance of it
and entered the details such as
values of co-ordinates x and y
and width and height of the rectangle.
so, this was my code earlier:
```
class Rectangle:
pass
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But when I ran this code it gave me an attribute error
and : class Rectangle has no attribute x
Therefore, I moved the following lines into the moveRect function
```
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
```
and thus the code became:
```
class Rectangle:
pass
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But, this code still gives me an error.
So,what's actually wrong with this code?
At the moment, I feel as if I wrote this code using trial and error,
and changed around the parts when I saw an error. I want to properly understand
how this works.so,please shed some light on this.
The book "how to think like a computer scientist" hasn't introduced init in chapter 12 and therefore I need to do it without using init.
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17420528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297440/"
] |
You must specify the members and methods you want to access and use in your class declaration. inside the class the Instance you are currently working on is refered to by the name `self` (see the link below!):
```
class Rectangle:
def __init__(self):
self.x = 0
self.y = 0
self.width = 50
self.height = 30
# may I recommend to make the moveRect function
# a method of Rectangle, like so:
def move(self, dx, dy):
self.x += dx
self.y += dy
```
Then instanciate your class and use the returned object:
```
r = Rectangle()
r.x = 5
r.y = 10
r.width = 50
r.height = 10
r.move(25, 10)
```
hope that helps.
Read: <http://www.diveintopython.net/object_oriented_framework/defining_classes.html>
|
Frob instances, not types.
```
moveRect(rect, dx, dy)
```
|
17,420,528
|
I am following the book "how to think like a computer scientist" to learn python
and am having some problems understanding the classes and object chapter.
An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by adding dx to the x co-ordinate of corner and dy to the y co-ordinate of corner.
Now, I am not really sure if the code I have written is correct or not.
So, let me tell you what i was trying to do
and you can tell me whether I was doing it right?
first I created a class Rectangle
then I created an instance of it
and entered the details such as
values of co-ordinates x and y
and width and height of the rectangle.
so, this was my code earlier:
```
class Rectangle:
pass
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But when I ran this code it gave me an attribute error
and : class Rectangle has no attribute x
Therefore, I moved the following lines into the moveRect function
```
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
```
and thus the code became:
```
class Rectangle:
pass
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But, this code still gives me an error.
So,what's actually wrong with this code?
At the moment, I feel as if I wrote this code using trial and error,
and changed around the parts when I saw an error. I want to properly understand
how this works.so,please shed some light on this.
The book "how to think like a computer scientist" hasn't introduced init in chapter 12 and therefore I need to do it without using init.
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17420528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297440/"
] |
In your first example, you passed the *class* as an argument instead of the *instance* you created. Because there is no `self.x` in the class `Rectangle`, the error was raised.
You could just put the function in the class:
```
class Rectangle:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def moveRect(self, dx, dy):
self.x += dx
self.y += dy
rect = Rectangle(3.0, 4.0, 50, 120)
dx = raw_input("enter dx value:")
dy = raw_input("enter dy value:")
rect.moveRect(float(dx), float(dy))
```
|
Without overly complicating things, all you need to make your code work is to change
```
moveRect(Rectangle,dx,dy)
```
to
```
moveRect(rect, float(dx), float(dy))
```
(You need to make sure to convert each string from `raw_input` into a number. In `moveRect`, you add `Rectangle.x` to `dx`, these two values need to be of the same type or you will get a `TypeError`.)
**Given the knowledge that the [book](http://www.greenteapress.com/thinkpython/html/index.html) you're reading expects you to have when completing this [exercise](http://www.greenteapress.com/thinkpython/html/thinkpython016.html#toc168), you have completed that problem correctly.**
As others have said, this isn't an approach that you would ever probably use to tackle this. If you carry on reading, you'll see the way to include a function as part of the class definition (as a method); it makes more sense to bundle data and the functions that operate on that data together into a unit.
|
17,420,528
|
I am following the book "how to think like a computer scientist" to learn python
and am having some problems understanding the classes and object chapter.
An exercise there says to write a function named moveRect that takes a Rectangle and 2 parameters named dx& dy. It should change the location of the rectangle by adding dx to the x co-ordinate of corner and dy to the y co-ordinate of corner.
Now, I am not really sure if the code I have written is correct or not.
So, let me tell you what i was trying to do
and you can tell me whether I was doing it right?
first I created a class Rectangle
then I created an instance of it
and entered the details such as
values of co-ordinates x and y
and width and height of the rectangle.
so, this was my code earlier:
```
class Rectangle:
pass
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But when I ran this code it gave me an attribute error
and : class Rectangle has no attribute x
Therefore, I moved the following lines into the moveRect function
```
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
```
and thus the code became:
```
class Rectangle:
pass
def moveRect(Rectangle,dx,dy):
Rectangle.x=Rectangle.x + dx
Rectangle.y=Rectangle.y + dy
rect=Rectangle()
rect.x=3.0
rect.y=4.0
rect.width=50
rect.height=120
dx=raw_input("enter dx value:")
dy=raw_input("enter dy value:")
moveRect(Rectangle,dx,dy)
```
But, this code still gives me an error.
So,what's actually wrong with this code?
At the moment, I feel as if I wrote this code using trial and error,
and changed around the parts when I saw an error. I want to properly understand
how this works.so,please shed some light on this.
The book "how to think like a computer scientist" hasn't introduced init in chapter 12 and therefore I need to do it without using init.
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17420528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297440/"
] |
You must specify the members and methods you want to access and use in your class declaration. inside the class the Instance you are currently working on is refered to by the name `self` (see the link below!):
```
class Rectangle:
def __init__(self):
self.x = 0
self.y = 0
self.width = 50
self.height = 30
# may I recommend to make the moveRect function
# a method of Rectangle, like so:
def move(self, dx, dy):
self.x += dx
self.y += dy
```
Then instanciate your class and use the returned object:
```
r = Rectangle()
r.x = 5
r.y = 10
r.width = 50
r.height = 10
r.move(25, 10)
```
hope that helps.
Read: <http://www.diveintopython.net/object_oriented_framework/defining_classes.html>
|
Without overly complicating things, all you need to make your code work is to change
```
moveRect(Rectangle,dx,dy)
```
to
```
moveRect(rect, float(dx), float(dy))
```
(You need to make sure to convert each string from `raw_input` into a number. In `moveRect`, you add `Rectangle.x` to `dx`, these two values need to be of the same type or you will get a `TypeError`.)
**Given the knowledge that the [book](http://www.greenteapress.com/thinkpython/html/index.html) you're reading expects you to have when completing this [exercise](http://www.greenteapress.com/thinkpython/html/thinkpython016.html#toc168), you have completed that problem correctly.**
As others have said, this isn't an approach that you would ever probably use to tackle this. If you carry on reading, you'll see the way to include a function as part of the class definition (as a method); it makes more sense to bundle data and the functions that operate on that data together into a unit.
|
30,460,461
|
I have this in my project urlconf `photocheck.urls`:
```
urlpatterns = patterns('',
url(r'^admin/docs/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^rest/', include('core.urls')),
url(r'^shotmaker/', include('shotmaker.urls')),
url(r'^report/', include('report.urls')),
url(r'^users/', include('users.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```
this is my `core` app urlconf:
```
router.register(r'cameras', views.CameraViewSet)
router.register(r'lamps', views.LampViewSet)
router.register(r'snapshots', views.SnapshotViewSet)
urlpatterns = patterns(
'core.views',
url(r'', include(router.urls))
)
```
this is `shotmaker` urlconf:
```
urlpatterns = patterns(
'shotmaker.views',
url(r'^$', views.CameraList.as_view(), name='camera_list'),
url(r'^camera/(?P<pk>[-\w]+)/$', views.CameraDetail.as_view(), name='camera_detail'),
url(r'^save_preview_image/(?P<pk>[-\w]+)/$', views.save_preview_image),
url(r'^get_position/(?P<pk>[-\w]+)/$', views.get_position),
url(r'^set_position/(?P<pk>[-\w]+)/$', views.set_position),
url(r'^update_calibrating_image/(?P<pk>[-\w]+)/$', views.update_calibrating_image),
url(r'^save_preview_get_position/(?P<pk>[-\w]+)/$', views.save_preview_get_position),
)
```
and `report` urlconf
```
urlpatterns = patterns(
'report.views',
url(r'^$', views.LampReportView.as_view(), name='lamp_report'),
)
```
and `users` urlconf
```
urlpatterns = patterns('',
url(r'^login/$', views.MyLoginView.as_view(), name="login"),
url(r'^logout/$', LogoutView.as_view(), name="logout"),
)
```
now when I do
```
reverse('lamp_report')
```
i get this:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 546, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in _reverse_with_prefix
self._populate()
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 269, in _populate
for pattern in reversed(self.url_patterns):
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 367, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 361, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/1111/_gost/photo/photo-monitoring/photocheck/urls.py", line 15, in <module>
url(r'^users/', include('users.urls')),
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 28, in include
urlconf_module = import_module(urlconf_module)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/1111/_gost/photo/photo-monitoring/users/urls.py", line 4, in <module>
import views
File "/Users/1111/_gost/photo/photo-monitoring/users/views.py", line 6, in <module>
class MyLoginView(LoginView):
File "/Users/1111/_gost/photo/photo-monitoring/users/views.py", line 8, in MyLoginView
success_url = reverse('lamp_report')
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 546, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 410, in _reverse_with_prefix
self._populate()
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 269, in _populate
for pattern in reversed(self.url_patterns):
File "/Users/1111/.virtualenvs/gost_photo/lib/python2.7/site-packages/django/core/urlresolvers.py", line 376, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
ImproperlyConfigured: The included urlconf 'photocheck.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
```
so where is the circular import here? and how can I avoid it?
|
2015/05/26
|
[
"https://Stackoverflow.com/questions/30460461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4057053/"
] |
Use [`reverse_lazy()`](https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy) instead of `reverse()`.
|
I got same error and solved but only `reverse_lazy()` is not enough, use `reverse_lazy()` like `reverse_lazy('app_name:url_name')`.
|
20,338,064
|
I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")
```
I keep getting the error that it cannot access 'file' no such file or directory.
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] |
```
os.system("chmod 700 file")
^^^^--- literal string, looking for a file named "file"
```
You probably want
```
os.system("chmod 700 " + file)
^^^^^^---concatenate your variable named "file"
```
|
It could be something like
```
os.system("chmod 700 %s" % file)
```
|
20,338,064
|
I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")
```
I keep getting the error that it cannot access 'file' no such file or directory.
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] |
It could be something like
```
os.system("chmod 700 %s" % file)
```
|
As pointed out by other answers, you need to place the value of the variable *file* instead.
However, following the suggested standard, you should use format and state it like
```
os.system("chmod 700 {:s}".format(file))
```
Using
```
os.system("chmod 700 %s" % file)
```
is discouraged, cf. also [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format).
|
20,338,064
|
I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")
```
I keep getting the error that it cannot access 'file' no such file or directory.
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] |
```
os.system("chmod 700 file")
^^^^--- literal string, looking for a file named "file"
```
You probably want
```
os.system("chmod 700 " + file)
^^^^^^---concatenate your variable named "file"
```
|
```
os.system("chmod 700 file")
```
file is not replaced by its value. Try this :
```
os.system("chmod 700 " + file)
```
BTW, you should check if the script was executed with parameters (you could have an error such as "list index out of range")
|
20,338,064
|
I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")
```
I keep getting the error that it cannot access 'file' no such file or directory.
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] |
```
os.system("chmod 700 file")
```
file is not replaced by its value. Try this :
```
os.system("chmod 700 " + file)
```
BTW, you should check if the script was executed with parameters (you could have an error such as "list index out of range")
|
As pointed out by other answers, you need to place the value of the variable *file* instead.
However, following the suggested standard, you should use format and state it like
```
os.system("chmod 700 {:s}".format(file))
```
Using
```
os.system("chmod 700 %s" % file)
```
is discouraged, cf. also [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format).
|
20,338,064
|
I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah
Where blah is the name of some file. The code I have is this:
```
#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")
```
I keep getting the error that it cannot access 'file' no such file or directory.
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20338064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058993/"
] |
```
os.system("chmod 700 file")
^^^^--- literal string, looking for a file named "file"
```
You probably want
```
os.system("chmod 700 " + file)
^^^^^^---concatenate your variable named "file"
```
|
As pointed out by other answers, you need to place the value of the variable *file* instead.
However, following the suggested standard, you should use format and state it like
```
os.system("chmod 700 {:s}".format(file))
```
Using
```
os.system("chmod 700 %s" % file)
```
is discouraged, cf. also [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format).
|
69,963,185
|
I am trying to convert excel database into python.
I have a trading data which I need to import into the system in xml format.
my code is following:
```
df = pd.read_excel("C:/Users/junag/Documents/XML/Portfolio2.xlsx", sheet_name="Sheet1", dtype=object)
root = ET.Element('trading-data')
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
tree = ET.ElementTree(root)
Portfolios = ET.SubElement(root, "Portfolios")
Defaults = ET.SubElement(Portfolios, "Defaults", BaseCurrency="USD")
for row in df.itertuples():
Portfolio = ET.SubElement(Portfolios, "Portfolio", Name=row.Name, BaseCurrency=row.BaseCurrency2, TradingPower=str(row.TradingPower),
ValidationProfile=row.ValidationProfile, CommissionProfile=row.CommissionProfile)
PortfolioPositions = ET.SubElement(Portfolio, "PortfolioPositions")
if row.Type == "Cash":
PortfolioPosition = ET.SubElement(PortfolioPositions, "PortfolioPosition", Type=row.Type, Volume=str(row.Volume))
Cash = ET.SubElement(PortfolioPosition, 'Cash', Currency=str(row.Currency))
else:
PortfolioPosition = ET.SubElement(PortfolioPositions, "PortfolioPosition", Type=row.Type, Volume=str(row.Volume),
Invested=str(row.Invested), BaseInvested=str(row.BaseInvested))
Instrument = ET.SubElement(PortfolioPosition, 'Instrument', Ticker=str(row.Ticker), ISIN=str(row.ISIN), Market=str(row.Market),
Currency=str(row.Currency2), CFI=str(row.CFI))
ET.indent(tree, space="\t", level=0)
tree.write("Portfolios_converted2.xml", encoding="utf-8")
```
The output looks like this:
[enter image description here](https://i.stack.imgur.com/wDnI8.png)
While I need it to look like this:
[enter image description here](https://i.stack.imgur.com/ee3YF.png)
How can I improve my code to make the output xml look better? please advise
here the excel data:
[](https://i.stack.imgur.com/TlR8G.png)
|
2021/11/14
|
[
"https://Stackoverflow.com/questions/69963185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17410005/"
] |
If you are creating a binding then the property must be notifiable, that is, have an associated signal and emit it when it changes:
```py
class Manager(QObject):
processResult = Signal(bool)
df_changed = Signal()
def __init__(self):
QObject.__init__(self)
self.ds = "loading .."
@Slot()
def start_processing(self):
self.set_ds("500")
def read_ds(self):
return self.ds
def set_ds(self, val):
self.ds = val
self.df_changed.emit()
paramDs = Property(str, read_ds, set_ds, notify=df_changed)
```
|
you should set Row value after setting property, like this:
```
tbModel.setRow(1,
{
param_name: "number of classes",
value: backend.paramDs
}
)
```
tbModel is id of your Table View's Model
|
39,533,766
|
I'm having a little problem with a modal in django.
I have a link which calls an id and the id is a modal. However, the modal isn't opening. I'm pretty sure that this is happening because the link is inside a "automatic" form, but I'm new in django and python so I have no idea.
The code is:
```
{% block body %}
<div class="col-lg-12 page-content">
<h1 class="content-title">Meus Dados</h1>
<hr class="star-light">
<div class="form-content">
<form class="form-horizontal" method = 'POST' action="/user/edituser/">
{% csrf_token %}
{% for field in form_user %}
{% bootstrap_field field exclude="password,repeat_password" %}
{% endfor %}
<div class="button-div">
<a class="btn btn-info btn-block btn-password" href="#change-password"
data-toggle="modal">Alterar senha</a>
{% buttons %}
<button class="btn btn-success btn-block btn-edit" type = 'submit'>Salvar Dados</button>
{% endbuttons %}
</div>
</form>
<a class="btn btn-danger btn-block btn-delete" href="/user/delete" name="delete">Excluir minha conta</a>
</div>
</div>
<div class="modal hide" id="change-password">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<p class="modal-title" id="myModalLabel">Change Password</p>
</div>
<div class="modal-body">
<div class="row">
<div class="modal-col col-sm-12">
<div class="well">
<form method="post" id="passwordForm">
<input type="password" class="input-lg form-control" name="password1"
id="password1" placeholder="New Password">
<input type="password" class="input-lg form-control" name="password2"
id="password2" placeholder="Repeat Password">
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-success btn-bloc">Alterar Senha</a>
</div>
</div>
{% endblock %}
```
Any doubts, please ask.
Thanks.
|
2016/09/16
|
[
"https://Stackoverflow.com/questions/39533766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5516104/"
] |
Change your `<a>` tag to the following:
```
<a class="btn btn-info btn-block btn-password" href="#"
data-toggle="modal" data-target="#change-password">Alterar senha</a>
```
At least this is how I do it in my Django templates. As I think **@souldeux** was trying to say, you need to use the `data-target` attribute to specify the modal itself, rather than the `href`; I usually just use `#` for that in cases like this.
Also, make sure that you are not only loading the bootstrap css code, but also the bootstrap js libraries. In other words, make sure you have the following (or some equivalent) in your template:
```
<!-- Latest compiled and minified JavaScript (at the time of this post) -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
```
In addition to your css:
```
<!-- Latest compiled and minified CSS (at the time of this post) -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
```
Which I assume you already have, because otherwise things would look weird.
|
```
<a class="btn btn-info btn-block btn-password" href="#change-password" data-toggle="modal">Alterar senha</a>
```
You need a `data-target` attribute in addition to your `data-toggle`. <http://getbootstrap.com/javascript/#live-demo>
|
39,533,766
|
I'm having a little problem with a modal in django.
I have a link which calls an id and the id is a modal. However, the modal isn't opening. I'm pretty sure that this is happening because the link is inside a "automatic" form, but I'm new in django and python so I have no idea.
The code is:
```
{% block body %}
<div class="col-lg-12 page-content">
<h1 class="content-title">Meus Dados</h1>
<hr class="star-light">
<div class="form-content">
<form class="form-horizontal" method = 'POST' action="/user/edituser/">
{% csrf_token %}
{% for field in form_user %}
{% bootstrap_field field exclude="password,repeat_password" %}
{% endfor %}
<div class="button-div">
<a class="btn btn-info btn-block btn-password" href="#change-password"
data-toggle="modal">Alterar senha</a>
{% buttons %}
<button class="btn btn-success btn-block btn-edit" type = 'submit'>Salvar Dados</button>
{% endbuttons %}
</div>
</form>
<a class="btn btn-danger btn-block btn-delete" href="/user/delete" name="delete">Excluir minha conta</a>
</div>
</div>
<div class="modal hide" id="change-password">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<p class="modal-title" id="myModalLabel">Change Password</p>
</div>
<div class="modal-body">
<div class="row">
<div class="modal-col col-sm-12">
<div class="well">
<form method="post" id="passwordForm">
<input type="password" class="input-lg form-control" name="password1"
id="password1" placeholder="New Password">
<input type="password" class="input-lg form-control" name="password2"
id="password2" placeholder="Repeat Password">
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<a href="#" class="btn btn-success btn-bloc">Alterar Senha</a>
</div>
</div>
{% endblock %}
```
Any doubts, please ask.
Thanks.
|
2016/09/16
|
[
"https://Stackoverflow.com/questions/39533766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5516104/"
] |
Change your `<a>` tag to the following:
```
<a class="btn btn-info btn-block btn-password" href="#"
data-toggle="modal" data-target="#change-password">Alterar senha</a>
```
At least this is how I do it in my Django templates. As I think **@souldeux** was trying to say, you need to use the `data-target` attribute to specify the modal itself, rather than the `href`; I usually just use `#` for that in cases like this.
Also, make sure that you are not only loading the bootstrap css code, but also the bootstrap js libraries. In other words, make sure you have the following (or some equivalent) in your template:
```
<!-- Latest compiled and minified JavaScript (at the time of this post) -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
```
In addition to your css:
```
<!-- Latest compiled and minified CSS (at the time of this post) -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
```
Which I assume you already have, because otherwise things would look weird.
|
try changing the tag "a" to tag "button" in
```
<a class="btn btn-info btn-block btn-password" href="#change-password"
data-toggle="modal">Alterar senha</a>
```
and hide to fade in
```
<div class="modal hide" id="change-password">
```
|
6,403,757
|
I tried installing pycurl via pip. it didn't work and instead it gives me this error.
```
running install
running build
running build_py
running build_ext
building 'pycurl' extension
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv
-Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch ppc
-arch x86_64 -pipe -DHAVE_CURL_SSL=1 -I/System/Library/Frameworks/
Python.framework/Versions/2.6/include/python2.6 -c src/pycurl.c -o
build/temp.macosx-10.6-universal-2.6/src/pycurl.o
src/pycurl.c:85:4: warning: #warning "libcurl was compiled with SSL
support, but configure could not determine which " "library was used;
thus no SSL crypto locking callbacks will be set, which may " "cause
random crashes on SSL requests"
/usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as: assembler (/usr/bin/
../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/darwin/
ppc/as) for architecture ppc not installed
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
/usr/bin/../libexec/gcc/darwin/i386/as for architecture i386
src/pycurl.c:85:4: warning: #warning "libcurl was compiled with SSL
support, but configure could not determine which " "library was used;
thus no SSL crypto locking callbacks will be set, which may " "cause
random crashes on SSL requests"
src/pycurl.c:3906: fatal error: error writing to -: Broken pipe
compilation terminated.
src/pycurl.c:85:4: warning: #warning "libcurl was compiled with SSL
support, but configure could not determine which " "library was used;
thus no SSL crypto locking callbacks will be set, which may " "cause
random crashes on SSL requests"
lipo: can't open input file: /var/tmp//ccspAJOg.out (No such file or
directory)
error: command 'gcc-4.2' failed with exit status 1
```
|
2011/06/19
|
[
"https://Stackoverflow.com/questions/6403757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200412/"
] |
I got it working using this
```
sudo env ARCHFLAGS="-arch x86_64" pip install pycurl
```
|
if you are on linux with apt-get:
```
lnx#> apt-get search pycurl
```
To install:
```
lnx#> sudo apt-get install python-pycurl
```
if on linux with yum:
```
lnx#> yum search pycurl
I get this on my comp:
python-pycurl.x86_64 : A Python interface to libcurl
```
To install i've did:
`lnx#> sudo yum install python-pycurl`
Another alternative, is to use easy\_install:
yum, or apt-get, install setuptools.
---
If you're using Holly Windows, then get pycurl from [HERE](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pycurl)
|
33,442,411
|
In one of our homework problems, we need to write a class in python called Gate which contains the drawing and function of many different gates in a circuit. It describes as follows:
```
in1 = Gate("input")
out1 = Gate("output")
not1 = Gate("not")
```
Here `in1`, `out1`, `not1` are all instances of this class. What do the `("input")` `("output")` `("not")` mean? are they subclass or something?
We are only told that when we define a class using:
```
class Gate(object)
```
when we make an instance we use:
```
in1 = Gate()
```
I haven't seen stuff inside a () after the class name, how to understand that?
|
2015/10/30
|
[
"https://Stackoverflow.com/questions/33442411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5508199/"
] |
Create a wrapper function around `fun` to select an element of the array. For example, the following will integrate the first element of the array.
```
from scipy.integrate import quad
# The function you want to integrate
def fun(x, a):
return np.asarray([a * x, a * x * x])
# The wrapper function
def wrapper(x, a, index):
return fun(x, a)[index]
# The integration
quad(wrapper, 0, 1, args=(1, 0))
```
Following @RobertB's suggestion, you should avoid defining a function `int` because it messes with the builtin names.
|
Your function returns an array, `integrate.quad` needs a float to integrate. So you want to give it a function that returns one of the elements from your array instead of the function itself. You can do that via a quick `lambda`:
```
def integrate(a, index=0)
return quad(lambda x,y: fun(x, y)[index], 0, 1, args=a)
```
|
38,668,389
|
Im in need of help outputting the json key with python. I tried to output the name "carl".
Python code :
```
from json import loads
import json,urllib2
class yomamma:
def __init__(self):
url = urlopen('http://localhost/name.php').read()
name = loads(url)
print "Hello" (name)
```
Php code (for the json which i made):
```
<?php
$arr = array('person_one'=>"Carl", 'person_two'=>"jack");
echo json_encode($arr);
```
the output of the php is :
{"person\_one":"Carl","person\_two":"jack"}
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38668389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6580871/"
] |
I'll just assume the PHP code works correctly, I don't know PHP very well.
On the client, I recommend using [`requests`](http://docs.python-requests.org/en/master/) (installable through `pip install requests`):
```
import requests
r = requests.get('http://localhost/name.php')
data = r.json()
print data['person_one']
```
The `.json` method returns a Python dictionary.
Taking a closer look at your code, it seems you're trying to concatenate two strings by just writing them next to eachother. Instead, use either the concatenation operator (`+`):
```
print "Hello" + data['person_one']
```
Alternatively, you can use the string formatting functionality:
```
print "Hello {}".format(data['person_one'])
```
Or even fancier (but maybe a bit complex to understand for the start):
```
r = requests.get('http://localhost/name.php')
print "Hello {person_one}".format(**r.json())
```
|
try this:
```
import json
person_data = json.loads(url)
print "Hello {}".format(person_data["person_one"])
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
Below is the code that worked for me:
```
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
```
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
```
os.chdir(dir_name) # change directory from working dir to dir with files
```
Then assign file\_name as
```
file_name = dir_name + "/" + item
```
|
You need to construct a `ZipFile` object with the filename, and *then* extract it:
```
zipfile.ZipFile.extract(item)
```
is wrong.
```
zipfile.ZipFile(item).extractall()
```
will extract all files from the zip file with the name contained in `item`.
I think you should more closely read the documentation to `zipfile` :) but you're on the right track!
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
The accepted answer works great!
Just to extend the idea to unzip all the files with .zip extension within all the sub-directories inside a directory the following code seems to work well:
```
import os
import zipfile
for path, dir_list, file_list in os.walk(dir_path):
for file_name in file_list:
if file_name.endswith(".zip"):
abs_file_path = os.path.join(path, file_name)
# The following three lines of code are only useful if
# a. the zip file is to unzipped in it's parent folder and
# b. inside the folder of the same name as the file
parent_path = os.path.split(abs_file_path)[0]
output_folder_name = os.path.splitext(abs_file_path)[0]
output_path = os.path.join(parent_path, output_folder_name)
zip_obj = zipfile.ZipFile(abs_file_path, 'r')
zip_obj.extractall(output_path)
zip_obj.close()
```
|
You need to construct a `ZipFile` object with the filename, and *then* extract it:
```
zipfile.ZipFile.extract(item)
```
is wrong.
```
zipfile.ZipFile(item).extractall()
```
will extract all files from the zip file with the name contained in `item`.
I think you should more closely read the documentation to `zipfile` :) but you're on the right track!
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
I think this is shorter and worked fine for me. First import the modules required:
```
import zipfile, os
```
Then, I define the working directory:
```
working_directory = 'my_directory'
os.chdir(working_directory)
```
After that you can use a combination of the `os` and `zipfile` to get where you want:
```
for file in os.listdir(working_directory): # get the list of files
if zipfile.is_zipfile(file): # if it is a zipfile, extract it
with zipfile.ZipFile(file) as item: # treat the file as a zip
item.extractall() # extract it in the working directory
```
|
You need to construct a `ZipFile` object with the filename, and *then* extract it:
```
zipfile.ZipFile.extract(item)
```
is wrong.
```
zipfile.ZipFile(item).extractall()
```
will extract all files from the zip file with the name contained in `item`.
I think you should more closely read the documentation to `zipfile` :) but you're on the right track!
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
Below is the code that worked for me:
```
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
```
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
```
os.chdir(dir_name) # change directory from working dir to dir with files
```
Then assign file\_name as
```
file_name = dir_name + "/" + item
```
|
The accepted answer works great!
Just to extend the idea to unzip all the files with .zip extension within all the sub-directories inside a directory the following code seems to work well:
```
import os
import zipfile
for path, dir_list, file_list in os.walk(dir_path):
for file_name in file_list:
if file_name.endswith(".zip"):
abs_file_path = os.path.join(path, file_name)
# The following three lines of code are only useful if
# a. the zip file is to unzipped in it's parent folder and
# b. inside the folder of the same name as the file
parent_path = os.path.split(abs_file_path)[0]
output_folder_name = os.path.splitext(abs_file_path)[0]
output_path = os.path.join(parent_path, output_folder_name)
zip_obj = zipfile.ZipFile(abs_file_path, 'r')
zip_obj.extractall(output_path)
zip_obj.close()
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
Below is the code that worked for me:
```
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
```
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
```
os.chdir(dir_name) # change directory from working dir to dir with files
```
Then assign file\_name as
```
file_name = dir_name + "/" + item
```
|
I think this is shorter and worked fine for me. First import the modules required:
```
import zipfile, os
```
Then, I define the working directory:
```
working_directory = 'my_directory'
os.chdir(working_directory)
```
After that you can use a combination of the `os` and `zipfile` to get where you want:
```
for file in os.listdir(working_directory): # get the list of files
if zipfile.is_zipfile(file): # if it is a zipfile, extract it
with zipfile.ZipFile(file) as item: # treat the file as a zip
item.extractall() # extract it in the working directory
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
Below is the code that worked for me:
```
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
```
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
```
os.chdir(dir_name) # change directory from working dir to dir with files
```
Then assign file\_name as
```
file_name = dir_name + "/" + item
```
|
**Recursive** version of [@tpdance answer](https://stackoverflow.com/a/31355555/3030195).
Use this for for **subfolders** and subfolder. Working on Python 3.8
```
import os
import zipfile
base_dir = '/Users/john/data' # absolute path to the data folder
extension = ".zip"
os.chdir(base_dir) # change directory from working dir to dir with files
def unpack_all_in_dir(_dir):
for item in os.listdir(_dir): # loop through items in dir
abs_path = os.path.join(_dir, item) # absolute path of dir or file
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(abs_path) # get full path of file
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(_dir) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
elif os.path.isdir(abs_path):
unpack_all_in_dir(abs_path) # recurse this function with inner folder
unpack_all_in_dir(base_dir)
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
I think this is shorter and worked fine for me. First import the modules required:
```
import zipfile, os
```
Then, I define the working directory:
```
working_directory = 'my_directory'
os.chdir(working_directory)
```
After that you can use a combination of the `os` and `zipfile` to get where you want:
```
for file in os.listdir(working_directory): # get the list of files
if zipfile.is_zipfile(file): # if it is a zipfile, extract it
with zipfile.ZipFile(file) as item: # treat the file as a zip
item.extractall() # extract it in the working directory
```
|
The accepted answer works great!
Just to extend the idea to unzip all the files with .zip extension within all the sub-directories inside a directory the following code seems to work well:
```
import os
import zipfile
for path, dir_list, file_list in os.walk(dir_path):
for file_name in file_list:
if file_name.endswith(".zip"):
abs_file_path = os.path.join(path, file_name)
# The following three lines of code are only useful if
# a. the zip file is to unzipped in it's parent folder and
# b. inside the folder of the same name as the file
parent_path = os.path.split(abs_file_path)[0]
output_folder_name = os.path.splitext(abs_file_path)[0]
output_path = os.path.join(parent_path, output_folder_name)
zip_obj = zipfile.ZipFile(abs_file_path, 'r')
zip_obj.extractall(output_path)
zip_obj.close()
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
The accepted answer works great!
Just to extend the idea to unzip all the files with .zip extension within all the sub-directories inside a directory the following code seems to work well:
```
import os
import zipfile
for path, dir_list, file_list in os.walk(dir_path):
for file_name in file_list:
if file_name.endswith(".zip"):
abs_file_path = os.path.join(path, file_name)
# The following three lines of code are only useful if
# a. the zip file is to unzipped in it's parent folder and
# b. inside the folder of the same name as the file
parent_path = os.path.split(abs_file_path)[0]
output_folder_name = os.path.splitext(abs_file_path)[0]
output_path = os.path.join(parent_path, output_folder_name)
zip_obj = zipfile.ZipFile(abs_file_path, 'r')
zip_obj.extractall(output_path)
zip_obj.close()
```
|
**Recursive** version of [@tpdance answer](https://stackoverflow.com/a/31355555/3030195).
Use this for for **subfolders** and subfolder. Working on Python 3.8
```
import os
import zipfile
base_dir = '/Users/john/data' # absolute path to the data folder
extension = ".zip"
os.chdir(base_dir) # change directory from working dir to dir with files
def unpack_all_in_dir(_dir):
for item in os.listdir(_dir): # loop through items in dir
abs_path = os.path.join(_dir, item) # absolute path of dir or file
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(abs_path) # get full path of file
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(_dir) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
elif os.path.isdir(abs_path):
unpack_all_in_dir(abs_path) # recurse this function with inner folder
unpack_all_in_dir(base_dir)
```
|
31,346,790
|
I would like to write a simple script to iterate through all the files in a folder and unzip those that are zipped (.zip) to that same folder. For this project, I have a folder with nearly 100 zipped .las files and I'm hoping for an easy way to batch unzip them. I tried with following script
```
import os, zipfile
folder = 'D:/GISData/LiDAR/SomeFolder'
extension = ".zip"
for item in os.listdir(folder):
if item.endswith(extension):
zipfile.ZipFile.extract(item)
```
However, when I run the script, I get the following error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 10, in <module>
extract = zipfile.ZipFile.extract(item)
TypeError: unbound method extract() must be called with ZipFile instance as first argument (got str instance instead)
```
I am using the python 2.7.5 interpreter. I looked at the documentation for the zipfile module (<https://docs.python.org/2/library/zipfile.html#module-zipfile>) and I would like to understand what I'm doing incorrectly.
I guess in my mind, the process would go something like this:
1. Get folder name
2. Loop through folder and find zip files
3. Extract zip files to folder
Thanks Marcus, however, when implementing the suggestion, I get another error:
```
Traceback (most recent call last):
File "D:/GISData/Tools/MO_Tools/BatchUnzip.py", line 12, in <module>
zipfile.ZipFile(item).extract()
File "C:\Python27\ArcGIS10.2\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'JeffCity_0752.las.zip'
```
When I use print statements, I can see that the files are in there. For example:
```
for item in os.listdir(folder):
if item.endswith(extension):
print os.path.abspath(item)
filename = os.path.basename(item)
print filename
```
yields:
```
D:\GISData\Tools\MO_Tools\JeffCity_0752.las.zip
JeffCity_0752.las.zip
D:\GISData\Tools\MO_Tools\JeffCity_0753.las.zip
JeffCity_0753.las.zip
```
As I understand the documentation,
```
zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])
```
>
> Open a ZIP file, where file can be either a path to a file (a string) or a file-like object
>
>
>
It appears to me like everything is present and accounted for. I just don't understand what I'm doing wrong.
Any suggestions?
Thank You
|
2015/07/10
|
[
"https://Stackoverflow.com/questions/31346790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688131/"
] |
I think this is shorter and worked fine for me. First import the modules required:
```
import zipfile, os
```
Then, I define the working directory:
```
working_directory = 'my_directory'
os.chdir(working_directory)
```
After that you can use a combination of the `os` and `zipfile` to get where you want:
```
for file in os.listdir(working_directory): # get the list of files
if zipfile.is_zipfile(file): # if it is a zipfile, extract it
with zipfile.ZipFile(file) as item: # treat the file as a zip
item.extractall() # extract it in the working directory
```
|
**Recursive** version of [@tpdance answer](https://stackoverflow.com/a/31355555/3030195).
Use this for for **subfolders** and subfolder. Working on Python 3.8
```
import os
import zipfile
base_dir = '/Users/john/data' # absolute path to the data folder
extension = ".zip"
os.chdir(base_dir) # change directory from working dir to dir with files
def unpack_all_in_dir(_dir):
for item in os.listdir(_dir): # loop through items in dir
abs_path = os.path.join(_dir, item) # absolute path of dir or file
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(abs_path) # get full path of file
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(_dir) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
elif os.path.isdir(abs_path):
unpack_all_in_dir(abs_path) # recurse this function with inner folder
unpack_all_in_dir(base_dir)
```
|
55,355,567
|
I am writing code to read data from a CSV file to a pandas dataframe and to get the unique values and concatenate them as a string. The problem is that one of the columns contains the values `True` and `False`. So while concatenating the values I am getting the error
>
>
> ```
> sequence item 0: expected str instance, bool found
>
> ```
>
>
I want python to treat `True` as string rather than boolean value.
I have tried many options but none worked.
The full code and a traceback are attached below.
```
import pandas as pd
df=pd.read_csv('C:/Users/jaiveeru/Downloads/run_test1.csv')
cols=df.columns.tolist()
for i in cols:
lst=df[i].unique().tolist()
str1 = ','.join(lst)
lst2=[str1]
```
>
>
> ```
> ----> 5 str1 = ','.join(lst)
> TypeError: sequence item 0: expected str instance, bool found
>
> ```
>
>
`lst2` should have values `['True,False']`
|
2019/03/26
|
[
"https://Stackoverflow.com/questions/55355567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584680/"
] |
Python 3 does not preform implicit casts. You will need to explicitly cast your booleans to strings.
This can be done easily with [`map` builtin function](https://docs.python.org/3/library/functions.html?highlight=builtin%20filter#map) which applies a function on each item of an iterable and returns the result:
```
str1 = ','.join(map(str, lst))
```
|
Use `.astype(str)`
**Ex:**
```
df[i].unique().astype(str).tolist()
```
|
54,880,349
|
I have installed Python 3.7 64-bit on my 64-bit OS. I have also Installed mysql-installer-community-8.0.15.0 plus I installed MySQL connector using this code `python -m pip install mysql-connector` and still when I try to import mysql.connector. I get this error.
>
> "C:\Users\Basir
> Payenda\PycharmProjects\newprj\venv\Scripts\python.exe"
> "C:/Users/Basir Payenda/PycharmProjects/newprj/app.py" Traceback (most
> recent call last): File "C:/Users/Basir
> Payenda/PycharmProjects/newprj/app.py", line 1, in
> import mysql.connector ModuleNotFoundError: No module named 'mysql'
>
>
>
In addition, I installed mysql-connector-python-8.0.15-py3.7-windows-x86-64bit as well on my machine.
Please help me solve this problem, I have tried all possible things I could. Thank you
edit:
Used the following codes to install mysql.connector
```
C:\Users\Basir Payenda\AppData\Local\Programs\Python\Python37\Scripts>python -m pip install mysql-connector
```
and
```
pip3 install mysql-connector
```
using pip3 I get this message:
>
> Requirement already satisfied: mysql-connector in C:\users\basir
> payenda\appdata\local\programs\python\python37\lib\site-packages
> <2.1.6>
>
>
>
and again when I go to pycharm and import mysql.connector I get above stated message no module 'mysql' found
edit after 2 hours:
No answers, I tried this. I uninstalled everything, python, mysql, pychar and reinstalled. Again the same problem. SHOULD I CHANGE MY COMPUTER?
|
2019/02/26
|
[
"https://Stackoverflow.com/questions/54880349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11080590/"
] |
You are doing
```
throw new InvalidTestScore("Invalid Test Score");
```
so you have to declare that your method is actually going to throw this exception
```
public static void inTestScore(int[] arr) throws InvalidTestScore
```
|
You must declare that your method may throw this exception:
```
public static void inTestScore(int[] arr) throws InvalidTestScore {
...
}
```
This allows the compiler to force any method that calls your method to either catch this exception, or declare that it may throw it.
|
63,710,044
|
I am trying to use Serverless Framework to deploy a Python Fast API WebApp.
Is is related to issue:
<https://github.com/jordaneremieff/mangum/issues/126>
When I deploy it using serverless, sls depoy and Invoke the function I am getting the following error:
```
[ERROR] KeyError: 'requestContext'
Traceback (most recent call last):
File "/var/task/mangum/adapter.py", line 110, in __call__
return self.handler(event, context)
File "/var/task/mangum/adapter.py", line 130, in handler
if "eventType" in event["requestContext"]:
```
I have tried with python 3.8 and 3.7.
Not able to find a resolution on the web for the same.
Also tried using the parameters spec\_version=2(which is not required I feel).
I feel something is missing here, the issue is somewhere around:
```
Adapter requires the information in the event and request context to form the ASGI connection scope.
```
Wondering if anyone has got FastAPI working on AWS Lambda using serverless Framework.
My handler:
```
from fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
handler = Mangum(app)
@app.get("/ping")
def ping():
return {'response': 'pong'}
```
serverless.yml:
```
provider:
name: aws
runtime: python3.8
stage: dev
region: ap-southeast-1
memorySize: 256
functions:
ping:
handler: ping.handler
events:
- http:
path: ping
method: get
cors: true
```
My requirements.txt
```
appnope==0.1.0
backcall==0.2.0
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
decorator==4.4.2
fastapi==0.61.1
h11==0.9.0
httpcore==0.10.2
httptools==0.1.1
httpx==0.14.1
idna==2.10
ipython==7.17.0
ipython-genutils==0.2.0
jedi==0.17.2
mangum==0.9.2
parso==0.7.1
pexpect==4.8.0
pickleshare==0.7.5
prompt-toolkit==3.0.6
ptyprocess==0.6.0
pydantic==1.6.1
Pygments==2.6.1
requests==2.24.0
rfc3986==1.4.0
six==1.15.0
sniffio==1.1.0
starlette==0.13.6
traitlets==4.3.3
typing-extensions==3.7.4.2
urllib3==1.25.10
uvicorn==0.11.8
uvloop==0.14.0
wcwidth==0.2.5
websockets==8.1
```
|
2020/09/02
|
[
"https://Stackoverflow.com/questions/63710044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694699/"
] |
The issue lies within the `mangum` adapter expecting input similar to the `event` content specified by [AWS API Gateway shown here](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html). You'll see that there's a `requestResponse` dictionary there that the Mangum adapter seems to strictly require to function. If your AWS Lambda event doesn't contain that key, then you'll need to add a placeholder field or construct a new context dictionary for it to look for.
This can be done by creating a custom handler [as shown within this part of the Mangum docs](https://mangum.io/adapter/). If you don't particularly care about what the adapter reads as the context then you can get a working version going with the following:
```
def handler(event, context):
event['requestContext'] = {} # Adds a dummy field; mangum will process this fine
asgi_handler = Mangum(app)
response = asgi_handler(event, context)
return response
```
|
You need to provide at least the **minimal** `Event data`, like in the example below,
when you invoke a FastAPI-based lambda function (for example via AWS console Lambda -> Test Event):
```
{
"resource": "/",
"path": "/api/v1/test/",
"httpMethod": "GET",
"requestContext": {
},
"multiValueQueryStringParameters": null
}
```
Please see details about the **Event format** in <https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html#apigateway-example-event>
The need comes from the `mangum` adapter for FastAPI, explained in the [answer](https://stackoverflow.com/a/64403553/392118).
|
24,478,623
|
I trying to setup virtualenvwrapper in GitBash (Windows 7). I write the next lines:
`1 $ export WORKON_HOME=$HOME/.virtualenvs
2 $ export MSYS_HOME=/c/msys/1.0
3 $ source /usr/local/bin/virtualenvwrapper.sh`
And the last line give me an error:
`source /usr/local/bin/virtualenvwrapper.sh
sh.exe: /usr/local/bin/virtualenvwrapper.sh: No such file or directory`
I find, where on my drive is `virtualenvwrapper.sh` and change directory name. On my computer it's `/c/Python27/Scripts/virtualenvwrapper.sh`. When I again run command
`$source /c/Python27/Scripts/virtualenvwrapper.sh`
I get the next ERROR message:
`sh.exe":mktemp:command not found ERROR: virtualenvwrapper could not create a temporary file name`
I check my enviroment variable: `C:\python27\;C:\python27\scripts\;C:\python27\scripts\virtualenvwrapper.sh\;C:\msys;C:\Program Files (x86)\Git\cmd;C:\Program Files (x86)\Git\bin\`
I don't know where i made a mistake
|
2014/06/29
|
[
"https://Stackoverflow.com/questions/24478623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I believe it has something to do with the "image" input.
have you considered using a button element instead?
```
<button type="submit" name="someName" value="someValue"><img src="someImage.png" alt="SomeAlternateText"></button>
```
|
Try this :-
```
<form action="dologin.php" method="post">
<input type="text" name="email" class="form-control" placeholder="Username">
<input type="password" name="password" class="form-control" placeholder="Password">
<input type="image" src="img/login.png" type="submit" alt="Login">
</form>
```
And in dologin.php :
```
email = $_POST['email'];
echo $email;
```
|
38,316,477
|
so i'm trying to convert a bash script, that i wrote, into python, that i'm learning, and the python equivalent of the bash whois just can't give me the answer that i need.
this is what i have in bash-
```
whois 'ip address' | grep -i abuse | \
grep -o [[:alnum:]]*\@[[:alnum:]]*\.[[:alpha:]]* | sort -u
```
and it works perfectly.
when trying to do something similar in python(3.5.2)-
```
IPWhois('ip address').lookup_whois()
```
it's giving me a dictionary with the object that i'm looking for in the first value about half way through the string.
i have tried to put it into `str(dict).splice('\n')[index]`, yet with each iteration the index changes so i can't put it into a script like that. also the bash whois can do both ip addresses and domain names with out having to convert.
i think that i have figured out the conversion, yet trying to grab the results from the IPWhois is giving me a pain in the butt.
i could call the bash `whois` from `subprocess.call`, yet would like to figure out how to do it in python. i know that i can grab part of it with `re.configure`, yet again the return changes so `re.compile` would have to change each time also.
do i keep trying or do i just stick with the bash script that works so well?
i have already written most of the python script and the things that i have to look up are helping me learn.
any ideas?
you can see the bash script [here](https://drive.google.com/open?id=0BwhDqxZzf5XHWk9nSTdLc2FiX28)
thanks,
em
|
2016/07/11
|
[
"https://Stackoverflow.com/questions/38316477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6576450/"
] |
This should do what you are looking for. It works correctly in the snippet.
```js
window.onload = onPageLoad();
function onPageLoad() {
document.getElementById("1403317").checked = true;
}
```
```html
<input type="checkbox" id="1403317">
```
|
try this one maybe ?
```
$(document).ready(function() {
$('#1403317').attr('checked', true)
};
```
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
If you highlight some code, you can right-click or run the command, `Run Selection/Line in Python Terminal`.
We are also planning on [implementing Ctrl-Enter](https://github.com/Microsoft/vscode-python/issues/1349) to do the same thing and looking at [Ctr-Enter executing the current line](https://github.com/Microsoft/vscode-python/issues/480).
|
One way you can do it is through the Integrated Terminal. Here is the guide to open/use it: <https://code.visualstudio.com/docs/editor/integrated-terminal>
After that, type `python3` or `python` since it is depending on what version you are using. Then, copy and paste the fraction of code you want to run into the terminal. It now has the same functionality as the console in Spyder. Hope this helps.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
In my ver of VSCode (1.25), shift+enter will run selection. Note that you will want to have your integrated terminal running python.
|
One way you can do it is through the Integrated Terminal. Here is the guide to open/use it: <https://code.visualstudio.com/docs/editor/integrated-terminal>
After that, type `python3` or `python` since it is depending on what version you are using. Then, copy and paste the fraction of code you want to run into the terminal. It now has the same functionality as the console in Spyder. Hope this helps.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
You can:
1. open a terminal at *Terminal>New Terminal*
2. Highlight the code you want to run
3. Hit *Terminal>Run Selected Text*
As for R you can hit `CTRL Enter` to execute the highlighted code. For python there's apparently no default shortcut (see below), but I am quite sure you can add yours.
[](https://i.stack.imgur.com/GKgeh.png)
|
One way you can do it is through the Integrated Terminal. Here is the guide to open/use it: <https://code.visualstudio.com/docs/editor/integrated-terminal>
After that, type `python3` or `python` since it is depending on what version you are using. Then, copy and paste the fraction of code you want to run into the terminal. It now has the same functionality as the console in Spyder. Hope this helps.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
If you highlight some code, you can right-click or run the command, `Run Selection/Line in Python Terminal`.
We are also planning on [implementing Ctrl-Enter](https://github.com/Microsoft/vscode-python/issues/1349) to do the same thing and looking at [Ctr-Enter executing the current line](https://github.com/Microsoft/vscode-python/issues/480).
|
In my ver of VSCode (1.25), shift+enter will run selection. Note that you will want to have your integrated terminal running python.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
If you highlight some code, you can right-click or run the command, `Run Selection/Line in Python Terminal`.
We are also planning on [implementing Ctrl-Enter](https://github.com/Microsoft/vscode-python/issues/1349) to do the same thing and looking at [Ctr-Enter executing the current line](https://github.com/Microsoft/vscode-python/issues/480).
|
I'm still trying to figure out how to make vscode do what I need (interactive python plots), but I can offer a more complete answer to the question at hand than what has been given so far:
1- Evaluate current selection in debug terminal is an option that is not enabled by default, so you may want to bind the 'editor.debug.action.selectionToRepl' action to whatever keyboard shortcut you choose (I'm using F9). As of today, there still appears to be no option to evaluate current line while debugging, only current selection.
2- Evaluate current line or selection in python terminal is enabled by default, but I'm on Windows where this isn't doing what I would expect - it evaluates in a new runtime, which does no good if you're trying to debug an existing runtime. So I can't say much about how useful this option is, or even if it is necessary since anytime you'd want to evaluate line-by-line, you'll be in debug mode anyway and sending to debug console as in 1 above. The Windows issue might have something to do with the settings.json entry
"terminal.integrated.inheritEnv": true,
not having an affect in Windows as of yet, per vscode documentation.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
You can:
1. open a terminal at *Terminal>New Terminal*
2. Highlight the code you want to run
3. Hit *Terminal>Run Selected Text*
As for R you can hit `CTRL Enter` to execute the highlighted code. For python there's apparently no default shortcut (see below), but I am quite sure you can add yours.
[](https://i.stack.imgur.com/GKgeh.png)
|
In my ver of VSCode (1.25), shift+enter will run selection. Note that you will want to have your integrated terminal running python.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
In my ver of VSCode (1.25), shift+enter will run selection. Note that you will want to have your integrated terminal running python.
|
I'm still trying to figure out how to make vscode do what I need (interactive python plots), but I can offer a more complete answer to the question at hand than what has been given so far:
1- Evaluate current selection in debug terminal is an option that is not enabled by default, so you may want to bind the 'editor.debug.action.selectionToRepl' action to whatever keyboard shortcut you choose (I'm using F9). As of today, there still appears to be no option to evaluate current line while debugging, only current selection.
2- Evaluate current line or selection in python terminal is enabled by default, but I'm on Windows where this isn't doing what I would expect - it evaluates in a new runtime, which does no good if you're trying to debug an existing runtime. So I can't say much about how useful this option is, or even if it is necessary since anytime you'd want to evaluate line-by-line, you'll be in debug mode anyway and sending to debug console as in 1 above. The Windows issue might have something to do with the settings.json entry
"terminal.integrated.inheritEnv": true,
not having an affect in Windows as of yet, per vscode documentation.
|
49,771,589
|
I just made the transition from Spyder to VScode for my python endeavours. Is there a way to run individual lines of code? That's how I used to do my on-the-spot debugging, but I can't find an option for it in VScode and really don't want to keep setting and removing breakpoints.
Thanks.
|
2018/04/11
|
[
"https://Stackoverflow.com/questions/49771589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4482349/"
] |
You can:
1. open a terminal at *Terminal>New Terminal*
2. Highlight the code you want to run
3. Hit *Terminal>Run Selected Text*
As for R you can hit `CTRL Enter` to execute the highlighted code. For python there's apparently no default shortcut (see below), but I am quite sure you can add yours.
[](https://i.stack.imgur.com/GKgeh.png)
|
I'm still trying to figure out how to make vscode do what I need (interactive python plots), but I can offer a more complete answer to the question at hand than what has been given so far:
1- Evaluate current selection in debug terminal is an option that is not enabled by default, so you may want to bind the 'editor.debug.action.selectionToRepl' action to whatever keyboard shortcut you choose (I'm using F9). As of today, there still appears to be no option to evaluate current line while debugging, only current selection.
2- Evaluate current line or selection in python terminal is enabled by default, but I'm on Windows where this isn't doing what I would expect - it evaluates in a new runtime, which does no good if you're trying to debug an existing runtime. So I can't say much about how useful this option is, or even if it is necessary since anytime you'd want to evaluate line-by-line, you'll be in debug mode anyway and sending to debug console as in 1 above. The Windows issue might have something to do with the settings.json entry
"terminal.integrated.inheritEnv": true,
not having an affect in Windows as of yet, per vscode documentation.
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This also works well:
```
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine(), 10); // Read and integer like this
// Read an array like this
const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));
let result; // result of some calculation as an example
ws.write(result + "\n");
ws.end();
}
```
Here my process.env.OUTPUT\_PATH is set, if yours is not, you can use something else.
|
First, install prompt-sync: `npm i prompt-sync`
Then in your JavaScript file:
```
const ps = require("prompt-sync");
const prompt = ps();
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
That's it.
You can improve this by adding `{sigint: true}` when initialising ps. With this configuration, the node app will stop at that point. With the above code, when you exit (Ctrl + C) when you're asked for the name, you will see `Hello, null`, but you will not get that with the change below:
```
const ps = require("prompt-sync");
const prompt = ps({sigint: true}); // Change on this line.
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
Of course, you simplify the above code...
```
const prompt = require("prompt-sync")({sigint: true});
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
The other solutions here are either async, or use the blocking `prompt-sync`. I want a blocking solution, but `prompt-sync` consistently corrupts my terminal.
I found [a lovely answer here](https://github.com/nodejs/node/issues/28243) which offers a good solution.
Create the function:
```js
const prompt = msg => {
fs.writeSync(1, String(msg));
let s = '', buf = Buffer.alloc(1);
while(buf[0] - 10 && buf[0] - 13)
s += buf, fs.readSync(0, buf, 0, 1, 0);
return s.slice(1);
};
```
Use it:
```js
const result = prompt('Input something: ');
console.log('Your input was: ' + result);
```
Disclaimer: I'm cross-posting my own answer [from here](https://stackoverflow.com/questions/55045812/exit-process-when-all-readline-online-callbacks-complete).
|
This also works well:
```
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine(), 10); // Read and integer like this
// Read an array like this
const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));
let result; // result of some calculation as an example
ws.write(result + "\n");
ws.end();
}
```
Here my process.env.OUTPUT\_PATH is set, if yours is not, you can use something else.
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This can also be done **natively with promises**. It is also more secure then using outside world NPM modules. No longer need to use callback syntax.
Updated answer from @Willian. This will work with async/await syntax and es6/7.
```js
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
// Usage inside aync function do not need closure demo only*
(async() => {
try {
const name = await prompt("What's your name: ");
// Can use name for next question if needed
const lastName = await prompt(`Hello ${name}, what's your last name?: `);
// Can prompt multiple times
console.log(name, lastName);
rl.close();
} catch (e) {
console.error("Unable to prompt", e);
}
})();
// When done reading prompt, exit program
rl.on('close', () => process.exit(0));
```
|
This also works well:
```
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine(), 10); // Read and integer like this
// Read an array like this
const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));
let result; // result of some calculation as an example
ws.write(result + "\n");
ws.end();
}
```
Here my process.env.OUTPUT\_PATH is set, if yours is not, you can use something else.
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
There are 3 options you could use. I will walk you through these examples:
(Option 1) **prompt-sync:**
In my opinion, it is the simpler one. It is a module available on npm and you can refer to the docs for more examples [prompt-sync](https://github.com/heapwolf/prompt-sync).
```sh
npm install prompt-sync
```
```js
const prompt = require("prompt-sync")({ sigint: true });
const age = prompt("How old are you? ");
console.log(`You are ${age} years old.`);
```
(Option 2) **prompt**: It is another module available on npm:
```sh
npm install prompt
```
```js
const prompt = require('prompt');
prompt.start();
prompt.get(['username', 'email'], function (err, result) {
if (err) { return onErr(err); }
console.log('Command-line input received:');
console.log(' Username: ' + result.username);
console.log(' Email: ' + result.email);
});
function onErr(err) {
console.log(err);
return 1;
}
```
(Option 3) **readline**: It is a built-in module in Node.js. You only need to run the code below:
```js
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
```
Enjoy!
|
We can use the built-in readline module which is a wrapper around Standard I/O, suitable for taking user input from command line(terminal).
Here's a simple example. Try the following in a new file:
```
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
```
For more: [How do I prompt users for input from a command-line script?](https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/)
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
The other solutions here are either async, or use the blocking `prompt-sync`. I want a blocking solution, but `prompt-sync` consistently corrupts my terminal.
I found [a lovely answer here](https://github.com/nodejs/node/issues/28243) which offers a good solution.
Create the function:
```js
const prompt = msg => {
fs.writeSync(1, String(msg));
let s = '', buf = Buffer.alloc(1);
while(buf[0] - 10 && buf[0] - 13)
s += buf, fs.readSync(0, buf, 0, 1, 0);
return s.slice(1);
};
```
Use it:
```js
const result = prompt('Input something: ');
console.log('Your input was: ' + result);
```
Disclaimer: I'm cross-posting my own answer [from here](https://stackoverflow.com/questions/55045812/exit-process-when-all-readline-online-callbacks-complete).
|
First, install prompt-sync: `npm i prompt-sync`
Then in your JavaScript file:
```
const ps = require("prompt-sync");
const prompt = ps();
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
That's it.
You can improve this by adding `{sigint: true}` when initialising ps. With this configuration, the node app will stop at that point. With the above code, when you exit (Ctrl + C) when you're asked for the name, you will see `Hello, null`, but you will not get that with the change below:
```
const ps = require("prompt-sync");
const prompt = ps({sigint: true}); // Change on this line.
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
Of course, you simplify the above code...
```
const prompt = require("prompt-sync")({sigint: true});
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This also works well:
```
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine(), 10); // Read and integer like this
// Read an array like this
const c = readLine().split(' ').map(cTemp => parseInt(cTemp, 10));
let result; // result of some calculation as an example
ws.write(result + "\n");
ws.end();
}
```
Here my process.env.OUTPUT\_PATH is set, if yours is not, you can use something else.
|
prompt package dont work properly in 'windows' environment.
instead 'inquirer' package is better
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This can also be done **natively with promises**. It is also more secure then using outside world NPM modules. No longer need to use callback syntax.
Updated answer from @Willian. This will work with async/await syntax and es6/7.
```js
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
// Usage inside aync function do not need closure demo only*
(async() => {
try {
const name = await prompt("What's your name: ");
// Can use name for next question if needed
const lastName = await prompt(`Hello ${name}, what's your last name?: `);
// Can prompt multiple times
console.log(name, lastName);
rl.close();
} catch (e) {
console.error("Unable to prompt", e);
}
})();
// When done reading prompt, exit program
rl.on('close', () => process.exit(0));
```
|
First, install prompt-sync: `npm i prompt-sync`
Then in your JavaScript file:
```
const ps = require("prompt-sync");
const prompt = ps();
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
That's it.
You can improve this by adding `{sigint: true}` when initialising ps. With this configuration, the node app will stop at that point. With the above code, when you exit (Ctrl + C) when you're asked for the name, you will see `Hello, null`, but you will not get that with the change below:
```
const ps = require("prompt-sync");
const prompt = ps({sigint: true}); // Change on this line.
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
Of course, you simplify the above code...
```
const prompt = require("prompt-sync")({sigint: true});
let name = prompt("What is your name? ");
console.log("Hello, ", name);
```
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This can also be done **natively with promises**. It is also more secure then using outside world NPM modules. No longer need to use callback syntax.
Updated answer from @Willian. This will work with async/await syntax and es6/7.
```js
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
// Usage inside aync function do not need closure demo only*
(async() => {
try {
const name = await prompt("What's your name: ");
// Can use name for next question if needed
const lastName = await prompt(`Hello ${name}, what's your last name?: `);
// Can prompt multiple times
console.log(name, lastName);
rl.close();
} catch (e) {
console.error("Unable to prompt", e);
}
})();
// When done reading prompt, exit program
rl.on('close', () => process.exit(0));
```
|
prompt package dont work properly in 'windows' environment.
instead 'inquirer' package is better
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
This can also be done **natively with promises**. It is also more secure then using outside world NPM modules. No longer need to use callback syntax.
Updated answer from @Willian. This will work with async/await syntax and es6/7.
```js
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const prompt = (query) => new Promise((resolve) => rl.question(query, resolve));
// Usage inside aync function do not need closure demo only*
(async() => {
try {
const name = await prompt("What's your name: ");
// Can use name for next question if needed
const lastName = await prompt(`Hello ${name}, what's your last name?: `);
// Can prompt multiple times
console.log(name, lastName);
rl.close();
} catch (e) {
console.error("Unable to prompt", e);
}
})();
// When done reading prompt, exit program
rl.on('close', () => process.exit(0));
```
|
If you want to use ESM (`import` instead of `require`):
```
import * as readline from 'node:readline/promises'; // This uses the promise-based APIs
import { stdin as input, stdout as output } from 'node:process';
const rl = readline.createInterface({ input, output });
const answer = await rl.question('What do you think of Node.js? ');
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
```
Source: <https://nodejs.org/api/readline.html#readline>
Note that this is a a new feature. From the source linked above, it seems like node v17.9.1 or above is required.
|
61,394,928
|
I have just started using Node.js, and I don't know how to get user input. I am looking for the JavaScript counterpart of the python function `input()` or the C function `gets`. Thanks.
|
2020/04/23
|
[
"https://Stackoverflow.com/questions/61394928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13262787/"
] |
Use this:
```js
let inpt = Object.values(process.argv).slice(2).join(' ').toString();
```
While running the file, you can provide inputs.
Example:
```
node <file_name>.js <this_is_a_input>
```
|
We can use the built-in readline module which is a wrapper around Standard I/O, suitable for taking user input from command line(terminal).
Here's a simple example. Try the following in a new file:
```
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("\nBYE BYE !!!");
process.exit(0);
});
```
For more: [How do I prompt users for input from a command-line script?](https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/)
|
46,776,264
|
My application requirement is to use our LDAP directory to authenticate a User based on their network login. I setup the LDAP correctly using ldap3 in my system.py. I'm able to bind to a user and identify credentials in python, not using Django. Which authentication backend would I set Django up to use to make my login function as I want?
|
2017/10/16
|
[
"https://Stackoverflow.com/questions/46776264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8570299/"
] |
This is a broad question and I am not sure your experience with Django so without more information I would suggest trying [this](https://github.com/etianen/django-python3-ldap) or [this](http://fle.github.io/combine-ldap-and-classical-authentication-in-django.html)
|
I am running Python 3 and have used the excellent `django-python3-ldap` package with both OpenLDAP and Active Directory from Django 1.6 through 2.0. You can find it here:
<https://github.com/etianen/django-python3-ldap>
It is a well maintained package that we've been able to use as we upgrade Django from version to version.
|
49,352,889
|
I installed `fiona` as follows:
```
conda install -c conda-forge fiona
```
It installed without any errors. When I try to import `fiona`, I get the following error:
Traceback (most recent call last):
```
File "<stdin>", line 1, in <module>
File "/home/name/anaconda3/lib/python3.6/site-packages/fiona/__init__.py", line 69, in <module>
from fiona.collection import Collection, BytesCollection, vsi_path
File "/home/name/anaconda3/lib/python3.6/site-packages/fiona/collection.py", line 9, in <module>
from fiona.ogrext import Iterator, ItemsIterator, KeysIterator
ImportError: /home/name/anaconda3/lib/python3.6/site-packages/fiona/../../.././libkea.so.1.4.7: undefined symbol: _ZN2H56H5FileC1ERKSsjRKNS_17FileCreatPropListERKNS_15FileAccPropListE
```
Incase it helps with diagnosis, here is the output of `conda list`:
```
_ipyw_jlab_nb_ext_conf 0.1.0 py36he11e457_0
alabaster 0.7.10 py36h306e16b_0
anaconda custom py36hbbc8b67_0
anaconda-client 1.6.9 py36_0
anaconda-navigator 1.7.0 py36_0
anaconda-project 0.8.2 py36h44fb852_0
asn1crypto 0.24.0 py36_0
astroid 1.6.1 py36_0
astropy 2.0.3 py36h14c3975_0
attrs 17.4.0 py36_0
automat 0.6.0 py36_0 conda-forge
Automat 0.6.0 <pip>
babel 2.5.3 py36_0
backports 1.0 py36hfa02d7e_1
backports.shutil_get_terminal_size 1.0.0 py36hfea85ff_2
beautifulsoup4 4.6.0 py36h49b8c8c_1
bitarray 0.8.1 py36h14c3975_1
bkcharts 0.2 py36h735825a_0
blaze 0.11.3 py36h4e06776_0
bleach 2.1.2 py36_0
bokeh 0.12.13 py36h2f9c1c0_0
boost 1.66.0 py36_1 conda-forge
boost-cpp 1.66.0 1 conda-forge
boto 2.48.0 py36h6e4cd66_1
bottleneck 1.2.1 py36haac1ea0_0
bzip2 1.0.6 h9a117a8_4
ca-certificates 2018.1.18 0 conda-forge
cairo 1.14.12 h77bcde2_0
certifi 2018.1.18 py36_0 conda-forge
cffi 1.11.4 py36h9745a5d_0
chardet 3.0.4 py36h0f667ec_1
click 6.7 py36h5253387_0
click-plugins 1.0.3 py36_0 conda-forge
cligj 0.4.0 py36_0 conda-forge
cloudpickle 0.5.2 py36_1
clyent 1.2.2 py36h7e57e65_1
colorama 0.3.9 py36h489cec4_0
conda 4.3.34 py36_0 conda-forge
conda-build 3.4.1 py36_0
conda-env 2.6.0 0 conda-forge
conda-verify 2.0.0 py36h98955d8_0
constantly 15.1.0 py_0 conda-forge
contextlib2 0.5.5 py36h6c84a62_0
cryptography 2.1.4 py36hd09be54_0
cssselect 1.0.3 py_0 conda-forge
curl 7.58.0 h84994c4_0
cycler 0.10.0 py36h93f1223_0
cython 0.27.3 py36h1860423_0
cytoolz 0.9.0 py36h14c3975_0
dask 0.16.1 py36_0
dask-core 0.16.1 py36_0
datashape 0.5.4 py36h3ad6b5c_0
dbus 1.12.2 hc3f9b76_1
decorator 4.2.1 py36_0
distributed 1.20.2 py36_0
docutils 0.14 py36hb0f60f5_0
entrypoints 0.2.3 py36h1aec115_2
et_xmlfile 1.0.1 py36hd6bccc3_0
expat 2.2.5 he0dffb1_0
fastcache 1.0.2 py36h14c3975_2
filelock 2.0.13 py36h646ffb5_0
fiona 1.7.11 py36_3 conda-forge
flask 0.12.2 py36hb24657c_0
flask-cors 3.0.3 py36h2d857d3_0
fontconfig 2.12.4 h88586e7_1
freetype 2.8 hab7d2ae_1
freexl 1.0.5 0 conda-forge
gdal 2.2.2 py36hc209d97_1
geos 3.6.2 1 conda-forge
get_terminal_size 1.0.0 haa9412d_0
gevent 1.2.2 py36h2fe25dc_0
giflib 5.1.4 0 conda-forge
glib 2.53.6 h5d9569c_2
glob2 0.6 py36he249c77_0
gmp 6.1.2 h6c8ec71_1
gmpy2 2.0.8 py36hc8893dd_2
graphite2 1.3.10 hf63cedd_1
greenlet 0.4.12 py36h2d503a6_0
gst-plugins-base 1.12.4 h33fb286_0
gstreamer 1.12.4 hb53b477_0
h5py 2.7.1 py36h3585f63_0
harfbuzz 1.7.4 hc5b324e_0
hdf4 4.2.13 0 conda-forge
hdf5 1.10.1 h9caa474_1
heapdict 1.0.0 py36_2
html5lib 1.0.1 py36h2f9c1c0_0
hyperlink 17.3.1 py_0 conda-forge
icu 58.2 h9c2bf20_1
idna 2.6 py36h82fb2a8_1
imageio 2.2.0 py36he555465_0
imagesize 0.7.1 py36h52d8127_0
incremental 17.5.0 py_0 conda-forge
intel-openmp 2018.0.0 hc7b2577_8
ipykernel 4.8.0 py36_0
ipython 6.2.1 py36h88c514a_1
ipython_genutils 0.2.0 py36hb52b0d5_0
ipywidgets 7.1.1 py36_0
isort 4.2.15 py36had401c0_0
itsdangerous 0.24 py36h93cc618_1
jbig 2.1 hdba287a_0
jdcal 1.3 py36h4c697fb_0
jedi 0.11.1 py36_0
jinja2 2.10 py36ha16c418_0
jpeg 9b h024ee3a_2
json-c 0.12.1 0 conda-forge
jsonschema 2.6.0 py36h006f8b5_0
jupyter 1.0.0 py36_4
jupyter_client 5.2.2 py36_0
jupyter_console 5.2.0 py36he59e554_1
jupyter_core 4.4.0 py36h7c827e3_0
jupyterlab 0.31.5 py36_0
jupyterlab_launcher 0.10.2 py36_0
kealib 1.4.7 4 conda-forge
krb5 1.14.2 0 conda-forge
lazy-object-proxy 1.3.1 py36h10fcdad_0
libcurl 7.58.0 h1ad7b7a_0
```
(...)
Any ideas what may be the problem?
|
2018/03/18
|
[
"https://Stackoverflow.com/questions/49352889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9400561/"
] |
I guess this problem comes from conflicts with stuff already installed in the Anaconda distribution. My inelegant workaround is:
```
conda install -c conda-forge geopandas
conda remove geopandas fiona
pip install geopandas fiona
```
|
Because I did not want to uninstall geopandas, I solved the issue by upgrading fiona via pip
```
pip install --upgrade fiona
```
|
56,378,783
|
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.
```py
def floorCompare(currentFloor,destinationFloor,calledFloor):
if calledFloor > currentFloor and calledFloor < destinationFloor:
return(True)
elif calledFloor < currentFloor and calledFloor > destinationFloor:
return(True)
else:
return(False)
floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
print("The Elevator is on floor: 1. The doors are "+doors+".")
for x in range(int(input("How many floors need to be visited? "))):
callFloor = int(input("Floor to call the elevator to: "))
queue.append(callFloor)
if callFloor > 10 or callFloor < 1:
raise Exception(str(callFloor)+" is not a valid floor.")
if queue[0] == 1:
del queue[0]
print("The elevator has arrived on floor 1, and the doors are open.")
print("The queue of floors to visit is...",queue)
for x in queue:
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
print("Continuing Queue")
elevator()
```
So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?
When I run the code with a basic trial set of floors, here's what I get as output.
```
The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...
The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...
The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.
Process finished with exit code 0
```
|
2019/05/30
|
[
"https://Stackoverflow.com/questions/56378783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10760049/"
] |
I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the `for x in queue:` operator runs into problems when you edit the list while it runs. I would recommend using `while queue:` instead and setting x to the first element.
```
while queue:
x = queue[0]
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
```
|
The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.
```
l=[3,6,9,10,14]
for i in l:
print(i)
```
Output:
3
6
9
10
14
```
for i in l:
print(i)
l.remove(i)
```
output:
3
9
14
|
56,378,783
|
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.
```py
def floorCompare(currentFloor,destinationFloor,calledFloor):
if calledFloor > currentFloor and calledFloor < destinationFloor:
return(True)
elif calledFloor < currentFloor and calledFloor > destinationFloor:
return(True)
else:
return(False)
floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
print("The Elevator is on floor: 1. The doors are "+doors+".")
for x in range(int(input("How many floors need to be visited? "))):
callFloor = int(input("Floor to call the elevator to: "))
queue.append(callFloor)
if callFloor > 10 or callFloor < 1:
raise Exception(str(callFloor)+" is not a valid floor.")
if queue[0] == 1:
del queue[0]
print("The elevator has arrived on floor 1, and the doors are open.")
print("The queue of floors to visit is...",queue)
for x in queue:
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
print("Continuing Queue")
elevator()
```
So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?
When I run the code with a basic trial set of floors, here's what I get as output.
```
The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...
The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...
The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.
Process finished with exit code 0
```
|
2019/05/30
|
[
"https://Stackoverflow.com/questions/56378783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10760049/"
] |
The reason for the early exit is because you are modifying the list while looping on it. To have a simple example:
```
l = [3,6,9,10]
for x in l:
print(x)
l.remove(x)
```
The output is
```
3
9
```
However, there are many other problems with your current code. Some I could catch are:
1. You aren't adding the newly called floors inside the `for` loop.
2. The `floorCompare` method is being called with `queue[0]` as the destination, while that isn't the *final* one. As you can see, `7` was not considered en route since you compared `3` and `6`. You should have compared `3` and `10`, the farthest one.
Also note that `queue` is not initially sorted, and the intermediate calls will also not be in order. So you need to keep that in mind while using it.
|
I think your problem lies in the use of a for loop in conjunction with the queue.remove() function. It seems like the `for x in queue:` operator runs into problems when you edit the list while it runs. I would recommend using `while queue:` instead and setting x to the first element.
```
while queue:
x = queue[0]
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
```
|
56,378,783
|
I'm doing a supposedly simple python challenge a friend gave me involving an elevator and the logic behind its movements. Everything was going well and good until I got to the point where I had to write how to determine if the elevator could move hit a called floor en route to its next queued floor.
```py
def floorCompare(currentFloor,destinationFloor,calledFloor):
if calledFloor > currentFloor and calledFloor < destinationFloor:
return(True)
elif calledFloor < currentFloor and calledFloor > destinationFloor:
return(True)
else:
return(False)
floor = "1"
doors = "closed"
queue = []
def elevator(): # function defines how the elevator should move
print("The Elevator is on floor: 1. The doors are "+doors+".")
for x in range(int(input("How many floors need to be visited? "))):
callFloor = int(input("Floor to call the elevator to: "))
queue.append(callFloor)
if callFloor > 10 or callFloor < 1:
raise Exception(str(callFloor)+" is not a valid floor.")
if queue[0] == 1:
del queue[0]
print("The elevator has arrived on floor 1, and the doors are open.")
print("The queue of floors to visit is...",queue)
for x in queue:
print("The elevator's doors are closed and it's moving to floor:",x)
floor = str(x)
print("...")
print()
print("The elevator has arrived on floor "+floor+", and the doors are open.")
queue.remove(x)
addFloor = int(input("Floor to call the elevator to: "))
if addFloor > 10 or addFloor < 1:
raise Exception(str(addFloor)+" is not a valid floor.")
print(queue)
if floorCompare(int(floor), int(queue[0]), int(addFloor)) == True:
print("The elevator can hit this stop en route to its next one.")
else:
print("The elevator must hit this stop separately.")
print("Continuing Queue")
elevator()
```
So in the For loop, there is a nested If/Else loop, which I would assume would be iterated along with the rest of the code in the for loop. However, when I run the code, upon reaching the If/Else loop, it breaks out of the For loop and continues on its merry way, disregarding any further iterations that need to be done in the array. What's going on here?
When I run the code with a basic trial set of floors, here's what I get as output.
```
The Elevator is on floor: 1. The doors are closed.
How many floors need to be visited? 4
Floor to call the elevator to: 3
Floor to call the elevator to: 6
Floor to call the elevator to: 9
Floor to call the elevator to: 10
The queue of floors to visit is... [3, 6, 9, 10]
The elevator's doors are closed and it's moving to floor: 3
...
The elevator has arrived on floor 3, and the doors are open.
Floor to call the elevator to: 7
[6, 9, 10]
The elevator must hit this stop seperately.
The elevator's doors are closed and it's moving to floor: 9
...
The elevator has arrived on floor 9, and the doors are open.
Floor to call the elevator to: 3
[6, 10]
The elevator must hit this stop separately.
Process finished with exit code 0
```
|
2019/05/30
|
[
"https://Stackoverflow.com/questions/56378783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10760049/"
] |
The reason for the early exit is because you are modifying the list while looping on it. To have a simple example:
```
l = [3,6,9,10]
for x in l:
print(x)
l.remove(x)
```
The output is
```
3
9
```
However, there are many other problems with your current code. Some I could catch are:
1. You aren't adding the newly called floors inside the `for` loop.
2. The `floorCompare` method is being called with `queue[0]` as the destination, while that isn't the *final* one. As you can see, `7` was not considered en route since you compared `3` and `6`. You should have compared `3` and `10`, the farthest one.
Also note that `queue` is not initially sorted, and the intermediate calls will also not be in order. So you need to keep that in mind while using it.
|
The reason for it to skip floor 6, is because of removing the data from the list, which is being iterated.
```
l=[3,6,9,10,14]
for i in l:
print(i)
```
Output:
3
6
9
10
14
```
for i in l:
print(i)
l.remove(i)
```
output:
3
9
14
|
69,869,854
|
Can I get the `__doc__` string of the main script?
Here is the starting script, which would be run from command line: `python a.py`
module a.py
```py
import b
b.func()
```
module b.py
```py
def func():
???.__doc__
```
How can I get the calling module, as an object?
I am not asking about how to get the file name as string. I know how to retrieve the file's name from stack trace. I don't want to retrieve the **doc** string by parsing manually. Also, I don't think I can just import by `m = __import__(a)` because of circular import loop.
|
2021/11/07
|
[
"https://Stackoverflow.com/questions/69869854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84196/"
] |
a.py
```
"""
Foo bar
"""
import b
if __name__ == '__main__':
b.show_your_docs()
```
b.py
```
def show_your_docs():
name = caller_name(1)
print(__import__(name).__doc__)
```
Where caller\_name is code from this [gist](https://gist.github.com/techtonik/2151727#gistcomment-2333747)
The weakness of this approach though is it is getting a string representation of the module name and reimporting it, instead of getting a reference to the module (type).
|
This is the full solution from @MatthewMartin 's accepted answer:
```
def show_your_docs():
name = caller_name(1)
print(__import__(name).__doc__)
def caller_docstring(level=1):
name = caller_name(level)
return __import__(name).__doc__
def caller_name(skip=2):
def stack_(frame):
framelist = []
while frame:
framelist.append(frame)
frame = frame.f_back
return framelist
stack = stack_(sys._getframe(1))
start = 0 + skip
if len(stack) < start + 1:
return ''
parentframe = stack[start]
name = []
module = inspect.getmodule(parentframe)
if module:
name.append(module.__name__)
if 'self' in parentframe.f_locals:
name.append(parentframe.f_locals['self'].__class__.__name__)
codename = parentframe.f_code.co_name
if codename != '<module>': # top level usually
name.append(codename) # function or a method
del parentframe
return ".".join(name)
```
```
text = caller_docstring(2)
```
|
18,587,208
|
can any one tell me how to simulate touch on Image Button using android view client python
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18587208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2741623/"
] |
Replace
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
```
Hope it helps.
|
change
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
```
|
18,587,208
|
can any one tell me how to simulate touch on Image Button using android view client python
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18587208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2741623/"
] |
Replace
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
```
Hope it helps.
|
`android:src="@drawable/capture"`
put this.
|
18,587,208
|
can any one tell me how to simulate touch on Image Button using android view client python
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18587208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2741623/"
] |
try this, put capture.png in any drawable folder
```
android:src="@drawable/capture"
```
|
change
```
android:src="res/drawable-hdpi/capture.PNG"
```
with
```
android:src="@drawable/capture"
```
|
18,587,208
|
can any one tell me how to simulate touch on Image Button using android view client python
|
2013/09/03
|
[
"https://Stackoverflow.com/questions/18587208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2741623/"
] |
try this, put capture.png in any drawable folder
```
android:src="@drawable/capture"
```
|
`android:src="@drawable/capture"`
put this.
|
28,180,511
|
I wrote a simple triple quote print statement. See below. For the OVER lineart, it gets truncated into two different lines (when you copy paste this into the interpreter.) But, if I insert a space or any at the end of each of the lines, then it prints fine. Any idea why this behavior in python.
I am inclined to think this is due to \ and / at the end of the lines, but I cannot find a concrete reason. I tried removing them and and have some observations but would like a clear reasoning..
```
print(
"""
_____ ____ __ __ ______
/ ____| / _ | / | /| | ____|
| | / / | | / /| /| | | |___
| | _ / /__| | / / |_/| | | ___|
| |__| | / / | | / / | | | |____
\_____/ /_/ |_| /_/ |_| |______|
______ _ _ ______ _____
/ __ \ | | / / | ____| | _ \
| | | | | | / / | |___ | |_| |
| | | | | | / / | ___| | _ /
| |__| | | |_/ / | |____ | | \ \
\______/ |____/ |______| |_| \_\
"""
)
```
|
2015/01/27
|
[
"https://Stackoverflow.com/questions/28180511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500493/"
] |
You have `\` backslash escapes in your string, one each on the last two lines as well as on the first line spelling *over*, all three part of the letter *R*. These signal to Python that you wanted to *ignore* the newline right after it.
Either use a space right after each `\` backslash at the end of a line, *double* the backslashes to escape the escape, or use a *raw* string by prefixing the triple quote with a `r`:
```
print(
r"""
_____ ____ __ __ ______
/ ____| / _ | / | /| | ____|
| | / / | | / /| /| | | |___
| | _ / /__| | / / |_/| | | ___|
| |__| | / / | | / / | | | |____
\_____/ /_/ |_| /_/ |_| |______|
______ _ _ ______ _____
/ __ \ | | / / | ____| | _ \
| | | | | | / / | |___ | |_| |
| | | | | | / / | ___| | _ /
| |__| | | |_/ / | |____ | | \ \
\______/ |____/ |______| |_| \_\
"""
)
```
Raw strings don't support backslash escapes, except for escaped quotes (`\"` and `\'`) which would be included *with the backslash*.
|
The problem is with `\` at the end of line so you need to escape them. For that i use another backslash.
```
print(
"""
_____ ____ __ __ ______
/ ____| / _ | / | /| | ____|
| | / / | | / /| /| | | |___
| | _ / /__| | / / |_/| | | ___|
| |__| | / / | | / / | | | |____
\_____/ /_/ |_| /_/ |_| |______|
______ _ _ ______ _____
/ __ \ | | / / | ____| | _ \\
| | | | | | / / | |___ | |_| |
| | | | | | / / | ___| | _ /
| |__| | | |_/ / | |____ | | \ \\
\______/ |____/ |______| |_| \_\\
"""
)
```
|
54,914,306
|
This code fails when it runs:
```
import datetime
import subprocess
startdate = datetime.datetime(2010,4,9)
for i in range(1):
startdate += datetime.timedelta(days=1)
enddate = datetime.datetime(2010,4,10)
for i in range(1):
enddate += datetime.timedelta(days=1)
subprocess.call("sudo mam-list-usagerecords -s \"" + str(startdate) + "\" -e \"" + str(enddate) + " --format csv --full")
```
The program has these errors when it runs:
```
File "QuestCommand.py", line 12, in <module>
subprocess.call("sudo mam-list-usagerecords -s \"" + str(startdate) + "\" -e \"" + str(enddate) + " --format csv --full")
File "/usr/lib64/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
```
I have ran this code multiple times with other ways, changing quotes and whatnot. I am fairly new to system calls and utilizing an HPC allocation database. I am stuck and if anyone can help me with resolving this issue that would be very helpful.
Thank you!
|
2019/02/27
|
[
"https://Stackoverflow.com/questions/54914306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11035382/"
] |
When possible, pass a *list* containing your command name and its arguments.
```
subprocess.call(["sudo", "mam-list-usagerecords",
"-s", str(startdate),
"-e", str(enddate),
"--format", "csv",
"--full"])
```
This avoids the need to even know how the shell will process a command line.
|
When I first started using some of the subprocess methods I ran into some of the same issues.
Try running your code like this:
```
import datetime
import subprocess
import shlex
startdate = datetime.datetime(2010, 4, 9) + datetime.timedelta(days=1)
enddate = datetime.datetime(2010, 4, 10) + datetime.timedelta(days=1)
command = (
"sudo mam-list-usagerecords -s "
+ str(startdate)
+ "-e"
+ str(enddate)
+ " --format csv --full"
)
print(command)
print(type(command))
print(shlex.split(command))
subprocess.call(shlex.split(command))
```
OUTPUT:
>
> sudo mam-list-usagerecords -s 2010-04-10 00:00:00-e2010-04-11 00:00:00 --format csv --full
>
>
> class 'str'
>
>
> ['sudo', 'mam-list-usagerecords', '-s', '2010-04-10', '00:00:00-e2010-04-11', '00:00:00', '--format', 'csv', '--full']
>
>
>
(Command output redacted.)
When the kwarg `shell` is set to `False` which is the default, the command may have to be a collection which is what [shlex.split](https://docs.python.org/3/library/shlex.html#shlex.split) does.
>
> args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.
>
>
>
[Popen constructor](https://docs.python.org/3/library/subprocess.html#popen-constructor)
This issue used to confuse me to no end until I found this in the docs.
|
34,999,726
|
Imagine I have an initializer with optional parameter
```
def __init__(self, seed = ...):
```
Now if parameter is not specified I want to provide a default value. But the seed is hard to calculate, so I have a class method that suggests the seed based on some class variables
```
MyClass.seedFrom(...)
```
Now how can I call it from that place? If I use `self`:
```
def __init__(self, seed = self.__class__.seedFrom(255)):
```
I definitely don't know what is self at that point. If I use the class name directly (which I hate to do):
```
def __init__(self, seed = MyClass.seedFrom(255)):
```
it complains that
>
> name 'MyClass' is not defined
>
>
>
I'm also interested to learn the pythonic way of doing this. And I hope that pythonic way is not hardcoding stuff and making it nil by default and checking it later…
|
2016/01/25
|
[
"https://Stackoverflow.com/questions/34999726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982238/"
] |
In case you only need to call `seedFrom` once, you can do so when `__init__` is defined.
```
class MyClass:
# Defining seedFrom as a function outside
# the class is also an option. Defining it
# as a class method is not, since you still
# have the problem of not having a class to
# pass as the first argument when it is time
# to declare __init__
@staticmethod
def seedFrom():
...
def __init__(self, seed=seedFrom()):
...
```
|
If you must do this in the **init** and want the seed method to be on the class, then you can make it a class method, eg as follows:
```
class SomeClass(object):
defaultSeed = 255
@classmethod
def seedFrom(cls, seed):
pass # some seed
def __init__(self, seed=None):
self.seedFrom(seed if seed is not None else self.defaultSeed)
# etc
```
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
This uses [dateutil](http://labix.org/python-dateutil) to parse the date (e.g. '11/11/2010 - 09:00am'), and [parsedatetime](http://code.google.com/p/parsedatetime/) to parse the relative time (e.g. '4 hours later'):
```
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import time
import datetime
import re
import pprint
pdt_parser = pdt.Calendar(pdc.Constants())
record_time_pat=re.compile(r'^(.+)\s+:')
sex_pat=re.compile(r'\b(he|she)\b',re.IGNORECASE)
death_time_pat=re.compile(r'died\s+(.+hours later).*$',re.IGNORECASE)
symptom_pat=re.compile(r'[,-]')
def parse_record(astr):
match=record_time_pat.match(astr)
if match:
record_time=dparser.parse(match.group(1))
astr,_=record_time_pat.subn('',astr,1)
else: sys.exit('Can not find record time')
match=sex_pat.search(astr)
if match:
sex=match.group(1)
sex='Female' if sex.lower().startswith('s') else 'Male'
astr,_=sex_pat.subn('',astr,1)
else: sys.exit('Can not find sex')
match=death_time_pat.search(astr)
if match:
death_time,date_type=pdt_parser.parse(match.group(1),record_time)
if date_type==2:
death_time=datetime.datetime.fromtimestamp(
time.mktime(death_time))
astr,_=death_time_pat.subn('',astr,1)
is_dead=True
else:
death_time=None
is_dead=False
astr=astr.replace('and','')
symptoms=[s.strip() for s in symptom_pat.split(astr)]
return {'Record Time': record_time,
'Sex': sex,
'Death Time':death_time,
'Symptoms': symptoms,
'Death':is_dead}
if __name__=='__main__':
tests=[('11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later',
{'Sex':'Male',
'Symptoms':['got nausea', 'vomiting'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 13, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)}),
('11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room',
{'Sex':'Female',
'Symptoms':['got heart burn', 'vomiting of blood'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 10, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)})
]
for record,answer in tests:
result=parse_record(record)
pprint.pprint(result)
assert result==answer
print
```
yields:
```
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 13, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Male',
'Symptoms': ['got nausea', 'vomiting']}
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 10, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Female',
'Symptoms': ['got heart burn', 'vomiting of blood']}
```
Note: Be careful parsing dates. Does '8/9/2010' mean August 9th, or September 8th? Do all the record keepers use the same convention? If you choose to use dateutil (and I really think that's the best option if the date string is not rigidly structured) be sure to read the section on "Format precedence" in the [dateutil documentation](http://labix.org/python-dateutil) so you can (hopefully) resolve '8/9/2010' properly.
If you can't guarantee that all the record keepers use the same convention for specifying dates, then the results of this script would have be checked manually. That might be wise in any case.
|
Here are some possible way you can solve this -
1. **Using Regular Expressions** - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)
2. **String Manipulation** - This approach is relatively simpler. Again one needs a good understanding of the format in which the data is. This is what I have done below.
3. **Machine Learning** - You could define all you rules & train a model on these rules. After this the model tries to extract data using the rules you provided. This is a lot more generic approach than the first two. Also the toughest to implement.
See if this work for you. Might need some adjustments.
```
new_file = open('parsed_file', 'w')
for rec in open("your_csv_file"):
tmp = rec.split(' : ')
date = tmp[0]
reason = tmp[1]
if reason[:2] == 'He':
sex = 'Male'
symptoms = reason.split(' and ')[0].split('He got ')[1]
else:
sex = 'Female'
symptoms = reason.split(' and ')[0].split('She got ')[1]
symptoms = [i.strip() for i in symptoms.split(',')]
symptoms = '\n'.join(symptoms)
if 'died' in rec:
died = 'True'
else:
died = 'False'
new_file.write("Sex: %s\nSymptoms: %s\nDeath: %s\nDeath Time: %s\n\n" % (sex, symptoms, died, date))
```
Ech record is newline separated `\n` & since you did not mention one patient record is 2 newlines separated `\n\n` from the other.
**LATER:** @Nurse what did you end up doing? Just curious.
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
Here are some possible way you can solve this -
1. **Using Regular Expressions** - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)
2. **String Manipulation** - This approach is relatively simpler. Again one needs a good understanding of the format in which the data is. This is what I have done below.
3. **Machine Learning** - You could define all you rules & train a model on these rules. After this the model tries to extract data using the rules you provided. This is a lot more generic approach than the first two. Also the toughest to implement.
See if this work for you. Might need some adjustments.
```
new_file = open('parsed_file', 'w')
for rec in open("your_csv_file"):
tmp = rec.split(' : ')
date = tmp[0]
reason = tmp[1]
if reason[:2] == 'He':
sex = 'Male'
symptoms = reason.split(' and ')[0].split('He got ')[1]
else:
sex = 'Female'
symptoms = reason.split(' and ')[0].split('She got ')[1]
symptoms = [i.strip() for i in symptoms.split(',')]
symptoms = '\n'.join(symptoms)
if 'died' in rec:
died = 'True'
else:
died = 'False'
new_file.write("Sex: %s\nSymptoms: %s\nDeath: %s\nDeath Time: %s\n\n" % (sex, symptoms, died, date))
```
Ech record is newline separated `\n` & since you did not mention one patient record is 2 newlines separated `\n\n` from the other.
**LATER:** @Nurse what did you end up doing? Just curious.
|
Maybe this can help you too , it's not tested
```
import collections
import datetime
import re
retrieved_data = []
Data = collections.namedtuple('Patient', 'Sex, Symptoms, Death, Death_Time')
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
with open('data.txt') as f:
for line in iter(f.readline, ""):
date, text = line.split(" : ")
if 'died' in text:
dict_data['Death'] = True
dict_data['Death_Time'] = datetime.datetime.strptime(date,
'%d/%m/%Y - %I:%M%p')
hours = re.findall('[\d]+', datetime.text)
if hours:
dict_data['Death_Time'] += datetime.timedelta(hours=int(hours[0]))
if 'she' in text:
dict_data['Sex'] = 'Female'
else:
dict_data['Sex'] = 'Male'
symptoms = text[text.index('got'):text.index('and')].split(',')
dict_data['Symptoms'] = '\n'.join(symptoms)
retrieved_data.append(Data(**dict_data))
# EDIT : Reset the data dictionary.
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
```
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
Here are some possible way you can solve this -
1. **Using Regular Expressions** - Define them according to the patterns in your text. Match the expressions, extract pattern and you repeat for all records. This approach needs good understanding of the format in which the data is & of course regular expressions :)
2. **String Manipulation** - This approach is relatively simpler. Again one needs a good understanding of the format in which the data is. This is what I have done below.
3. **Machine Learning** - You could define all you rules & train a model on these rules. After this the model tries to extract data using the rules you provided. This is a lot more generic approach than the first two. Also the toughest to implement.
See if this work for you. Might need some adjustments.
```
new_file = open('parsed_file', 'w')
for rec in open("your_csv_file"):
tmp = rec.split(' : ')
date = tmp[0]
reason = tmp[1]
if reason[:2] == 'He':
sex = 'Male'
symptoms = reason.split(' and ')[0].split('He got ')[1]
else:
sex = 'Female'
symptoms = reason.split(' and ')[0].split('She got ')[1]
symptoms = [i.strip() for i in symptoms.split(',')]
symptoms = '\n'.join(symptoms)
if 'died' in rec:
died = 'True'
else:
died = 'False'
new_file.write("Sex: %s\nSymptoms: %s\nDeath: %s\nDeath Time: %s\n\n" % (sex, symptoms, died, date))
```
Ech record is newline separated `\n` & since you did not mention one patient record is 2 newlines separated `\n\n` from the other.
**LATER:** @Nurse what did you end up doing? Just curious.
|
It would be relatively easy to do most of the processing with regards to sex, date/time, etc., as those before you have shown, since you can really just define a set of keywords that would indicate these things and use those keywords.
However, the matter of processing symptoms is a bit different, as a definitive list of keywords representing symptoms would be difficult and most likely impossible.
Here's the choice you have to make: does processing this data really represent enough work to spend days writing a program to do it for me? If that's the case, then you should look into natural language processing (or machine learning, as someone before me said). I've heard pretty good things about [nltk](http://www.nltk.org/), a natural language toolkit for Python. If the format is as consistent as you say it is, the natural language processing might not be too difficult.
But, if you're not willing to expend the time and effort to tackle a truly difficult CS problem (and believe me, natural language processing is), then you ought to do most of the processing in Python by parsing dates, gender-specific pronouns, etc. and enter in the tougher parts by hand (e.g. symptoms).
Again, it depends on whether or not you think the programmatic or the manual solution will take less time in the long run.
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
This uses [dateutil](http://labix.org/python-dateutil) to parse the date (e.g. '11/11/2010 - 09:00am'), and [parsedatetime](http://code.google.com/p/parsedatetime/) to parse the relative time (e.g. '4 hours later'):
```
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import time
import datetime
import re
import pprint
pdt_parser = pdt.Calendar(pdc.Constants())
record_time_pat=re.compile(r'^(.+)\s+:')
sex_pat=re.compile(r'\b(he|she)\b',re.IGNORECASE)
death_time_pat=re.compile(r'died\s+(.+hours later).*$',re.IGNORECASE)
symptom_pat=re.compile(r'[,-]')
def parse_record(astr):
match=record_time_pat.match(astr)
if match:
record_time=dparser.parse(match.group(1))
astr,_=record_time_pat.subn('',astr,1)
else: sys.exit('Can not find record time')
match=sex_pat.search(astr)
if match:
sex=match.group(1)
sex='Female' if sex.lower().startswith('s') else 'Male'
astr,_=sex_pat.subn('',astr,1)
else: sys.exit('Can not find sex')
match=death_time_pat.search(astr)
if match:
death_time,date_type=pdt_parser.parse(match.group(1),record_time)
if date_type==2:
death_time=datetime.datetime.fromtimestamp(
time.mktime(death_time))
astr,_=death_time_pat.subn('',astr,1)
is_dead=True
else:
death_time=None
is_dead=False
astr=astr.replace('and','')
symptoms=[s.strip() for s in symptom_pat.split(astr)]
return {'Record Time': record_time,
'Sex': sex,
'Death Time':death_time,
'Symptoms': symptoms,
'Death':is_dead}
if __name__=='__main__':
tests=[('11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later',
{'Sex':'Male',
'Symptoms':['got nausea', 'vomiting'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 13, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)}),
('11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room',
{'Sex':'Female',
'Symptoms':['got heart burn', 'vomiting of blood'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 10, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)})
]
for record,answer in tests:
result=parse_record(record)
pprint.pprint(result)
assert result==answer
print
```
yields:
```
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 13, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Male',
'Symptoms': ['got nausea', 'vomiting']}
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 10, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Female',
'Symptoms': ['got heart burn', 'vomiting of blood']}
```
Note: Be careful parsing dates. Does '8/9/2010' mean August 9th, or September 8th? Do all the record keepers use the same convention? If you choose to use dateutil (and I really think that's the best option if the date string is not rigidly structured) be sure to read the section on "Format precedence" in the [dateutil documentation](http://labix.org/python-dateutil) so you can (hopefully) resolve '8/9/2010' properly.
If you can't guarantee that all the record keepers use the same convention for specifying dates, then the results of this script would have be checked manually. That might be wise in any case.
|
Maybe this can help you too , it's not tested
```
import collections
import datetime
import re
retrieved_data = []
Data = collections.namedtuple('Patient', 'Sex, Symptoms, Death, Death_Time')
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
with open('data.txt') as f:
for line in iter(f.readline, ""):
date, text = line.split(" : ")
if 'died' in text:
dict_data['Death'] = True
dict_data['Death_Time'] = datetime.datetime.strptime(date,
'%d/%m/%Y - %I:%M%p')
hours = re.findall('[\d]+', datetime.text)
if hours:
dict_data['Death_Time'] += datetime.timedelta(hours=int(hours[0]))
if 'she' in text:
dict_data['Sex'] = 'Female'
else:
dict_data['Sex'] = 'Male'
symptoms = text[text.index('got'):text.index('and')].split(',')
dict_data['Symptoms'] = '\n'.join(symptoms)
retrieved_data.append(Data(**dict_data))
# EDIT : Reset the data dictionary.
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
```
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
This uses [dateutil](http://labix.org/python-dateutil) to parse the date (e.g. '11/11/2010 - 09:00am'), and [parsedatetime](http://code.google.com/p/parsedatetime/) to parse the relative time (e.g. '4 hours later'):
```
import dateutil.parser as dparser
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import time
import datetime
import re
import pprint
pdt_parser = pdt.Calendar(pdc.Constants())
record_time_pat=re.compile(r'^(.+)\s+:')
sex_pat=re.compile(r'\b(he|she)\b',re.IGNORECASE)
death_time_pat=re.compile(r'died\s+(.+hours later).*$',re.IGNORECASE)
symptom_pat=re.compile(r'[,-]')
def parse_record(astr):
match=record_time_pat.match(astr)
if match:
record_time=dparser.parse(match.group(1))
astr,_=record_time_pat.subn('',astr,1)
else: sys.exit('Can not find record time')
match=sex_pat.search(astr)
if match:
sex=match.group(1)
sex='Female' if sex.lower().startswith('s') else 'Male'
astr,_=sex_pat.subn('',astr,1)
else: sys.exit('Can not find sex')
match=death_time_pat.search(astr)
if match:
death_time,date_type=pdt_parser.parse(match.group(1),record_time)
if date_type==2:
death_time=datetime.datetime.fromtimestamp(
time.mktime(death_time))
astr,_=death_time_pat.subn('',astr,1)
is_dead=True
else:
death_time=None
is_dead=False
astr=astr.replace('and','')
symptoms=[s.strip() for s in symptom_pat.split(astr)]
return {'Record Time': record_time,
'Sex': sex,
'Death Time':death_time,
'Symptoms': symptoms,
'Death':is_dead}
if __name__=='__main__':
tests=[('11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later',
{'Sex':'Male',
'Symptoms':['got nausea', 'vomiting'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 13, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)}),
('11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room',
{'Sex':'Female',
'Symptoms':['got heart burn', 'vomiting of blood'],
'Death':True,
'Death Time':datetime.datetime(2010, 11, 11, 10, 0),
'Record Time':datetime.datetime(2010, 11, 11, 9, 0)})
]
for record,answer in tests:
result=parse_record(record)
pprint.pprint(result)
assert result==answer
print
```
yields:
```
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 13, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Male',
'Symptoms': ['got nausea', 'vomiting']}
{'Death': True,
'Death Time': datetime.datetime(2010, 11, 11, 10, 0),
'Record Time': datetime.datetime(2010, 11, 11, 9, 0),
'Sex': 'Female',
'Symptoms': ['got heart burn', 'vomiting of blood']}
```
Note: Be careful parsing dates. Does '8/9/2010' mean August 9th, or September 8th? Do all the record keepers use the same convention? If you choose to use dateutil (and I really think that's the best option if the date string is not rigidly structured) be sure to read the section on "Format precedence" in the [dateutil documentation](http://labix.org/python-dateutil) so you can (hopefully) resolve '8/9/2010' properly.
If you can't guarantee that all the record keepers use the same convention for specifying dates, then the results of this script would have be checked manually. That might be wise in any case.
|
It would be relatively easy to do most of the processing with regards to sex, date/time, etc., as those before you have shown, since you can really just define a set of keywords that would indicate these things and use those keywords.
However, the matter of processing symptoms is a bit different, as a definitive list of keywords representing symptoms would be difficult and most likely impossible.
Here's the choice you have to make: does processing this data really represent enough work to spend days writing a program to do it for me? If that's the case, then you should look into natural language processing (or machine learning, as someone before me said). I've heard pretty good things about [nltk](http://www.nltk.org/), a natural language toolkit for Python. If the format is as consistent as you say it is, the natural language processing might not be too difficult.
But, if you're not willing to expend the time and effort to tackle a truly difficult CS problem (and believe me, natural language processing is), then you ought to do most of the processing in Python by parsing dates, gender-specific pronouns, etc. and enter in the tougher parts by hand (e.g. symptoms).
Again, it depends on whether or not you think the programmatic or the manual solution will take less time in the long run.
|
4,011,526
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
```
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
```
I should get the following data
```
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
```
Another example
```
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
```
And I get
```
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
```
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
```
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
```
|
2010/10/25
|
[
"https://Stackoverflow.com/questions/4011526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/485991/"
] |
Maybe this can help you too , it's not tested
```
import collections
import datetime
import re
retrieved_data = []
Data = collections.namedtuple('Patient', 'Sex, Symptoms, Death, Death_Time')
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
with open('data.txt') as f:
for line in iter(f.readline, ""):
date, text = line.split(" : ")
if 'died' in text:
dict_data['Death'] = True
dict_data['Death_Time'] = datetime.datetime.strptime(date,
'%d/%m/%Y - %I:%M%p')
hours = re.findall('[\d]+', datetime.text)
if hours:
dict_data['Death_Time'] += datetime.timedelta(hours=int(hours[0]))
if 'she' in text:
dict_data['Sex'] = 'Female'
else:
dict_data['Sex'] = 'Male'
symptoms = text[text.index('got'):text.index('and')].split(',')
dict_data['Symptoms'] = '\n'.join(symptoms)
retrieved_data.append(Data(**dict_data))
# EDIT : Reset the data dictionary.
dict_data = {'Death':'',
'Death_Time':'',
'Sex' :'',
'Symptoms':''}
```
|
It would be relatively easy to do most of the processing with regards to sex, date/time, etc., as those before you have shown, since you can really just define a set of keywords that would indicate these things and use those keywords.
However, the matter of processing symptoms is a bit different, as a definitive list of keywords representing symptoms would be difficult and most likely impossible.
Here's the choice you have to make: does processing this data really represent enough work to spend days writing a program to do it for me? If that's the case, then you should look into natural language processing (or machine learning, as someone before me said). I've heard pretty good things about [nltk](http://www.nltk.org/), a natural language toolkit for Python. If the format is as consistent as you say it is, the natural language processing might not be too difficult.
But, if you're not willing to expend the time and effort to tackle a truly difficult CS problem (and believe me, natural language processing is), then you ought to do most of the processing in Python by parsing dates, gender-specific pronouns, etc. and enter in the tougher parts by hand (e.g. symptoms).
Again, it depends on whether or not you think the programmatic or the manual solution will take less time in the long run.
|
49,100,167
|
So I'm optimizing a game playing bot and have run out of optimizations in pure python. Currently, most of the time is spent translating one game state into the next game state for the alpha-beta search. The current thinking is that I could speed this up by writing the state-transition code in C. My problem comes from trying to convert the python State into a struct that C can operate on and back again.
Currently, states are uniquely represented by a byte string:
```
import itertools
import struct
BINCODE = struct.Struct('BBBBBBBBBBBBBBb')
class State:
__slots__ = '_bstring'
TOP = 1
BOTTOM = 0
def __init__(self, seeds=4, *, top=None, bottom=None, turn=0):
top = top if top else [seeds] * 6 + [0]
bottom = bottom if bottom else [seeds] * 6 + [0]
self._bstring = BINCODE.pack(*itertools.chain(bottom, top), turn)
@property
def top():
...
```
The idea was that the state.\_bstring, which is convieniently already packed as binary data could be turned nicely into a c struct similar to this:
```
struct State
{
unsigned int bottom[7];
unsigned int top[7];
int turn;
}
```
which my C code could operate on, generate the resulting C State as new binary data and be slotted directly into a new python `State` object.
However I can't seem to find any information about how to go about this. Almost all the information I can find is about packing and unpacking C data from a file.
I've considered using the `PyObject_GetBuffer` on the bytes object, but the game logic is pretty complex and I'd prefer to deal with the data as a struct rather than an array. Moreover I'd like to reduce the amount of copying to a minimum.
The other option I looked into was using a `PyCapsule` object defined in C as the new State for python, but I would lose all of the State classes python specific functionality. I'd really rather keep changes to the python code to an absolute minimum, as many of the previous python optimizations are dependent on the data format.
Cython doesn't seem to have a way to coerce binary data into a C struct pointer. And re-writing `State` to be numba compatible would lose crucial functionality like unique hashing etc.
It seems like there should be a fairly straight forward way to do this, but I can't seem to find it. Any and all help would be appreciated.
|
2018/03/04
|
[
"https://Stackoverflow.com/questions/49100167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/409106/"
] |
This is not the expected behaviour. Components that do not change should not re-execute the mounted hook.
I would search for the problem someplace in the top of the vue component hierarchy, because it sounds like some other piece of code might force the re-rendering of the hierarchy.
|
When router's path changes, components will mount again,if you want to mount component only one time, you can try the Vue's build-in component **keep-alive**, it will only trigger its activated hook and deactivated hook.And you can do something in these two hooks.
**The html:**
```
<div id="app">
<router-link to="/link-one">link-one</router-link>
<router-link to="/link-two">link-two</router-link>
<keep-alive>
<router-view>
</router-view>
</keep-alive>
</div>
```
---
**The javascript:**
```
Vue.use(VueRouter);
function createLink(path) {
let routePath = '/' + path;
return {
path: routePath,
component: {
name: path,
template: '<span>{{path}} mountedTimes:{{mountedTimes}}, activatedTimes: {{activatedTimes}}</span>',
data() {
return {
mountedTimes: 0,
activatedTimes: 0,
path: routePath
}
},
mounted() {
console.log('mounted')
this.mountedTimes++;
},
activated() {
this.activatedTimes++;
}
}
}
}
const routes = [createLink('link-one'), createLink('link-two')];
const router = new VueRouter({
routes
})
const app = new Vue({
el: "#app",
router
})
```
---
[CodePen](https://codepen.io/wangyi7099/pen/OvVaQr)
|
74,009,340
|
My question is similar to this([Python sum on keys for List of Dictionaries](https://stackoverflow.com/questions/8584504/python-sum-on-keys-for-list-of-dictionaries)), but need to sum up the values based on two or more key-value elements.
I have a list of dictionaries as following:
```
list_to_sum=
[{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'A', 'City': 'W','amt':300},
{'Name': 'C', 'City': 'X','amt':400},
{'Name': 'C', 'City': 'X','amt':500},
{'Name': 'A', 'City': 'W','amt':600}]
```
So based on a combination of Name and City key values, amt should be summed. Please let me know how to solve this.
```
Output: [{'Name': 'A', 'City': 'W','amt':900},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'C', 'City': 'X','amt':900}]
```
|
2022/10/10
|
[
"https://Stackoverflow.com/questions/74009340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20188249/"
] |
You could create a [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter).Then you can simply add the values as the appear using the tuple as `(Name, City)` as the key:
```
from collections import Counter
list_to_sum=[
{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'A', 'City': 'W','amt':300},
{'Name': 'C', 'City': 'X','amt':400},
{'Name': 'C', 'City': 'X','amt':500},
{'Name': 'A', 'City': 'W','amt':600}
]
totals = Counter()
for d in list_to_sum:
totals[(d['Name'],d['City'])] += d['amt']
print(totals[('A','W')]) # 1000
print(totals[('B','A')]) # 200
print(totals[('C','X')]) # 900
```
This will produce a dictionary-like object `Counter`:
```
Counter({('A', 'W'): 1000, ('B', 'A'): 200, ('C', 'X'): 900})
```
With this you can convert the dict back to a list of dicts like:
```
sums_list = [{'Name':Name, 'City':City, 'amt':amt} for (Name, City), amt in totals.items()]
```
giving `sums_list`:
```
[{'Name': 'A', 'City': 'W', 'amt': 1000},
{'Name': 'B', 'City': 'A', 'amt': 200},
{'Name': 'C', 'City': 'X', 'amt': 900}]
```
|
```
list_to_sum = [{'Name': 'A', 'City': 'W', 'amt': 100},
{'Name': 'B', 'City': 'A', 'amt': 200},
{'Name': 'A', 'City': 'W', 'amt': 300},
{'Name': 'C', 'City': 'X', 'amt': 400},
{'Name': 'C', 'City': 'X', 'amt': 500},
{'Name': 'A', 'City': 'W', 'amt': 600}]
sum_store = {}
for entry in list_to_sum:
key = (entry['Name'], entry['City'])
if key in sum_store:
sum_store[key] += entry['amt']
else:
sum_store[key] = entry['amt']
print(sum_store)
```
output:
```
{('A', 'W'): 1000, ('B', 'A'): 200, ('C', 'X'): 900}
```
|
74,009,340
|
My question is similar to this([Python sum on keys for List of Dictionaries](https://stackoverflow.com/questions/8584504/python-sum-on-keys-for-list-of-dictionaries)), but need to sum up the values based on two or more key-value elements.
I have a list of dictionaries as following:
```
list_to_sum=
[{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'A', 'City': 'W','amt':300},
{'Name': 'C', 'City': 'X','amt':400},
{'Name': 'C', 'City': 'X','amt':500},
{'Name': 'A', 'City': 'W','amt':600}]
```
So based on a combination of Name and City key values, amt should be summed. Please let me know how to solve this.
```
Output: [{'Name': 'A', 'City': 'W','amt':900},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'C', 'City': 'X','amt':900}]
```
|
2022/10/10
|
[
"https://Stackoverflow.com/questions/74009340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20188249/"
] |
You could create a [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter).Then you can simply add the values as the appear using the tuple as `(Name, City)` as the key:
```
from collections import Counter
list_to_sum=[
{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'A', 'City': 'W','amt':300},
{'Name': 'C', 'City': 'X','amt':400},
{'Name': 'C', 'City': 'X','amt':500},
{'Name': 'A', 'City': 'W','amt':600}
]
totals = Counter()
for d in list_to_sum:
totals[(d['Name'],d['City'])] += d['amt']
print(totals[('A','W')]) # 1000
print(totals[('B','A')]) # 200
print(totals[('C','X')]) # 900
```
This will produce a dictionary-like object `Counter`:
```
Counter({('A', 'W'): 1000, ('B', 'A'): 200, ('C', 'X'): 900})
```
With this you can convert the dict back to a list of dicts like:
```
sums_list = [{'Name':Name, 'City':City, 'amt':amt} for (Name, City), amt in totals.items()]
```
giving `sums_list`:
```
[{'Name': 'A', 'City': 'W', 'amt': 1000},
{'Name': 'B', 'City': 'A', 'amt': 200},
{'Name': 'C', 'City': 'X', 'amt': 900}]
```
|
Besides the answers proposed by the others, it can be done in a pandas one-liner. It groups rows by name and city and calculates the sum over their amt feature.
```py
import pandas as pd
list_to_sum=[
{'Name': 'A', 'City': 'W','amt':100},
{'Name': 'B', 'City': 'A','amt':200},
{'Name': 'A', 'City': 'W','amt':300},
{'Name': 'C', 'City': 'X','amt':400},
{'Name': 'C', 'City': 'X','amt':500},
{'Name': 'A', 'City': 'W','amt':600}
]
df = pd.DataFrame(list_to_sum)
t = df.groupby(['Name','City']).amt.sum()
print(t)
Output:
Name City
A W 400
B A 200
C X 900
```
|
50,692,816
|
I am getting the following SSL issue when running pip install:
```
python -m pip install zeep
Collecting zeep
Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'SSLError(SSLError("bad handshake:
Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify
failed')],)",),)': /simple/zeep/
```
|
2018/06/05
|
[
"https://Stackoverflow.com/questions/50692816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045057/"
] |
I was able to resolve the issue by using the following:
```
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --index-url=https://pypi.org/simple/ zeep
```
|
If using windows then make sure the below three paths are added in Windows environment variable :
1. ....\Anaconda\Library\bin
2. ....\Anaconda\Scripts
3. ....\Anaconda
If not using Anaconda then in place of Anaconda the path where python is installed.
|
64,251,311
|
First post so be gentle please.
I have a bash script running on a Linux server which does a daily sftp download of an Excel file. The file is moved to a Windows share.
An additional requirement has arisen in that i'd like to add the number of rows to the filename which is also timestamped so different each day. Ideally at the end before the xlsx extension.
After doing some research it would seem I may be able to do it all in the same script if I use Python and one of the Excel modules. I'm a complete noob in Python but i have done some experimenting and have some working code using the Pandas module.
Here's what i have working in a test spreadsheet with a worksheet named mysheet and counting a column named code.
```
>>> excel_file = pd.ExcelFile('B:\PythonTest.xlsx')
>>> df = excel_file.parse('mysheet')
>>> df[['code']].count()
code 10
dtype: int64
>>> mycount = df[['code']].count()
>>> print(mycount)
code 10
dtype: int64
>>>
```
I have 2 questions please.
First how do I pass todays filename into the python script to then do the count on and how do i return this to bash. Also how do i just return the count value e.g 10 in the above example. i dont want column name or dtype passed back.
Thanks in advance.
|
2020/10/07
|
[
"https://Stackoverflow.com/questions/64251311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14409634/"
] |
Assuming we put your python into a separate script file, something like:
```py
# count_script.py
import sys
import pandas as pd
excel_file = pd.ExcelFile(sys.argv[1])
df = excel_file.parse('mysheet')
print(df[['code']].count().at(0))
```
We could then easily call that script from within the bash script that invoked it in the first place (the one that downloads the file).
```sh
TODAYS_FILE="PythonTest.xlsx"
# ...
# Download the file
# ...
# Pass the file into your python script (manipulate the file name to include
# the correct path first, if necessary).
# By printing the output in the python script, the bash subshell (invoking a
# command inside the $(...) will slurp up the output and store it in the COUNT variable.
COUNT=$(python count_script.py "${TODAYS_FILE}")
# this performs a find/replace on $TODAYS_FILE, replacing the ending ".xlsx" with an
# underscore, then the count obtained via pandas, then tacks on a ".xlsx" again at the end.
NEW_FILENAME="${TODAYS_FILE/\.xlsx/_$COUNT}.xlsx"
# Then rename it
mv "${TODAYS_FILE}" "${NEW_FILENAME}"
```
|
You can pass command-line arguments to python programs, by invoking them as such:
```
python3 script.py argument1 argument2 ... argumentn
```
They can then be accessed within the script using `sys.argv`. You must `import sys` before using it. `sys.argv[0]` is the name of the python script, and the rest are the additional command-line arguments.
Alternatively you may pass it in stdin, which can be read in Python using normal standard input functions like input(). To pass input in stdin, in bash do this:
```
echo $data_to_pass | python3 script.py
```
To give output you can write to stdout using print(). Then redirect output in bash, to say, a file:
```
echo $data_to_pass | python3 script.py > output.txt
```
To get the count value within Python, you simply need to add `.at(0)` at the end to get the first value; that is:
```
df[["code"]].count().at(0)
```
You can then `print()` it to send it to bash.
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
Use **shutil.copy2** instead of **shutil.copyfile**
```
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
```
|
well the questionis old, for new viewer of Python 3.6
use
```
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
```
instead of
```
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
```
`r` argument is passed for reading file not for copying
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
Use **shutil.copy2** instead of **shutil.copyfile**
```
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
```
|
Make sure you aren't in (locked) any of the the files you're trying to use shutil.copy in.
This should assist in solving your problem
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
First of all, make sure that your files aren't locked by Windows, some applications, like MS Office, locks the oppened files.
I got erro 13 when i was is trying to rename a long file list in a directory, but Python was trying to rename some folders that was at the same path of my files. So, if you are not using shutil library, check if it is a directory or file!
```
import os
path="abc.txt"
if os.path.isfile(path):
#do yor copy here
print("\nIt is a normal file")
```
Or
```
if os.path.isdir(path):
print("It is a directory!")
else:
#do yor copy here
print("It is a file!")
```
|
well the questionis old, for new viewer of Python 3.6
use
```
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
```
instead of
```
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
```
`r` argument is passed for reading file not for copying
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
use
shutil.copy instead of shutil.copyfile
example:
```
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
```
|
I solved this problem, you should be the complete target file name for destination
destination = pathdirectory + filename.\*
I use this code fir copy wav file with shutil :
```
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
```
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
I solved this problem, you should be the complete target file name for destination
destination = pathdirectory + filename.\*
I use this code fir copy wav file with shutil :
```
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
```
|
Visual Studio 2019
Solution : Administrator provided full Access to this folder "C:\ProgramData\Docker"
it is working.
>
> ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\\_data\edge-chain-ca.cert.pem'
> [ERROR]: Failed to run 'iotedgehubdev start -d "C:\Users\radhe.sah\source\repos\testing\AzureIotEdgeApp1\config\deployment.windows-amd64.json" -v' with error: WARNING! Using --password via the CLI is insecure. Use --password-stdin.
> ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\\_data\edge-chain-ca.cert.pem'
>
>
>
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
Read the [docs](http://docs.python.org/library/shutil.html#shutil.copyfile):
>
> `shutil.copyfile(src, dst)`
>
>
> Copy the contents (no metadata) of the file named *src* to a file
> named *dst*. *dst* must be the **complete target file name**; look at `copy()`
> for a copy that accepts a target directory path.
>
>
>
|
Use **shutil.copy2** instead of **shutil.copyfile**
```
import shutil
shutil.copy2('/src/dir/file.ext','/dst/dir/newname.ext') # file copy to another file
shutil.copy2('/src/file.ext', '/dst/dir') # file copy to diff directory
```
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
use
shutil.copy instead of shutil.copyfile
example:
```
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
```
|
Make sure you aren't in (locked) any of the the files you're trying to use shutil.copy in.
This should assist in solving your problem
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
I solved this problem, you should be the complete target file name for destination
destination = pathdirectory + filename.\*
I use this code fir copy wav file with shutil :
```
# open file with QFileDialog
browse_file = QFileDialog.getOpenFileName(None, 'Open file', 'c:', "wav files (*.wav)")
# get file name
base = os.path.basename(browse_file[0])
os.path.splitext(base)
print(os.path.splitext(base)[1])
# make destination path with file name
destination= "test/" + os.path.splitext(base)[0] + os.path.splitext(base)[1]
shutil.copyfile(browse_file[0], destination)
```
|
This works for me:
```
import os
import shutil
import random
dir = r'E:/up/2000_img'
output_dir = r'E:/train_test_split/out_dir'
files = [file for file in os.listdir(dir) if os.path.isfile(os.path.join(dir, file))]
if len(files) < 200:
# for file in files:
# shutil.copyfile(os.path.join(dir, file), dst)
pass
else:
# Amount of random files you'd like to select
random_amount = 10
for x in range(random_amount):
if len(files) == 0:
break
else:
file = random.choice(files)
shutil.copyfile(os.path.join(dir, file), os.path.join(output_dir, file))
```
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
use
shutil.copy instead of shutil.copyfile
example:
```
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
```
|
well the questionis old, for new viewer of Python 3.6
use
```
shutil.copyfile( "D:\Out\myfile.txt", "D:\In" )
```
instead of
```
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
```
`r` argument is passed for reading file not for copying
|
7,518,067
|
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:
```
>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
```
What's the problem?
|
2011/09/22
|
[
"https://Stackoverflow.com/questions/7518067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/490908/"
] |
use
shutil.copy instead of shutil.copyfile
example:
```
shutil.copy(PathOf_SourceFileName.extension,TargetFolderPath)
```
|
use
```
> from shutil import copyfile
>
> copyfile(src, dst)
```
for src and dst use:
```
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
```
|
41,857,659
|
My python code works correctly in the below example. My code combines a directory of CSV files and matches the headers. However, I want to take it a step further - how do I add a column that appends the filename of the CSV that was used?
```
import pandas as pd
import glob
globbed_files = glob.glob("*.csv") #creates a list of all csv files
data = [] # pd.concat takes a list of dataframes as an agrument
for csv in globbed_files:
frame = pd.read_csv(csv)
data.append(frame)
bigframe = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes
bigframe.to_csv("Pandas_output2.csv")
```
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41857659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067066/"
] |
This should work:
```
import os
for csv in globbed_files:
frame = pd.read_csv(csv)
frame['filename'] = os.path.basename(csv)
data.append(frame)
```
`frame['filename']` creates a new column named `filename` and `os.path.basename()` turns a path like `/a/d/c.txt` into the filename `c.txt`.
|
Mike's answer above works perfectly. In case any googlers run into the following error:
```
>>> TypeError: cannot concatenate object of type "<type 'str'>";
only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid
```
It's possibly because the separator is not correct. I was using a custom csv file so the separator was `^`. Becuase of that I needed to include the separator in the `pd.read_csv` call.
```
import os
for csv in globbed_files:
frame = pd.read_csv(csv, sep='^')
frame['filename'] = os.path.basename(csv)
data.append(frame)
```
|
41,857,659
|
My python code works correctly in the below example. My code combines a directory of CSV files and matches the headers. However, I want to take it a step further - how do I add a column that appends the filename of the CSV that was used?
```
import pandas as pd
import glob
globbed_files = glob.glob("*.csv") #creates a list of all csv files
data = [] # pd.concat takes a list of dataframes as an agrument
for csv in globbed_files:
frame = pd.read_csv(csv)
data.append(frame)
bigframe = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes
bigframe.to_csv("Pandas_output2.csv")
```
|
2017/01/25
|
[
"https://Stackoverflow.com/questions/41857659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6067066/"
] |
This should work:
```
import os
for csv in globbed_files:
frame = pd.read_csv(csv)
frame['filename'] = os.path.basename(csv)
data.append(frame)
```
`frame['filename']` creates a new column named `filename` and `os.path.basename()` turns a path like `/a/d/c.txt` into the filename `c.txt`.
|
files variable contains all list of csv files in your present directory. Such as
`['FileName1.csv',FileName2.csv']`. You also need to remove `".csv"`. You can use `.split()` function. Below is simple logic. This will work for you.
```
files = glob.glob("*.csv")
for i in files:
df=pd.read_csv(i)
df['New Column name'] = i.split(".")[0]
df.to_csv(i.split(".")[0]+".csv")
```
|
34,971,363
|
I am heavily using python threading, and my many use-cases require that I would log separate task executions under different logger names.
A typical code example would be:
```
def task(logger=logger):
global_logger.info('Task executing')
for item in [subtask(x) for x in range(100000)]:
# While debugging, one would generally prefer to see these
global_logger.debug('Task executed item {}'.format(item))
global_logger.info('Task done')
def thread_task(task_index, logger=logger):
task(logger=global_logger.getChild('main.task.{}'.format(task_index)))
def main():
pool = Pool(10)
for item in pool.map(thread_task, range(128))
pass
```
Is there any standard approach in python logging module that would allow me to set the logging level for all threads at once?
In code, what I am trying to do is:
```
# For all threads
logger.getChild('main.task.0').setLevel('INFO')
logger.getChild('main.task.1').setLevel('INFO')
logger.getChild('main.task.2').setLevel('INFO')
```
I should note that am aware that I could set the levels inside `task_thread`. My question is there to find out if this can be done easier.
|
2016/01/24
|
[
"https://Stackoverflow.com/questions/34971363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055356/"
] |
Because loggers inherit their parent's level if not explicitly set, you could just do e.g.
```
root_name = global_logger.name
logging.getLogger(root_name + '.main.task').setLevel(logging.INFO)
```
and that would mean that all child loggers inherit that level, unless a level were explicitly set for one of them.
Note that unless you want to attach different handlers to the different thread loggers, you don't get much benefit from having a logger per thread - you can always use [other methods](https://docs.python.org/2/howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output) to put the `task_index` value in the log.
|
I was having the same issue suppressing the output from the `BAC0` library. I tried changing the parent logger and that did not update the children (Python 3.9)
This answer is based on the accepted answer in this post: [How to list all existing loggers using python.logging module](https://stackoverflow.com/questions/53249304/how-to-list-all-existing-loggers-using-python-logging-module)
```py
for name in logging.root.manager.loggerDict:
if name.startswith("main.task."):
logging.getLogger(name).setLevel(logging.INFO)
```
You could probably replace the `name.startswith("main.task.")` with some regex matching for wild card notation, but this should do the trick for you.
What it does is it gets and iterates over every logger which has been configured, and checks if the name matches your search criteria. If it does, it will get the logger by that name, and set the level to `INFO`.
|
35,204,703
|
one script starts automatically when my raspberry is booted up, within this script there is motion sensor, if detected, it starts a subproces camera.py (recording a video, then converts the video and emails)
within the main script that starts u on booting up, there is another if statement, if button pressed then stop the camera.py and everything in it and do something else.
I am unable to kill process by PID because it keeps changing. The only other option is to kill camera.py by its name, but it doesn't work.
main script:
```
p1 = subprocess.Popen("sudo python /home/pi/camera.py", shell=True)
```
this is my camera.py script:
```
import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py
os.system(.... python script1.py
```
i can do:
```
os.system("sudo killall raspivid")
```
if i try
```
os.system("sudo killall camera.py")
```
it gives me a message: No process found
this only stops the recording but i also want to kill every other script within camera.py
Can anyone help please? thanks
|
2016/02/04
|
[
"https://Stackoverflow.com/questions/35204703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5794219/"
] |
Use `pkill`:
```
$ sudo pkill -f camera.py
```
|
If you make camera.py executable, put it on your $PATH and make line 1 of the script `#!/usr/bin/python`, then execute camera.py without the python command in front of it, your `"sudo killall camera.py"` command should work.
|
35,204,703
|
one script starts automatically when my raspberry is booted up, within this script there is motion sensor, if detected, it starts a subproces camera.py (recording a video, then converts the video and emails)
within the main script that starts u on booting up, there is another if statement, if button pressed then stop the camera.py and everything in it and do something else.
I am unable to kill process by PID because it keeps changing. The only other option is to kill camera.py by its name, but it doesn't work.
main script:
```
p1 = subprocess.Popen("sudo python /home/pi/camera.py", shell=True)
```
this is my camera.py script:
```
import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py
os.system(.... python script1.py
```
i can do:
```
os.system("sudo killall raspivid")
```
if i try
```
os.system("sudo killall camera.py")
```
it gives me a message: No process found
this only stops the recording but i also want to kill every other script within camera.py
Can anyone help please? thanks
|
2016/02/04
|
[
"https://Stackoverflow.com/questions/35204703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5794219/"
] |
If you make camera.py executable, put it on your $PATH and make line 1 of the script `#!/usr/bin/python`, then execute camera.py without the python command in front of it, your `"sudo killall camera.py"` command should work.
|
instead of using:
```
import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py)
os.system(.... python script1.py)
```
you should use the same Popen structure as how you spawn this process.
This gives you access to the Popen object of the calls.
```
import os
pvid = subprocess.Popen("raspivid -n -o /home/pi/viseo.h264 -t 10000")
p1 = subprocess.Popen(.... python script0.py)
p2 = subprocess.Popen(.... python script1.py)
```
Then you can get the pid of all the different scripts and kill them through that.
This should actually be done through an shutdown sequence.
You should never Force close applications if you can let it close itself.
|
35,204,703
|
one script starts automatically when my raspberry is booted up, within this script there is motion sensor, if detected, it starts a subproces camera.py (recording a video, then converts the video and emails)
within the main script that starts u on booting up, there is another if statement, if button pressed then stop the camera.py and everything in it and do something else.
I am unable to kill process by PID because it keeps changing. The only other option is to kill camera.py by its name, but it doesn't work.
main script:
```
p1 = subprocess.Popen("sudo python /home/pi/camera.py", shell=True)
```
this is my camera.py script:
```
import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py
os.system(.... python script1.py
```
i can do:
```
os.system("sudo killall raspivid")
```
if i try
```
os.system("sudo killall camera.py")
```
it gives me a message: No process found
this only stops the recording but i also want to kill every other script within camera.py
Can anyone help please? thanks
|
2016/02/04
|
[
"https://Stackoverflow.com/questions/35204703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5794219/"
] |
Use `pkill`:
```
$ sudo pkill -f camera.py
```
|
instead of using:
```
import os
os.system("raspivid -n -o /home/pi/viseo.h264 -t 10000")
os.system(.... python script0.py)
os.system(.... python script1.py)
```
you should use the same Popen structure as how you spawn this process.
This gives you access to the Popen object of the calls.
```
import os
pvid = subprocess.Popen("raspivid -n -o /home/pi/viseo.h264 -t 10000")
p1 = subprocess.Popen(.... python script0.py)
p2 = subprocess.Popen(.... python script1.py)
```
Then you can get the pid of all the different scripts and kill them through that.
This should actually be done through an shutdown sequence.
You should never Force close applications if you can let it close itself.
|
40,866,883
|
I use python 3.4 , pyQt5 and Qt designer (Winpython distribution). I like the idea of making guis by designer and importing them in python with setupUi. I'm able to show MainWindows and QDialogs. However, now I would like to set my MainWindow, always on top and with the close button only. I know this can be done by setting Windows flags. I tried to do as following:
```
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())
```
The MainWindow shows up (without error) but Flags are not applied. I suppose this is because I asked to change Windows properties after it was already created. Now, questions are : how I can do it without modify Ui\_MainWindow directly? It is possible to change flags in Qt designer ? Thanks
|
2016/11/29
|
[
"https://Stackoverflow.com/questions/40866883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491532/"
] |
Every call of `setWindowFlags` will completely override the current settings, so you need to set all the flags at once. Also, you must include the `CustomizeWindowHint` flag, otherwise all the other hints will be ignored. The following will probably work on Windows:
```
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.WindowTitleHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
```
However, it is highly unlikely this will work on all platforms. "Hint" really does mean just that. Window managers are completely free to ignore these flags and there's no guarantee they will all behave in the same way.
PS:
It is not possible to set the window flags in Qt Designer.
|
I would propose a different solution, because it keeps the existing flags. Reason to do this, is to NOT mingle with UI-specific presets (like that a dialog has not by default a "maximize" or "minimize" button).
```
self.setWindowFlags(self.windowFlags() # reuse initial flags
& ~QtCore.Qt.WindowContextHelpButtonHint # negate the flag you want to unset
)
```
|
47,689,456
|
I was trying to connect oracle database using python like below.
```
import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')
```
I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See <https://oracle.github.io/odpi/doc/installation.html#linux> for help.
I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,
`'admin/admin@10.10.10.10:1010/orcl'`.
Why coudn't it connect?
Ahh, btw I'm running all the code in azure notebooks.
|
2017/12/07
|
[
"https://Stackoverflow.com/questions/47689456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176741/"
] |
That error indicates that you are missing a 64-bit Oracle client installation or it hasn't been configured correctly. Take a look at the link mentioned in the error message. It will give instructions on how to perform the Oracle client installation and configuration.
[Update on behalf of Anthony: his latest cx\_Oracle release doesn't need Oracle Client libraries so you won't see the DPI-1047 error if you upgrade. The driver got renamed to python-oracledb but the API still supports the Python DB API 2.0 specification. See the [homepage](https://oracle.github.io/python-oracledb/).]
|
This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine instead using azure notebooks.
|
47,689,456
|
I was trying to connect oracle database using python like below.
```
import cx_Oracle
conn = cx_Oracle.connect('user/password@host:port/database')
```
I've faced an error when connecting oracle.
DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See <https://oracle.github.io/odpi/doc/installation.html#linux> for help.
I've been struggling to figure it out. I used my user name, password, host, port and database('orcl') for example,
`'admin/admin@10.10.10.10:1010/orcl'`.
Why coudn't it connect?
Ahh, btw I'm running all the code in azure notebooks.
|
2017/12/07
|
[
"https://Stackoverflow.com/questions/47689456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176741/"
] |
This seems a problem with version 6.X.This problem didnot appeared in 5.X.But for my case a little workaround worked.I installed in my physical machine and only thing that i need to do was a pc reboot or reopen the terminal as i have added in the path of environment variables.You can try to install in physical machine instead using azure notebooks.
|
Here is the full program to connect Oracle using python.
First, you need to install cx\_Oracle. to install it fire the below command.
`pip install cx_Oracle`
```js
import cx_Oracle
def get_databse_coonection():
try:
host='hostName'
port ='portnumber'
serviceName='sid of you database'
user = 'userName'
password = 'password'
dns = cx_Oracle.makedsn(host,port,service_name=serviceName)
con = cx_Oracle.connect(user, password, dns)
cursor = con.cursor()
query ="select * from table"
cursor.execute(query)
for c in cursor:
print(c)
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
finally:
if cursor:
cursor.close()
if con:
con.close()
get_databse_coonection()
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.