lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I have a list like so : I want it to look like sowhat 's the most efficient way to do this ? edit : what about going the other way ? -- >
[ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ] [ [ ' a ' , ' b ' , ' c ' ] , [ 'd ' , ' e ' , ' f ' ] , [ ' g ' , ' h ' , ' i ' ] ] [ [ ' a ' , ' b ' , ' c ' ] , [ 'd ' , ' e ' , ' f ' ] , [ ' g ' , ' h ' , ' i ' ] ] [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' ]
python split string every 3rd value but into a nested format
Python
I have a nested function that I 'm using as a callback in pyglet : But then I run into problems later when I need to reference the nested function again : This does n't work because of the way python treats functions : Thanks to two similar questions I understand what is going on but I 'm not sure what the workaround i...
def get_stop_function ( stop_key ) : def stop_on_key ( symbol , _ ) : if symbol == getattr ( pyglet.window.key , stop_key ) : pyglet.app.exit ( ) return stop_on_keypyglet.window.set_handler ( 'on_key_press ' , get_stop_function ( 'ENTER ' ) ) pyglet.window.remove_handler ( 'on_key_press ' , get_stop_function ( 'ENTER '...
Workaround for equality of nested functions
Python
I 'm looking for optimizations on the following problem ( I 've got some working code but I 'm fairly sure it could be quicker and is written in a bad way ) . I 've got a list of SKUs ( between 6 and 9 digit numbers ) that I 'm looking up information on on Amazon . The working code is given below : where x is a diction...
def buildDictionary2 ( stringy ) : x = stringy.xpath ( '//sellersku/text ( ) |//product/descendant : :amount [ 1 ] /text ( ) ' ) Sku_To_Price = { } for items in range ( len ( x ) ) : if x [ items ] in myList : try : if x [ items+1 ] not in myList : Sku_To_Price [ x [ items ] ] = x [ items+1 ] else : Sku_To_Price [ x [ ...
Most efficient way to produce a Python dictionary given a list
Python
If I take a simply and empty numpy array i can see it has 96 bytes of overhead , What is that 96 bytes storing ? Where in the C source for numpy or Python 3 ( cpython ) is this set up ?
> > > sys.getsizeof ( np.array ( [ ] ) ) 96
Why does a numpy array have 96 bytes of overhead ?
Python
Let 's say one file has 10 global constants that I want to import into another file.Instead of doing the following , is there any simpler way to import all the global constants without doing something like : from file_one.py import * . I do n't want it to import the entire file , just the global variables .
DEFINE1 = 1DEFINE2 = 2DEFINE3 = 3 ... DEFINE10 = 10 from file_one.py import DEFINE1 , DEFINE2 , DEFINE3 , ... ... ... ... ..
How to import large number of global variables without listing each one ? ( Python )
Python
I 'm trying to create a regex that matches a third person form of a verb created using the following rule : If the verb ends in e not preceded by i , o , s , x , z , ch , sh , add s. So I 'm looking for a regex matching a word consisting of some letters , then not i , o , s , x , z , ch , sh , and then `` es '' . I tri...
\b\w* [ ^iosxz ( sh ) ( ch ) ] es\b
Regex for a third-person verb
Python
Python ( and ipython ) has very powerful post-mortem debugging capabilities , allowing variable inspection and command execution at each scope in the traceback . The up/down debugger commands allow changing frame for the stack trace of the final exception , but what about the __cause__ of that exception , as defined by...
Python 3.7.6 ( default , Jan 8 2020 , 13:42:34 ) Type 'copyright ' , 'credits ' or 'license ' for more informationIPython 7.11.1 -- An enhanced Interactive Python . Type ' ? ' for help.In [ 1 ] : def foo ( ) : ... : bab = 42 ... : raise TypeError ... : In [ 2 ] : try : ... : foo ( ) ... : except TypeError as err : ... ...
How to debug the stack trace that causes a subsequent exception in python ?
Python
These are 3 dicts I made each with the 4 same keys but of course different values.I stored the dicts in a list.What I 'd like to do is loop through the list and display each like so : I was thinking a for loop would do the trick for student in students : and I could store each in a empty dict current = { } but after th...
lloyd = { `` name '' : `` Lloyd '' , `` homework '' : [ 90.0 , 97.0 , 75.0 , 92.0 ] , `` quizzes '' : [ 88.0 , 40.0 , 94.0 ] , `` tests '' : [ 75.0 , 90.0 ] } alice = { `` name '' : `` Alice '' , `` homework '' : [ 100.0 , 92.0 , 98.0 , 100.0 ] , `` quizzes '' : [ 82.0 , 83.0 , 91.0 ] , `` tests '' : [ 89.0 , 97.0 ] } ...
Looping through a list that contains dicts and displaying it a certain way
Python
I have a multi-index dataframe and I want to know the percentage of clients who paid a certain threshold of debt for each of the 3 criteria : City , Card and Collateral.This is a working script : And this is the result : To overcome this issue I tried the following without success : And this is the result I wish to acc...
import pandas as pdd = { 'City ' : [ 'Tokyo ' , 'Tokyo ' , 'Lisbon ' , 'Tokyo ' , 'Tokyo ' , 'Lisbon ' , 'Lisbon ' , 'Lisbon ' , 'Tokyo ' , 'Lisbon ' , 'Tokyo ' , 'Tokyo ' , 'Tokyo ' , 'Lisbon ' , 'Tokyo ' , 'Tokyo ' , 'Lisbon ' , 'Lisbon ' , 'Lisbon ' , 'Tokyo ' , 'Lisbon ' , 'Tokyo ' ] , 'Card ' : [ 'Visa ' , 'Visa '...
Count if in multiple index Dataframe
Python
I would expect both cases to raise a TypeError , but this is not the case . Why not ? The Python documentation on this subject talks about strings , tuples and dictionaries , but says nothing about lists . I 'm a bit confused about this behavior . I 've been able to duplicate it in Python 2.7 and 3.2 .
> > > 'string with no string formatting markers ' % [ 'string ' ] 'string with no string formatting markers ' > > > 'string with no string formatting markers ' % ( 'string ' , ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : not all arguments converted during string form...
Why does using a list as a string formatting parameter , even with no % s identifier , return the original string ?
Python
I have an environment of conda configurated with python 3.6 and dvc is installed there , but when I try to execute dvc run with python , dvc call the python version of main installation of conda and not find the installed libraries .
$ conda activate py36 $ python -- versionPython 3.6.6 : : Anaconda custom ( 64-bit ) $ dvc run python -- versionRunning command : python -- versionPython 3.7.0Saving information to 'Dvcfile ' .
How to execute python from conda environment by dvc run
Python
I have a Fargate ECS container that I use to run a Docker container through tasks in ECS . When the task starts , an sh script is called , runner.sh , This in turn starts a long-running Python script , my_python_script.py . I know the Python script is running fine because it does what it needs to do , but I ca n't see ...
# ! /bin/shecho `` this line will get logged to ECS ... '' python3 src/my_python_script.py # however print statements from this Python script are not logged to ECS { `` ipcMode '' : null , `` executionRoleArn '' : `` myecsTaskExecutionRolearn '' , `` containerDefinitions '' : [ { `` dnsSearchDomains '' : null , `` envi...
How to see Python print statements from running Fargate ECS task ?
Python
Folks , After building and deploying a package called myShtuff to a local pypicloud server , I am able to install it into a separate virtual env.Everything seems to work , except for the path of the executable ... If I try running the script directly , I get : However , I can run it via : Am I making a mistake when bui...
( venv ) [ ec2-user @ ip-10-0-1-118 ~ ] $ pip freezeFabric==1.10.1boto==2.38.0myShtuff==0.1ecdsa==0.13paramiko==1.15.2pycrypto==2.6.1wsgiref==0.1.2 ( venv ) [ ec2-user @ ip-10-0-1-118 ~ ] $ myShtuff-bash : myShtuff : command not found ( venv ) [ ec2-user @ ip-10-0-1-118 ~ ] $ python /home/ec2-user/venv/lib/python2.7/si...
running a python package after compiling and uploading to pypicloud server
Python
The following code : outputs : However when enabling PEP 563 – Postponed Evaluation of Annotations : The output is : How can I get the exact same object of type inspect.Signature with PEP 563 like without it ?
import inspectfrom typing import NamedTupleclass Example ( NamedTuple ) : a : strif __name__== `` __main__ '' : signature : inspect.Signature = inspect.signature ( Example ) print ( signature ) ( a : str ) from __future__ import annotationsimport inspectfrom typing import NamedTupleclass Example ( NamedTuple ) : a : st...
inspect.signature with PEP 563
Python
Say we want to import a script named user.py , which may fail.How can we make sure to only catch the possible import failure of user.py itself , and not of the imports that may be contained in user.py ?
try : import userexcept ImportError : logging.info ( 'No user script loaded . ' )
How to catch an ImportError non-recursively ?
Python
For instance , consider the case : the exception does not print the value that was out of range . My guess is that we do n't know if the __str__ function of whatever was passed in raises an exception , so we do n't touch it ?
> > > a = [ ] > > > a [ 12 ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > IndexError : list index out of range
Why do python exceptions typically not print offending values ?
Python
I 'm trying to get different college names and their rankings from a webpage . The script I 've tried with can parse the first few names and their rankings accordingly . However , there are 233 names and their rankings in that page but they can only be visible when that page is made to scroll downward . The thing is wh...
import requestsfrom bs4 import BeautifulSoupurl = 'https : //www.usnews.com/best-colleges/rankings/national-liberal-arts-colleges ' r = requests.get ( url , headers= { 'User-Agent ' : 'Mozilla/5.0 ' } ) soup = BeautifulSoup ( r.text , '' lxml '' ) for item in soup.select ( `` [ id^='school- ' ] '' ) : name = item.selec...
Script grabs fewer content out of many
Python
My DataFrame has a string in the first column , and a number in the second one : What I want to do is to manipulate this DataFrame in order to have a list object that contains a string , made out of the 5th character for each `` GEOSTRING '' value , for each different `` IDactivity '' value . So in this case , I have 3...
GEOSTRING IDactivity9 wydm2p01uk0fd2z 210 wydm86pg6r3jyrg 211 wydm2p01uk0fd2z 212 wydm80xfxm9j22v 239 wydm9w92j538xze 440 wydm8km72gbyuvf 441 wydm86pg6r3jyrg 442 wydm8mzt874p1v5 443 wydm8mzmpz5gkt8 544 wydm86pg6r3jyrg 545 wydm8w1q8bjfpcj 546 wydm8w1q8bjfpcj 5 [ '2828 ' , '9888 ' , '8888 ' ]
I need to create a python list object , or any object , out of a pandas DataFrame object grouping pieces of values from different rows
Python
Monday 27 jul 2020 , I 'm running pytube module perfectly but after one day later its code is not working any more . It 's show 's too many values to unpack ( expected 2 ) Anyone know this ? Or other modules like this to extract YouTube captions ?
from pytube import YouTubeurl = input ( `` Entry url : `` ) yt = YouTube ( url ) captions = yt.captions.get_by_language_code ( 'en ' ) all = captions.generate_srt_captions ( ) print ( all )
Too many values to unpack in pytube module problem
Python
I want to implement users in my system . I know that Django already has an authentication system , and I 've been reading the documentation . But I do n't know yet the difference between And I do n't want to know why to use one or another , but what happens under the hoods . What 's the difference ?
from django.contrib.auth.models import User class Profile ( User ) : # others fields from django.contrib.auth.models import User class Profile ( models.Model ) : user = models.OneToOneField ( User ) # others fields
Under the hoods what 's the difference between subclassing the user and creating a one to one field ?
Python
I 'm trying to make a mapping between the grade categories in the picture below . Then I would like to be able to call a function that converts a grade to the same grade in an equivalent format . Ex : I thought of making three parallel lists for the equivalence and then the function would end up using a bunch of if sta...
def convert ( num , letter , gpa ) : `` '' '' Converts a grade into an equivalent grade . The desired output will be specified by -1 and the grade format not to be involved in the conversion will be specified by None . When converting to GPA , the minimum of the gpa range will be returned . '' '' '' > > > convert ( 83 ...
How to make a triple equivalence dictionary ?
Python
I have made a like button powered by ajax and I have defined a function that it refresh the text . Now I want to change it for updating from font awesome fa-heart-o to fa-heart and viceversa . How can I do it ? see the code belowbase.htmland button like htmlThank you for your help .
< script > $ ( document ) .ready ( function ( ) { function updateText ( btn , newCount , iconClass , verb ) { verb = verb || `` '' ; $ ( btn ) .html ( newCount + ' < i class= '' ' + iconClass + ' '' > < /i > ' + verb ) btn.attr ( `` data-likes '' , newCount ) } $ ( `` .like-btn '' ) .click ( function ( e ) { e.preventD...
Toggle icon on Like with Javascript
Python
I 'm looking for a way to automatically produce an abstract , basically the first few sentances/paragraphs of a blog entry , to display in a list of articles ( which are written in markdown ) . Currently , I 'm doing something like this : to just grab the first few lines worth of text , but i 'm not totally happy with ...
def abstract ( article , paras=3 ) : return '\n'.join ( article.split ( '\n ' ) [ 0 : paras ] )
Computing article abstracts
Python
Is there any difference , subtle or not so subtle , between the effects of the following import statements ? I have found both used in example programs and sure enough , they both seem to work . It would go against the grain of Python 's `` there is only one way to do stuff '' if they were totally equivalent in functio...
from scipy import interpolate as spi import scipy.interpolate as spi
Pythonic way to import modules from packages
Python
Question motivation : In standard numerical languages of which I am aware ( e.g . Matlab , Python numpy , etc . ) , if , for example , you take the exponential of a modestly large number , the output is infinity as the result of numerical overflow . If this is multiplied by 0 , you get NaN . Separately , these steps ar...
> > > import numpy as np > > > np.exp ( 709 ) *00.0 > > > np.exp ( 710 ) *0nan
Do numerical programming languages distinguish between a `` largest finite number '' and `` infinity '' ?
Python
I was investigating Python generators and decided to run a little experiment.Memory usage ( using psutil to get process RSS memory ) and time taken ( using time.time ( ) ) are shown below after running each method several times and taking the average : I noticed that producing a generator by using xrange is consistentl...
TOTAL = 100000000def my_sequence ( ) : i = 0 while i < TOTAL : yield i i += 1def my_list ( ) : return range ( TOTAL ) def my_xrange ( ) : return xrange ( TOTAL ) sequence_of_values = my_sequence ( ) # Memory usage : 6782976B Time taken : 9.53674e-07 ssequence_of_values2 = my_xrange ( ) # Memory usage : 6774784B Time ta...
Why is a generator produced by yield faster than a generator produced by xrange ?
Python
There are already a bunch of answers that solve how to do this general thing , but my main question is Why doesnt this approach work ? I am trying to `` live stream '' the stdout and stderr from a subprocess . I can do this by doing : and this works giving me the result : However this causes a problem as it really only...
import sysimport subprocessdef run_command ( cmd ) : process = subprocess.Popen ( cmd , stderr=subprocess.PIPE , stdout=subprocess.PIPE ) for out in iter ( process.stdout.readline , b '' ) : print ( out ) for err in iter ( process.stderr.readline , b '' ) : print ( err ) run_command ( [ 'echo ' , 'hello ' , 'world ' ] ...
python stream subprocess stdout and stderr zip doesnt work
Python
I have an array of strings grouped into three fields : I would like to convert to a numerical array ( of type np.int8 for a preference , but not required ) , shaped 4x3 , instead of the fields.My general approach is to transform into a 4x3 array of type 'S2 ' , then use astype to make it numerical . The only problem is...
x = np.array ( [ ( -1 , 0 , 1 ) , ( -1 , 1 , 0 ) , ( 0 , 1 , -1 ) , ( 0 , -1 , 1 ) ] , dtype= [ ( ' a ' , 'S2 ' ) , ( ' b ' , 'S2 ' ) , ( ' c ' , 'S2 ' ) ] ) y = np.lib.stride_tricks.as_strided ( x.view ( dtype='S2 ' ) , shape= ( 4 , 3 ) , strides= ( 6 , 2 ) ) z = y.astype ( np.int8 )
converting numpy array of string fields to numerical format
Python
I have an image with a missing part that I know has been coloured in green ( first image ) . What is the most pythonic way of generating another `` boolean '' image that shows white for the missing parts and black for the non-missing parts ( second image ) ? Is it possible to do it without a for-loop , but just with ar...
mask = image [ : , : ] == [ 0 , 255 , 0 ]
What is the most pythonic way of generating a boolean mask of an RGB image based on the colour of the pixels ?
Python
Part of a models objective is weighted by items in a scalar list.I am solving for this by using a list of 0-1 range variables , and then using LinearExpr.ScalProd to weight the objective.Is there a way to do this with just one integer variable ( other than the objective variable ) , where I can either use a lambda or s...
def argmax ( model : cp_model.CpModel , values : List [ int ] ) - > Tuple [ List [ cp_model.IntVar ] , cp_model.IntVar ] : objective_var = model.NewIntVar ( 0 , 1000000 , `` objective_var '' ) ret_vars = [ model.NewIntVar ( 0 , 1 , `` x ( % i ) '' % i ) for i in range ( len ( values ) ) ] model.Add ( sum ( ret_vars ) =...
Is it possible to compute argmax with or-tools with just one integer variable ?
Python
What is the most pythonic and correct way of doing composition aliases ? Here 's a hypothetical scenario : AFAIK with # 1 my tested editors understand these just as fine as # 2 - auto completion , doc strings etc . Are there any down-sides to # 1 approach ? Which way is more correct from python 's point of view ? To ex...
class House : def cleanup ( self , arg1 , arg2 , kwarg1=False ) : # do somethingclass Person : def __init__ ( self , house ) : self.house = house # aliases house.cleanup # 1. self.cleanup_house = self.house.cleanup # 2. def cleanup_house ( self , arg1 , arg2 , kwarg1=False ) : return self.house.cleanup ( arg1=arg1 , ar...
Pythonic way of doing composition aliases
Python
I 'm a Python beginner and I am from C/C++ background . I 'm using Python 2.7.I read this article : A Beginner ’ s Guide to Python ’ s Namespaces , Scope Resolution , and the LEGB Rule , and I think I have some understanding of Python 's these technologies.Today I realized that I can write Python code like this : That ...
if condition_1 : var_x = some_valueelse : var_x = another_valueprint var_x
Python : Variables are still accessible if defined in try or if ?
Python
I want to initialize a list in python . I do not understand why the code below does not work : There are other ways to initialize the list , like : But , my question is why the first code does not work.Edit : I am a newbie to Python , and programming . Unfortunately I do not understand some parts of your answers . For ...
u = [ 'abc ' , 'de ' , 'fghi ' , 'jklm ' , ' n ' , `` ] for item in u : item = len ( item ) u = [ len ( item ) for item in u ]
initializing members of a list
Python
I 'm doing some work with logs . Need to calculate a sum of time duration when the process was running without long interruptions . Set the maximum possible interruption to 30 seconds . Logs are emitted every 3 seconds.So , for example if it was running since 10:20:00 ( hours ) to 10:30:00 and was interrupted from 10:2...
for k , v in proc_activity.items ( ) : proc_activity [ k ] [ 'duration ' ] = 0 start , next = v [ 'timestamps ' ] [ 0 ] , `` for time in v [ 'timestamps ' ] : next = time diff = next - start if diff.seconds < 30 : proc_activity [ k ] [ 'duration ' ] += diff.seconds else : print ( `` diff : % s '' % diff.seconds ) start...
python 3.6 sum of the short periods between timestamps
Python
I have a local GitLab installation that comes with a local PyPI server to store company internal Python packages.How can I configure my PyPI to search packages in both index servers ? I read about .pypirc / pip/pip.ini and found various settings but no solution so far.Most solutions permanently switch all searches to t...
[ global ] [ install ] find-links = https : //pypi.org https : //gitlab.company.de/api/v4/projects/2142423/packages/pypitrusted-host = https : //pypi.org https : //gitlab.company.de/api/v4/projects/2142423/packages/pypi [ distutils ] index-servers = gitlab [ gitlab ] repository = https : //gitlab.company.de/api/v4/proj...
How to setup two PyPI indices
Python
I 've really tried to start isolating my unit tests so I can pinpoint where errors occur rather than having my entire screen turn red with failures when one thing goes wrong . It 's been working in all instances except when something in an initializer fails.Check out these tests : I 'm mocking dependent methods so that...
@ setup_directory ( test_path ) def test_filename ( self ) : flexmock ( lib.utility.time ) .should_receive ( 'timestamp_with_random ' ) .and_return ( 1234 ) f = SomeFiles ( self.test_path ) assert f.path == os.path.join ( self.test_path , '1234.db ' ) @ setup_directory ( test_path ) def test_filename_with_suffix ( self...
Good way to isolate tests that depend on an initializer
Python
I 'm relatively new to python , so I 'm not even sure if I 'm approaching this in the correct way . But I have n't found a good solution anywhere.In order to avoid very ugly and repetitive code , i want to loop the elif part of the if statement.This is the ugly code i want to fix : As you can see , the index is increme...
def codeToChar ( code ) : chars = `` QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm '' if code == ord ( chars [ 0 ] ) : # # # # # SUPER UGLY return chars [ 0 ] elif code == ord ( chars [ 1 ] ) : return chars [ 1 ] elif code == ord ( chars [ 2 ] ) : return chars [ 2 ] elif code == ord ( chars [ 3 ] ) : return char...
Python : Loop through the elif section of an if statement
Python
So I have a list of dictionaries like so : Of course , this is not the exact data . But ( maybe ) from my example here you can catch my problem . I have many records with the same `` Organization '' name , but not one of them has the complete information for that record . Is there an efficient method for searching over...
data = [ { 'Organization ' : '123 Solar ' , 'Phone ' : '444-444-4444 ' , 'Email ' : `` , 'website ' : 'www.123solar.com ' } , { 'Organization ' : '123 Solar ' , 'Phone ' : `` , 'Email ' : 'joey @ 123solar.com ' , 'Website ' : 'www.123solar.com ' } , { etc ... } ]
Sort a list of dictionaries while consolidating duplicates in Python ?
Python
The input parameters are a list of tuples representing the intervals and a list of integers . The goal is to write a function that counts the number of intervals each integer is present in and return this result as a associative array . So for example : Other example : How would I go about writing a function that does ...
Input intervals : [ ( 1 , 3 ) , ( 5 , 6 ) , ( 6 , 9 ) ] Input integers : [ 2 , 4 , 6 , 8 ] Output : { 2 : 1 , 4 : 0 , 6 : 2 , 8 : 1 } Input intervals : [ ( 3 , 3 ) , ( 22 , 30 ) , ( 17 , 29 ) , ( 7 , 12 ) , ( 12 , 34 ) , ( 18 , 38 ) , ( 30 , 40 ) , ( 5 , 27 ) , ( 19 , 26 ) , ( 27 , 27 ) , ( 1 , 31 ) , ( 17 , 17 ) , ( 2...
How to count the presence of a set of numbers in a set of intervals efficiently
Python
Suppose I have a list L of unknown objects , O1 to On , and I want to remove another object reference M which may refer to one of the objects in L , I 've managed to do it using : which is lovely and idiomatic ... but I 'm having to do it a lot , and I wonder if there 's not another more idiomatic way , or if there is ...
L = [ O1 , O2 , ... On ] ... L = [ j for j in L if j not in [ M ] ]
Fastest or most idiomatic way to remove object from list of objects in Python
Python
I am going to write a set of scripts , each independent from the others but with some similarities . The structure will most likely be the same for all the scripts and probably looks like : For each script , I would like to write documentation and export it in PDF . I need a library/module/parser which reads the script...
# -*- coding : utf-8 -*- '' '' '' Small description and information @ author : Author '' '' '' # Importsimport numpy as npimport mathfrom scipy import signal ... # Constant definition ( always with variable in capital letters ) CONSTANT_1 = 5CONSTANT_2 = 10 # Main classclass Test ( ) : def __init__ ( self , run_id , pa...
Documenting and detailing a single script based on the comments inside
Python
Problem ContextI am trying to create a chat log dataset from Whatsapp chats . Let me just provide the context of what problem I am trying to solve . Assume message to be M and response to be R. The natural way in which chats happen is not always alternate , for e.g . chats tend to happen like this [ M , M , M , R , R ,...
Input -- > [ `` M : Hi '' , `` M : How are you ? `` , `` R : Heyy '' , `` R : Im cool '' , `` R : Wbu ? '' ] ( length=5 ) Output -- > [ `` M : Hi M : How are you ? `` , `` R : Heyy R : Im cool R : Wbu ? '' ] ( length = 2 ) final= [ ] temp = `` change = 0for i , ele in enumerate ( chats ) : if i > 0 : prev = chats [ i-1...
Is there a better way to concatenate continuous string elements in Python ?
Python
I 'm a newcomer to Python but I understand that things should not be done this way , so please consider the following code snippets as purely educational : - ) I 'm currently reading 'Learning Python ' and trying to fully understand the following example : I did not understand if this behavior was somewhat related to t...
> > > L = [ 1 , 2 , 3 , 4 , 5 ] > > > for x in L : ... x += 1 ... > > > L [ 1 , 2 , 3 , 4 , 5 ] > > > L = [ [ 1 ] , [ 2 ] , [ 3 ] , [ 4 ] , [ 5 ] ] > > > for x in L : ... x += [ ' _ ' ] ... > > > L [ [ 1 , ' _ ' ] , [ 2 , ' _ ' ] , [ 3 , ' _ ' ] , [ 4 , ' _ ' ] , [ 5 , ' _ ' ] ]
List modification in a loop
Python
I want to know whether a generated sequence has fewer than 2 entries.My inefficient method is to create a list , and measure its length : Obviously , this consumes the whole generator.In my real case the generator could be traversing a large network . I want to do the check without consuming the whole generator , or bu...
> > > def sequence ( ) : ... for i in xrange ( secret ) : ... yield i > > > secret = 5 > > > len ( list ( sequence ( ) ) ) < 2True def take ( n , iterable ) : `` Return first n items of the iterable as a list '' return list ( islice ( iterable , n ) ) > > > len ( take ( 2 , sequence ( ) ) < 2
How to know a generated sequence is at most a certain length
Python
When attempting to make a cross-compatible order preserving QueryDict subclass : Output on Python 3.x ( correct and expected result ) : Output on Python 2.7 ( this querystring was corrupted ) : Why does this idea work on Python 3 but not on Python 2 ? Django v1.11.20 .
from collections import OrderedDictfrom django.http import QueryDictfrom django.conf import settingssettings.configure ( ) class OrderedQueryDict ( QueryDict , OrderedDict ) : passquerystring = ' z=33 & x=11'print ( QueryDict ( querystring ) .urlencode ( ) ) print ( OrderedQueryDict ( querystring ) .urlencode ( ) ) z=3...
Creating an order-preserving multi-value dict for Django
Python
I 'm developing an application using Flask . I want a quick , automated way to add and remove debug=True to the main function call : Development : Production : For security reasons , as I might expose private/sensitive information about the app if I leave debug mode on `` in the wild '' .I was thinking of using sed or ...
app.run ( debug=True ) app.run ( )
What Unix tool to quickly add/remove some text to a Python script ?
Python
I want to process every line in my log file , and extract IP address if line matches my pattern . There are several different types of messages , in example below I am using p1andp2 ` .I could read the file line by line , and for each line match to each pattern . ButSince there can be many more patterns , I would like ...
import reIP = r ' ( ? P < ip > \d { 1,3 } \.\d { 1,3 } \.\d { 1,3 } \.\d { 1,3 } ) 'p1 = 'Registration from ' + IP + '- Wrong password ' p2 = 'Call from ' + IP + 'rejected because extension not found ' c = re.compile ( r ' ( ? : ' + p1 + '| ' + p2 + ' ) ' ) for line in sys.stdin : match = re.search ( c , line ) if matc...
python3 : extract IP address from compiled pattern
Python
I am reading the faster-rcnn code of tensorflow models . I am confused with the use of tf.stop_gradient.Consider the following code snippet : More code is here . My question is : what happens if tf.stop_gradient is not set for proposal_boxes ?
if self._is_training : proposal_boxes = tf.stop_gradient ( proposal_boxes ) if not self._hard_example_miner : ( groundtruth_boxlists , groundtruth_classes_with_background_list , _ , groundtruth_weights_list ) = self._format_groundtruth_data ( true_image_shapes ) ( proposal_boxes , proposal_scores , num_proposals ) = se...
What happens if tf.stop_gradient is not set ?
Python
I was reading about Default Parameter Values in Python on Effbot . There is a section later in the article where the author talks about Valid uses for mutable defaults and cites the following example : I have n't been able to locate how this causes fast/highly optimised execution of code . Can somebody enlighten on thi...
and , for highly optimized code , local rebinding of global names : import mathdef this_one_must_be_fast ( x , sin=math.sin , cos=math.cos ) : ...
How does local rebinding of global names in Python make code faster/optimized ?
Python
Lets say that I have MyModel that has created_at and name fields . created_at is DateTime.Lets say that I have the following model objects : I want to make query that will return to me these models in this order : I want to group all models by created_at field , but only using Date part of DateTime field . I know that ...
< id : 1 , name : A , created_at : 04.06.2020T17:49 > < id : 2 , name : B , created_at : 04.06.2020T18:49 > < id : 3 , name : C , created_at : 05.06.2020T20:00 > < id : 4 , name : D , created_at : 06.06.2020T19:20 > < id : 5 , name : E , created_at : 06.06.2020T13:29 > < id : 6 , name : F , created_at : 06.06.2020T12:5...
Django , how to group models by date ?
Python
Why is this ? I expected a ( ) , b ( ) , c ( ) , to be 1 , 4 , and 9 .
l = [ 1 , 2 , 3 ] a , b , c = [ lambda : n*n for n in l ] a ( ) # = > 9b ( ) # = > 9c ( ) # = > 9
Confused by lexical closure in list comprehension
Python
From a runtime efficiency perspective in python are these equally efficient ? VSI have a more complex problem that can essentially be boiled down to this question : Obviously , from a code length perspective the second is more efficient , but is the runtime better as well ? If they are not , why not ?
x = foo ( ) x = bar ( x ) x = bar ( foo ( ) )
Is splitting assignment into two lines still just as efficient ?
Python
I am writing an interpreter in python and I am following this example http : //www.dabeaz.com/ply/example.htmlI would like to know how I can implement multiple assignment such as : a=b=c=1 and a= ( b=1 ) *1I have tried a few rules but all in vain . I know the parsing should be something like this.I am just not sure how...
a b c 1 \ \ \/ \ \ / \ \ / \ /
How to implement multiple assignment in an interpreter written in python ?
Python
I have a function f that produces a PS1 prompt for python , set as such : Following the instructions in the documentation , I ended up with the following : However , this does n't work , since f returns a string with color codes , which python prints directly to the terminal , leading to a colorful prompt , while ipyth...
sys.ps1 = f from IPython.terminal.prompts import Prompts , Tokenfrom IPython import get_ipythonclass MyPrompt ( Prompts ) : def in_prompt_tokens ( self , cli=None ) : return [ ( Token , f ( ) ) ] ipython = get_ipython ( ) ipython.prompts = MyPrompt ( ipython ) def f ( ) : return '\x01\x1b [ 1m\x1b [ 33m\x02kavi\x01\x1b...
How to reuse an existing sys.ps1 formatter in an IPython prompt ?
Python
i have a edit_profile view at my django application that also checks if the pgp key the users saves to his profile is in RSA format , Anyways if i add a profile avatar for the very first time it works like a charm , if i want to clear or delete it , im always jumping onto the execpt block and the user avatar remains un...
def default_image_file_extension ( value ) : ext = os.path.splitext ( value.name ) [ 1 ] # [ 0 ] returns path+filename valid_extensions = [ '.jpg ' , '.jpeg ' , '.png ' ] if not ext.lower ( ) in valid_extensions : raise ValidationError ( u'Unsupported extension . Allowed are are : .jpg , .jpeg , .png ' ) def default_im...
Django unable to delete/clear data on form
Python
I have a numpy array arr . It 's a numpy.ndarray , size is ( 5553110 , ) , dtype=float32.When I do : Why is the first comparison getting it wrong ? And how can I fix it ? The values : Is the problem with precision ?
( arr > np.pi ) [ 3154950 ] False ( arr [ 3154950 ] > np.pi ) True arr [ 3154950 ] = 3.1415927np.pi= 3.141592653589793
Array comparison not matching elementwise comparison in numpy
Python
Say I have an array of atoms like this : ( the length may be any ) And I want to create a list of sets that can be made with them : Is it possible to do it easily in python ? Maybe it 's very easy to do , but I 'm not getting it myself.Thank you .
[ ' a ' , ' b ' , ' c ' ] [ [ ' a ' ] , [ ' b ' ] , [ ' c ' ] , [ ' a ' , ' b ' ] , [ ' a ' , ' c ' ] , [ ' b ' , ' c ' ] , [ ' a ' , ' b ' , ' c ' ] ]
Create a list of sets of atoms
Python
my purpose of this code is to extract all the integers from the text and sum them up together.I have been looking for solutions to pluck out all the integers in a line of text . I saw some solutions suggesting to use \D and \b , I just got started with regular expression and still unfamiliar with how it can fit into my...
import reimport urllib2data = urllib2.urlopen ( `` http : //python-data.dr-chuck.net/regex_sum_179860.txt '' ) aList = [ ] for word in data : data = ( str ( w ) for w in data ) s = re.findall ( r ' [ \d ] + ' , word ) if len ( s ) ! = 1 : continue num = int ( s [ 0 ] ) aList.append ( num ) print aList
Find all occurrences of integer within text in Python
Python
I 'm trying to run some calculation in loop , each calculation creates , uses and closes a pool . But the calculation only runs once and then throws an error : `` Pool not running '' . Of course the old one is not running , but should n't the new one be created ? Below is a simplified example , similar to my code . Mor...
from pathos.multiprocessing import ProcessingPool as Pooldef add_two ( number ) : return ( number + 2 ) def parallel_function ( numbers ) : pool = Pool ( 10 ) result = pool.imap ( add_two , numbers ) pool.close ( ) pool.join ( ) return ( result ) sets= [ [ 1 , 2 , 3 ] , [ 2 , 3 , 4 ] , [ 3 , 4 , 5 ] ] for one_set in se...
Multiprocessing in a loop , `` Pool not running '' error
Python
Executing the following mergeresults in this data frame : Why does Pandas take the index from the right data frame as the index for the result , instead of the index from the left series , even though I specified both a left merge and left_index=True ? The documentation says left : use only keys from left framewhich I ...
import pandas as pds = pd.Series ( range ( 5 , 10 ) , index=range ( 10 , 15 ) , name='score ' ) df = pd.DataFrame ( { 'id ' : ( 11 , 13 ) , 'value ' : ( ' a ' , ' b ' ) } ) pd.merge ( s , df , 'left ' , left_index=True , right_on='id ' ) score id valueNaN 5 10 NaN0.0 6 11 aNaN 7 12 NaN1.0 8 13 bNaN 9 14 NaN score id va...
Setting the index after merging with pandas ?
Python
Python 3 integers have unlimited precision . In practice , this is limited by a computer 's memory.Consider the followng code : This will obviously fail . But what will be the result of this ? The entire RAM ( and the page file ) filled with this one integer ( except for the space occupied by other processes ) ? Or is ...
i = 12345while True : i = i * 123
Python Infinite Integers
Python
I have an input.pdf which is `` normal '' ( a number of pages all the same orientation and direction ) and I want to create a new pdf which can arbitrarily rearrange the input pagesFor example : I only need rotation and scaling . Each input page will be present in its entirety as some component of the output . I do n't...
in = open_pdf ( `` input.pdf '' ) out = new_pdf ( ) p = createpage ( size ) p.add ( in.get_page ( 123 ) , origin= ( 0,100 ) , scale= ( 0.5,0.5 ) , angle=degrees ( 270 ) ) p.add ( ... ) out.add ( p ) out.save ( `` output.pdf '' )
How can I arbitarily rotate , rearrange etc pdf pages in Python ?
Python
Lets say I have a tuple generator , which I simulate as follows : For this specific generator , I wish to write a function to output the following : So I 'm iterating over three consecutive items at a time and printing them , except when I approach the end . Should the first line in my function be : In other words , is...
g = ( x for x in ( 1,2,3,97,98,99 ) ) ( 1,2,3 ) ( 2,3,97 ) ( 3,97,98 ) ( 97,98,99 ) ( 98,99 ) ( 99 ) t = tuple ( g ) def f ( data , l ) : t = tuple ( data ) for j in range ( len ( t ) ) : print ( t [ j : j+l ] ) data = ( x for x in ( 1,2,3,4,5 ) ) f ( data,3 )
Accessing consecutive items when using a generator
Python
I 've got an endpoint built with Django Rest Framework , to which I now want to add permissions so that only users belonging to a certain group can access an endpoint . So I 'm using token based access and inspired by this example I 'm trying to use the following code : But unfortunately I get anAttributeError : 'User ...
class ReadPermission ( BasePermission ) : def has_permission ( self , request , view ) : return request.user.groups.filter ( name=settings.GROUP_POST_DATA ) .exists ( ) class MyEndpoint ( mixins.ListModelMixin , viewsets.GenericViewSet ) : permission_classes = [ IsAuthenticated , ReadPermission ] http_method_names = [ ...
Why does n't my request.user have groups in Django ?
Python
I have a df and I want to grab the most recent row below by CUSIP.I am using : I want this : Instead I am getting : How do I get last ( ) to take the last row of the groupby including the NaN 's ? Thank you .
In [ 374 ] : df.head ( ) Out [ 374 ] : CUSIP COLA COLB COLC date 1992-05-08 AAA 238 4256 3.523346 1992-07-13 AAA NaN 4677 3.485577 1992-12-12 BBB 221 5150 3.241995-12-12 BBB 254 5150 3.251997-12-12 BBB 245 Nan 3.251998-12-12 CCC 234 5140 3.241451999-12-12 CCC 223 5120 3.65145 df = df.reset_index ( ) .groupby ( 'CUSIP '...
Groupby - taking last element - how do I keep nan 's ?
Python
Suppose I want to create a CLI that looks like thisHow would I do this ? I 've tried doing something like this -when I run cliName user create , the print statements do not run . Nothing runs .
cliName user createcliName user update @ click.group ( ) def user ( ) : print ( `` USER '' ) pass @ user.command ( ) def create ( ) : click.echo ( `` create user called '' )
Creating hierarchical commands using Python Click
Python
Consider the following scenario : You have a module M defined in m.py containing a function f.It can be called like this : The module grows to a size where it is impractical to have in a single file . You split M up into submodules M.X , M.Y , M.Z and put the following in M/__init__.py : The original code still works :...
import M ; M.f ( ) from .X import *from .Y import *from .Z import *__all__ = [ `` f '' ] import M ; M.f ( ) import M.X ; M.X.f ( )
How do I prevent users from importing x from a submodule when it exposed in the parent using __all__
Python
I have big file ( few GBs ) with text.For example , it have next text : I need to insert word `` funny '' at 5 position , and offset the rest of text : How I can do n't read all file for offsetting rest ? Or how I can optimise this operation ? Thanks .
Hello , World ! Hello , funny World !
string insertion in big file
Python
I am running a website application and am using Flask which queries a mongodb database using mongoengine . Am getting an error when the application tries to query the database.I have mongodb installed in one of the containers and I can connect to it successfully.Docker SetupPython setup : Error occurs when I doError st...
mongodb : 2019-09-06T03:45:11.801+0000 I NETWORK [ conn1 ] received client metadata from 172.20.0.3:43918 conn1 : { driver : { name : `` PyMongo '' , version : `` 3.9.0 '' } , os : { type : `` Linux '' , name : `` Linux '' , architecture : `` x86_64 '' , version : `` 3.10.0-957.27.2.el7.x86_64 '' } , platform : `` CPyt...
Flask app unable to query data from mongodb using mongoengine in a dockerized setup
Python
IntroductionI have a function func which is vectorizable , and I vectorize it using np.frompyfunc . Rather than using a nested for loop , I want to call it only once , and thus I 'll need to pad the inputs with np.newaxis's.My goal is to get rid of the two nested for loops and use the numpy.array broadcasting feature i...
for i , b_0 in enumerate ( b_00 ) : for j , b_1 in enumerate ( b_11 ) : factor = b_0 + b_1 rn = ( b_0 * coord + b_1 * coord2 ) / factor rn_1 = coord - rn rn_2 = coord2 - rn results = np.add ( results , np.prod ( myfunc ( c_0 [ : ,None , : ] , c_1 [ None , : , : ] , rn_1 , rn_2 , factor ) , axis=2 ) ) factor = b_00 [ : ...
A broadcasting issue involving where to put the padding
Python
I have created a script that scrape website : 1688.com and the problem is , the site is in Chinese so whenever i try to retrieve the text , it gives me a bunch of unicode and when i export to a CSV file , there 's nothing in the file.My code : for item in lst : writer_content.writerow ( [ item ] ) The output is And i h...
# -*- coding : utf-8 -*-import csvfrom urllib import urlopenfrom bs4 import BeautifulSoup as BScsv_content = open ( 'content.csv ' , ' w+ ' ) writer_content = csv.writer ( csv_content ) url = urlopen ( 'https : //fuzhuang.1688.com/nvzhuang ? spm=a260k.635.1998214976.1.7eqUGT ' ) html = BS ( url , 'lxml ' ) container = ...
Unable to retrieve Chinese texts while scraping
Python
I 'm having difficulties in understanding the concept of how Python reads a file when it was deleted after being open'ed . Here is the code : Text and binary modes give the same result . I tried this also for big files with more than 1Gb size and they were also read after being deleted . The operation of open happens a...
> > > import os > > > os.system ( 'cat foo.txt ' ) Hello world ! 0 > > > f < _io.TextIOWrapper name='foo.txt ' mode= ' r ' encoding='UTF-8 ' > > > > os.system ( 'rm -f foo.txt ' ) 0 > > > os.system ( 'cat foo.txt ' ) cat : foo.txt : No such file or directory256 > > > f.read ( ) 'Hello world ! \n ' > > >
How Python reads a file when it was deleted after being opened
Python
I am using itertools.product to find the possible weights an asset can take given that the sum of all weights adds up to 100 . The above code works , but it is too slow as it goes through the combinations that are not acceptable , example [ 50,50,50,50,50 ] eventually testing 3125 combinations instead of 121 possible c...
min_wt = 10max_wt = 50step = 10nb_Assets = 5weight_mat = [ ] for i in itertools.product ( range ( min_wt , ( max_wt+1 ) , step ) , repeat = nb_Assets ) : if sum ( i ) == 100 : weight = [ i ] if np.shape ( weight_mat ) [ 0 ] == 0 : weight_mat = weight else : weight_mat = np.concatenate ( ( weight_mat , weight ) , axis =...
Any way to speedup itertool.product
Python
Consider following codeWhat I am trying to in this code is to randomly split my data in Sales Sframe ( which is similar to Pandas DataFrame ) into roughly 4 equal parts.What is a Pythonic/Efficient way to achieve this ?
one , two = sales.random_split ( 0.5 , seed=0 ) set_1 , set_2 = one.random_split ( 0.5 , seed=0 ) set_3 , set_4 = two.random_split ( 0.5 , seed=0 )
Efficient splitting of data in Python
Python
My project consists of several django applications that need to be deployed differently , possibly on different machines . However often these apps occasionally need to access each other 's models , so I was thinking of `` externalizing '' my models so that they can be accessed more elegantly from any app . So the idea...
/ + application1+ application2+ models
Is it a good programming practice to separate models from the rest of the application
Python
According to the Documentation : The current implementation keeps an array of integer objects for all integers between -5 and 256 , when you create an int in that range you actually just get back a reference to the existing object . So it should be possible to change the value of 1 . I suspect the behaviour of Python i...
> > > a = 256 > > > b = 256 > > > a is bTrue > > > c = 257 > > > d = 257 > > > c is dFalse > > > e = 258 ; f=258 ; > > > e is fTrue > > > id ( e ) 43054020 > > > id ( f ) 43054020
Comparing two variables with 'is ' operator which are declared in one line in Python
Python
I have found an interesting performance optimization . Instead of using all ( ) : I have profiled that it 's faster when a loop is used instead : With all ( ) the profiler shows 1160 additional < genexpr > calls : With the for loop , there are no < genexpr > calls : My question is where does the difference come from ? ...
def matches ( self , item ) : return all ( c.applies ( item ) for c in self.conditions ) def matches ( self , item ) : for condition in self.conditions : if not condition.applies ( item ) : return False return True 4608 function calls ( 4600 primitive calls ) in 0.015 seconds Ordered by : internal time ncalls tottime p...
all ( ) vs for loop with break performance
Python
I have the following class which is being subclassed : I then have a specific manager for various database . And I can call those like this : However , is there a way to do the following instead ? Basically , I want to be able to call things in reverse order , is that possible ?
class ConnectionManager ( object ) : def __init__ ( self , type=None ) : self.type = None self.host = None self.username = None self.password = None self.database = None self.port = None def _setup_connection ( self , type ) : pass c = MySQLConnectionManager ( ) c._setup_connection ( ... ) c = ConnectionManager ( `` My...
Python : How to subclass while calling parent class ?
Python
Using Python , is it possible to insert from ss into pp and maintain pp sorted by two attributes , let 's say by the2nd then 3rd position in order to have the following result ( both attributes ascending ) : Or ( both attributes descending ) : I do n't want to use the following two statments after the loop which alread...
ss = [ ( 0 , 'bb ' , 'jj ' ) , ( 1 , 'aa ' , 'mm ' ) , ( 2 , 'aa ' , 'kk ' ) , ( 3 , 'bb ' , 'ee ' ) , ( 4 , 'gg ' , 'ff ' ) ] for x in ss : pp = < somthing > pp = [ ( 2 , 'aa ' , 'kk ' ) , ( 1 , 'aa ' , 'mm ' ) , ( 3 , 'bb ' , 'ee ' ) , ( 0 , 'bb ' , 'jj ' ) , ( 4 , 'gg ' , 'ff ' ) ] pp = [ ( 4 , 'gg ' , 'ff ' ) , ( 0...
Maintain a list sorted by multiple attributes ?
Python
From my understanding , function and class scopes behave pretty much the same : When , however , I define a closure , behaviors are different . A function simply returns the local binding , as expected : whereas in a class the binding appears to be lost : Can anyone explain the discrepancy ?
> > > def x ( ) : ... a = 123 ... print ( locals ( ) ) ... > > > x ( ) { ' a ' : 123 } > > > class x ( ) : ... a = 123 ... print ( locals ( ) ) ... { ' a ' : 123 , '__module__ ' : '__main__ ' } > > > def x ( ) : ... a = 123 ... t = lambda : a ... return t ... > > > x ( ) ( ) 123 > > > class x ( ) : ... a = 123 ... t = ...
Closures in a class scope
Python
I have a string that is the full year followed by the ISO week of the year ( so some years have 53 weeks , because the week counting starts at the first full week of the year ) . I want to convert it to a datetime object using pandas.to_datetime ( ) . So I do : and it returns : which is not right . Or if I try : it tel...
pandas.to_datetime ( '201145 ' , format= ' % Y % W ' ) Timestamp ( '2011-01-01 00:00:00 ' ) pandas.to_datetime ( '201145 ' , format= ' % Y % V ' )
Formatting string into datetime using Pandas - trouble with directives
Python
I have a COVID-19 reporting web app hosted on Heroku ( http : //www.rajcovid19.info ) , the data for which I get from the John Hopkins University Git Repository . I have added the repository as a submodule of my main project repository which I use to push changes to Heroku . This enables me to pull updates to the COVID...
# Root directory for the COVID-19 Local repository root=os.getcwd ( ) if os . path.isdir ( root+ '' /COVID-19 '' ) : root+= '' /COVID-19 '' repo=Repo ( root ) git=repo.git git . pullelse : root+= '' /COVID-19 '' os.system ( `` git clone https : //github.com/CSSEGISandData/COVID-19.git '' )
How to automatically pull the latest commit from a git submodule on Heroku ?
Python
I frequently find myself with a list that looks like this : What is the most pythonic way to convert specific strings in this list to ints ? I typically do something like this : The above approach seems wrong . Are there better way to convert only certain items in lists to integers ?
lst = [ ' A ' , ' 1 ' , ' 2 ' , ' B ' , ' 1 ' , ' C ' , 'D ' , ' 4 ' , ' 1 ' , ' 4 ' , ' 5 ' , ' Z ' , 'D ' ] lst = [ lst [ 0 ] , int ( lst [ 1 ] ) , int ( lst [ 2 ] ) , lst [ 3 ] , ... ]
Converting subset of strings to integers in a list
Python
I am trying to retrieve the questions , comments on questions , and answers of questions related to Python from stack overflow using Stack exchange API . I want to extract all information including body of text of questions , comments , and answers . For extracting questions , I am using following code : This filter re...
questions = SITE.fetch ( 'questions ' , tagged='python ' , fromdate=from_date , todate=today , filter= ' ! 9YdnSIN*P ' ) answers = SITE.fetch ( 'questions/ { ids } /answers ' , ids= [ 59239886 ] , filter= ' ! 9YdnSIN*P ' ) ' ! *SU8CGYZitCB.D* ( BDVIficKj7nFMLLDij64nVID ) N9aK3GmR9kT4IzT*5iO_1y3iZ ) 6W.G* '
Retrieving text body of answers and comments using Stackexchange API
Python
I have the following snippet : The idea is to dynamically create one class method ( like notify_fan_mail ) for each feed type . It works almost great , the only problem is that the print statement always prints `` notifying new_event '' , regardless of the method I call ( same for notify_new_mail , notify_review , etc ...
FEED_TYPES = [ ( 'fan_mail ' , 'Fan Mail ' ) , ( 'review ' , 'Review ' ) , ( 'tip ' , 'Tip ' ) , ( 'fan_user ' , 'Fan User ' ) , ( 'fan_song ' , 'Fan Song ' ) , ( 'fan_album ' , 'Fan Album ' ) , ( 'played_song ' , 'Played Song ' ) , ( 'played_album ' , 'Played Album ' ) , ( 'played_radio ' , 'Played Radio ' ) , ( 'new_...
Dynamically adding class methods to a class
Python
I am new to python so apologies for the naive question . I have a list and another list of tuples I want to output a list l3 of size l1 that compares the value of l1 to the first co-ordinates of l2 and stores the second co-ordinate if the first co-ordinate is found in l1 , else stores 0.output : I tired to do a for loo...
l1 = [ 2 , 4 , 6 , 7 , 8 ] l2 = [ ( 4,6 ) , ( 6,8 ) , ( 8,10 ) ] l3 = [ 0 , 6 , 8 , 0 , 10 ] l3 = [ ] for i in range ( len ( l1 ) ) : if l1 [ i ] == l2 [ i ] [ 0 ] : l3.append ( l2 [ i ] [ 1 ] ) else : l3.append ( 0 ) IndexError : list index out of range
Compare a list to a list of tuple to get another list
Python
I need to stop running my threads after a period of time , In this example I put only 120 seconds . I try by using this methods by it does not work .
from threading import Threadfrom Queue import Queueimport osimport timetimeout = 120 # [ seconds ] timeout_start = time.time ( ) # while True : def OpenWSN ( ) : os.system ( `` ./toto '' ) def Wireshark ( ) : os.system ( `` tshark -i tun0 -T ek -w /home/ptl/PCAP_Brouillon/Sim_Run3rd.pcap > /dev/null `` ) def wrapper1 (...
How to stop running my threads after a period of time ?
Python
I am writing a script that , if an array 's elements are the subset of the main array , then it print PASS , otherwise , it print FAIL instead.What should I add to my if-else statement below to make it works ?
a = [ 1,2,3,4,5 ] b = [ 1,2 ] c = [ 1,9 ] # The Passing Scenario if ( i in a for i in b ) : print `` PASS '' else : print `` FAIL '' # The Failing Scenarioif ( i in a for i in c ) : print `` PASS '' else : print `` FAIL ''
Simple if-else statement in Python
Python
I have observed a very strange behavior of nosetests when using the @ mock.patch.object function : When I run multiple tests at the same time I get different results than when I run them individually . Specifically , it happens , that the override with @ mock.patch.object seems to have no effect , in certain cases when...
@ patch.object ( ObjectToOverride , ... . ) def test_mytest ( ) # check the override def test_mytest ( ) with patch.object ( ObjectToOverride , ... . ) : # check the override
Running multiple tests cause interference in nosetests when patching with @ mock.patch.object and sometimes also when using ` with mock.patch.object `
Python
I 'm trying to extract rows from a df based on multiple conditions , ALL of the conditions must be met before any rows are selected else nothing . My dfMy conditions which must be in this format : Expected output :
columns = [ 'is_net ' , 'is_pct ' , 'is_mean ' , 'is_wgted ' , 'is_sum ' ] index = [ ' a ' , ' b ' , ' c ' , 'd ' ] data = [ [ 'True ' , 'True ' , 'False ' , 'False ' , 'False ' ] , [ 'True ' , 'True ' , 'True ' , 'False ' , 'False ' ] , [ 'True ' , 'True ' , 'False ' , 'False ' , 'True ' ] , [ 'True ' , 'True ' , 'Fal...
get subsection of df based on multiple conditions
Python
How can I start REPL at the end of python script for debugging ? In Node I can do something like this : Is there any python alternative ?
code ; code ; code ; require ( 'repl ' ) .start ( global ) ;
How to start REPL at the end of python script ?
Python
I want to do a simple thing : monkey-patch datetime . I ca n't do that exactly , since datetime is a C class.So I wrote the following code : This is on a file called datetime.py inside a package I called pimp.From the error message I 'm given : I assume that I ca n't have a module called datetime importing anything fro...
from datetime import datetime as _datetimeclass datetime ( _datetime ) : def withTimeAtMidnight ( self ) : return self.replace ( hour=0 , minute=0 , second=0 , microsecond=0 ) Traceback ( most recent call last ) : File `` run.py '' , line 1 , in from pimp.datetime import datetime File `` /home/lg/src/project/library/pi...
Python pimping / monkey-patching
Python
Given a list of strings like : I need to extract all integers with length 4 between separators # or @ , and also extract the first and last integers . No floats.My solution is a bit overcomplicated - replace with space and then applied this solution : Is it possible to change the regex for not using re.sub necessarily ...
L = [ '1759 @ 1 @ 83 @ 0 # 1362 @ 0.2600 @ 25.7400 @ 2.8600 # 1094 @ 1 @ 129.6 @ 14.4 ' , '1356 @ 0.4950 @ 26.7300 @ 2.9700 ' , '1354 @ 1.78 @ 35.244 @ 3.916 # 1101 @ 2 @ 40 @ 0 # 1108 @ 2 @ 30 @ 0 ' , '1430 @ 1 @ 19.35 @ 2.15 # 1431 @ 3 @ 245.62 @ 60.29 # 1074 @ 12 @ 385.2 @ 58.8 # 1109 ' , '1809 @ 8 @ 75.34 @ 292.66 ...
Extract integers with specific length between separators
Python
For example , here is my function : and when I : call Test ( ) , what I see is `` ^ @ ^ @ '' .Why would this happen and how can I use the origin '\n ' ?
function ! Test ( ) python < < EOFimport vimstr = `` \n\n '' vim.command ( `` let rs = append ( line ( ' $ ' ) , ' % s ' ) '' % str ) EOFendfunction
Why would `` \n '' become `` ^ @ '' when writing Python in a .vim file ?
Python
I have a Python program that uses Pytables and queries a table in this simple manner : To reduce the query time , I decided to try to sort the table with table.copy ( sortby='colname ' ) . This indeed improved the query time ( spent in where ) , but it increased the time spent in the next ( ) built-in function by sever...
def get_element ( table , somevar ) : rows = table.where ( `` colname == somevar '' ) row = next ( rows , None ) if row : return elem_from_row ( row ) # ! /usr/bin/env python # -*- coding : utf-8 -*-import tablesimport timeimport sysdef create_set ( sort , withdata ) : # Table description with or without data tabledesc...
Why is querying a table so much slower after sorting it ?
Python
Joining a list containing an object - is there any magic method I could set to convert the object to a string before join fails ? I tried __str__ and __repr__ but neither did work
' , '.join ( [ … , Obj , … ] )
Is any magic method called on an object in a list during join ( ) ?
Python
Is there a way to get the complement of a set of columns using itemgetter ? For example , you can get the first , third , and fifth elements of a list using Is there a ( simple and performant ) way to get all of the elements except for the first , third and fifth ?
from operator import itemgetterf = itemgetter ( 0 , 2 , 4 ) f ( [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] ) # # == ( ' a ' , ' c ' , ' e ' )
Itemgetter Except Columns
Python
Given a file looks like this : The first field is an ID which is in range ( 0 , 200000000 ) . The second field represents a type , which is in range ( 1 , 5 ) . And type 1 and type 2 belong to a common category S1 , while type 3 and type 4 belong to S2 . One single ID may have several records with different type . The ...
1440927 11727557 31440927 29917156 4 def gen ( path ) : line_count = 0 for line in open ( path ) : tmp = line.split ( ) id = int ( tmp [ 0 ] ) yield id , int ( tmp [ 1 ] ) max_id = 200000000S1 = bitarray.bitarray ( max_id ) S2 = bitarray.bitarray ( max_id ) for id , type in gen ( path ) : if type ! = 3 and type ! = 4 :...
How to improve performance of this counting program ?
Python
I have a very simple Python question , with examples using Django . When running a Python script , do I always have to precede the script filename with the python command ? In the Django tutorial I am following , some commands are as follows : However , other are like this : Why does the top one not need the python com...
django-admin.py startproject mysite python manage.py runserver
Differences in the ways to running Python scripts
Python
I am self learning python and I was doing an exercise , the solution to which was posted in this thread . Could anyone translate into english what this piece of code means ? When I learned if statements I never came across this syntax .
consonants = 'bcdfghjklmnpqrstvwxz ' return `` .join ( l + ' o ' + l if l in consonants else l for l in s )
What is this piece of code doing , python