lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I want a pandas period range with 25 hours offset , and I saw there are two ways to do this ( see here ) : The first way is to use freq=25H , which I tried , and gave me the right answer : and the result is The second way , using freq=1D1H , however , gave me a rather strange result : and I gotSo maybe 1D1H is not a va...
import pandas as pdpd.period_range ( start='2016-01-01 10:00 ' , freq = '25H ' , periods = 10 ) PeriodIndex ( [ '2016-01-01 10:00 ' , '2016-01-02 11:00 ' , '2016-01-03 12:00 ' , '2016-01-04 13:00 ' , '2016-01-05 14:00 ' , '2016-01-06 15:00 ' , '2016-01-07 16:00 ' , '2016-01-08 17:00 ' , '2016-01-09 18:00 ' , '2016-01-1...
Pandas ` period_range ` gives strange results
Python
In another question I was provided with a great answer involving generating certain sets for the Chinese Postman Problem.The answer provided was : This will output the desire result of : This really shows off the expressiveness of Python because this is almost exactly how I would write the pseudo-code for the algorithm...
def get_pairs ( s ) : if not s : yield [ ] else : i = min ( s ) for j in s - set ( [ i ] ) : for r in get_pairs ( s - set ( [ i , j ] ) ) : yield [ ( i , j ) ] + rfor x in get_pairs ( set ( [ 1,2,3,4,5,6 ] ) ) : print x [ ( 1 , 2 ) , ( 3 , 4 ) , ( 5 , 6 ) ] [ ( 1 , 2 ) , ( 3 , 5 ) , ( 4 , 6 ) ] [ ( 1 , 2 ) , ( 3 , 6 ) ...
What is the best way to translate this recursive python method into Java ?
Python
Consider this function getPos ( ) which returns a tuple . What is the difference between the two following assignments ? Somewhere I saw an example where the first assignment was used but when I just tried the second one , I was surprised it also worked . So , is there really a difference , or does Python just figure o...
def getPos ( ) : return ( 1 , 1 ) ( x , y ) = getPos ( ) # First assignmentx , y = getPos ( ) # Second assignment
x , y = getPos ( ) vs. ( x , y ) = getPos ( )
Python
I 've read about Raymond Hettinger 's new method of implementing compact dicts . This explains why dicts in Python 3.6 use less memory than dicts in Python 2.7-3.5 . However there seems to be a difference between the memory used in Python 2.7 and 3.3-3.5 dicts . Test code : Python 2.7 : 12568Python 3.5 : 6240Python 3.6...
import sysd = { i : i for i in range ( n ) } print ( sys.getsizeof ( d ) )
Why does Python2.7 dict use more space than Python3 dict ?
Python
Why are decimal points only allowed in base 10 ? Why does the following raise a syntax error ? Is there some ambiguity to the number I 'm typing ? It seems there is no possible number that string could represent other than 93.8125The same issue applies to other bases as well : I can program my way around this with a fa...
0b1011101.1101 0x5d.d def base_float ( number_string , base ) : n = number_string.split ( ' . ' ) number = int ( n [ 0 ] , base ) if len ( n ) > 1 and len ( n [ 1 ] ) : frac_part = float ( int ( n [ 1 ] , base ) ) / base**len ( n [ 1 ] ) if number < 0 : frac_part = -frac_part number += frac_part return number > > > bas...
Binary/Hex Floating Point Entry
Python
I am using opencv_traincascade for object detection . I try to find glasses on photo . For this , I 've downloaded 830 pictures like this : http : //pi1.lmcdn.ru/product/V/I/VI060DWIHZ27_1_v2.jpgThen I 've downloaded many pictures with model in dresses or just dresses photos , 1799 photos.Then I 've start opencv_trainc...
➜ pictureFeature opencv_traincascade -data Feature/classifier -vec samples.vec -bg negatives.txt -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 830 -numNeg 1799 -w 60 -h 90 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024PARAMETERS : cascadeDirName : Feature/classifiervecFileName : samples.vecb...
OpenCV exception after 1 day calculation
Python
I have a defaultdict : and a dataframe that looks like this : and the output I 'd like is to SUM the dataframe based on the values of the dictionary , with the keys as the columns : The pandas groupby documentation says it does this if you pass a dictionary but all I end up with is an empty df using this code :
dd = defaultdict ( list , { 'Tech ' : [ 'AAPL ' , 'GOOGL ' ] , 'Disc ' : [ 'AMZN ' , 'NKE ' ] } AAPL AMZN GOOGL NKE1/1/10 100 200 500 2001/2/10 100 200 500 2001/310 100 200 500 200 TECH DISC 1/1/10 600 400 1/2/10 600 400 1/3/10 600 400 df.groupby ( by=dd ) .sum ( ) # # returns empty df
pandas groupby using dictionary values , applying sum
Python
The following code works as expected and does not trigger the assertion : The following code breaks , triggering the assertion : I tried replacing the decorator with an ndb.transaction call or an ndb.transaction_async call , but neither worked.Is there a bug with ndb.toplevel and transactions ?
@ ndb.transactional @ ndb.taskletdef Foo ( ) : assert ndb.in_transaction ( ) @ ndb.transactional @ ndb.topleveldef Foo ( ) : assert ndb.in_transaction ( )
Does ndb.toplevel break transactions ?
Python
I have data twitter in a CSV file ( that I 'm mining with a Python API ) . I get around 1000 lines of data . Now I want to shorten the tweet data using the specific Indonesian words “ macet ” or “ kecelakaan ” ( in English “ traffic ” or “ accident ” ) and put the matching rows into a new separate CSV file , just like ...
import reimport csvwith open ( 'example1.csv ' , ' r ' ) as csvFile : reader = csv.reader ( csvFile ) if re.search ( r'macet ' , reader ) : for row in reader : myData = list ( row ) print ( row ) newFile = open ( 'example2.csv ' , ' w ' ) with newFile : writer = csv.writer ( newFile ) writer.writerows ( myData ) print ...
Python how to get the tweet data using specific word in csv file and put it in new csv file
Python
I 'm selecting some object for update and then perform operation on itBut I need still to keep FOR UPDATE lock on this object.PostgreSQL documentation says that FOR UPDATE lock will live until the end of transaction , which will be ended , because save will trigger commit.Even if I will manage commit manually , I need ...
obj = Model.objects.select_for_update ( ) .get ( id=someID ) obj.somefield = 1obj.save ( )
Keep lock on database object after commit
Python
I am trying to detect playing cards and transform them to get a bird 's eye view of the card using python opencv . My code works fine for simple cases but I did n't stop at the simple cases and want to try out more complex ones . I 'm having problems finding correct contours for cards.Here 's an attached image where I ...
path1 = `` F : \\ComputerVisionPrograms\\images\\cards4.jpeg '' g = cv2.imread ( path1,0 ) img = cv2.imread ( path1 ) edge = cv2.Canny ( g,50,200 ) p , c , h = cv2.findContours ( edge , cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE ) rect = [ ] for i in c : p = cv2.arcLength ( i , True ) ap = cv2.approxPolyDP ( i , 0.02 ...
How do i separate overlapping cards from each other using python opencv ?
Python
I have two functions which both take iterators as inputs . Is there a way to write a generator which I can supply to both functions as input , which would not require a reset or a second pass through ? I want to do one pass over the data , but supply the output to two functions : Example : I know I could have two diffe...
def my_generator ( data ) : for row in data : yield rowgen = my_generator ( data ) func1 ( gen ) func2 ( gen )
Two functions , One generator
Python
So , this question ends up being both about python and S3.Let 's say I have an S3 Bucket with these files : These files were uploaded using a presigned post URL for S3What I need to do is to give the client the ability to download them all in a ZIP ( or similar ) , but I ca n't do it in memory neither on the server sto...
file1 -- -- -- -- - 2GBfile2 -- -- -- -- - 3GBfile3 -- -- -- -- - 1.9GBfile4 -- -- -- -- - 5GB # Let 's assume Flask @ app.route ( /'download_bucket_as_zip ' ) : def stream_file ( ) : def stream ( ) : # Probably needs to yield zip headers/metadata ? for file in getFilesFromBucket ( ) : for chunk in file.readChunk ( 400...
Creating large zip files in AWS S3 in chunks
Python
Currently I have referencing some old project created in django 1.9 version of my company and I have found that they have used render_to_string function many times as of now I am using render function but I have never used render_to_string.Example code of render_to_string function is as below.I have tried to search onl...
return HttpResponse ( render_to_string ( 'sales/sale.html ' , { 'sale_id ' : sale_id , ` unique_number ` : uni_id } , RequestContext ( request ) ) )
What is difference between render & render_to_string ?
Python
Please download the file simple.7z and install in your sphinx to reproduce issues what i described here , in order to reproduce it , you can run : download and install in your sphinx to reproduce issuesThere are two articles in sample/source , the content are same , only difference is the title.One contains ? in it , t...
make cleanmake html cd samplels source |grep `` for-loop '' What does `` _ '' in Python mean in a for-loop.rstWhat does `` _ '' in Python mean in a for-loop ? .rst make htmlls build/html|grep `` for-loop '' What does `` _ '' in Python mean in a for-loop.htmlWhat does `` _ '' in Python mean in a for-loop ? .html
Why the html file converted from rst file containing question mark ca n't displayed on browser when to click the catalog ?
Python
I was reading the lexical definition for valid decimal string syntax in the documentation for decimal.Decimal and the following struck me as kind of odd : This looked really strange to me , but apparently digits can be included after 'NaN ' without any issues , but any character besides digits after 'NaN ' raises Inval...
nan : := 'NaN ' [ digits ] | 'sNaN ' [ digits ] > > > Decimal ( 'NaN10 ' ) Decimal ( 'NaN10 ' )
Meaning of digits after NaN in Python Decimal object
Python
For version 3.7.1 of the Transcrypt Python to JavaScript compiler I am currently using the new @ dataclass decorator . I had expected that == , ! = , < , > , > = , < = would be supported , as per the PEP 's abstract , but it does n't seem to be the case : Some comparisons are not working : Why are the comparison operat...
from dataclasses import dataclass @ dataclassclass C : x : int = 10 > > > c1 = C ( 1 ) > > > c2 = C ( 2 ) > > > c1 == c2 # okFalse > > > c1 < c2 # crashTypeError : ' < ' not supported between instances of ' C ' and ' C '
Why do n't Python 3.7 dataclasses support < > < = and > = , or do they ?
Python
For apply function , you can refer to hereMy confusion is more from this sample , and I have added some print to below code snippet to output more debug information , The output is like below , and confused what are the numbers like 6. , 3. and 10. mean ? And how they are related to the final classification result ?
grd = GradientBoostingClassifier ( n_estimators=n_estimator ) grd_enc = OneHotEncoder ( ) grd_lm = LogisticRegression ( ) grd.fit ( X_train , y_train ) test_var = grd.apply ( X_train ) [ : , : , 0 ] print `` test_var.shape '' , test_var.shapeprint `` test_var '' , test_vargrd_enc.fit ( grd.apply ( X_train ) [ : , : , 0...
confused by apply function of GradientBoostingClassifier
Python
In the custom LoginSerializer : the login panel is this : I want to optimize the login panel to two fields . one for username/telphone/email , the other for password.But how to change the LoginSerializer ?
class LoginSerializer ( serializers.Serializer ) : username = serializers.CharField ( required=False , allow_blank=True ) email = serializers.EmailField ( required=False , allow_blank=True ) password = serializers.CharField ( style= { 'input_type ' : 'password ' } ) def _validate_email ( self , email , password ) : use...
How to alter the LoginSerializer for one field for username/telephone/email ?
Python
I am creating a program which iterates over the width and height of an image as well as makes use of a set of keys.Here is an example : The width and height are a range of integers up to the size of the width and height.The keys are any set of numbers ( actually ASCII values ) but are not ordered numbers.I would like t...
width = [ 0,1,2,3,4,6,7,8,9 ] height = [ 0,1,2,3,4 ] keys = [ 18,20,11 ] 0 0 180 1 200 2 110 3 180 4 201 0 111 1 18. . ..9 0 209 1 119 2 189 3 209 4 11 w = [ 0,1,2,3,4,6,7,8,9 ] h = [ 0,1,2,3,4 ] k = [ 18,20,11 ] kIndex = 0for i in w : for j in h : print ( i , j , k [ kIndex ] ) # Cycle through the keys index . # The m...
Better method to iterate over 3 lists
Python
I am still learning the Python programmimg language . I asked myself in terms of code exceptions , when it is neccessary to handle such situations in a pythonic way . I read a few times `` you should never pass an error silently '' .For example a little function : Is it neccessary to write an error-handler , if somebod...
def square ( list_with_items ) : return [ i**2 for i in list_with_items ]
Python exception handling - How to do it pythonic ?
Python
SetupI 'm implementing a recommender system running on a Ubuntu 12.4 Server using Titan Rexster ( titan-server-0.4.4.zip ) with the Elasticsearch backend . In order to connect to the Rexster Server I use the Bulbflow library for python.Beta seemed to run fine for 3 weeks , but with the load `` increasing '' ( only a co...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < rexster > < http > < server-port > 8182 < /server-port > < server-host > 0.0.0.0 < /server-host > < base-uri > http : //MY_IP < /base-uri > < web-root > public < /web-root > < character-set > UTF-8 < /character-set > < enable-jmx > false < /enable-jmx > < enable-do...
Why does Rexster Server ( and Titan ) stop responding ?
Python
I am attempting to implement the algorithm from the TD-Gammon article by Gerald Tesauro . The core of the learning algorithm is described in the following paragraph : I have decided to have a single hidden layer ( if that was enough to play world-class backgammon in the early 1990 's , then it 's enough for me ) . I am...
import numpy as npclass TD_network : `` '' '' Neural network with a single hidden layer and a Temporal Displacement training algorithm taken from G. Tesauro 's 1995 TD-Gammon article. `` '' '' def __init__ ( self , num_input , num_hidden , num_output , hnorm , dhnorm , onorm , donorm ) : self.w21 = 2*np.random.rand ( n...
Implementing the TD-Gammon algorithm
Python
I have a Python program that parses files , takes a path as and argument and parses all files in the given path and all sub directories - using os.walk ( path ) . I want to call this from my php Web App , so the user can specify a path , which is then passed as an argument to the parser . ( Passing a path is ok because...
$ path = $ _REQUEST [ 'location ' ] ; echo `` Path given is : `` . $ path ; $ command = 'python C : \Workspaces\parsers\src\main\main.py ' . intval ( $ mode ) . ' `` '. $ path . ' '' ' ; echo `` < p > '' . $ command . `` < /p > '' ; $ parser = popen ( $ command , ' r ' ) ; if ( $ parser ) { echo `` < p > Ran the progra...
Passing a valid path to Python from PHP
Python
I have two pandas DataFrames / Series containing one row each.I now want to get all possible combinations into an n*n matrix / DataFrame with values for all cross-products being the output from a custom function.This should therefore result in : While I can build my own matrix through itertools.product , this seems lik...
df1 = pd.DataFrame ( [ 1 , 2 , 3 , 4 ] ) df2 = pd.DataFrame ( [ 'one ' , 'two ' , 'three ' , 'four ' ] ) def my_function ( x , y ) : return f '' { x } : { y } '' df = pd.DataFrame ( [ [ ' 1 : one ' , ' 2 : one ' , ' 3 : one ' , ' 4 : one ' ] , [ ' 1 : two ' , ' 2 : two ' , ' 3 : two ' , ' 4 : two ' ] , [ ' 1 : three ' ...
Apply function to pandas row-row cross product
Python
Under Python 2.7.5Where are the three refcount ? PS : when the 10000 PyIntObject would be Py_DECREF to 0 ref and deallocated ? Do not say about gc stuff , reference count itself can work without gc .
> > > import sys > > > sys.getrefcount ( 10000 ) 3
Unexpected value from sys.getrefcount
Python
My framework is raising a syntax error when I try to execute this code : And here 's the error : What 's going on ?
from django.template import Template , TemplateSyntaxError try : Template ( value ) except TemplateSyntaxError as error : raise forms.ValidationError ( error ) return value from template_field import TemplateTextField , TemplateCharField File `` C : \django\internal\..\internal\cmsplugins\form_designer\template_field.p...
Be my human compiler : What is wrong with this Python 2.5 code ?
Python
I really like the python coverage module : and the HTML pages it generates . Is there a combination of this and profiling so that one could see a unified HTML report of coverage+profiling.Thanks in advance .
http : //nedbatchelder.com/code/coverage/
combination of coverage and profiler ?
Python
input : a sorted list , like this : [ 1,2,3,8,10,15,16,17,18,22,23,27,30,31 ] a threshold , like this : max_diff = 2expected output : a list of sub lists ; each sub list contains the values that the neighboring difference is smaller than max_diff , like this : [ [ 1 , 2 , 3 ] , [ 8 , 10 ] , [ 15 , 16 , 17 , 18 ] , [ 22...
test_list = [ 1,2,3,8,10,15,16,17,18,22,23,27,30,31 ] max_diff = 2splited_list = [ ] temp_list = [ test_list [ 0 ] ] for i in xrange ( 1 , len ( test_list ) ) : if test_list [ i ] - temp_list [ -1 ] > max_diff : splited_list.append ( temp_list ) temp_list = [ test_list [ i ] ] else : temp_list.append ( test_list [ i ] ...
How to split a sorted list into sub lists when two neighboring value difference is larger than a threshold
Python
I have some data like this : i want add a column that contain the max value of each code : is there any way to do this with pandas ?
pd.DataFrame ( { 'code ' : [ ' a ' , ' a ' , ' a ' , ' b ' , ' b ' , ' c ' ] , 'value ' : [ 1,2,3 , 4 , 2 , 1 ] } ) + -- -- -- -+ -- -- -- + -- -- -- -+| index | code | value |+ -- -- -- -+ -- -- -- + -- -- -- -+| 0 | a | 1 |+ -- -- -- -+ -- -- -- + -- -- -- -+| 1 | a | 2 |+ -- -- -- -+ -- -- -- + -- -- -- -+| 2 | a | ...
filling a column values with max value in pandas
Python
Given 3 nested vectors : I can add these vectors together with a map/sum/zip comprehension like so : I 've manually expanded this from adding two lists together , but is there a pythonic way to generalize this to handle an arbitrary number of lists ? ( Python 2.7 without using external libraries preferred )
> > > a [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] > > > b [ [ 10 , 20 , 30 ] , [ 40 , 50 , 60 ] , [ 70 , 80 , 90 ] ] > > > c [ [ 100 , 200 , 300 ] , [ 400 , 500 , 600 ] , [ 700 , 800 , 900 ] ] > > > [ map ( sum , zip ( i , j , k ) ) for i , j , k in zip ( a , b , c ) ] [ [ 111 , 222 , 333 ] , [ 444 , 555 , 666 ...
Generalizing adding nested lists
Python
Let 's say I have a simple piece of code like this : Does the list [ 150 , 300 , 500 , 750 ] get created every iteration of the loop ? Or can I assume that the interpreter ( say , CPython 2.7 ) is smart enough to optimize this away ?
for i in range ( 1000 ) : if i in [ 150 , 300 , 500 , 750 ] : print ( i )
Loop while checking if element in a list in Python
Python
Trying to add email notification to my app in the cleanest way possible . When certain fields of a model change , app should send a notification to a user . Here 's my old solution : This worked fine while I had one or two notification types , but after that just felt wrong to have so much code in my save ( ) method . ...
from django.contrib.auth import Userclass MyModel ( models.Model ) : user = models.ForeignKey ( User ) field_a = models.CharField ( ) field_b = models.CharField ( ) def save ( self , *args , **kwargs ) : old = self.__class__.objects.get ( pk=self.pk ) if self.pk else None super ( MyModel , self ) .save ( *args , **kwar...
Is it approproate it use django signals within the same app
Python
I 've run into a somewhat unusual situation . I 'm trying to script the interactive console ( for teaching/testing purposes ) , and I tried the following:3 is n't printed , so clearly everything else was on stderr . So far so good . But then we redirect stderr : How can the prompt be printed in both cases ? EDIT : Redi...
$ python > /dev/nullPython 2.7.3 ( v2.7.3:70274d53c1dd , Apr 9 2012 , 20:52:43 ) [ GCC 4.2.1 ( Apple Inc. build 5666 ) ( dot 3 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > print 3 > > > $ python 2 > /dev/null > > > print 33 > > >
Where does Python 's interactive prompt `` > > > '' output to ?
Python
I 'm using Enthought EPD-Free 7.3-1 on a small function , and when I cut/paste into an interactive session ( PyLab ) and run it , it takes less than a second . When I run the same code from the command line `` python probtest.py '' it takes over 16 seconds . I 've confirmed both are using the same python environment . ...
import numpy as npimport sysdef runTest ( numDice , numSixes , numThrows = 10000 ) : nSuccess = 0 for i in range ( numThrows ) : dList = np.random.randint ( 1,7 , numDice ) if sum ( dList==6 ) > = numSixes : nSuccess += 1 return float ( nSuccess ) /numThrowsprint runTest ( 900,150,5000 ) print sys.version
python interactive shell 16x faster than command line - what 's wrong ?
Python
ContextI have several groups of data ( defined by 3 columns w/i the dataframe ) and would like perform a linear fit and each group and then append the estimate values ( with lower + upper bounds of the fit ) .ProblemAfter performing the operation , I get an error related to the shapes of the final vs original dataframe...
from io import StringIO # modern python # from StringIO import StringIO # old pythonimport numpyimport pandasdef fake_model ( group , formula ) : # add the results to the group modeled = group.assign ( fit=numpy.random.normal ( size=group.shape [ 0 ] ) , ci_lower=numpy.random.normal ( size=group.shape [ 0 ] ) , ci_uppe...
Appending columns during groupby-apply operations
Python
Let 's say I have this python code : It prints `` 2 '' , just as expected.I can make a generator in c++20 like that : This generator just produces a string letter by letter , but the string is hardcoded in it . In python , it is possible not only to yield something FROM the generator but to yield something TO it too . ...
def double_inputs ( ) : while True : x = yield yield x * 2gen = double_inputs ( ) next ( gen ) print ( gen.send ( 1 ) ) # include < coroutine > template < class T > struct generator { struct promise_type ; using coro_handle = std : :coroutine_handle < promise_type > ; struct promise_type { T current_value ; auto get_re...
Making python generator via c++20 coroutines
Python
I 'm having a bit of trouble with this . My dataframe looks like this : So , what I need to do is , after the dummy gets value = 1 , I need to fill the amount variable with zeroes for each id , like this : I 'm guessing I 'll need some combination of groupby ( 'id ' ) , fillna ( method='ffill ' ) , maybe a .loc or a sh...
id amount dummy1 130 01 120 01 110 11 nan nan 1 nan nan 2 nan 02 50 02 20 12 nan nan 2 nan nan id amount dummy1 130 01 120 01 110 11 0 nan 1 0 nan 2 nan 02 50 02 20 12 0 nan 2 0 nan
Forward fill missing values by group after condition is met in pandas
Python
The lazy me is thinking about adding a column to some textfiles.The textfiles are in directories and I would like to add the directory name to the text file.Like the text file text.txt in the folder the_peasant : would become : Then I have similar text files in other folders called `` the_king '' etc.I would think this...
has a wart was dressed up like a witch has a false nose the_peasant has a wart the_peasant was dressed up like a witch the_peasant has a false nose
Use the folder name as a column in a text file
Python
I have a python script with the following code : I want to run this python script ( test.py ) from test.ts using Deno . This is the code in test.ts so far : How can I get the output , of the python script in Deno ?
print ( `` Hello Deno '' ) const cmd = Deno.run ( { cmd : [ `` python3 '' , `` test.py '' ] } ) ;
How to run a Python Script from Deno ?
Python
I know its a very common question at first , but I have n't found one that specific . ( If you do , please tell me . ) And all ways I found didnt work for me . I need to check if all elements of list 1 appears in the same amount in the list2 . Ex : i 'm trying this way : It works when the elements are not repeated in t...
# If list1 = [ 2,2,2,6 ] # and list2 = [ 2,6,2,5,2,4 ] # then all list1 are in list2. # If list2 = [ 2,6 ] then all list1 are not in list2 . list1 = [ 6,2 ] import itertoolsfor i in itertools.product ( ( 2,4,5,1 ) , repeat=3 ) : asd = i [ 0 ] + i [ 1 ] asd2= i [ 1 ] + i [ 2 ] list2 = [ asd , asd2 ] if all ( elem in lis...
How to check if all elements of 1 list are in the *same quantity* and in any order , in the list2 ?
Python
I 'm new to Python so please be gentle.I seriously do n't know what is wrong with my code.Here it is : Since epsilon ( 0 ) = 0 , I 'd expect ( analytically ) to get r = ( -16/4 ) ^ ( 1/4 ) = ( -1 ) ^ ( 1/4 ) *sqrt ( 2 ) = exp ( i pi /4 ) *sqrt ( 2 ) = 1 + 1 iBut instead I get : I 've tried to find the error . If I prin...
import numpy as npdef epsilon ( t ) : epsilon = ( 1 - np.exp ( -pow ( t , 4 ) ) ) return epsilondef r ( t ) : r = pow ( ( epsilon ( t ) - 16 ) / 4 , 1/4 ) return rprint ( r ( 0 ) ) RuntimeWarning : invalid value encountered in double_scalars r = pow ( ( 4 * epsilon ( t ) - 16 ) / 4 , 1/4 ) nan def r ( t ) : r = pow ( 0...
New to Python , do n't know what is wrong with my code
Python
In Cython code , I can allocate some memory and wrap it in a memory view , e.g . like this : If I now free the memory using PyMem_Free ( ptr ) , trying to access elements like ptr [ i ] throws an error , as it should . However , I can safely try to access view [ i ] ( it does not return the original data though ) .My q...
cdef double* ptrcdef double [ : :1 ] viewptr = < double* > PyMem_Malloc ( N*sizeof ( 'double ' ) ) view = < double [ : N ] > ptr
Cython : Memory view of freed memory
Python
I 'm struggling with this strange behaviour in Python ( 2 and 3 ) : This results in : But if you writewhere x , y ! = 2 , 1 ( can be 1 , 1 , 2 , 2 , 3 , 5 , etc . ) , this results in : As one would expect . Why does n't a [ a.index ( 1 ) ] , a [ a.index ( 2 ) ] = 2 , 1 produce the result a == [ 2 , 1 ] ?
> > > a = [ 1 , 2 ] > > > a [ a.index ( 1 ) ] , a [ a.index ( 2 ) ] = 2 , 1 > > > a [ 1 , 2 ] > > > a = [ 1 , 2 ] > > > a [ a.index ( 1 ) ] , a [ a.index ( 2 ) ] = x , y > > > a == [ x , y ] True > > > a == [ 2 , 1 ] False
Strange inline assignment
Python
I have to find SHA256 hashes of 2^25 random strings . And then look for collision ( using birthday paradox for the last , say , 50 bits of the hash only ) .I am storing the string : hash pair in a dict variable . Then sorting the variable with values ( not keys ) and then looking for collision using a O ( n ) loop.The ...
from Crypto.Hash import SHA256import osimport randomimport stringfrom operator import itemgetterdef shaa ( ) : trun= [ ] clist= { } for i in range ( 0,33554432 ) : sha=SHA256.new ( str ( i ) ) .hexdigest ( ) sha=int ( bin ( int ( sha,16 ) ) [ -50 : ] ,2 ) clist [ i ] =sha print 'Hashes done . ' clist=sorted ( clist.ite...
How to handle a dict variable with 2^50 elements ?
Python
What I mean to ask is : TLDR : how do I have my package 's help include all underlying docstrings ? I have created a package . That package has all the proper __init__.py files and all the proper docstrings ( module , function , class , and method level docstrings ) . However , when I perform help ( mypackage ) , the o...
> > > help ( numpy ) > > > help ( pandas )
Python : how to embed all docstring help at package level help menu ?
Python
I 'm currently porting some Scala code to Python and I am wondering what is the most pythonic way to do something similar to Scala 's partition ? In particular , in the Scala code I have a situation where I am partitioning a list of items based on whether they return true or false from some filter predicate that I pass...
val ( inGroup , outGroup ) = items.partition ( filter )
python equivalent of scala partition
Python
I 'm looking for a way to expand numbers that are separated by slashes . In addition to the slashes , parentheses , may be used around some ( or all ) numbers to indicate a `` group '' which may be repeated ( by the number of times directly following the parentheses ) or repeated in reverse ( followed by 's ' as shown ...
1 - > [ ' 1 ' ] - > No slashes , no parentheses1/2/3/4 - > [ ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' ] - > basic example with slashes1/ ( 2 ) 4/3 - > [ ' 1 ' , ' 2 ' , ' 2 ' , ' 2 ' , ' 2 ' , ' 3 ' ] - > 2 gets repeated 4 times1/ ( 2/3 ) 2/4 - > [ ' 1 ' , ' 2 ' , ' 3 ' , ' 2 ' , ' 3 ' , ' 4 ' ] - > 2/3 is repeated 2 times ( 1/2/...
Python/Regex - Expansion of Parentheses and Slashes
Python
I am looking for the most efficient way to convert a pandas DataFrame into a list of typed NamedTuple - below is a simple example with the expected output.I would like to get the correct type conversion aligned with the type defined in the dataframe .
from typing import NamedTupleimport pandas as pdif __name__ == `` __main__ '' : data = [ [ `` tom '' , 10 ] , [ `` nick '' , 15 ] , [ `` juli '' , 14 ] ] People = pd.DataFrame ( data , columns= [ `` Name '' , `` Age '' ] ) Person = NamedTuple ( `` Person '' , [ ( `` name '' , str ) , ( `` age '' , int ) ] ) # ... # ......
Convert a pandas dataframe into a list of named tuple
Python
Say I have some data like this : I want to process it looking for `` bumps '' that meet a certain pattern.Imagine I have my own customized regex language for working on numbers , where [ [ > =5 ] ] represents any number > = 5 . I want to capture this case : In other words , I want to begin capturing any time I look ahe...
number_stream = [ 0,0,0,7,8,0,0,2,5,6,10,11,10,13,5,0,1,0 , ... ] ( [ [ > =5 ] ] { 3 , } ) [ [ < 3 ] ] { 2 , } > > > stream_processor.process ( number_stream ) [ [ 5,6,10,11,10,13,5 ] , ... ]
regex numeric data processing : match a series of numbers greater than X
Python
I am writing a parser to parse mathematical expressions , which contain variables among other things . I want a list of all the captured variables . But I am only getting the last captured variable . Below is a minimal example to show the problem . I was expecting [ ' x ' , ' y ' , ' z ' ] . I am using pyparsing versio...
> > > from pyparsing import * > > > var = Word ( alphas ) > > > expr = Forward ( ) > > > expr < < var ( 'var ' ) + ZeroOrMore ( Literal ( '+ ' ) + expr ) > > > foo = expr.parseString ( `` x + y + z '' ) > > > foo ( [ ' x ' , '+ ' , ' y ' , '+ ' , ' z ' ] , { 'var ' : [ ( ' x ' , 0 ) , ( ' y ' , 2 ) , ( ' z ' , 4 ) ] } ...
pyparsing : named results ?
Python
I have an asyncio.Condition named cond . I wish to wait on it , but only for so long before giving up . As asyncio.Condition.wait does not take a timeout , this can not be done directly . The docs state that asyncio.wait_for should be used to wrap and provide a timeout instead : The asyncio.wait_for ( ) function can be...
async def coro ( ) : print ( `` Taking lock ... '' ) async with cond : print ( `` Lock acquired . '' ) print ( `` Waiting ! '' ) await asyncio.wait_for ( cond.wait ( ) , timeout=999 ) print ( `` Was notified ! '' ) print ( `` Lock released . '' ) Taking lock ... Lock acquired.Waiting ! ERROR : asyncio : Task exception ...
Waiting on condition variable with timeout : lock not reacquired in time
Python
I can now load single video URLs of youtube . But the problem now is to load the playlist videos of youtube . So my question is , how do I replace two same pattern , but both having different replacements of a url ? Eg : Actual url : Replace the pattern to become like this : Here the first & amp ; changes to ? and the ...
< iframe width= '' 400 '' height= '' 327 '' src= '' http : //www.youtube.com/embed/1UiICgvrsFI & amp ; list=PLvAOICvbvsbnc5dLG0YR9Mq_tFfzAhQSp & amp ; index=1 '' allowfullscreen= '' true '' > < /iframe > < iframe width= '' 560 '' height= '' 315 '' src= '' //www.youtube.com/embed/1UiICgvrsFI ? list=PLvAOICvbvsbnc5dLG0YR...
Django - replace parts of urlfield
Python
I want to drop specific rows from a pandas dataframe . Usually you can do that using something likeWhat df [ 'some_column ' ] ! = 1234 does is creating an indexing array that is indexing the new df , thus letting only rows with value True to be present.But in some cases , like mine , I do n't see how I can express the ...
df [ df [ 'some_column ' ] ! = 1234 ] df [ df [ 'some_column ' ] not in my_dict.keys ( ) ]
Apply condition on pandas columns to create a boolen indexing array
Python
Why the following two decoding methods return different results ? Is this a bug or expected behavior ? My Python version 2.7.13 .
> > > import codecs > > > > > > data = [ `` , `` , ' a ' , `` ] > > > list ( codecs.iterdecode ( data , 'utf-8 ' ) ) [ u ' a ' ] > > > [ codecs.decode ( i , 'utf-8 ' ) for i in data ] [ u '' , u '' , u ' a ' , u '' ]
Why codecs.iterdecode ( ) eats empty strings ?
Python
I have a list of dictionary and a string . I want to add a selected attribute in each dictionary inside the list . I am wondering if this is possible using a one liner.Here are my inputs : This is my expected output : I tried this :
saved_fields = `` apple|cherry|banana '' .split ( '| ' ) fields = [ { 'name ' : 'cherry ' } , { 'name ' : 'apple ' } , { 'name ' : 'orange ' } ] [ { 'name ' : 'cherry ' , 'selected ' : True } , { 'name ' : 'apple ' , 'selected ' : True } , { 'name ' : 'orange ' , 'selected ' : False } ] new_fields = [ item [ item [ 'se...
How to add another attribute in dictionary inside a one line for loop
Python
I am researching how python implements dictionaries . One of the equations in the python dictionary implementation relates the pseudo random probing for an empty dictionary slot using the equationwhich is explained here.I have read this question , How are Python 's Built In Dictionaries Implemented ? , and basically un...
j = ( ( j*5 ) + 1 ) % 2**i j = ( ( j*5 ) + 1 ) % 2**i 016745230 0 1 6 15 12 13 2 11 8 9 14 7 4 5 10 3 0
In Python Dictionaries , how does ( ( j*5 ) +1 ) % 2**i cycle through all 2**i
Python
There 's this error in Python when calling builtin type ( ) with no arguments : How can we define such a method ? Is there a builtin way ? Or we need to do something like this :
TypeError : type ( ) takes 1 or 3 arguments > > > def one_or_three ( *args ) : ... if len ( args ) not in [ 1,3 ] : ... raise TypeError ( `` one_or_three ( ) takes 1 or 3 arguments '' ) ... > > > one_or_three ( 1 ) > > > one_or_three ( ) TypeError : one_or_three ( ) takes 1 or 3 arguments > > > one_or_three ( 1,2 ) Typ...
Is there a builtin way to define a function that takes either 1 argument or 3 ?
Python
I 've been trying to get started with unit-testing while working on a little cli program.My program basically parses the command line arguments and options , and decides which function to call . Each of the functions performs some operation on a database.So , for instance , I might have a create function : Should my te...
def create ( self , opts , args ) : # I 've left out the error handling . strtime = datetime.datetime.now ( ) .strftime ( `` % D % H : % M '' ) vals = ( strtime , opts.message , opts.keywords , False ) self.execute ( `` insert into mytable values ( ? , ? , ? , ? ) '' , vals ) self.commit ( )
How should I rewrite my database execute/commit to make it amenable to unit testing ?
Python
I 'm trying to add a social media authentication to a website using Social-auth-app-django.So I 've created different apps for the most popular social media websites ( Facebook , Twitter , Google+ ) , and have set the callback url there.But I 'm coming across an error when I 'm redirected back to the website from say F...
Internal Server Error : /oauth/complete/facebook/Traceback ( most recent call last ) : File `` /usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py '' , line 39 , in inner response = get_response ( request ) File `` /usr/local/lib/python3.5/site-packages/django/core/handlers/base.py '' , line 187 , ...
unhashable type when redirecting back to the website using python-social-auth in Django
Python
My problem is thatdoes not return 0 , but returns array ( [ 2147483648 ] , dtype=uint32 ) instead . The same is true for ( so I believe this is simply how > > is implemented ) .Interestingly , all these alternatives seem to work as expected , returning some kind of 0 : In particular , what is different between Numpy ar...
np.array ( [ 2**31 ] , dtype=np.uint32 ) > > 32 np.right_shift ( np.array ( [ 2**31 ] , dtype=np.uint32 ) , 32 ) print ( 2**31 > > 32 , np.uint32 ( 2**31 ) > > 32 , np.array ( 2**31 , dtype=np.uint32 ) > > 32 , np.right_shift ( 2**31 , 32 ) , np.right_shift ( [ 2**31 ] , 32 ) , np.right_shift ( np.uint32 ( 2**31 ) , 32...
Why is ( 2^31 ) > > 32 not 0 ?
Python
This command , subprocess.check_call ( [ 'echo ' , 'hi ' ] , stderr=sys.stdout ) , works just fine in Python 2.7 and Python 3 . What is Python 2.6 doing differently ?
Python 2.6.9 ( unknown , Mar 7 2016 , 11:15:18 ) [ GCC 5.3.0 ] on linux2Type `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > import sys > > > import subprocess > > > subprocess.check_call ( [ 'echo ' , 'hi ' ] , stderr=sys.stdout ) echo : write error : Bad file descriptorTraceb...
Why does ` subprocess.check_call ( ... , stderr=sys.stdout ) ` fail in Python 2.6 ?
Python
It is well known that tuples are not defined by parentheses , but commas . Quote from documentation : A tuple consists of a number of values separated by commasTherefore : Another striking example is this : Even the single-element tuple needs a comma , and parentheses are always used just to avoid confusion . My questi...
myVar1 = ' a ' , ' b ' , ' c'type ( myVar1 ) # Result : < type 'tuple ' > myVar2 = ( ' a ' ) type ( myVar2 ) # Result : < type 'str ' > myVar3 = ( ' a ' , ) type ( myVar3 ) # Result : < type 'tuple ' > myList1 = [ ' a ' , ' b ' ] myList2 = [ ' c ' , 'd ' ] print ( [ ( v1 , v2 ) for v1 in myList1 for v2 in myList2 ] ) #...
Why do tuples in a list comprehension need parentheses ?
Python
The is the input `` dirty '' list in pythoneach list element contains either empty spaces with new line chars or data with newline charsCleaned it up using the below code..givesDoes python internally call strip ( ) twice during the above list comprehension ? or would i have to use a for loop iteration and strip ( ) jus...
input_list = [ ' \n ' , ' data1\n ' , ' data2\n ' , ' \n ' , 'data3\n ' ... .. ] cleaned_up_list = [ data.strip ( ) for data in input_list if data.strip ( ) ] cleaned_up_list = [ 'data1 ' , 'data2 ' , 'data3 ' , 'data4'.. ] for data in input_list clean_data = data.strip ( ) if ( clean_data ) : cleaned_up_list.append ( ...
Python - list comprehension in this case is efficient ?
Python
So if I have a list a and append a to it , I will get a list that contains it own reference.And this basically results in seemingly infinite recursions.And not only in lists , dictionaries as well : It could have been a good way to store the list in last element and modify other elements , but that would n't work as th...
> > > a = [ 1,2 ] > > > a.append ( a ) > > > a [ 1 , 2 , [ ... ] ] > > > a [ -1 ] [ -1 ] [ -1 ] [ 1 , 2 , [ ... ] ] > > > b = { ' a':1 , ' b':2 } > > > b [ ' c ' ] = b > > > b { ' a ' : 1 , ' b ' : 2 , ' c ' : { ... } }
Is there any usage of self-referential lists or circular reference in list , eg . appending a list to itself
Python
I have a the following DataArrayThis gives the following outputor sorted below with x and output ( z ) next to each other for convenience . The data I have is the result of several input values . One of them is the x value . There are several other dimensions ( such as y ) for other input values . I want to know when m...
arr = xr.DataArray ( [ [ 0.33 , 0.25 ] , [ 0.55 , 0.60 ] , [ 0.85 , 0.71 ] , [ 0.92,0.85 ] , [ 1.50,0.96 ] , [ 2.5,1.1 ] ] , [ ( ' x ' , [ 0.25,0.5,0.75,1.0,1.25,1.5 ] ) , ( ' y ' , [ 1,2 ] ) ] ) < xarray.DataArray ( x : 6 , y : 2 ) > array ( [ [ 0.33 , 0.25 ] , [ 0.55 , 0.6 ] , [ 0.85 , 0.71 ] , [ 0.92 , 0.85 ] , [ 1....
xarray reverse interpolation ( on coordinate , not on data )
Python
I 'm using generators in list comprehensions , and getting some unexpected behavior with one of the generators ending early . Why does creating the generator outside of the list comprehension cause the behavior to change ? The generator I created is as follows : The first way of calling is as follows : This gives me th...
def inc_range ( a , b ) : for i in range ( min ( a , b ) , max ( a , b ) + 1 ) : yield i [ ( i , j ) for i in inc_range ( 1,3 ) for j in inc_range ( 4,6 ) ] [ ( 1 , 4 ) , ( 1 , 5 ) , ( 1 , 6 ) , ( 2 , 4 ) , ( 2 , 5 ) , ( 2 , 6 ) , ( 3 , 4 ) , ( 3 , 5 ) , ( 3 , 6 ) ] a = inc_range ( 1,3 ) b = inc_range ( 4,6 ) [ ( i , j...
Premature ending of generator in list comprehension
Python
OverviewContextI am writing unit tests for some higher-order logic that depends on writing to an SQLite3 database . For this I am using twisted.trial.unittest and twisted.enterprise.adbapi.ConnectionPool.Problem statementI am able to create a persistent sqlite3 database and store data therein . Using sqlitebrowser , I ...
CREATE TABLE ajxp_changes ( seq INTEGER PRIMARY KEY AUTOINCREMENT , node_id NUMERIC , type TEXT , source TEXT , target TEXT , deleted_md5 TEXT ) ; CREATE TABLE ajxp_index ( node_id INTEGER PRIMARY KEY AUTOINCREMENT , node_path TEXT , bytesize NUMERIC , md5 TEXT , mtime NUMERIC , stat_result BLOB ) ; CREATE TABLE ajxp_l...
Why is Twisted 's adbapi failing to recover data from within unittests ?
Python
Say I have two 3 dimensional matrices , like so ( taken from this matlab example http : //www.mathworks.com/help/matlab/ref/dot.html ) : If I want to take pairwise dot products along the third dimension , I could do so like this in matlab : Which would give the result : What would be the equivalent operation in numpy ,...
A = cat ( 3 , [ 1 1 ; 1 1 ] , [ 2 3 ; 4 5 ] , [ 6 7 ; 8 9 ] ) B = cat ( 3 , [ 2 2 ; 2 2 ] , [ 10 11 ; 12 13 ] , [ 14 15 ; 16 17 ] ) C = dot ( A , B,3 ) C = 106 140 178 220
Numpy equivalent of dot ( A , B,3 )
Python
The following Python 3 code exhibits some strange behavior ( to me , at least ) when I run it through strace : Since I/O is buffered , if you run this code with /dev/full , it does n't fail until fp closes at the end of the with block . That 's no surprise . In Python 2.7.3rc2 ( on my system ) , the code runs the excep...
import osimport sysif len ( sys.argv ) ! = 2 : print ( 'Usage : ecpy < filename > ' ) sys.exit ( 1 ) try : print ( 'my PID : % d ' % os.getpid ( ) ) with open ( sys.argv [ 1 ] , ' w ' ) as fp : try : fp.write ( 'Hello Stack Overflow ! ' ) except IOError as e : print ( ' # # # before close ' ) print ( str ( e ) ) sys.st...
What happens to file descriptors in Python 3 when .close ( ) fails ?
Python
I need to join all PostgreSQL tables and convert them in a Python dictionary . There are 72 tables in the database . The total number of columns is greater than 1600 . I wrote a simple Python script that joins several tables but fails to join all of them due to the memory error . All memory is occupied during the scrip...
from sqlalchemy import create_engineimport pandas as pdauth = 'user : pass'engine = create_engine ( 'postgresql : // ' + auth + ' @ host.com:5432/db ' ) sql_tables = [ 'table0 ' , 'table1 ' , 'table3 ' , ... , 'table72 ' ] df_arr = [ ] [ df_arr.append ( pd.read_sql_query ( 'select * from `` ' + table + ' '' ' , con=eng...
Join all PostgreSQL tables and make a Python dictionary
Python
In the following example : Given func , how would I get the `` volume '' ? Is there something within the func namespace which gives the value of 10 ? I thought perhaps it would be in func.__globals__ or func.__dict__ but it 's in neither .
def speak ( volume ) : def whisper ( text ) : print ( text.lower ( ) + ( ' . ' * volume ) ) def yell ( text ) : print ( text.upper ( ) + ( ' ! ' * volume ) ) if volume > 1 : return yell elif volume < = 1 : return whisperfunc = speak ( volume=10 ) func ( 'hello ' ) HELLO ! ! ! ! ! ! ! ! ! ! # < == obviously ` 10 ` is st...
How to access closed over variables given only the closure function ?
Python
I am trying to use lambda do to some sorting on a list . What I wanted to do is sort the coordinates based on their manhattan distance from an inital poisition . I know I have most of the syntax down but it seems like I am missing something small , Thanks !
while ( len ( queue ) > 0 ) : queue.sort ( queue , lambda x : util.manhattanDistance ( curr , x ) )
Using lambda in Python
Python
I am following this template for configuring my custom vim with Nix . My vim-config/default.nix is as follows : Although there is a ( pkgs // { python = pkgs.python3 ; } ) override on line 5 , python3 is still not used ( when I run vim -- version it shows +python -python3 ) . Am I missing anything ?
{ pkgs } : let my_plugins = import ./plugins.nix { inherit ( pkgs ) vimUtils fetchFromGitHub ; } ; in with ( pkgs // { python = pkgs.python3 ; } ) ; vim_configurable.customize { name = `` vim '' ; vimrcConfig = { customRC = `` syntax on filetype on `` ... `` ; vam.knownPlugins = vimPlugins // my_plugins ; vam.pluginDic...
Overriding python with python3 in vim_configurable.customize
Python
I 'm trying to simulate a simple diffusion based on Fick 's 2nd law.for the first few time steps everything looks fine , but then I start to get high frequency noise , do to build-up from numerical errors which are amplified through the second derivative . Since it seems to be hard to increase the float precision I 'm ...
from pylab import *import numpy as npgridpoints = 128def profile ( x ) : range = 2. straggle = .1576 dose = 1 return dose/ ( sqrt ( 2*pi ) *straggle ) *exp ( - ( x-range ) **2/2/straggle**2 ) x = linspace ( 0,4 , gridpoints ) nx = profile ( x ) dx = x [ 1 ] - x [ 0 ] # use np.diff ( x ) if x is not uniformdxdx = dx**2f...
High frequency noise at solving differential equation
Python
The tracker in the lower-right corner ( highlighted in red ) reports y-values relative to the y-axis on the right . How can I get the tracker to report y-values relative to the y-axis on the left instead ? I know swapping y1 with y2 will make the tracker report y1-values , but this also places the y1 tickmarks on the r...
import matplotlib.pyplot as pltimport numpy as npnp.random.seed ( 6 ) numdata = 100t = np.linspace ( 0.05 , 0.11 , numdata ) y1 = np.cumsum ( np.random.random ( numdata ) - 0.5 ) * 40000y2 = np.cumsum ( np.random.random ( numdata ) - 0.5 ) * 0.002fig = plt.figure ( ) ax1 = fig.add_subplot ( 111 ) ax2 = ax1.twinx ( ) ax...
Controlling the tracker when using twinx
Python
I 've got a numpy array containing labels . I 'd like to get calculate a number for each label based on its size and bounding box . How can I write this more efficiently so that it 's realistic to use on large arrays ( ~15000 labels ) ?
A = array ( [ [ 1 , 1 , 0 , 3 , 3 ] , [ 1 , 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 2 , 2 ] , [ 1 , 0 , 2 , 2 , 2 ] ] ) B = zeros ( 4 ) for label in range ( 1 , 4 ) : # get the bounding box of the label label_points = argwhere ( A == label ) ( y0 , x0 ) , ( y1 , x1 ) = label_points.min ( 0 ) , label_points.max ( 0 ) + 1 # assu...
How can I improve the efficiency of this numpy loop
Python
I have two columns in a dataframe title and store containing text strings by which I want to subset the dataframe : When I try : I get : However , when I do this : I get : I do n't know what to make of this ! I tried copying the characters 'coffee-mate ' to do an equivalency test and got False . I have a feeling this i...
In [ 84 ] : 2631 coffee‑mate sugar free french ... jet.com 2633 nestle coffeemate natural bliss ... jet.com 2634 coffee‑mate liquid coffee creamer , ... jet.com 3085 coffee‑mate hazelnut ... jet.com df [ ( df.title.str.contains ( 'coffee-mate ' ) ) & ( df.store.str.contains ( 'jet.com ' ) ) ] Out [ 84 ] : Empty DataFra...
Exact same text strings not matching
Python
I came across the following code in ipython : What is the point of that ? Why not use just args or ' _ ' ?
oname = args and args or ' _ '
What is the purpose of `` a and a or b '' ?
Python
I currently process sections of a string like this : I want to avoid the overhead of generating these temporary substrings . Any ideas ? Perhaps a wrapper that somehow uses index offsets ? This is currently my bottleneck.Note that process ( ) is another python module that expects a string as input.Edit : A few people d...
for ( i , j ) in huge_list_of_indices : process ( huge_text_block [ i : j ] ) import timeimport stringtext = string.letters * 1000def timeit ( fn ) : t1 = time.time ( ) for i in range ( len ( text ) ) : fn ( i ) t2 = time.time ( ) print ' % s took % 0.3f ms ' % ( fn.func_name , ( t2-t1 ) * 1000 ) def test_1 ( i ) : ret...
how to avoid substrings
Python
I 'm developing an app in Google App Engine . One of my methods is taking never completing , which makes me think it 's caught in an infinite loop . I 've stared at it , but ca n't figure it out.Disclaimer : I 'm using http : //code.google.com/p/gaeunitlink text to run my tests . Perhaps it 's acting oddly ? This is th...
def _traverseForwards ( course , c_levels ) : `` ' Looks forwards in the dependency graph `` ' result = { 'nodes ' : [ ] , 'arcs ' : [ ] } if c_levels == 0 : return result model_arc_tails_with_course = set ( _getListArcTailsWithCourse ( course ) ) q_arc_heads = DependencyArcHead.all ( ) for model_arc_head in q_arc_head...
Python : why does this code take forever ( infinite loop ? )
Python
While learning java through an online course , I came across type conversions using helper classes . Eg : However they does n't explain how can I find the methods like do.intvalue ( ) if I am unaware of the existing methods . In Python , I can do a dir ( do ) and it would list all the methods . How can I check the same...
double d = 5.99 ; double do = new Double ( d ) ; int i = do.intvalue ( ) ;
What is the alternate of python 's dir ( ) in Java ?
Python
Please consider the below codeThis is my decorator method to decorate the setter method of property of other class , I want to set some attribute to the method . but it does n't allow me.I tried as belowGot the below error when ran thisWhat am I doing wrong , and how can I set some attribute to setter method .
class DataMember ( ) : def __init__ ( self , **args ) : self.default = { `` required '' : False , `` type '' : `` string '' , `` length '' : -1 } self.default.update ( args ) def __call__ ( self , func ) : # Here I want to set the attribute to method setattr ( func , `` __dbattr__ '' , self.default ) def validate ( obj...
how to get the attribute of setter method of property in python
Python
For some reason , pylint 1.6.4 ( astroid 1.4.9 ) does not like this : It complains : I find this surprising because : I think this is a bug in pylint.However , am I doing something wrong ? What is the `` pythonic '' way here ? PS . Yes , I know that the right way is to define my own exception subclass , but I have no c...
try : some_package.their_function ( ) except Exception as ex : if ex.message.startswith ( ... ) : ... error ( E1101 , no-member , feed_sentiment ) Class 'message ' has no 'startswith ' member > > > type ( Exception ( `` foo '' ) .message ) < type 'str ' > > > > Exception ( `` foo '' ) .message.startswith < built-in met...
pylint : Class 'message ' has no 'startswith ' member
Python
I have a specific situation in which I would like to do the following ( actually it is more involved than this , but I reduced the problem to the essence ) : which is a difficult way of writing : but in reality ' 1 ' , 'True ' and ' 2 ' are additional expressions that get evaluated and which require the variable ' e ' ...
> > > ( lambda e : 1 ) ( 0 ) if ( lambda e : True ) ( 0 ) else ( lambda e : 2 ) ( 0 ) True > > > 1 if True else 21 > > > ( lambda e : 1 ) ( 0 ) 1 > > > ( lambda e : True ) ( 0 ) True > > > ( lambda e : 2 ) ( 0 ) 2 > > > ( lambda e : 3 ) ( 0 ) if ( lambda e : True ) ( 0 ) else ( lambda e : 2 ) ( 0 ) 3 > > > ( lambda e :...
Unexpected output using Pythons ' ternary operator in combination with lambda
Python
I have a huge traits application , which is running into the limitations of enthought traits . Mainly performance issues when using the @ on_traits_changed decorator . It would be pretty straightforward to circumvent those issues with PyQt4 ( or PyQt5 ) signals , if i could do : Error stack : But from all i know that i...
from traits.api import *from PyQt4 import QtCoreclass Foo ( HasTraits , QtCore.QObject ) : pass TypeError Traceback ( most recent call last ) < ipython-input-3-ecdfa57492f7 > in < module > ( ) 2 from PyQt4 import QtCore 3 -- -- > 4 class Foo ( HasTraits , QtCore.QObject ) : 5 passC : \Python27\lib\site-packages\traits\...
Use HasTraits and PyQt signals in one class
Python
I 'm subclasssing OrderedDict ( Cpython , 2.7.3 ) to represent a datafile . __getitem__ pulls a field out of the datafile and sets it on the current instance similar to the code I 've posted below . now I would like to override __contains__ to return True if the field is in the dictionary or in the file on the disk sin...
from collections import OrderedDictdictclass = OrderedDictclass Foo ( dictclass ) : def __getitem__ ( self , key ) : try : return dictclass.__getitem__ ( self , key ) except KeyError : pass data = key*2 self [ key ] = data return data def __contains__ ( self , whatever ) : return dictclass.__contains__ ( self , whateve...
Why does overriding __contains__ break OrderedDict.keys ?
Python
On nearly every system , Python can give you human-readable , short representation of a floating point , not the 17 digit machine-precision : On an ARM926EJ-S , you do n't get the short representation : Python 2.7 apparently added this short representation to repr ( ) , for most systems : Conversions between floating-p...
Python 3.3.0 ( default , Dec 20 2014 , 13:28:01 ) [ GCC 4.8.2 ] on linuxType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > 0.10.1 > > > import sys ; sys.float_repr_style'short ' Python 3.3.0 ( default , Jun 3 2014 , 12:11:19 ) [ GCC 4.7.3 ] on linuxType `` help '' , `` copyri...
What causes Python 's float_repr_style to use legacy ?
Python
Let 's say I have a function : In IDLE if I call : It will print TrueIf I call : It will print FalseDo you know why ? I can not find an explanation in the Python documentation .
def get_tuple ( ) : return ( 1 , ) get_tuple ( ) is get_tuple ( ) ( 1 , ) is ( 1 , )
Why are these tuples returned from a function identical ?
Python
Yahoo finance updated their website . I had an lxml/etree script that used to extract the analyst recommendations . Now , however , the analyst recommendations are there , but only as a graphic . You can see an example on this page . The graph called Recommendation Trends on the right hand column shows the number of an...
url = 'https : //finance.yahoo.com/quote/'+code+'/analyst ? p='+codetree = etree.HTML ( urllib.request.urlopen ( url ) .read ( ) )
python lxml etree applet information from yahoo
Python
Every time I try to invoke a command that does not exist ( $ a , for example ) in the console ( /bin/bash ) the interpreter waits for a long time . And when I interrupt it ( ^C ) , I get a error message from Python interpreter . Instead of that , I expect it to tell me that the command was unrecognized . Why is this ha...
$ a^CTraceback ( most recent call last ) : File `` /usr/lib/python2.7/encodings/__init__.py '' , line 32 , in < module > root @ dell : /home/antonio/workspace/biz_index # from encodings import aliases File `` /usr/lib/python2.7/encodings/aliases.py '' , line 17 , in < module > `` '' '' KeyboardInterrupt^C
Unrecognized commands in bash are captured by the python interpreter
Python
I have data in the following format for people punching their work times in : I am looking to write a function in R or Python that will extract the total number of hours each person worked into 24 different buckets with each bucket as its own column . It would look something like this : So in the first case , the perso...
( dat < -data.frame ( Date = c ( `` 1/1/19 '' , `` 1/2/19 '' , `` 1/4/19 '' , `` 1/2/19 '' ) , Person = c ( `` John Doe '' , `` Brian Smith '' , `` Jane Doe '' , `` Alexandra Wakes '' ) , Time_In = c ( `` 1:15pm '' , `` 1:45am '' , `` 11:00pm '' , `` 1:00am '' ) , Time_Out = c ( `` 2:30pm '' , '' 3:33pm '' , '' 3:00am ...
Function that will extract hour values from one table and populate `` buckets '' of one hour increments in another table
Python
I want to find the pixels of a video stream that are static . This way I can detect logos and other non-moving items on my video stream . My idea behind the script is as follows : collect a number of equally-sized and graysized frames in a list called previousif a certain amount of frames is collected , call the functi...
import mathimport cv2import numpy as npvideo = cv2.VideoCapture ( 0 ) previous = [ ] n_of_frames = 200while True : ret , frame = video.read ( ) if ret : cropped_img = frame [ 0:150 , 0:500 ] gray = cv2.cvtColor ( cropped_img , cv2.COLOR_BGR2GRAY ) if len ( previous ) == n_of_frames : stdev_gray = np.std ( previous , ax...
Fastest way to detect the non/least-changing pixels of successive images
Python
I have been reading the tutorial of numpy i : j : k slicing at Scipy.org . After the second example , it says Assume n is the number of elements in the dimension being sliced . Then , if i is not given it defaults to 0 for k > 0 and n - 1 for k < 0 . If j is not given it defaults to n for k > 0 and -1 for k < 0 . If k ...
> > > import numpy as np > > > x = np.array ( [ 0,1,2,3,4 ] ) > > > x [ : :-1 ] array ( [ 4 , 3 , 2 , 1 , 0 ] ) > > > x [ : -1 : -1 ] array ( [ ] , dtype=int64 ) > > > x [ : - ( len ( x ) +1 ) : -1 ] array ( [ 4 , 3 , 2 , 1 , 0 ] ) > > > x [ : - ( len ( x ) +1 ) : -1 ] array ( [ 4 , 3 , 2 , 1 , 0 ] )
What is the default value of j in ( i : j : k ) numpy slicing ?
Python
Iam using python regex to extract certain values from a given string . This is my string : mystring.txtand I need to extract the course name and corresponding marks for a particular student . For example , I need the course and marks for MyName from the above string.I tried : But this works only if MyName is present un...
sometextsomemore text heresome other text course : course1Id Name marks____________________________________________________1 student1 652 student2 753 MyName 694 student4 43 course : course2Id Name marks____________________________________________________1 student1 842 student2 738 student7 994 student4 32 course : cou...
Python : regex findall
Python
I want to replace the None in the list with the previous variables ( for all the consecutive None ) . I did it with if and for ( multiple lines ) . Is there any way to do this in a single line ? i.e. , List comprehension , Lambda and or mapAnd my idea was using the list comprehension but I was not able to assign variab...
def none_replace ( ls ) : ret = [ ] prev_val = None for i in ls : if i : prev_val = i ret.append ( i ) else : ret.append ( prev_val ) return retprint ( 'Replaced None List : ' , none_replace ( [ None , None , 1 , 2 , None , None , 3 , 4 , None , 5 , None , None ] ) )
How to replace None in the List with previous value
Python
I have n data points in some arbitrary space and I cluster them.The result of my clustering algorithm is a partition represented by an int vector l of length n assigning each point to a cluster . Values of l ranges from 0 to ( possibly ) n-1.Example : Is a partition of n=7 points into 4 clusters : first three points ar...
l_1 = [ 1 1 1 0 0 2 6 ] l_2 = [ 2 2 2 9 9 3 1 ] l_3 = [ 2 2 2 9 9 3 3 ] c1 = bsxfun ( @ eq , l_1 , l_1 ' ) ; c2 = bsxfun ( @ eq , l_2 , l_2 ' ) ; l_1_l_2_are_identical = all ( c1 ( : ) ==c2 ( : ) ) ;
How to determine if two partitions ( clusterings ) of data points are identical ?
Python
I found this piece of code in the subprocess documentation , where one process 's stdout is being piped into another process : And I 'm confused by that stdout.close ( ) call . Surely closing the stdout handle prevents the process from producing any output ? So I ran an experiment , and to my surprise the process was n...
p1 = Popen ( [ `` dmesg '' ] , stdout=PIPE ) p2 = Popen ( [ `` grep '' , `` hda '' ] , stdin=p1.stdout , stdout=PIPE ) p1.stdout.close ( ) # Allow p1 to receive a SIGPIPE if p2 exits.output = p2.communicate ( ) [ 0 ] from subprocess import Popen , PIPEp1 = Popen ( [ 'python ' , '-c ' , 'import time ; time.sleep ( 5 ) ;...
Why can a subprocess still write to stdout after it 's been closed ?
Python
I 'm looking for solution to my problem . At the moment I have two list of elements : What I want to achieve is to create for loop which wil give me following output : Nested for loop doe n't work for me : Is there any other way to generate this output ?
column_width = [ `` 3 '' , `` 3 '' , `` 6 '' , `` 8 '' , `` 4 '' , `` 4 '' , `` 4 '' , `` 4 '' ] fade = [ `` 100 '' , `` 200 '' , `` 300 '' ] column-3-fade-100column-3-fade-200column-6-fade-300column-8-fade-100column-4-fade-200 ... for i in fade : for c in column_width_a : print ( `` column- { 0 } -fade- { 1 } '' .form...
For loop using more than one list in Python
Python
I 'm trying to implement the R package TSdist from python jupyter notebook . This gives me an NA and I got a warning : /usr/lib64/python3.4/site-packages/rpy2/rinterface/init.py:186 : RRuntimeWarning : Error : The series must be univariate vectors warnings.warn ( x , RRuntimeWarning ) Any ideas of how to properly imple...
import rpy2.robjects.numpy2rifrom rpy2.robjects.packages import importrrpy2.robjects.numpy2ri.activate ( ) R = rpy2.robjects.r # # load in package TSdist = importr ( 'TSdist ' ) # # t , c are two series dist = TSdist.ERPDistance ( t.values , c.values , g=0 , sigma =30 ) # # dist is a R Boolean vector with one valuedist...
Implement R package TSdist from python