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
34,461,003
I'm new to programming and am learning Python with the book Learning Python the Hard Way. I'm at exercise 36, where we're asked to write our own simple game. <http://learnpythonthehardway.org/book/ex36.html> (The problem is, when I'm in the hallway (or more precisely, in 'choices') and I write 'gate' the game respond...
2015/12/25
[ "https://Stackoverflow.com/questions/34461003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5713452/" ]
> > The problem is, when I'm in the hallway (or more precisely, in > 'choices') and I write 'gate' the game responds as if I said "man" of > "oldman" etc. > > > Explanation ----------- What you were doing was being seen by Python as: ``` if ("oldman") or ("man") or ("ask" in choice): ``` Which evaluates to T...
Look carefully at the evaluation of your conditions: ``` if "oldman" or "man" or "ask" in choice: ``` This will first evaluate if `"oldman"` is `True`, which happens to be the case, and the `if` condition will evaluate to be `True`. I think what you intended is: ``` if "oldman" in choice or "man" in choice...
49,978,967
I have a nested list like this : ``` [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'D', '17816.00'], . . . . ['Asan', '20180415', 'N', '18027.00']] ``` I need to do some calculations for the 3rd element in every list...
2018/04/23
[ "https://Stackoverflow.com/questions/49978967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8077586/" ]
[`zip`](https://docs.python.org/3.4/library/functions.html#zip) makes things easy here for pair-wise comparison: ``` l = [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'C', '200.00'], ['Asan', '20180416', 'D...
Do you mean something like this? ``` l = [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'C', '200.00'], ['Asan', '20180416', 'D', '17816.00']] last_seen = l[0] new_list = [] for r in l[1:]: if r[2] == ...
49,978,967
I have a nested list like this : ``` [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'D', '17816.00'], . . . . ['Asan', '20180415', 'N', '18027.00']] ``` I need to do some calculations for the 3rd element in every list...
2018/04/23
[ "https://Stackoverflow.com/questions/49978967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8077586/" ]
Do you mean something like this? ``` l = [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'C', '200.00'], ['Asan', '20180416', 'D', '17816.00']] last_seen = l[0] new_list = [] for r in l[1:]: if r[2] == ...
Try like this ``` for i in range(len(l)): if l[i][2] <Operator> l[i + 1][2] <Condtion> exp/value: Do something here ```
49,978,967
I have a nested list like this : ``` [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'D', '17816.00'], . . . . ['Asan', '20180415', 'N', '18027.00']] ``` I need to do some calculations for the 3rd element in every list...
2018/04/23
[ "https://Stackoverflow.com/questions/49978967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8077586/" ]
[`zip`](https://docs.python.org/3.4/library/functions.html#zip) makes things easy here for pair-wise comparison: ``` l = [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'C', '200.00'], ['Asan', '20180416', 'D...
Since you need to test your condition for every element in the top list, you will need to iterate it. Since the condition can not be computed for the first element (no 'before' element) we can start at index 1 instead of 0. The 3rd element in the sublists can be referenced by it's index. We can get the sublist before...
49,978,967
I have a nested list like this : ``` [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'D', '17816.00'], . . . . ['Asan', '20180415', 'N', '18027.00']] ``` I need to do some calculations for the 3rd element in every list...
2018/04/23
[ "https://Stackoverflow.com/questions/49978967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8077586/" ]
Since you need to test your condition for every element in the top list, you will need to iterate it. Since the condition can not be computed for the first element (no 'before' element) we can start at index 1 instead of 0. The 3rd element in the sublists can be referenced by it's index. We can get the sublist before...
Try like this ``` for i in range(len(l)): if l[i][2] <Operator> l[i + 1][2] <Condtion> exp/value: Do something here ```
49,978,967
I have a nested list like this : ``` [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'D', '17816.00'], . . . . ['Asan', '20180415', 'N', '18027.00']] ``` I need to do some calculations for the 3rd element in every list...
2018/04/23
[ "https://Stackoverflow.com/questions/49978967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8077586/" ]
[`zip`](https://docs.python.org/3.4/library/functions.html#zip) makes things easy here for pair-wise comparison: ``` l = [['Asan', '20180418', 'A', '17935.00'], ['Asan', '20180417', 'B', '17948.00'], ['Asan', '20180416', 'C', '17979.00'], ['Asan', '20180416', 'C', '200.00'], ['Asan', '20180416', 'D...
Try like this ``` for i in range(len(l)): if l[i][2] <Operator> l[i + 1][2] <Condtion> exp/value: Do something here ```
9,874,042
I'm trying to complete 100 model runs on my 8-processor 64-bit Windows 7 machine. I'd like to run 7 instances of the model concurrently to decrease my total run time (approx. 9.5 min per model run). I've looked at several threads pertaining to the Multiprocessing module of Python, but am still missing something. [Usin...
2012/03/26
[ "https://Stackoverflow.com/questions/9874042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698809/" ]
I don't see any computations in the Python code. If you just need to execute several external programs in parallel it is sufficient to use `subprocess` to run the programs and `threading` module to maintain constant number of processes running, but the simplest code is using `multiprocessing.Pool`: ``` #!/usr/bin/env ...
Here is my way to maintain the minimum x number of threads in the memory. Its an combination of threading and multiprocessing modules. It may be unusual to other techniques like respected fellow members have explained above BUT may be worth considerable. For the sake of explanation, I am taking a scenario of crawling a...
34,889,737
I am a new programmer that just learned python so I made a small program just for fun: ``` year = int(input("Year Of Birth: "), 10) if year < 2016: print("You passed! You may continue!") else: break ``` I searched this up and I tried using break but I got a error saying I have to use break outside of the l...
2016/01/20
[ "https://Stackoverflow.com/questions/34889737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4584838/" ]
`Break` is used in a `loop`. For example: ``` i = 3 while True: i = i + 1 #increments i by 1 print(i) if i == 5: break print("Done!") ``` Normally, `while True` will execute indefinitely because `True` is always equal to `True`. (This is equivalent to something like `1==1`). The `break` stateme...
`Break` is used inside a loop to get out of that loop which looks something like `while`, `for` and you are trying to use it in Flow Control statements i.e `if` , `elif` and `else`
68,940,884
I have written a code in javascript that I don't know how to write in python. The use of it is rather simple. There are 2 variables: Buy and Sell. E.g There is Buy, Buy, Sell, Buy, Sell, Sell the javascript gives me a new list with Buy,Sell,Buy,Sell ``` ´´const fs = require('fs'); class Trade { price; side; } const...
2021/08/26
[ "https://Stackoverflow.com/questions/68940884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16480780/" ]
You can try: 1. `stack` all the dates into one column 2. `drop_duplicates`: effectively getting rid of equal end and start dates 3. Keep every second row and restructure the result ``` df = df.sort_values(["category", "start", "end"]) stacked = df.set_index("category").stack().droplevel(-1).rename("start") output = s...
You could do it like this: **Sample data:** ``` import pandas as pd d = {'category': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'}, 'start': {0: '2015-01-01', 1: '2016-01-01', 2: '2016-06-01', 3: '2016-01-01', 4: '2018-01-01'}, 'end': {0: '2016-01-01', 1: '2016-06-01', 2: '2016-12-01', 3: '2016-07-01', 4: '2018-08...
57,665,576
I’m new to nix and would like to be able to install openconnect with it. Darwin seems to be unsupported at this time via nix, though it can be installed with either brew or macports. I’ve tried both a basic install and allowing unsupported. I didn’t see anything on google or stackoverflow as yet that helped. Basic ...
2019/08/26
[ "https://Stackoverflow.com/questions/57665576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1241878/" ]
Please check this ``` let dataJobs = await page.evaluate(()=>{ var a = document.getElementById("task-listing-datatable").getAttribute("data-tasks"); //Search job list var ar = eval(a);//Convert string to arr var keyword = ['Image Annotation', 'What Is The Best Dialogue Category About Phones', 'Lab...
why not try and save the result of the match in a dynamic array instead of returning the value, something like a global array: ``` let array = []; let dataJobs = await page.evaluate(()=>{ var a = document.getElementById("task-listing-datatable").getAttribute("data-tasks"); //Search job list var ar = eval(a);//...
60,920,262
First I have created an environment in anaconda navigator in which i have installed packages like Keras,Tensorflow and Theano. Now I have activated my environment through anaconda navigator and have launched the Spyder Application. Now When i try to import keras it is showing error stating that: ``` Traceback (most r...
2020/03/29
[ "https://Stackoverflow.com/questions/60920262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13148984/" ]
You could use below aggregation for unique active users over day and month wise. I've assumed ct as timestamp field. ``` db.collection.aggregate( [ {"$match":{"ct":{"$gte":dateFrom,"$lt":dateTo}}}, {"$facet":{ "dau":[ {"$group":{ "_id":{ "user":"$user", "ymd":{"$dateToString":...
I made a quick test on a large database of events, and counting with a distinct is much faster than an aggregate if you have the right indexes : ``` collection.distinct('user', { ct: { $gte: dateFrom, $lt: dateTo } }).length ```
60,920,262
First I have created an environment in anaconda navigator in which i have installed packages like Keras,Tensorflow and Theano. Now I have activated my environment through anaconda navigator and have launched the Spyder Application. Now When i try to import keras it is showing error stating that: ``` Traceback (most r...
2020/03/29
[ "https://Stackoverflow.com/questions/60920262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13148984/" ]
I made a quick test on a large database of events, and counting with a distinct is much faster than an aggregate if you have the right indexes : ``` collection.distinct('user', { ct: { $gte: dateFrom, $lt: dateTo } }).length ```
you can use sum at the time of group. ``` collection.aggregate([ { $match: {'date': {$gte: dateFrom, $lt: dateTo }}}, // fetch all requests from/to { $group: { _id: '$user', total: { $sum: 1 }}}, // group all requests by user and sum the count of collection for a group { $sort: { total: -1 }} ], functio...
60,920,262
First I have created an environment in anaconda navigator in which i have installed packages like Keras,Tensorflow and Theano. Now I have activated my environment through anaconda navigator and have launched the Spyder Application. Now When i try to import keras it is showing error stating that: ``` Traceback (most r...
2020/03/29
[ "https://Stackoverflow.com/questions/60920262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13148984/" ]
You could use below aggregation for unique active users over day and month wise. I've assumed ct as timestamp field. ``` db.collection.aggregate( [ {"$match":{"ct":{"$gte":dateFrom,"$lt":dateTo}}}, {"$facet":{ "dau":[ {"$group":{ "_id":{ "user":"$user", "ymd":{"$dateToString":...
you can use sum at the time of group. ``` collection.aggregate([ { $match: {'date': {$gte: dateFrom, $lt: dateTo }}}, // fetch all requests from/to { $group: { _id: '$user', total: { $sum: 1 }}}, // group all requests by user and sum the count of collection for a group { $sort: { total: -1 }} ], functio...
51,549,234
I'm trying to spin up an EMR cluster with a Spark step using a Lambda function. Here is my lambda function (python 2.7): ``` import boto3 def lambda_handler(event, context): conn = boto3.client("emr") cluster_id = conn.run_job_flow( Name='LSR Batch Testrun', ServiceRole='EMR_DefaultR...
2018/07/27
[ "https://Stackoverflow.com/questions/51549234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175894/" ]
I could solve the problem eventually. Main problem was the broken "Applications" configuration, which has to look like the following instead: ``` Applications=[{ 'Name': 'Spark' }, { 'Name': 'Hive' }], ``` The final Steps element: ``` Steps=[{ 'Name': 'lsr-step1', ...
Not all EMR pre-built with ability to copy your jar, script from S3 so you must do that in bootstrap steps: ``` BootstrapActions=[ { 'Name': 'Install additional components', 'ScriptBootstrapAction': { 'Path': code_dir + '/scripts' + '/emr_bootstrap.sh' } } ], ``` And here ...
53,503,196
I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable ``` h=[w for w in 'text.txt' if w.endswith('os')] ``` does not give what I want when I call it. On the other hand, if I try naming the open file ``` f=open('text.txt') h=[w fo...
2018/11/27
[ "https://Stackoverflow.com/questions/53503196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10502088/" ]
Open the file first and then process it like this: ``` with open('text.txt', 'r') as file: content = file.read() h=[w for w in content.split() if w.endswith('os')] ```
``` with open('text.txt') as f: words = [word for line in f for word in line.split() if word.endswith('os')] ``` Your first attempt does not read the file, or even open it. Instead, it loops over the characters of the string `'text.txt'` and checks each of them if it ends with `'os'`. Your second attempt iterate...
53,503,196
I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable ``` h=[w for w in 'text.txt' if w.endswith('os')] ``` does not give what I want when I call it. On the other hand, if I try naming the open file ``` f=open('text.txt') h=[w fo...
2018/11/27
[ "https://Stackoverflow.com/questions/53503196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10502088/" ]
``` with open('text.txt') as f: words = [word for line in f for word in line.split() if word.endswith('os')] ``` Your first attempt does not read the file, or even open it. Instead, it loops over the characters of the string `'text.txt'` and checks each of them if it ends with `'os'`. Your second attempt iterate...
``` f=open('text.txt') h=[w for w in f if w.endswith('os')] ``` This should work properly. Reasons it may be not working for you, 1. You should `strip` the line first. There may be hidden ascii chars, like "\n". You can use `rstrip()` method for that. Something like this. `h=[w.rstrip() for w in f if w.rstrip().end...
53,503,196
I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable ``` h=[w for w in 'text.txt' if w.endswith('os')] ``` does not give what I want when I call it. On the other hand, if I try naming the open file ``` f=open('text.txt') h=[w fo...
2018/11/27
[ "https://Stackoverflow.com/questions/53503196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10502088/" ]
Open the file first and then process it like this: ``` with open('text.txt', 'r') as file: content = file.read() h=[w for w in content.split() if w.endswith('os')] ```
Splitting the seperate words into a list (assuming they are seperated by spaces) ``` f = open('text.txt').read().split(' ') ``` Then to get a list of the words ending in "os", like you had: ``` h=[w for w in f if w.endswith('os')] ```
53,503,196
I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable ``` h=[w for w in 'text.txt' if w.endswith('os')] ``` does not give what I want when I call it. On the other hand, if I try naming the open file ``` f=open('text.txt') h=[w fo...
2018/11/27
[ "https://Stackoverflow.com/questions/53503196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10502088/" ]
Open the file first and then process it like this: ``` with open('text.txt', 'r') as file: content = file.read() h=[w for w in content.split() if w.endswith('os')] ```
``` f=open('text.txt') h=[w for w in f if w.endswith('os')] ``` This should work properly. Reasons it may be not working for you, 1. You should `strip` the line first. There may be hidden ascii chars, like "\n". You can use `rstrip()` method for that. Something like this. `h=[w.rstrip() for w in f if w.rstrip().end...
53,503,196
I want to separate the exact words of a text file (*text.txt*) ending in a certain string by using 'endswith'. The fact is that my variable ``` h=[w for w in 'text.txt' if w.endswith('os')] ``` does not give what I want when I call it. On the other hand, if I try naming the open file ``` f=open('text.txt') h=[w fo...
2018/11/27
[ "https://Stackoverflow.com/questions/53503196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10502088/" ]
Splitting the seperate words into a list (assuming they are seperated by spaces) ``` f = open('text.txt').read().split(' ') ``` Then to get a list of the words ending in "os", like you had: ``` h=[w for w in f if w.endswith('os')] ```
``` f=open('text.txt') h=[w for w in f if w.endswith('os')] ``` This should work properly. Reasons it may be not working for you, 1. You should `strip` the line first. There may be hidden ascii chars, like "\n". You can use `rstrip()` method for that. Something like this. `h=[w.rstrip() for w in f if w.rstrip().end...
55,318,862
I want to try to make a little webserver where you can put location data into a database using a grid system in Javascript. I've found a setup that I really liked and maked an example in CodePen: <https://codepen.io/anon/pen/XGxEaj>. A user can click in a grid to point out the location. In the console log I see the dat...
2019/03/23
[ "https://Stackoverflow.com/questions/55318862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9606978/" ]
This can be achieved by converting your JS object into JSON: ``` var json = JSON.stringify(myJsObj); ``` And then converting your Python object to JSON: ``` import json myPythonObj = json.loads(json) ``` More information about the JSON package for Python can be found [here](https://www.w3schools.com/python/python...
You should use the python [json](https://docs.python.org/3/library/json.html) module. Here is how you can perform such operation using the module. ``` import json json_data = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}' loaded_json = json.loads(json_data) ```
66,602,656
I am following the instruction (<https://github.com/huggingface/transfer-learning-conv-ai>) to install conv-ai from huggingface, but I got stuck on the docker build step: `docker build -t convai .` I am using Mac 10.15, python 3.8, increased Docker memory to 4G. I have tried the following ways to solve the issue: 1....
2021/03/12
[ "https://Stackoverflow.com/questions/66602656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11210924/" ]
It seems that pip does not install the pre-built wheel, but instead tries to build *spacy* from source. This is a fragile process and requires extra dependencies. To avoid this, you should ensure that the Python packages *pip*, *wheel* and *setuptools* are up to date before proceeding with the installation. ``` # rep...
Did you try adding numpy into the requirements.txt? It looks to me that it is missing.
47,186,849
Given an iterable consisting of a finite set of elements: > > (a, b, c, d) > > > as an example What would be a Pythonic way to generate the following (pseudo) ordered pair from the above iterable: ``` ab ac ad bc bd cd ``` A trivial way would be to use for loops, but I'm wondering if there is a pythonic way ...
2017/11/08
[ "https://Stackoverflow.com/questions/47186849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962891/" ]
Try using [combinations](https://docs.python.org/2/library/itertools.html#itertools.combinations). ``` import itertools combinations = itertools.combinations('abcd', n) ``` will give you an iterator, you can loop over it or convert it into a list with `list(combinations)` In order to only include pairs as in your e...
You can accomplish this in a list comprehension. ``` data = [1, 2, 3, 4] output = [(data[n], next) for n in range(0,len(data)) for next in data[n:]] print(repr(output)) ``` Pulling the comprehension apart, it's making a tuple of the first member of the iterable and the first object in a list composed of all other ...
47,186,849
Given an iterable consisting of a finite set of elements: > > (a, b, c, d) > > > as an example What would be a Pythonic way to generate the following (pseudo) ordered pair from the above iterable: ``` ab ac ad bc bd cd ``` A trivial way would be to use for loops, but I'm wondering if there is a pythonic way ...
2017/11/08
[ "https://Stackoverflow.com/questions/47186849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/962891/" ]
Try using [combinations](https://docs.python.org/2/library/itertools.html#itertools.combinations). ``` import itertools combinations = itertools.combinations('abcd', n) ``` will give you an iterator, you can loop over it or convert it into a list with `list(combinations)` In order to only include pairs as in your e...
Use list comprehensions - they seem to be considered pythonic. ``` stuff = ('a','b','c','d') ``` Obtain the n-digit binary numbers, in string format, where only two of the digits are *one* and n is the length of the items. ``` n = len(stuff) s = '{{:0{}b}}'.format(n) z = [s.format(x) for x in range(2**n) if s.forma...
54,551,016
I am trying to use cloud SQL / mysql instance for my APPEngine account. The app is an python django-2.1.5 appengine app. I have created an instance of MYSQL in the google cloud. I have added the following in my app.yaml file copied from the SQL instance details: ``` beta_settings: cloud_sql_instances: <INSTANCE_CO...
2019/02/06
[ "https://Stackoverflow.com/questions/54551016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3204942/" ]
App Engine doesn't have any guarantees regarding IP address of a particular instance, and may change at any time. Since it is a Serverless platform, it abstracts away the infrastructure to allow you to focus on your app. There are two options when using App Engine Flex: Unix domain socket and TCP port. Which one App ...
I've encountered this issue before and after hours of scratching my head, all I needed to do was enable "Cloud SQL Admin API" and the deployed site connected to the database. This also sets permissions on your GAE service account for cloud proxy to connect to your GAE service.
60,765,225
right now i use ``` foo() import pdb; pdb.set_trace() bar() ``` for debugging purposes. Its a tad cumbersome, is there a better way to implement a breakpoint in python? edit: i understand there are IDE's that are useful, but i want to do this programatically, furthermore all the documentation i can find is for...
2020/03/19
[ "https://Stackoverflow.com/questions/60765225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898750/" ]
Personally I prefer to use my editor for debugging. I can visually set break points and use keyboard shortcuts to step through my code and evaluate variables and expressions. Visual Studio Code, Eclipse and PyCharm are all popular choices. If you insist on using the command line, you can use the interactive debugger....
Python 3.7 added a [breakpoint() function](https://docs.python.org/3/library/functions.html#breakpoint) that, by default, performs the same job without the explicit import (to keep it lower overhead). It's [quite configurable](https://docs.python.org/3/whatsnew/3.7.html#whatsnew37-pep553) though, so you can have it do ...
50,885,291
Trying to upgrade pip in my terminal. Here's my code: ``` (env) macbook-pro83:zappatest zorgan$ pip install --upgrade pip Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping...
2018/06/16
[ "https://Stackoverflow.com/questions/50885291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6733153/" ]
a. Check your system date and time and see whether it is correct. b. If the 1st solution doesn't fix it try using a lower security method: ``` pip install --index-url=http://pypi.python.org/simple/linkchecker ``` This bypasses HTTPS and uses HTTP instead, try this workaround only if you are in a hurry. c. Try down...
You can get more details about upgrade failed by using `$ pip install --upgrade pip -vvv` there will be more details help you debug it. --- Try `pip --trusted-host pypi.python.org install --upgrade pip` Maybe useful. --- Another solution: `$ pip install certifi` then run install.
50,885,291
Trying to upgrade pip in my terminal. Here's my code: ``` (env) macbook-pro83:zappatest zorgan$ pip install --upgrade pip Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping...
2018/06/16
[ "https://Stackoverflow.com/questions/50885291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6733153/" ]
Managed to fix it (uninstall and reinstall pip) via the following command: `curl https://bootstrap.pypa.io/get-pip.py | python`
You can get more details about upgrade failed by using `$ pip install --upgrade pip -vvv` there will be more details help you debug it. --- Try `pip --trusted-host pypi.python.org install --upgrade pip` Maybe useful. --- Another solution: `$ pip install certifi` then run install.
50,885,291
Trying to upgrade pip in my terminal. Here's my code: ``` (env) macbook-pro83:zappatest zorgan$ pip install --upgrade pip Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:645) - skipping...
2018/06/16
[ "https://Stackoverflow.com/questions/50885291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6733153/" ]
Managed to fix it (uninstall and reinstall pip) via the following command: `curl https://bootstrap.pypa.io/get-pip.py | python`
a. Check your system date and time and see whether it is correct. b. If the 1st solution doesn't fix it try using a lower security method: ``` pip install --index-url=http://pypi.python.org/simple/linkchecker ``` This bypasses HTTPS and uses HTTP instead, try this workaround only if you are in a hurry. c. Try down...
1,195,494
Was wondering how you'd do the following in Windows: From a c shell script (extension csh), I'm running a Python script within an 'eval' method so that the output from the script affects the shell environment. Looks like this: ``` eval `python -c "import sys; run_my_code_here(); "` ``` Was wondering how I would do ...
2009/07/28
[ "https://Stackoverflow.com/questions/1195494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101126/" ]
If it's in `cmd.exe`, using a temporary file is the only option [that I know of]: ``` python -c "print(\"Hi\")" > temp.cmd call temp.cmd del temp.cmd ```
(Making some guesses where details are missing from your question) In CMD, when a batch script modifies the environment, the default behavior is that it modifies the environment of the CMD process that is executing it. Now, if you have a batch script that calls another batch script, there are 3 ways to do it. 1. ex...
36,510,859
I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine ``` def svm(X, Y, c): m = len(X) P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T)) q = matrix(np.ones(m) * -1) g1 = np.asarray(np.diag(np.ones(m) * -1)) g2 = np.asarray(np.diag(np.ones(m))) ...
2016/04/08
[ "https://Stackoverflow.com/questions/36510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681410/" ]
Your matrix elements have to be of the floating-point type as well. So the error is removed by using `A = A.astype('float')` to cast it.
The error - `"TypeError: 'A' must be a 'd' matrix with 1000 columns:"` has two condition namely: 1. if the type code is not equal to '`d`' 2. if the `A.size[1] != c.size[0]`. Check for these conditions.
36,510,859
I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine ``` def svm(X, Y, c): m = len(X) P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T)) q = matrix(np.ones(m) * -1) g1 = np.asarray(np.diag(np.ones(m) * -1)) g2 = np.asarray(np.diag(np.ones(m))) ...
2016/04/08
[ "https://Stackoverflow.com/questions/36510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681410/" ]
Your matrix elements have to be of the floating-point type as well. So the error is removed by using `A = A.astype('float')` to cast it.
i have try `A=A.astype(double)` to solve it, but it is invalid, since python doesn't know what double is or A has no method astype. therefore --------- via using `A = matrix(A, (1, m), 'd')` could actually solve this problem!
36,510,859
I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine ``` def svm(X, Y, c): m = len(X) P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T)) q = matrix(np.ones(m) * -1) g1 = np.asarray(np.diag(np.ones(m) * -1)) g2 = np.asarray(np.diag(np.ones(m))) ...
2016/04/08
[ "https://Stackoverflow.com/questions/36510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681410/" ]
Your matrix elements have to be of the floating-point type as well. So the error is removed by using `A = A.astype('float')` to cast it.
To convert CVXOPT matrix items to floats: ``` A = A * 1.0 ```
36,510,859
I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine ``` def svm(X, Y, c): m = len(X) P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T)) q = matrix(np.ones(m) * -1) g1 = np.asarray(np.diag(np.ones(m) * -1)) g2 = np.asarray(np.diag(np.ones(m))) ...
2016/04/08
[ "https://Stackoverflow.com/questions/36510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681410/" ]
The error - `"TypeError: 'A' must be a 'd' matrix with 1000 columns:"` has two condition namely: 1. if the type code is not equal to '`d`' 2. if the `A.size[1] != c.size[0]`. Check for these conditions.
To convert CVXOPT matrix items to floats: ``` A = A * 1.0 ```
36,510,859
I'm trying to use the CVXOPT qp solver to compute the Lagrange Multipliers for a Support Vector Machine ``` def svm(X, Y, c): m = len(X) P = matrix(np.dot(Y, Y.T) * np.dot(X, X.T)) q = matrix(np.ones(m) * -1) g1 = np.asarray(np.diag(np.ones(m) * -1)) g2 = np.asarray(np.diag(np.ones(m))) ...
2016/04/08
[ "https://Stackoverflow.com/questions/36510859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681410/" ]
i have try `A=A.astype(double)` to solve it, but it is invalid, since python doesn't know what double is or A has no method astype. therefore --------- via using `A = matrix(A, (1, m), 'd')` could actually solve this problem!
To convert CVXOPT matrix items to floats: ``` A = A * 1.0 ```
51,940,568
I'm trying to learn Python with [CS Dojo's tutorial](https://www.youtube.com/watch?v=NSbOtYzIQI0). I'm currently working on the task he gave us, which was building a "miles to kilometers converter". The task itself was very simple, but I want to build a program that does a little more than that. I want the output to be...
2018/08/21
[ "https://Stackoverflow.com/questions/51940568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10252435/" ]
The value **d** needs to be converted into a string before it can be concatenated with the rest of the return statement: ``` d = str(distance * 1.6) ```
In Python 3.6+, f-string saves your time typing ugly quotes and plus signs and improves the readability a lot. ``` return f"The distance {name} is {d} in kilometers." ``` You can also do formatting easily inside f-strings ``` return f"The distance {name.title()} is {d:.2f} in kilometers." ```
9,885,071
I am reading a text file which I guess is encoded in utf-8. Some lines can only be decoded as latin-1 though. I would say this is very bad practice, but nevertheless I have to cope with it. I have the following questions: First: how can I "guess" the encoding of a file? I have tried `enca`, but in my machine: ``` en...
2012/03/27
[ "https://Stackoverflow.com/questions/9885071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
1. Guess the text encoding a file - in what? Python, Perl, Java, C? Note that this sometimes produces unexpected results (e.g. [the "bush hid the facts" bug](http://en.wikipedia.org/wiki/Bush_hid_the_facts)) 2. Sometimes a file will have text encoded in different encodings. Either the file format specifies different en...
When you say "partially encoded in different encodings", are you sure it's not just UTF-8? UTF-8 mixes single-byte, 2-byte and more-byte encodings, depending on the complexity of the character, so part of it looks like ASCII / latin-1 and part of it looks like Unicode. <http://www.joelonsoftware.com/articles/Unicode.h...
70,463,263
I am not able to serialize a custom object in python 3 . Below is the explanation and code ``` packages= [] data = { "simplefield": "value1", "complexfield": packages, } ``` where packages is a list of `custom object Library`. `Library object` is a class as below (I have also sub-classed `json.JSONEncoder` b...
2021/12/23
[ "https://Stackoverflow.com/questions/70463263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281182/" ]
Inheriting `json.JSONEncoder` will not make a class serializable. You should define your encoder separately and then provide the encoder instance in the `json.dumps` call. See an example approach below ``` import json from typing import Any class Library: def __init__(self, name): print("calling Library ...
You can use the `default` parameter of `json.dump`: ``` def default(obj): if isinstance(obj, Library): return {"name": obj.name} raise TypeError(f"Can't serialize {obj!r}.") json.dumps(data, default=default) ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`. As an example, what would you expect the following source code to output? ```py a = [] i = a i = [1] print(a) ``` Here, you are reassigning `i` after you've assigned `a` to it. `a` its...
You created a variable called i, to it you assigned (in turn) a, then 1, then b, then 1, then c, then 1. Then you printed a, unaltered. If you want to change a, you need to assign to a. That is: ``` a = [1] ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`. As an example, what would you expect the following source code to output? ```py a = [] i = a i = [1] print(a) ``` Here, you are reassigning `i` after you've assigned `a` to it. `a` its...
Part of your problem is inside your for loop. You are saying i = 1, but that is not connected to any list. Your for loop should look like this: ``` for i in [a, b, c]: try: i[0] = 1 except IndexError: i.append(1) ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`. As an example, what would you expect the following source code to output? ```py a = [] i = a i = [1] print(a) ``` Here, you are reassigning `i` after you've assigned `a` to it. `a` its...
You rather have to do this way: ``` a,b,c=[],[],[] def change(p): p.append(1) for i in [a,b,c]: change(i) print(a) ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`. As an example, what would you expect the following source code to output? ```py a = [] i = a i = [1] print(a) ``` Here, you are reassigning `i` after you've assigned `a` to it. `a` its...
You are only changing the variable `i`. You are not changing the original list variables: `a, b, c`. In the For loop, the variable `i` is assigned with copy of reference of `a, b, c`. It is a different variable altogether. Changing the value of `i`, does not change the value of `a, b, c`. If you want to actually ch...
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
What you're doing here is you're re-assigning the variable `i` within the loop, but you're not actually changing `a`, `b`, or `c`. As an example, what would you expect the following source code to output? ```py a = [] i = a i = [1] print(a) ``` Here, you are reassigning `i` after you've assigned `a` to it. `a` its...
Please refer to [this answer](https://stackoverflow.com/a/22055029/5974685) for changing external list inside function. ``` In [45]: a,b,c=[],[],[] ...: def change(): ...: return [1] ...: for i in [a,b,c]: ...: i[:]=change() ...: print(a) ...: print(b) [1] [1] ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
Please refer to [this answer](https://stackoverflow.com/a/22055029/5974685) for changing external list inside function. ``` In [45]: a,b,c=[],[],[] ...: def change(): ...: return [1] ...: for i in [a,b,c]: ...: i[:]=change() ...: print(a) ...: print(b) [1] [1] ```
You created a variable called i, to it you assigned (in turn) a, then 1, then b, then 1, then c, then 1. Then you printed a, unaltered. If you want to change a, you need to assign to a. That is: ``` a = [1] ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
Please refer to [this answer](https://stackoverflow.com/a/22055029/5974685) for changing external list inside function. ``` In [45]: a,b,c=[],[],[] ...: def change(): ...: return [1] ...: for i in [a,b,c]: ...: i[:]=change() ...: print(a) ...: print(b) [1] [1] ```
Part of your problem is inside your for loop. You are saying i = 1, but that is not connected to any list. Your for loop should look like this: ``` for i in [a, b, c]: try: i[0] = 1 except IndexError: i.append(1) ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
Please refer to [this answer](https://stackoverflow.com/a/22055029/5974685) for changing external list inside function. ``` In [45]: a,b,c=[],[],[] ...: def change(): ...: return [1] ...: for i in [a,b,c]: ...: i[:]=change() ...: print(a) ...: print(b) [1] [1] ```
You rather have to do this way: ``` a,b,c=[],[],[] def change(p): p.append(1) for i in [a,b,c]: change(i) print(a) ```
57,584,229
I tried the following python code to assign a new value to a list. ``` a,b,c=[],[],[] def change(): return [1] for i in [a,b,c]: i=change() print(a) ``` The output is `[]`, but what I need is `[1]`
2019/08/21
[ "https://Stackoverflow.com/questions/57584229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4917205/" ]
Please refer to [this answer](https://stackoverflow.com/a/22055029/5974685) for changing external list inside function. ``` In [45]: a,b,c=[],[],[] ...: def change(): ...: return [1] ...: for i in [a,b,c]: ...: i[:]=change() ...: print(a) ...: print(b) [1] [1] ```
You are only changing the variable `i`. You are not changing the original list variables: `a, b, c`. In the For loop, the variable `i` is assigned with copy of reference of `a, b, c`. It is a different variable altogether. Changing the value of `i`, does not change the value of `a, b, c`. If you want to actually ch...
38,193,878
I am trying to automate my project create process and would like as part of it to create a new jupyter notebook and populate it with some cells and content that I usually have in every notebook (i.e., imports, titles, etc.) Is it possible to do this via python?
2016/07/05
[ "https://Stackoverflow.com/questions/38193878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5983171/" ]
You can do it using **nbformat**. Below an example taken from [Creating an IPython Notebook programatically](https://gist.github.com/fperez/9716279): ```py import nbformat as nbf nb = nbf.v4.new_notebook() text = """\ # My first automatic Jupyter Notebook This is an auto-generated notebook.""" code = """\ %pylab inl...
This is absolutely possible. Notebooks are just json files. This [notebook](https://gist.github.com/anonymous/1c79fa2d43f656b4463d7ce7e2d1a03b "notebook") for example is just: ``` { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Header 1" ] }, { "cell_type": "code", "...
55,411,549
**EDIT:** I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (`LineString`) and **area percent** and **area** (`Text` and `Area` in `Point`), I want to combine them to a single JSON object. As an example, the data from files are as follows: ``` data ...
2019/03/29
[ "https://Stackoverflow.com/questions/55411549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410477/" ]
Can you try the following: ``` >>> df = pd.DataFrame([[1, 2, 4], [4, 5, 6], [7, '[8', 9]]) >>> df = df.astype('str') >>> df 0 1 2 0 1 2 4 1 4 5 6 2 7 [8 9 >>> df[df.columns[[df[i].str.contains('[', regex=False).any() for i in df.columns]]] 1 0 2 1 5 2 [8 >>> ```
Use this: ``` s=df.applymap(lambda x: '[' in x).any() print(df[s[s].index]) ``` Output: ``` col2 col4 0 b [d 1 [f h 2 j l 3 n [pa ```
55,411,549
**EDIT:** I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (`LineString`) and **area percent** and **area** (`Text` and `Area` in `Point`), I want to combine them to a single JSON object. As an example, the data from files are as follows: ``` data ...
2019/03/29
[ "https://Stackoverflow.com/questions/55411549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410477/" ]
Can you try the following: ``` >>> df = pd.DataFrame([[1, 2, 4], [4, 5, 6], [7, '[8', 9]]) >>> df = df.astype('str') >>> df 0 1 2 0 1 2 4 1 4 5 6 2 7 [8 9 >>> df[df.columns[[df[i].str.contains('[', regex=False).any() for i in df.columns]]] 1 0 2 1 5 2 [8 >>> ```
**Please try this, hope this works for you** ``` df = pd.DataFrame([['a', 'b', 'c','[d'], ['e','[f','g','h'],['i','j','k','l'],['m','n','o','[p']],columns=['col1','col2','col3','col4']) cols = [] for col in df.columns: if df[col].str.contains('[',regex=False).any() == True: cols.append(col) df[cols] ``` ...
55,411,549
**EDIT:** I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (`LineString`) and **area percent** and **area** (`Text` and `Area` in `Point`), I want to combine them to a single JSON object. As an example, the data from files are as follows: ``` data ...
2019/03/29
[ "https://Stackoverflow.com/questions/55411549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410477/" ]
> > I want to load only the columns that contain a value that starts with right bracket [ > > > For this you need [`series.str.startswith()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html): ``` df.loc[:,df.apply(lambda x: x.str.startswith('[')).any()] ``` --- ```...
Use this: ``` s=df.applymap(lambda x: '[' in x).any() print(df[s[s].index]) ``` Output: ``` col2 col4 0 b [d 1 [f h 2 j l 3 n [pa ```
55,411,549
**EDIT:** I am trying to manipulate JSON files in Python. In my data some polygons have multiple related information: coordinates (`LineString`) and **area percent** and **area** (`Text` and `Area` in `Point`), I want to combine them to a single JSON object. As an example, the data from files are as follows: ``` data ...
2019/03/29
[ "https://Stackoverflow.com/questions/55411549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8410477/" ]
> > I want to load only the columns that contain a value that starts with right bracket [ > > > For this you need [`series.str.startswith()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.startswith.html): ``` df.loc[:,df.apply(lambda x: x.str.startswith('[')).any()] ``` --- ```...
**Please try this, hope this works for you** ``` df = pd.DataFrame([['a', 'b', 'c','[d'], ['e','[f','g','h'],['i','j','k','l'],['m','n','o','[p']],columns=['col1','col2','col3','col4']) cols = [] for col in df.columns: if df[col].str.contains('[',regex=False).any() == True: cols.append(col) df[cols] ``` ...
62,461,130
I am trying to update a Lex bot using the python SDK put\_bot function. I need to pass a checksum value of the function as specified [here](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lex-models.html#LexModelBuildingService.Client.put_bot). How do I get this value? So far I have tried usi...
2020/06/18
[ "https://Stackoverflow.com/questions/62461130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13765073/" ]
The issue here seems to be that in the first example you got one `div` with multiple components in it: ``` <div id="controls"> <NavControl /> <NavControl /> <NavControl /> </div> ``` The problem is that in the second example you are creating multiple `div` elements with the same id and each of them have nes...
I am unsure of the actual desired scope, so I will go over both. If we want multiple `controls` in the template, as laid out, switch `id="controls"` to `class="controls"`: ``` <template> <div id="navControlPanel"> <div class="controls" v-bind:key="control.id" v-for="control in controls"> <NavC...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
This behavior is specific to the Python interactive shell. If I put the following in a .py file: ``` print id('so') print id('so') print id('so') ``` and execute it, I receive the following output: ``` 2888960 2888960 2888960 ``` In CPython, a string literal is treated as a constant, which we can see in the byte...
In your first example a new instance of the string `'so'` is created each time, hence different id. In the second example you are binding the string to a variable and Python can then maintain a shared copy of the string.
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
In your first example a new instance of the string `'so'` is created each time, hence different id. In the second example you are binding the string to a variable and Python can then maintain a shared copy of the string.
So while Python is not guaranteed to intern strings, it will frequently reuse the same string, and `is` may mislead. It's important to know that you shouldn't check `id` or `is` for equality of strings. To demonstrate this, one way I've discovered to force a new string in Python 2.6 at least: ``` >>> so = 'so' >>> ne...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
CPython does not promise to intern *all* strings by default, but in practice, a lot of places in the Python codebase do reuse already-created string objects. A lot of Python internals use (the C-equivalent of) the [`sys.intern()` function call](https://docs.python.org/3/library/sys.html#sys.intern) to explicitly intern...
In your first example a new instance of the string `'so'` is created each time, hence different id. In the second example you are binding the string to a variable and Python can then maintain a shared copy of the string.
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
This behavior is specific to the Python interactive shell. If I put the following in a .py file: ``` print id('so') print id('so') print id('so') ``` and execute it, I receive the following output: ``` 2888960 2888960 2888960 ``` In CPython, a string literal is treated as a constant, which we can see in the byte...
So while Python is not guaranteed to intern strings, it will frequently reuse the same string, and `is` may mislead. It's important to know that you shouldn't check `id` or `is` for equality of strings. To demonstrate this, one way I've discovered to force a new string in Python 2.6 at least: ``` >>> so = 'so' >>> ne...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
CPython does not promise to intern *all* strings by default, but in practice, a lot of places in the Python codebase do reuse already-created string objects. A lot of Python internals use (the C-equivalent of) the [`sys.intern()` function call](https://docs.python.org/3/library/sys.html#sys.intern) to explicitly intern...
This behavior is specific to the Python interactive shell. If I put the following in a .py file: ``` print id('so') print id('so') print id('so') ``` and execute it, I receive the following output: ``` 2888960 2888960 2888960 ``` In CPython, a string literal is treated as a constant, which we can see in the byte...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
This behavior is specific to the Python interactive shell. If I put the following in a .py file: ``` print id('so') print id('so') print id('so') ``` and execute it, I receive the following output: ``` 2888960 2888960 2888960 ``` In CPython, a string literal is treated as a constant, which we can see in the byte...
A more simplified way to understand the behaviour is to check the following [Data Types and Variables](http://www.python-course.eu/variables.php). Section "A String Pecularity" illustrates your question using special characters as example.
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
CPython does not promise to intern *all* strings by default, but in practice, a lot of places in the Python codebase do reuse already-created string objects. A lot of Python internals use (the C-equivalent of) the [`sys.intern()` function call](https://docs.python.org/3/library/sys.html#sys.intern) to explicitly intern...
So while Python is not guaranteed to intern strings, it will frequently reuse the same string, and `is` may mislead. It's important to know that you shouldn't check `id` or `is` for equality of strings. To demonstrate this, one way I've discovered to force a new string in Python 2.6 at least: ``` >>> so = 'so' >>> ne...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
A more simplified way to understand the behaviour is to check the following [Data Types and Variables](http://www.python-course.eu/variables.php). Section "A String Pecularity" illustrates your question using special characters as example.
So while Python is not guaranteed to intern strings, it will frequently reuse the same string, and `is` may mislead. It's important to know that you shouldn't check `id` or `is` for equality of strings. To demonstrate this, one way I've discovered to force a new string in Python 2.6 at least: ``` >>> so = 'so' >>> ne...
24,245,324
Something about the `id` of objects of type `str` (in python 2.7) puzzles me. The `str` type is immutable, so I would expect that once it is created, it will always have the same `id`. I believe I don't phrase myself so well, so instead I'll post an example of input and output sequence. ``` >>> id('so') 14061415512388...
2014/06/16
[ "https://Stackoverflow.com/questions/24245324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565828/" ]
CPython does not promise to intern *all* strings by default, but in practice, a lot of places in the Python codebase do reuse already-created string objects. A lot of Python internals use (the C-equivalent of) the [`sys.intern()` function call](https://docs.python.org/3/library/sys.html#sys.intern) to explicitly intern...
A more simplified way to understand the behaviour is to check the following [Data Types and Variables](http://www.python-course.eu/variables.php). Section "A String Pecularity" illustrates your question using special characters as example.
7,927,904
How do I close a file in python after opening it this way: `line = open("file.txt", "r").readlines()[7]`
2011/10/28
[ "https://Stackoverflow.com/questions/7927904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/442852/" ]
Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection ``` with open("file.txt", "r") as f: line = f.readlines()[7] ```
There are several ways, e.g you could just use `f = open(...)` and `del f`. If your Python version supports it you can also use the `with` statement: ``` with open("file.txt", "r") as f: line = f.readlines()[7] ``` This automatically closes your file. **EDIT:** I don't get why I'm downvoted for explaining how ...
37,582,199
How I can pass the data from object oriented programming to mysql in python? Do I need to make connection in every class? Update: This is my object orinted ``` class AttentionDataPoint(DataPoint): def __init__ (self, _dataValueBytes): DataPoint._init_(self, _dataValueBytes) self.attentionValue=se...
2016/06/02
[ "https://Stackoverflow.com/questions/37582199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341585/" ]
You asked a [similar question](https://stackoverflow.com/questions/37575008/adding-sheet2-to-existing-excelfile-from-data-of-sheet1-with-pandas-python) on adding data to a second excel sheet. Perhaps you can address there any issues around the `to_excel()` part. On the category count, you can do: ``` df.Manufacturer....
As answered by [Stefan](https://stackoverflow.com/users/1494637/stefan), using `value_counts()` over the designated column would do. Since you are saving multiple DataFrames to a single workbook, I'd use `pandas.ExcelWriter`: ``` import pandas as pd writer = pd.ExcelWriter('file_name.xlsx') df.to_excel(writer) # ...
4,870,393
We have a gazillion spatial coordinates (x, y and z) representing atoms in 3d space, and I'm constructing a function that will translate these points to a new coordinate system. Shifting the coordinates to an arbitrary origin is simple, but I can't wrap my head around the next step: 3d point rotation calculations. In o...
2011/02/02
[ "https://Stackoverflow.com/questions/4870393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572043/" ]
Using quaternions to represent rotation isn't difficult from an algebraic point of view. Personally, I find it hard to reason *visually* about quaternions, but the formulas involved in using them for rotations are not overly complicated. I'll provide a basic set of reference functions here.1 (See also this lovely answe...
Note that the inversion of matrix is not that trivial at all! Firstly, all n (where n is the dimension of your space) points must be in general position (i.e. no individual point can be expressed as a linear combination of rest of the points [caveat: this may seem to be a simple requirement indeed, but in the realm of ...
4,870,393
We have a gazillion spatial coordinates (x, y and z) representing atoms in 3d space, and I'm constructing a function that will translate these points to a new coordinate system. Shifting the coordinates to an arbitrary origin is simple, but I can't wrap my head around the next step: 3d point rotation calculations. In o...
2011/02/02
[ "https://Stackoverflow.com/questions/4870393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572043/" ]
Using quaternions to represent rotation isn't difficult from an algebraic point of view. Personally, I find it hard to reason *visually* about quaternions, but the formulas involved in using them for rotations are not overly complicated. I'll provide a basic set of reference functions here.1 (See also this lovely answe...
This question and the answer given by @senderle really helped me with one of my projects. The answer is minimal and covers the core of most quaternion computations that one might need to perform. For my own project, I found it tedious to have separate functions for all the operations and import them one by one every ...
4,870,393
We have a gazillion spatial coordinates (x, y and z) representing atoms in 3d space, and I'm constructing a function that will translate these points to a new coordinate system. Shifting the coordinates to an arbitrary origin is simple, but I can't wrap my head around the next step: 3d point rotation calculations. In o...
2011/02/02
[ "https://Stackoverflow.com/questions/4870393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572043/" ]
This question and the answer given by @senderle really helped me with one of my projects. The answer is minimal and covers the core of most quaternion computations that one might need to perform. For my own project, I found it tedious to have separate functions for all the operations and import them one by one every ...
Note that the inversion of matrix is not that trivial at all! Firstly, all n (where n is the dimension of your space) points must be in general position (i.e. no individual point can be expressed as a linear combination of rest of the points [caveat: this may seem to be a simple requirement indeed, but in the realm of ...
6,931,112
I was wondering how the random number functions work. I mean is the server time used or which other methods are used to generate random numbers? Are they really random numbers or do they lean to a certain pattern? Let's say in python: ``` import random number = random.randint(1,10) ```
2011/08/03
[ "https://Stackoverflow.com/questions/6931112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366121/" ]
Try: ``` links.parent().addClass('current') .closest('li').addClass('current'); ``` [jQuery Docs](http://api.jquery.com/parent/)
Use the `.parent()` api to do it [Docs](http://api.jquery.com/parent/) **EDIT** Something like this: ``` $(this).parent().parent().addClass("current") ```
6,931,112
I was wondering how the random number functions work. I mean is the server time used or which other methods are used to generate random numbers? Are they really random numbers or do they lean to a certain pattern? Let's say in python: ``` import random number = random.randint(1,10) ```
2011/08/03
[ "https://Stackoverflow.com/questions/6931112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366121/" ]
Try: ``` links.parent().addClass('current') .closest('li').addClass('current'); ``` [jQuery Docs](http://api.jquery.com/parent/)
Seems to me like it's working. I only changed the hrefs in your links so they wouldn't be duplicates and added some CSS to show the highlighted elements [in this JSFiddle](http://jsfiddle.net/3BYwT/2/)
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
Use this to get the dimension of pdf ``` from PyPDF2 import PdfWriter, PdfReader, PdfMerger reader = PdfReader("/Users/user.name/Downloads/sample.pdf") page = reader.pages[0] print(page.cropbox.lower_left) print(page.cropbox.lower_right) print(page.cropbox.upper_left) print(page.cropbox.upper_right) ``` After this ...
Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB.
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
You are probably looking for a free solution, but if you have money to spend, [PDFlib](http://pdflib.com) is a fabulous library. It has never disappointed me.
You can convert the PDF to Postscript (pstopdf or ps2pdf) and than use text processing on the Postscript file. After that you can convert the output back to PDF. This works nicely if the PDFs you want to process are all generated by the same application and are somewhat similar. If they come from different sources it ...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
How do I know the coordinates to crop? -------------------------------------- Thanks for all answers above. Step 1. Run the following code to get (x1, y1). ```py from PyPDF2 import PdfWriter, PdfReader reader = PdfReader("test.pdf") page = reader.pages[0] print(page.cropbox.upper_right) ``` Step 2. View the pdf f...
Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB.
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
You are probably looking for a free solution, but if you have money to spend, [PDFlib](http://pdflib.com) is a fabulous library. It has never disappointed me.
Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB.
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
Use this to get the dimension of pdf ``` from PyPDF2 import PdfWriter, PdfReader, PdfMerger reader = PdfReader("/Users/user.name/Downloads/sample.pdf") page = reader.pages[0] print(page.cropbox.lower_left) print(page.cropbox.lower_right) print(page.cropbox.upper_left) print(page.cropbox.upper_right) ``` After this ...
You can convert the PDF to Postscript (pstopdf or ps2pdf) and than use text processing on the Postscript file. After that you can convert the output back to PDF. This works nicely if the PDFs you want to process are all generated by the same application and are somewhat similar. If they come from different sources it ...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
[pyPdf](https://pypi.org/project/pyPdf/) does what I expect in this area. Using the following script: ``` #!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader with open("in.pdf", "rb") as in_f: input1 = PdfFileReader(in_f) output = PdfFileWriter() numPages = input1.getNumPages() print ...
Cropping pages of a .pdf file ============================= ``` from PIL import Image def ImageCrop(): img = Image.open("page_1.jpg") left = 90 top = 580 right = 1600 bottom = 2000 img_res = img.crop((left, top, right, bottom)) with open(outfile4, 'w') as f: img_res.save(outfile4,'J...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
Acrobat Javascript API has a setPageBoxes method, but Adobe doesn't provide any Python code samples. Only C++, C# and VB.
Cropping pages of a .pdf file ============================= ``` from PIL import Image def ImageCrop(): img = Image.open("page_1.jpg") left = 90 top = 580 right = 1600 bottom = 2000 img_res = img.crop((left, top, right, bottom)) with open(outfile4, 'w') as f: img_res.save(outfile4,'J...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
[pyPdf](https://pypi.org/project/pyPdf/) does what I expect in this area. Using the following script: ``` #!/usr/bin/python # from pyPdf import PdfFileWriter, PdfFileReader with open("in.pdf", "rb") as in_f: input1 = PdfFileReader(in_f) output = PdfFileWriter() numPages = input1.getNumPages() print ...
How do I know the coordinates to crop? -------------------------------------- Thanks for all answers above. Step 1. Run the following code to get (x1, y1). ```py from PyPDF2 import PdfWriter, PdfReader reader = PdfReader("test.pdf") page = reader.pages[0] print(page.cropbox.upper_right) ``` Step 2. View the pdf f...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
Use this to get the dimension of pdf ``` from PyPDF2 import PdfWriter, PdfReader, PdfMerger reader = PdfReader("/Users/user.name/Downloads/sample.pdf") page = reader.pages[0] print(page.cropbox.lower_left) print(page.cropbox.lower_right) print(page.cropbox.upper_left) print(page.cropbox.upper_right) ``` After this ...
How do I know the coordinates to crop? -------------------------------------- Thanks for all answers above. Step 1. Run the following code to get (x1, y1). ```py from PyPDF2 import PdfWriter, PdfReader reader = PdfReader("test.pdf") page = reader.pages[0] print(page.cropbox.upper_right) ``` Step 2. View the pdf f...
457,207
I was wondering if anyone had any experience in working programmatically with .pdf files. I have a .pdf file and I need to crop every page down to a certain size. After a quick Google search I found the pyPdf library for python but my experiments with it failed. When I changed the cropBox and trimBox attributes on a p...
2009/01/19
[ "https://Stackoverflow.com/questions/457207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367099/" ]
How do I know the coordinates to crop? -------------------------------------- Thanks for all answers above. Step 1. Run the following code to get (x1, y1). ```py from PyPDF2 import PdfWriter, PdfReader reader = PdfReader("test.pdf") page = reader.pages[0] print(page.cropbox.upper_right) ``` Step 2. View the pdf f...
You are probably looking for a free solution, but if you have money to spend, [PDFlib](http://pdflib.com) is a fabulous library. It has never disappointed me.
16,128,572
I have number of molecules in smiles format and I want to get molecular name from smiles format of molecule and I want to use python for that conversion. for example : ``` CN1CCC[C@H]1c2cccnc2 - Nicotine OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2 - Thiamin ``` which python module will help me in doing such conversions?...
2013/04/21
[ "https://Stackoverflow.com/questions/16128572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
I don't know of any one module that will let you do this, I had to play at data wrangler to try to get a satisfactory answer. I tackled this using Wikipedia which is being used more and more for structured bioinformatics / chemoinformatics data, but as it turned out my program reveals that a lot of that data is incorr...
Reference: [NCI/CADD](https://cactus.nci.nih.gov/chemical/structure) from urllib.request import urlopen ``` def CIRconvert(smi): try: url ="https://cactus.nci.nih.gov/chemical/structure/" + smi+"/iupac_name" ans = urlopen(url).read().decode('utf8') return ans except: return 'N...
16,128,572
I have number of molecules in smiles format and I want to get molecular name from smiles format of molecule and I want to use python for that conversion. for example : ``` CN1CCC[C@H]1c2cccnc2 - Nicotine OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2 - Thiamin ``` which python module will help me in doing such conversions?...
2013/04/21
[ "https://Stackoverflow.com/questions/16128572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
I don't know of any one module that will let you do this, I had to play at data wrangler to try to get a satisfactory answer. I tackled this using Wikipedia which is being used more and more for structured bioinformatics / chemoinformatics data, but as it turned out my program reveals that a lot of that data is incorr...
Download the RDkit module and use something like this: ``` ms_smis = [["CN1CCC[C@H]1c2cccnc2", "Nicotine"], ["OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2", "Thiamin"]] ms = [[Chem.MolFromSmiles(x[0]), x[1]] for x in ms_smis] for m in ms: Draw.MolToFile(m[0], m[1] + ".png", size=(800, 800)) ``` Here is the documen...
16,128,572
I have number of molecules in smiles format and I want to get molecular name from smiles format of molecule and I want to use python for that conversion. for example : ``` CN1CCC[C@H]1c2cccnc2 - Nicotine OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2 - Thiamin ``` which python module will help me in doing such conversions?...
2013/04/21
[ "https://Stackoverflow.com/questions/16128572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
There is a section in the [open babel documentation](http://openbabel.org/docs/dev/Fingerprints/fingerprints.html#similarity-searching) on similarity searching you may want to look at, you could combine this with a sdl file derived from [Chembl](https://www.ebi.ac.uk/chembl/downloads). I will give this a go later as i...
Reference: [NCI/CADD](https://cactus.nci.nih.gov/chemical/structure) from urllib.request import urlopen ``` def CIRconvert(smi): try: url ="https://cactus.nci.nih.gov/chemical/structure/" + smi+"/iupac_name" ans = urlopen(url).read().decode('utf8') return ans except: return 'N...
16,128,572
I have number of molecules in smiles format and I want to get molecular name from smiles format of molecule and I want to use python for that conversion. for example : ``` CN1CCC[C@H]1c2cccnc2 - Nicotine OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2 - Thiamin ``` which python module will help me in doing such conversions?...
2013/04/21
[ "https://Stackoverflow.com/questions/16128572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/778942/" ]
There is a section in the [open babel documentation](http://openbabel.org/docs/dev/Fingerprints/fingerprints.html#similarity-searching) on similarity searching you may want to look at, you could combine this with a sdl file derived from [Chembl](https://www.ebi.ac.uk/chembl/downloads). I will give this a go later as i...
Download the RDkit module and use something like this: ``` ms_smis = [["CN1CCC[C@H]1c2cccnc2", "Nicotine"], ["OCCc1c(C)[n+](=cs1)Cc2cnc(C)nc(N)2", "Thiamin"]] ms = [[Chem.MolFromSmiles(x[0]), x[1]] for x in ms_smis] for m in ms: Draw.MolToFile(m[0], m[1] + ".png", size=(800, 800)) ``` Here is the documen...
68,236,416
I am trying to install django using pipenv but failing to do so. ``` pipenv install django Creating a virtualenv for this project... Pipfile: /home/djangoTry/Pipfile Using /usr/bin/python3.9 (3.9.5) to create virtualenv... ⠴ Creating virtual environment...RuntimeError: failed to query /usr/bin/python3.9 with code 1 e...
2021/07/03
[ "https://Stackoverflow.com/questions/68236416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16091170/" ]
The problem isn't with installing Django, is on creating your venv, I don't create on this way so I will pass the way that i create Step 1 - Install pip Step 2 - Install virtaulEnv [check here how to install both](https://gist.github.com/Geoyi/d9fab4f609e9f75941946be45000632b) after installed, `run python3 -m venv ...
Try pipenv install --python 3.9
72,664,661
I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created. When I run this code, only Account3.csv is being crea...
2022/06/17
[ "https://Stackoverflow.com/questions/72664661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19361388/" ]
you need to use a `TextInput` component to handle this kind of event. You can find the API here: <https://reactnative.dev/docs/textinput>. Bear in mind that react library is built as an API so it can take advantage of different renders. But the issue is that when using the mobile native renderer you will not have the ...
First, you add `onKeyDown={keyDownHandler}` to a React element. This will trigger your `keyDownHandler` function each time a key is pressed. Ex: ``` <div className='example-class' onKeyDown={keyDownHandler}> ``` You can set up your function like this: ``` const keyDownHandler = ( event: React.KeyboardEvent<HTML...
72,664,661
I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created. When I run this code, only Account3.csv is being crea...
2022/06/17
[ "https://Stackoverflow.com/questions/72664661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19361388/" ]
I am not sure about the View component, but for TextInput this might work! ``` <TextInput onKeyPress={handleKeyDown} placeholder="Sample Text" /> ``` and for function part: ``` const handleKeyDown = (e) => { if(e.nativeEvent.key == "Enter"){ dismissKeyboard(); } } ```
First, you add `onKeyDown={keyDownHandler}` to a React element. This will trigger your `keyDownHandler` function each time a key is pressed. Ex: ``` <div className='example-class' onKeyDown={keyDownHandler}> ``` You can set up your function like this: ``` const keyDownHandler = ( event: React.KeyboardEvent<HTML...
72,664,661
I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created. When I run this code, only Account3.csv is being crea...
2022/06/17
[ "https://Stackoverflow.com/questions/72664661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19361388/" ]
Well, it's not the most elegant way, but it does exactly as you want: ``` import { Keyboard, TextInput } from 'react-native'; <TextInput autoFocus onFocus={() => Keyboard.dismiss()} /> ``` The keyboard key event listener will get key presses now without showing the keyboard. Hope this helps.
First, you add `onKeyDown={keyDownHandler}` to a React element. This will trigger your `keyDownHandler` function each time a key is pressed. Ex: ``` <div className='example-class' onKeyDown={keyDownHandler}> ``` You can set up your function like this: ``` const keyDownHandler = ( event: React.KeyboardEvent<HTML...
72,664,661
I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created. When I run this code, only Account3.csv is being crea...
2022/06/17
[ "https://Stackoverflow.com/questions/72664661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19361388/" ]
Well, it's not the most elegant way, but it does exactly as you want: ``` import { Keyboard, TextInput } from 'react-native'; <TextInput autoFocus onFocus={() => Keyboard.dismiss()} /> ``` The keyboard key event listener will get key presses now without showing the keyboard. Hope this helps.
you need to use a `TextInput` component to handle this kind of event. You can find the API here: <https://reactnative.dev/docs/textinput>. Bear in mind that react library is built as an API so it can take advantage of different renders. But the issue is that when using the mobile native renderer you will not have the ...
72,664,661
I’m new to python and trying to get a loop working. I’m trying to iterate through a dataframe – for each unique value in the “Acct” column I want to create a csv file, with the account name. So there should be an Account1.csv, Account2.csv and Account3.csv created. When I run this code, only Account3.csv is being crea...
2022/06/17
[ "https://Stackoverflow.com/questions/72664661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19361388/" ]
Well, it's not the most elegant way, but it does exactly as you want: ``` import { Keyboard, TextInput } from 'react-native'; <TextInput autoFocus onFocus={() => Keyboard.dismiss()} /> ``` The keyboard key event listener will get key presses now without showing the keyboard. Hope this helps.
I am not sure about the View component, but for TextInput this might work! ``` <TextInput onKeyPress={handleKeyDown} placeholder="Sample Text" /> ``` and for function part: ``` const handleKeyDown = (e) => { if(e.nativeEvent.key == "Enter"){ dismissKeyboard(); } } ```
43,536,182
i am having on HDFS this huge file which is an extract of my db. e.g.: ``` 1||||||1||||||||||||||0002||01||1999-06-01 16:18:38||||2999-12-31 00:00:00||||||||||||||||||||||||||||||||||||||||||||||||||||||||2||||0||W.ISHIHARA||||1999-06-01 16:18:38||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||19155||...
2017/04/21
[ "https://Stackoverflow.com/questions/43536182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5013752/" ]
I found the databrick csv reader quite useful to do that. ``` toProcessFileDF_raw = sqlContext.read.format('com.databricks.spark.csv')\ .options(header='false', inferschema='false', ...
Logs would have been helpful. `binaryFiles` will read this as binary file from HDFS as a single record and returned in a key-value pair, where the key is the path of each file, the value is the content of each file. Note from Spark documentation: Small files are preferred, large file is also allowable, but may cause ...
60,054,247
I have a python list of list that I would like to insert into a MySQL database. The list looks like this: ``` [[column_name_1,value_1],[column_name_2, value_2],.......] ``` I want to insert this into the database table which has column names as `column_name_1, column_name_2.....` so that the database table looks li...
2020/02/04
[ "https://Stackoverflow.com/questions/60054247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12675531/" ]
You have several options. ``` working_directory=$PWD python3.8 main.py "$working_directory" ``` This will pass the value of your variable as a command line argument. In Python you will use `sys.argv[1]` to access it. ``` export working_directory=$PWD python3.8 main.py ``` This will add an environment variable usi...
You can use the `pathlib` library to avoid putting it as a parameter: ``` import pathlib working_derictory = pathlib.Path().absolute() ```
7,521,623
I am trying to parse HTML with BeautifulSoup. The content I want is like this: ``` <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> ``` i tried and got the following error: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ---------------------------------...
2011/09/22
[ "https://Stackoverflow.com/questions/7521623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648866/" ]
You're missing a close-quote after `"class`: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ``` should be ``` maxx = soup.findAll("href", {"class": "yil-biz-ttl"}) ``` also, I don't think you can search for an attribute like `href` like that, I think you need to search for a tag: ``` maxx = [link['h...
Well first of all you have a syntax error. You have your quotes wrong in `class` part. Try: `maxx = soup.findAll("href", {"class": "yil-biz-ttl"})`
7,521,623
I am trying to parse HTML with BeautifulSoup. The content I want is like this: ``` <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> ``` i tried and got the following error: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ---------------------------------...
2011/09/22
[ "https://Stackoverflow.com/questions/7521623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648866/" ]
``` soup.findAll('a', {'class': 'yil-biz-ttl'})[0]['href'] ``` To find all such links: ``` for link in soup.findAll('a', {'class': 'yil-biz-ttl'}): try: print link['href'] except KeyError: pass ```
You're missing a close-quote after `"class`: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ``` should be ``` maxx = soup.findAll("href", {"class": "yil-biz-ttl"}) ``` also, I don't think you can search for an attribute like `href` like that, I think you need to search for a tag: ``` maxx = [link['h...
7,521,623
I am trying to parse HTML with BeautifulSoup. The content I want is like this: ``` <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> ``` i tried and got the following error: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ---------------------------------...
2011/09/22
[ "https://Stackoverflow.com/questions/7521623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648866/" ]
``` soup.findAll('a', {'class': 'yil-biz-ttl'})[0]['href'] ``` To find all such links: ``` for link in soup.findAll('a', {'class': 'yil-biz-ttl'}): try: print link['href'] except KeyError: pass ```
Well first of all you have a syntax error. You have your quotes wrong in `class` part. Try: `maxx = soup.findAll("href", {"class": "yil-biz-ttl"})`
7,521,623
I am trying to parse HTML with BeautifulSoup. The content I want is like this: ``` <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> ``` i tried and got the following error: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ---------------------------------...
2011/09/22
[ "https://Stackoverflow.com/questions/7521623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648866/" ]
To find all `<a/>` elements from CSS class `"yil-biz-ttl"` that have `href` attribute with anything in it: ``` from bs4 import BeautifulSoup # $ pip install beautifulsoup4 soup = BeautifulSoup(HTML) for link in soup("a", "yil-biz-ttl", href=True): print(link['href']) ``` At the moment all other answers don't s...
Well first of all you have a syntax error. You have your quotes wrong in `class` part. Try: `maxx = soup.findAll("href", {"class": "yil-biz-ttl"})`
7,521,623
I am trying to parse HTML with BeautifulSoup. The content I want is like this: ``` <a class="yil-biz-ttl" id="yil_biz_ttl-2" href="http://some-web-url/" title="some title">Title</a> ``` i tried and got the following error: ``` maxx = soup.findAll("href", {"class: "yil-biz-ttl"}) ---------------------------------...
2011/09/22
[ "https://Stackoverflow.com/questions/7521623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648866/" ]
``` soup.findAll('a', {'class': 'yil-biz-ttl'})[0]['href'] ``` To find all such links: ``` for link in soup.findAll('a', {'class': 'yil-biz-ttl'}): try: print link['href'] except KeyError: pass ```
To find all `<a/>` elements from CSS class `"yil-biz-ttl"` that have `href` attribute with anything in it: ``` from bs4 import BeautifulSoup # $ pip install beautifulsoup4 soup = BeautifulSoup(HTML) for link in soup("a", "yil-biz-ttl", href=True): print(link['href']) ``` At the moment all other answers don't s...
4,302,201
I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them together into one long iterator. Is there a standard utility to make this possible? Here is a contrived examp...
2010/11/29
[ "https://Stackoverflow.com/questions/4302201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125921/" ]
You can use [`itertools.chain.from_iterable`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable) ``` >>> import itertools >>> x = iter([ xrange(0,5), xrange(5,10)]) >>> a = itertools.chain.from_iterable(x) >>> list(a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` If that's not available on your versio...
Here's the old-fashioned way: ``` Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import generators >>> def mychain(iterables): ... for it in iterables: ... for item in it: ... yie...
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
The `or` operator *short circuits*; the right-hand expression is not evaluated when the left-hand returns a true value. This applies to the `and` operator as well; when the left-hand side expression returns a false value, the right-hand expression is not evaluated. You could not do this with a function; all operands *...
The reason you are getting `1` after executing `>>> 1 or 2` is because `1` is `true` so the expression has been satisfied. It might make more sense if you try executing `>>> 0 or 2`. It will return `2` because the first statement is `0` or `false` so the second statement gets evaluated. In this case `2` evaluates to ...
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
The `or` operator *short circuits*; the right-hand expression is not evaluated when the left-hand returns a true value. This applies to the `and` operator as well; when the left-hand side expression returns a false value, the right-hand expression is not evaluated. You could not do this with a function; all operands *...
The closest thing to a built-in `or` function is [any](http://docs.python.org/2.7/library/functions.html#any): ``` >>> any((1, 2)) True ``` If you wanted to duplicate `or`'s functionality of returning non-boolean operands, you could use [next](http://docs.python.org/2.7/library/functions.html#next) with a filter: `...
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
The `or` operator *short circuits*; the right-hand expression is not evaluated when the left-hand returns a true value. This applies to the `and` operator as well; when the left-hand side expression returns a false value, the right-hand expression is not evaluated. You could not do this with a function; all operands *...
It's not possible: ------------------ [This can explicitly be found in the docs](http://docs.python.org/2/reference/expressions.html#boolean-operations): > > The expression x or y first evaluates x; if x is true, its value is > returned; otherwise, y is evaluated and the resulting value is > returned. > > > It...
22,385,108
On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`). However I can't seem to find the logical or (`or`). The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi...
2014/03/13
[ "https://Stackoverflow.com/questions/22385108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595865/" ]
The closest thing to a built-in `or` function is [any](http://docs.python.org/2.7/library/functions.html#any): ``` >>> any((1, 2)) True ``` If you wanted to duplicate `or`'s functionality of returning non-boolean operands, you could use [next](http://docs.python.org/2.7/library/functions.html#next) with a filter: `...
The reason you are getting `1` after executing `>>> 1 or 2` is because `1` is `true` so the expression has been satisfied. It might make more sense if you try executing `>>> 0 or 2`. It will return `2` because the first statement is `0` or `false` so the second statement gets evaluated. In this case `2` evaluates to ...