lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Python
I am not a python guy and I am trying to understand some python code . I wonder what the last line of below code does ? Is that kind of multiple objects returned ? or list of 3 objects returned ?
req = SomeRequestBean ( ) req.setXXX ( xxx ) req.YYY = int ( yyy ) device , resp , fault = yield req # < -- -- - What does this mean ?
What does this python syntax mean ?
Python
How can I read a camera and display the images at the cameras frame rate ? I want to continuously read images from my webcam , ( do some fast preprocessing ) and then display the image in a window . This should run at the frame rate , that my webcam provides ( 29 fps ) .It seems like the OpenCV GUI and Tkinter GUI is t...
import cv2import timedef main ( ) : cap = cv2.VideoCapture ( 0 ) window_name = `` FPS Single Loop '' cv2.namedWindow ( window_name , cv2.WINDOW_NORMAL ) start_time = time.time ( ) frames = 0 seconds_to_measure = 10 while start_time + seconds_to_measure > time.time ( ) : success , img = cap.read ( ) img = img [ : , : :-...
Python3 process and display webcam stream at the webcams fps
Python
I have some experience with socket programming using the Berkeley socket API in C. Generally , any socket programming requires a strategy that enables the receiving socket to know how much data it should receive . This can be accomplished with either header length fields , or delimiter characters . Generally , I prefer...
uint16_t bytes_to_receive ; recv ( sock , & bytes_to_receive , sizeof ( bytes_to_receive ) , 0 ) ; bytes_to_receive = ntohs ( bytes_to_receive ) ; // Now receive 'bytes_to_receive ' bytes ...
Idiom for socket receive in Python
Python
I have a simple app with a class representing a data structure and a class for GUI . I use a logger inside the first class : etc.The GUI consists in one Tkinter window with a Listbox.How can I direct the logs to the listbox ? I would like to see the messages populate the list instead as they get logged instead of showi...
class A ( object ) : def __init__ ( self ) : self.logger = logging.getLogger ( self.__class__.__name__ ) self.logger.info ( 'creating new A object ' )
how to direct python logger to Tkinker 's Listbox ?
Python
Is there a limit to the size of a Python module ? It seems to me that the Python bytecode instruction POP_JUMP_IF_FALSE takes a 1-byte operand , telling it the instruction index to jump to.Quoting some of the relevant CPython code from ceval.c ( comment mine ) : Does this mean a Python module can not contain more than ...
case TARGET ( POP_JUMP_IF_FALSE ) : { PREDICTED ( POP_JUMP_IF_FALSE ) ; PyObject *cond = POP ( ) ; int err ; if ( cond == Py_True ) { Py_DECREF ( cond ) ; FAST_DISPATCH ( ) ; } if ( cond == Py_False ) { Py_DECREF ( cond ) ; JUMPTO ( oparg ) ; # < -- - this FAST_DISPATCH ( ) ; }
Is there a limit to the size of a Python module ?
Python
I 'm trying to implement the quicksort algorithm choosing the pivot as the rightmost element as described in Cormey et al. , Introduction to Algorithms : Here is my Python implementation : However , if I try to test it like so : I get an array which is not sorted but just partitioned once : ( That is , all the elements...
def partition ( A , p , r ) : pivot = A [ r ] i = p - 1 for j in range ( p , r-1 ) : if A [ j ] < pivot : i += 1 A [ i ] , A [ j ] = A [ j ] , A [ i ] A [ i+1 ] , A [ r ] = A [ r ] , A [ i+1 ] return i+1def quicksort ( A , p , r ) : if p < r : q = partition ( A , p , r ) quicksort ( A , p , q-1 ) quicksort ( A , q+1 , ...
What 's wrong with this implementation of quicksort ?
Python
Using google app engine : If two different users request the webpage on two different machine , two individual instances of the server will be invoked ? Or just one instance of the server is running all the time which handle all the requests ? How about if one user open the webpage twice in the same browser ? Edit : Ac...
# more code ahead not shownapplication = webapp.WSGIApplication ( [ ( '/ ' , Home ) ] , debug=True ) def main ( ) : run_wsgi_app ( application ) if __name__ == `` __main__ '' : main ( ) class User ( db.Model ) : email = db.EmailProperty ( ) nickname = db.StringProperty ( )
Does Google App Engine run one instance of an app per one request ? or for all requests ?
Python
I 'm using python 's multiprocessing library to create several processes.I want them to run for some duration and then if they have not completed , terminate them.A bad way to do it is as follows ( bad because if the processes finish faster than DURATION , it still waits for all of DURATION ) : Another bad way to do it...
from multiprocessing import Processprocesses = [ Process ( target=function ) for function in FUNCTIONS ] for p in processes : p.start ( ) DURATION = 3600 from time import sleepsleep ( duration ) for p in processes : p.join ( 0 ) p.terminate ( ) for p in processes : p.join ( DURATION ) p.terminate ( )
Join a group of python processes with a timeout
Python
I am using a decorator : and a function : But when using doctest module ( python mycode.py -v ) : Python ca n't find the test in doc-string . I know that is a problem with decorator . But how can I fix it ? PS : functools.update_wrapper ( self , func ) is not working !
class Memoized ( object ) : __cache = { } def __init__ ( self , func ) : self.func = func key = ( func.__module__ , func.__name__ ) # print key if key not in self.__cache : self.__cache [ key ] = { } self.mycache = self.__cache [ key ] def __call__ ( self , *args ) : try : return self.mycache [ args ] except KeyError :...
How to use doctest with a decorated function in python ?
Python
I [ surely re ] invented this [ wheel ] when I wanted to compute the union and the intersection and diff of two sets ( stored as lists ) at the same time . Initial code ( not the tightest ) : Then I realized that I should use 00 , 01 , 10 , and 11 instead of -1 , 1 , 0 , ... So , a bit at position n indicates membershi...
dct = { } for a in lst1 : dct [ a ] = 1for b in lst2 : if b in dct : dct [ b ] -= 1 else : dct [ b ] = -1union = [ k for k in dct ] inter = [ k for k in dct if dct [ k ] == 0 ] oneminustwo = [ k for k in dct if dct [ k ] == 1 ] twominusone = [ k for k in dct if dct [ k ] == -1 ]
the official name of this programming approach to compute the union and the intersection
Python
My goal is to accurately measure the diameter of a hole from a microscope . Workflow is : take an image , process for fitting , fit , convert radius in pixels to mm , write to a csvThis is an output of my image processing script used to measure the diameter of a hole . I 'm having an issue where it seems like my circle...
( thresh , blackAndWhiteImage0 ) = cv2.threshold ( img0 , 100 , 255 , cv2.THRESH_BINARY ) # make black + white median0 = cv2.medianBlur ( blackAndWhiteImage0 , 151 ) # get rid of noise circles0 = cv2.HoughCircles ( median0 , cv2.HOUGH_GRADIENT,1 , minDist=5 , param1= 25 , param2=10 , minRadius=min_radius_small , maxRad...
Open CV trivial circle detection -- how to get least squares instead of a contour ?
Python
I 'd like to do the following : Why ? Primarily as insurance against the late-binding closure gotcha as described elsewhere . Namely : And whenever I get warned about a free variable , I would either add an explicit exception ( in the rare case that I would want this behaviour ) or fix it like so : Then the behaviour b...
for every nested function f anywhere in this_py_file : if has_free_variables ( f ) : print warning > > > def outer ( ) : ... rr = [ ] ... for i in range ( 3 ) : ... def inner ( ) : ... print i ... rr.append ( inner ) ... return rr ... > > > for f in outer ( ) : f ( ) ... 222 > > > ... def inner ( i=i ) :
Warn for every ( nested ) function with free variables ( recursively )
Python
Hi everyone i 'm trying to fit a curve through points using python , however I have not been succed , i 'm a beginner using python and what i found it did n't help me.I have a set of data and I want to analyse which line describes it best ( polynomials of different orders ) .In numpy and for polynomial fitting there is...
File `` plantilla.py '' , line 28 , in < module > polinomio=np.polyfit ( x , y,5 ) File `` /usr/lib/python2.7/dist-packages/numpy/lib/polynomial.py '' , line 581 , in polyfitc , resids , rank , s = lstsq ( lhs , rhs , rcond ) File `` /usr/lib/python2.7/dist-packages/numpy/linalg/linalg.py '' , line 1867 , in lstsq0 , w...
Fit a curve through points using python
Python
I am so confused with different indexing methods using iloc in pandas . Let say I am trying to convert a 1-d Dataframe to a 2-d Dataframe . First I have the following 1-d DataframeAnd I am going to convert that into a 2-d Dataframe with the size of 2x4 . I start by preseting the 2-d Dataframe as follow : Then I use for...
a_array = [ 1,2,3,4,5,6,7,8 ] a_df = pd.DataFrame ( a_array ) .T b_df = pd.DataFrame ( columns=range ( 4 ) , index=range ( 2 ) ) for i in range ( 2 ) : b_df.iloc [ i , : ] = a_df.iloc [ 0 , i*4 : ( i+1 ) *4 ] 0 1 2 30 1 2 3 41 NaN NaN NaN NaN 0 1 2 30 1 2 3 41 5 6 7 8
Why does assigning with [ : ] versus iloc [ : ] yield different results in pandas ?
Python
I am stuck with a ( hopefully ) simple problem.My aim is to plot a dashed line interrupted with data ( not only text ) .As I only found out to create a dashed line via linestyle = 'dashed ' , any help is appreciated to put the data between the dashes.Something similar , regarding the labeling , is already existing with...
line_string2 = '-10 ' + u '' \u00b0 '' + '' C '' l , = ax1.plot ( T_m10_X_Values , T_m10_Y_Values ) pos = [ ( T_m10_X_Values [ -2 ] +T_m10_X_Values [ -1 ] ) /2. , ( T_m10_Y_Values [ -2 ] +T_m10_Y_Values [ -1 ] ) /2 . ] # transform data points to screen spacexscreen = ax1.transData.transform ( zip ( T_m10_Y_Values [ -2 ...
Plot dashed line interrupted with data ( similar to contour plot )
Python
I 'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested . For example : would return the nested dict : This could be used to turn a set of values with hierarchical keys into a tree : I could write some FORTRANish code to do the conversion using brute force and multiple lo...
dtree ( [ `` a '' , `` b '' , `` c '' ] ) = 42 ordtree ( `` a/b/c '' .split ( sep='/ ' ) ) = 42 { `` a '' : { `` b '' : { `` c '' : 42 } } } dtree ( { `` a/b/c '' : 10 , `` a/b/d '' : 20 , `` a/e '' : `` foo '' , `` a/f '' : False , `` g '' : 30 } ) would result in : { `` a '' : { `` b '' : { `` c '' : 10 , `` d '' : 2...
Is there a pythonic way to process tree-structured dict keys ?
Python
I have a set of document objects and label objects , and I want those two objects to be linked . It 's a typical many-to-many relationship . I have the following code : Models.py : Views.py : When I upload a document , it gets added to the database , however no labels are being created or associated with the document ....
class Document ( models.Model ) : title = models.CharField ( max_length=50 , unique=True ) title_slug = models.SlugField ( max_length=50 , unique=True , editable=False ) labels = models.ManyToManyField ( 'Label ' ) def save ( self , *args , **kwargs ) : self.title_slug = slugify ( self.title ) super ( Document , self )...
When and how is a many-to-many relationship created when saving a model ?
Python
When I run it on cpython 3.6 , the following program prints hello world a single time and then spins forever.As a side note , uncommenting the await asyncio.sleep ( 0 ) line causes it to print hello world every second , which is understandable.This behavior ( printing hello world a single time ) makes sense to me , bec...
import asyncioasync def do_nothing ( ) : # await asyncio.sleep ( 0 ) passasync def hog_the_event_loop ( ) : while True : await do_nothing ( ) async def timer_print ( ) : while True : print ( `` hello world '' ) await asyncio.sleep ( 1 ) loop = asyncio.get_event_loop ( ) loop.create_task ( timer_print ( ) ) loop.create_...
When will/wo n't Python suspend execution of a coroutine ?
Python
I 'm using a little app for Python called Pythonista which allows me to change text colour on things every few seconds . Here 's an example of how I 've been trying to go about doing this in an infinite loop ; The issue here is that this freezes my program because Python keeps sleeping over and over , and I never see a...
while True : v [ 'example ' ] .text_color = 'red ' time.sleep ( 0.5 ) v [ 'example ' ] .text_color = 'blue ' time.sleep ( 0.5 ) # and so on..
Python : Do something then sleep , repeat
Python
I 'm trying to compile a quick extension for a module that was pre-compiled on install ( .pyd ) . Below is a simplistic example of what i 'm trying to do . Given foo.pyd : baz.pxdbaz.pyxsetup.pyI 've tried many variations of the above , to no avail .
from foo.bar cimport Barcdef class Baz ( Bar ) : pass cdef class Baz ( Bar ) : def __init__ ( self , *a , **k ) : ... from distutils.core import setupfrom Cython.Build import cythonizefrom distutils.extension import Extensionextensions = [ Extension ( 'baz ' , [ 'baz.pyx ' , ] , libraries= [ 'foo.pyd ' , ] ) ] setup ( ...
How do i work with pre-compiled libraries in cython ?
Python
Consider the following class : I use it to calculate the distance between two elements of a vector . I basically create one instance of that class for every dimension of the vector that uses this distance measure ( there are dimensions that use other distance measures ) . Profiling reveals that the __call__ function of...
class SquareErrorDistance ( object ) : def __init__ ( self , dataSample ) : variance = var ( list ( dataSample ) ) if variance == 0 : self._norm = 1.0 else : self._norm = 1.0 / ( 2 * variance ) def __call__ ( self , u , v ) : # u and v are floats return ( u - v ) ** 2 * self._norm
Suggestions on how to speed up a distance calculation
Python
For example , here is an or expression : Here is the compiled C code : Why not output this ? is the goto version faster than || ?
c = f1 == 0 or f1 - f0 > th __pyx_t_24 = ( __pyx_v_f1 == 0 ) ; if ( ! __pyx_t_24 ) { } else { __pyx_t_23 = __pyx_t_24 ; goto __pyx_L5_bool_binop_done ; } __pyx_t_24 = ( ( __pyx_v_f1 - __pyx_v_f0 ) > __pyx_v_th ) ; __pyx_t_23 = __pyx_t_24 ; __pyx_L5_bool_binop_done : ; __pyx_v_c = __pyx_t_23 ; __pyx_v_c = ( __pyx_v_f1 =...
Why do n't cython compile logic or to ` || ` expression ?
Python
I am a bit confused how Django handles '_id ' property when we use ORM with some models that use foreign key.For example : And when I use ORM with 'filter ' I can easily use something like : And Django kind of 'see ' that I refer to 'id ' , but when I use exacly the same line of code , but with 'create ' instead of 'fi...
class CartItem ( models.Model ) : user = models.ForeignKey ( 'accounts.CustomUser ' , related_name='carts ' , on_delete=models.CASCADE , verbose_name='User ' ) product = models.ForeignKey ( 'pizza.Product ' , related_name='carts ' , on_delete=models.CASCADE , verbose_name=_ ( 'Product ' ) ) quantity = models.SmallInteg...
Using '_id ' in Django
Python
I 'm looking into these two related questions : here and here.I am seeing a behavior I do not expect in Python 3.6 , which differs from behavior using plain reload in Python 2.7 ( and 3.4 ) . Namely , it seems that a module attribute that would be populated during module initialization or when re-exec-ing the module du...
In [ 1 ] : import importlibIn [ 2 ] : import mathIn [ 3 ] : del math.cosIn [ 4 ] : math.cos -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -AttributeError Traceback ( most recent call last ) < ipython-input-4-05b06e378197 > in < module > ( ) -- -- > 1 math...
Should importlib.reload restore a deleted attribute in Python 3.6 ?
Python
BACKGROUNDWhen playing around , I often write simple recursive functions looking something like : ( For example , when computing weighted edit distances , or evaluating recursively defined mathematical formulas . ) I then use a memoizing decorator to cache the results automatically.PROBLEMWhen I try something like f ( ...
def f ( a , b ) : if a > =0 and b > =0 : return min ( f ( a-1 , b ) , f ( b , a-1 ) ) # + some cost that depends on a , b else : return 0 RuntimeError : maximum recursion depth exceeded
How can I write a Python decorator to increase stackdepth ?
Python
I have the code for calculating the sum of square root as above.By using cython -a , I got the result as in the picture . The cython code interacts with python at function call np.sqrt ( i ) , and there is no improvement compared to pure python code . I do n't know if I have done something wrong in specifying the type ...
% % cythonimport numpy as npcimport numpy as npdef cy_sum ( int n ) : cdef double s=0 cdef int i for i in range ( n ) : s += np.sqrt ( i ) return s
Call np.sqrt in cython
Python
I have the following classes : In words , I 'm trying to create a relationship maximum_a with the largest a_id of all the A 's pointed to by a given B. I specifically want this to be a relationship so that I can prefetch it with joinedload to avoid a case where we now have O ( N ) queries.When I try to preload the maxi...
class A : a_id = Column ( Integer , primary_key=True ) a_remote = Column ( UnicodeText ) class B : b_id = Column ( Integer , primary_key=True ) foreign_to_a = Column ( UnicodeText ) maximum_a = relationship ( A , primaryjoin=lambda : and_ ( remote ( a_remote ) == foreign ( foreign_to_a ) , A.a_id = select ( [ func.max ...
Correlating a SQLAlchemy relationship with an awkward join
Python
I have code executing in a subprocess that is supposed to raise an exception.I would like to raise the same exception in the main process when the exception is returned from the subprocess ( preferably while preserving the stack trace ) but I am not sure how to do this.I capture the stderr from the subprocess just fine...
import subprocessexample=subprocess.Popen ( [ `` python '' , '' example.py '' ] , stdout = subprocess.PIPE , stderr = subprocess.PIPE ) return_obj , return_error = example.communicate ( ) if return_error : # replace with error from subprocess print `` Should raise `` , NameError ( 'HiThere ' ) raise TypeError ( 'Wrong ...
Reraise exception from subprocess
Python
I have the following code : I expect it to throw an exception because of shape mismatch . But pandas silently accepted the assignment : y 's first column is assigned to x.Is this an intentional design ? If yes , what is the rationale behind ? I tried both pandas 0.21 and 0.23.Thanks for those who tried to help . Howeve...
x = pd.DataFrame ( np.zeros ( ( 4 , 1 ) ) , columns= [ ' A ' ] ) y = np.random.randn ( 4 , 2 ) x [ ' A ' ] = y
Unexpected behavior in assigning 2d numpy array to pandas DataFrame
Python
I am a complete beginner in Python , and would like to start learning it by doing . Namely , I 'd love to correct some EXIF information in a huge bunch of family photos I have . To start with , I want to just get this information out of JPEG files properly.Some of them have a title written in EXIF . It can be obtained ...
import pyexiv2metadata = pyexiv2.ImageMetadata ( filename ) metadata.read ( ) title = metadata [ 'Exif.Image.XPTitle ' ] ` МиР» ой МамуР» е от Майи , 11 ÑÐ½Ð²Ð°Ñ€Ñ 1944. ` < Exif.Image.XPTitle [ Byte ] = 28 4 56 4 59 4 62 4 57 4 32 0 28 4 48 4 60 4 67 4 59 4 53 4 32 0 62 4 66 4 32 0 28 4 48 4 57 4 56 4...
Python : extract Cyrillic string from EXIF
Python
I 'm trying to use rolling and apply function to print windowbut I got the error says My code is following My data is like How should I slove this error ? I did n't find similar questions on this error Thanks !
File `` pandas/_libs/window.pyx '' , line 1649 , in pandas._libs.window.roll_genericTypeError : must be real number , not NoneType def print_window ( window ) : print ( window ) print ( '================== ' ) def example ( ) : df = pd.read_csv ( 'window_example.csv ' ) df.rolling ( 5 ) .apply ( print_window ) number s...
Rolling apply function must be real number , not Nonetype
Python
I 'm trying to wrap the LAPACK function dgtsv ( a solver for tridiagonal systems of equations ) using Cython.I came across this previous answer , but since dgtsv is not one of the LAPACK functions that are wrapped in scipy.linalg I do n't think I can use this particular approach . Instead I 've been trying to follow th...
ctypedef int lapack_intcdef extern from `` lapacke.h '' nogil : int LAPACK_ROW_MAJOR int LAPACK_COL_MAJOR lapack_int LAPACKE_dgtsv ( int matrix_order , lapack_int n , lapack_int nrhs , double * dl , double * d , double * du , double * b , lapack_int ldb ) # ! pythoncimport cythonfrom lapacke cimport *cpdef TDMA_lapacke...
Wrapping a LAPACKE function using Cython
Python
Just for the sake of curiosity I wan na know this..I know scope of inner function is limited to outer function body only , but still is there any way so that we can access the inner function variable outside its scope or call the inner function outside its scope ?
In [ 7 ] : def main ( ) : ... : def sub ( ) : ... : a=5 ... : print a ... : In [ 8 ] : main ( ) In [ 9 ] : main.sub ( ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -AttributeError Traceback ( most recent call last ) /home/dubizzle/webapps/django/dubizzl...
Can we access inner function outside its scope of outer function in python using outer function ?
Python
I have seen a lot of cases missing values are either filled by mean or medians . I was wondering how can we fill misssing values with frequency.Here is my setup : Is there a generic way it can be done so ? My attemptNOTEThis example is only for binary values , I was looking for categorical values having more than two c...
import numpy as npimport pandas as pddf = pd.DataFrame ( { 'sex ' : [ 1,1,1,1,0,0 , np.nan , np.nan , np.nan ] } ) df [ 'sex_fillna ' ] = df [ 'sex ' ] .fillna ( df.sex.mode ( ) [ 0 ] ) print ( df ) sex sex_fillna0 1.0 1.0 We have 4 males1 1.0 1.02 1.0 1.03 1.0 1.04 0.0 0.0 we have 2 females , so ratio is 25 0.0 0.06 N...
Python fill missing values according to frequency
Python
I 've found the following puzzling behavior with NumPy and a custom dtype for an ndarray : Now , this comes back as containing not [ 1 . 1 . 1 . ] as I would expect , but instead [ 1 . 0 . 0 . ] , only performing the assignment on the first coordinate . I can get around this by performing the assignment coordinate-wise...
import numpy as np # Make a custom dtype with a single triplet of floats ( my actual dtype has other # components , but this suffices to demonstrate the problem.dt = np.dtype ( [ ( ' a ' , np.float64 , 3 ) ] ) # Make a zero array with this dtype : points = np.zeros ( ( 4 , 4 ) , dtype=dt ) # Try to edit an entry : poin...
NumPy : array assignment issue when using custom dtype
Python
List r : If I do a reverse sort : What I want is to start with Upper case elements and than the lower case elements.Is there an easy way in Python3 to sort the list as I want ?
r= [ [ 'Paris ' , 10 ] , [ 'amsterdam ' , 5 ] , [ 'London ' , 18 ] , [ 'london ' , 15 ] , [ 'Berlin ' , 2 ] , [ 'Stockholm ' , 4 ] , [ 'oslo ' , 14 ] , [ 'helsinki ' , 16 ] , [ 'Zurich ' , 17 ] ] sorted ( r , reverse=True ) [ [ 'oslo ' , 14 ] , [ 'london ' , 15 ] , [ 'helsinki ' , 16 ] , [ 'amsterdam ' , 5 ] , [ 'Zuric...
How to Reverse Sort a nested list starting with Uppercase entries ?
Python
I like being able to measure performance of the python functions I code , so very often I do something similar to this ... Yes , I know you are supposed to measure performance with timeit , but this works just fine for my needs , and allows me to turn this information on and off for debugging very smoothly.That code of...
import timedef some_function ( arg1 , arg2 , ... , argN , verbose = True ) : t = time.clock ( ) # works best in Windows # t = time.time ( ) # apparently works better in Linux # Function code goes here t = time.clock ( ) - t if verbose : print `` some_function executed in '' , t , '' sec . '' return return_val some_func...
Function Decorators
Python
I 'm trying to create a function that returns a numpy.array with n pseudo-random uniformly distributed numbers between 0 and 1 . The details of the method used can be found here : https : //en.wikipedia.org/wiki/Linear_congruential_generatorSo far , it works great . The only problem is that each new value is calculated...
import numpy as npimport timedef unif ( n ) : m = 2**32 a = 1664525 c = 1013904223 result = np.empty ( n ) result [ 0 ] = int ( ( time.time ( ) * 1e7 ) % m ) for i in range ( 1 , n ) : result [ i ] = ( a*result [ i-1 ] +c ) % m return result / m
How to optimize a for loop that uses consecutive values with Numpy ?
Python
I 'm trying to use scikit-learn 's DBSCAN implementation to clusterize a bunch of documents . First I create the TF-IDF matrix using scikit-learn 's TfidfVectorizer ( it 's a 163405x13029 sparse matrix of type numpy.float64 ) . Then I try to clusterize specific subsets of this matrix . Things work fine when the subset ...
ValueError Traceback ( most recent call last ) < ipython-input-1-73ee366d8de5 > in < module > ( ) 193 # use descriptions to clusterize items 194 ncm_clusterizer = DBSCAN ( ) -- > 195 ncm_clusterizer.fit_predict ( tfidf [ idxs ] ) 196 idxs_clusters = list ( zip ( idxs , ncm_clusterizer.labels_ ) ) 197 for e in idxs_clus...
`` could not convert integer scalar '' error when using DBSCAN
Python
I would try to post a minimal working example , but unfortunately this problem just requires a lot of pieces so I have stripped it down best I can.First of all , I 'm using a simple script that simulates pressing keys through a function call . This is tweaked from here.I stored this in a file named keyPress.py.Using th...
import ctypesSendInput = ctypes.windll.user32.SendInputPUL = ctypes.POINTER ( ctypes.c_ulong ) class KeyBdInput ( ctypes.Structure ) : _fields_ = [ ( `` wVk '' , ctypes.c_ushort ) , ( `` wScan '' , ctypes.c_ushort ) , ( `` dwFlags '' , ctypes.c_ulong ) , ( `` time '' , ctypes.c_ulong ) , ( `` dwExtraInfo '' , PUL ) ] c...
Key echo in Python in separate thread does n't display first key stroke
Python
I have a pandas dataframe : I would like to convert this to the following : How can I do it ? Thanks a lot .
apple banana carrot diet coke1 1 1 00 1 0 01 0 0 01 0 1 10 1 1 00 1 1 0 [ [ 'apple ' , 'banana ' , 'carrot ' ] , [ 'banana ' ] , [ 'apple ' ] , [ 'apple ' , 'carrot ' , 'diet coke ' ] , [ 'banana ' , 'carrot ' ] , [ 'banana ' , 'carrot ' ] ]
Convert pandas dataframe to a list
Python
I 'm trying to port some python code to cython and I 'm encountering some minor problems.Below you see a code snippet ( simplified example ) of the code.I do n't understand why the inner-most loop does not fully translate to C code ( i.e . the last line , celle [ l ] = ... ) , see output from cython -a feedback : What ...
cimport numpy as npcimport cython @ cython.boundscheck ( False ) # turn of bounds-checking for entire function @ cython.wraparound ( False ) @ cython.nonecheck ( False ) def Interpolation ( cells , int nmbcellsx ) : cdef np.ndarray [ float , ndim=1 ] celle cdef int cellnonzero cdef int i , l for i in range ( nmbcellsx ...
numpy array with cython
Python
First the code : Every time I do .append ( ) on ListStore object I get such error : Of course the ListStore object is ( str , str , str , boolean ) type . The error message is ridiculous , can anyone tell what 's going on ?
from gi.repository import Gtk , GtkSource , GObjectimport os.pathimport shelveclass MusicCollection ( object ) : def __init__ ( self ) : self.builder = Gtk.Builder ( ) self.glade_file = 'music.glade ' GObject.type_register ( GtkSource.View ) self.builder.add_from_file ( self.glade_file ) self.window = self.builder.get_...
Adding a row to ListStore not working - ridiculous exception
Python
I am using an exported classification model from Google AutoML Vision , hence I only have a saved_model.pb and no variables , checkpoints etc . I want to load this model graph into a local TensorFlow installation , use it for inference and continue training with more pictures . Main questions : Is this plan possible , ...
import tensorflow as tfimport numpy as npimport base64path_img = `` input/testimage.jpg '' path_mdl = `` input/model '' # input to network expected to be base64 encoded imagewith io.open ( path_img , 'rb ' ) as image_file : encoded_image = base64.b64encode ( image_file.read ( ) ) .decode ( 'utf-8 ' ) # reshaping to ( 1...
How to do Inference and Transfer Learning with TensorFlow Frozen GraphDef ( single saved_model.pb ) from Google AutoML Vision Classification
Python
I am trying to make the following template snippet work : As you can see name is a variable that I need to expand into string before passing it to the url built-in tag.Unfortunately the aforementioned template snippet results in the following exception : Any ideas or alternative methods on how to achieve this ?
< ul > { % for name , label in entries.items % } < li > < a href= '' { % url name % } '' > { { label } } < /a > < /li > { % endfor % } < /ul > Exception Type : TemplateSyntaxErrorException Value : Caught NoReverseMatch while rendering : Reverse for 'name ' with arguments ' ( ) ' and keyword arguments ' { } ' not found ...
django templates : how to expand a variable into the string argument for the built-in tag ` url `
Python
I 'm revisiting a question I posted some time ago posted here : LinkedList - Insert Between Nodes not InsertingI 'm having a hard time figuring out how to insert a node in between other nodes in a singly linked list . In the solution above I wrote an additional getNodes method that turns data into a node and pushes it ...
class Node ( object ) : def __init__ ( self , data ) : self.data = data self.nextNode = None def __str__ ( self ) : return str ( self.data ) class LinkedList ( object ) : def __init__ ( self ) : self.head = None self.tail = None def insert_in_between2 ( self , data , prev_data ) : # instantiate the new node new_node = ...
How to Insert a Node between another node in a Linked List ?
Python
I am trying to connect from a python app with pyodbc to a MS SQL server . I have pyodbc and unixODBC installed and I tried to install the MS driver for linux . I think the issue is that the MS driver has missing dependencies but as near as I can tell the dependencies are installed . Because the Microsoft driver was not...
ldd /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.0.so.0.0 /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.0.so.0.0 : /lib64/libstdc++.so.6 : version ` GLIBCXX_3.4.20 ' not found ( required by /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.0.so.0.0 ) /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.0.so.0.0 : /lib64/libs...
Linker errors with libmsodbcsql-13.0.so.0.0 preventing pyODBC to MS SQL connection . CentOS 7
Python
I have an class which decorates some methods using a decorator from another library . Specifically , the class subclasses flask-restful resources , decorates the http methods with httpauth.HTTPBasicAuth ( ) .login_required ( ) , and does some sensible defaults on a model service . On most subclasses I want the decorato...
def auth_required ( fn ) : def new_fn ( *args , **kwargs ) : print ( 'Auth required for this resource ... ' ) fn ( *args , **kwargs ) return new_fnclass Resource : name = None @ auth_required def get ( self ) : self._get ( ) def _get ( self ) : print ( 'Getting % s ' % self.name ) class Eggs ( Resource ) : name = 'Eggs...
Is there a pythonic way to skip decoration on a subclass ' method ?
Python
I 'm trying to extract a pattern that we are using in our code base into a more generic , reusable construct . However , I ca n't seem to get the generic type annotations to work with mypy.Here 's what I got : I commented out some code that works but does n't quite fulfill my needs . Basically I want that the DemoMsgQu...
from abc import ( ABC , abstractmethod ) import asyncioimport contextlibfrom typing import ( Any , Iterator , Generic , TypeVar ) _TMsg = TypeVar ( '_TMsg ' ) class MsgQueueExposer ( ABC , Generic [ _TMsg ] ) : @ abstractmethod def subscribe ( self , subscriber : 'MsgQueueSubscriber [ _TMsg ] ' ) - > None : raise NotIm...
Get mypy to accept subtype of generic type as a method argument
Python
The mathematical problem is : The expression within the sums is actually much more complex than the one above , but this is for a minimal working example to not over-complicate things . I have written this in Python using 6 nested for loops and as expected it performs very badly ( the true form performs badly and needs...
import numpy as npdef func1 ( a , b , c , d ) : `` ' Minimal working example of multiple summation `` ' B = 0 for ai in range ( 0 , a ) : for bi in range ( 0 , b ) : for ci in range ( 0 , c ) : for di in range ( 0 , d ) : for ei in range ( 0 , ai+bi ) : for fi in range ( 0 , ci+di ) : B += ( 2 ) ** ( ei-fi-ai-ci-di+1 )...
Vectorize a 6 for loop cumulative sum in python
Python
Is there a substantial difference in Python 3.x between : andMy question is n't particular to the above usage , but is more general or essential - is this syntactical difference working in a different way , even though the result is the same ? Is there a logical difference ? Are there tasks where one is more appropriat...
for each_line in data_file : if each_line.find ( `` : '' ) ! = -1 : # placeholder for code # more placeholder for each_line in data : if not each_line.find ( `` : '' ) == -1 : # placeholder for code # more placeholder
Is there a logical difference between 'not == ' and ' ! = ( without is )
Python
A very nice tool to check for dead links ( e.g . links pointing to 404 errors ) is wget -- spider . However , I have a slightly different use-case where I generate a static website , and want to check for broken links before uploading . More precisely , I want to check both : Relative links like < a href= '' some/file....
python3 -m http.server & pid= $ ! sleep .5error=0wget -- spider -nd -nv -H -r -l 1 http : //localhost:8000/index.html || error= $ ? kill $ pidwait $ pidexit $ error
Checking for dead links locally in a static website ( using wget ? )
Python
I 've got a mark_area chart that is stacking in an apparently-nonsensical order . I 'd prefer to order the layers with the biggest on the bottom , and decreasing above.Here is a picture of the graph , labelled with the preferred order : I tried to make a toy-example : This automatically produces the chart like : I trie...
import randomimport altair as altseed = { `` date '' : pd.date_range ( ' 1/1/2019 ' , periods=20 , freq= '' M '' ) , `` jack '' : random.sample ( range ( 100 , 500 ) , 20 ) , `` roy '' : random.sample ( range ( 20 , 90 ) , 20 ) , `` bill '' : random.sample ( range ( 600 , 900 ) , 20 ) , } df = pd.DataFrame.from_dict ( ...
Controlling stack-order of an altair area
Python
According to the Python docs : `` when defining __eq__ ( ) , one should also define __ne__ ( ) so that the operators will behave as expected '' . However , it appears that Python computes __ne__ as not __eq__ automatically : So what 's the point of defining __ne__ if it 's just going to be return not self.__eq__ ( othe...
In [ 8 ] : class Test : def __eq__ ( self , other ) : print ( `` calling __eq__ '' ) ... : return isinstance ( other , Test ) ... : In [ 9 ] : a = Test ( ) In [ 10 ] : b = Test ( ) In [ 11 ] : a == bcalling __eq__Out [ 11 ] : TrueIn [ 12 ] : a ! = bcalling __eq__Out [ 12 ] : FalseIn [ 13 ] : a == 1calling __eq__Out [ 1...
Why do the Python docs say I need to define __ne__ when I define __eq__ ?
Python
I have an expression in Sympy ( like ) and I would like to create a formal linear function , says f , and apply it to my expression , in order to get , after simplification : Is it possible to tell sympy that a property such as linearity is verified ? A very hacky way to do it would be to apply the function f to every ...
-M - n + x ( n ) -f ( M ) - f ( n ) + f ( x ( n ) ) [ -M , -n , x ( n ) ]
Create a formal linear function in Sympy
Python
If I have an input string and an array : I am trying to find the longest common prefix between the consecutive elements of the array pos referencing the original s. I am trying to get the following output : The way I obtained this is by computing the longest common prefix of the following pairs : s [ 15 : ] which is _b...
s = `` to_be_or_not_to_be '' pos = [ 15 , 2 , 8 ] longest = [ 3,1 ]
Longest common prefix using buffer ?
Python
I am contributing code to a currently only Python 2 project to allow it to run on Python 3 . Should I put the following import : On every file on the project or just use the ones I need on each file ?
from __future__ import ( unicode_literals , print_function , absolute_imports , division )
Should I add __future__ statements to every file on my project ?
Python
I 'm trying to train a LSTM neural net using Keras ( version 2.2.0 ) and TensorFlow ( version 1.1.0 ) . I know that there are more recent TensorFlow versions but unfortunately I 'm having some issues installing them . However , I do n't believe that my problem is related to the TensorFlow version.This is how my Keras c...
[ ... ] from keras.layers import Dense , Dropout , LeakyReLU , LSTM , Activation , Dense , Dropout , Input , Embeddingdef LSTM ( X , Y ) : inputDimension = len ( X [ 0 ] ) inputSize = len ( X ) # create the model model = Sequential ( ) model.add ( Embedding ( input_length=inputDimension , input_dim=inputDimension , out...
Keras LSTM neural net : TypeError : LSTM ( ) missing 1 required positional argument : ' Y '
Python
I was going to try using fuzzywuzzy with a tuned acceptable score parameteressentially it would check if the word is in the vocabulary as-is , and if not , it would ask fuzzywuzzy to choose the best fuzzy match , and accept that for the list of tokens if it was at least a certain score.If this is n't the best approach ...
class FuzzyCountVectorizer ( CountVectorizer ) : def __init__ ( self , input='content ' , encoding='utf-8 ' , decode_error='strict ' , strip_accents=None , lowercase=True , preprocessor=None , tokenizer=None , stop_words=None , token_pattern= '' ( ? u ) \b\w\w+\b '' , ngram_range= ( 1 , 1 ) , analyzer='word ' , max_df=...
sklearn : Would like to extend CountVectorizer to fuzzy match against vocabulary
Python
I have a homework problem in Python . I am using Python version 3.4.0 on Linux.The design document states that I am to read a CSV file using built in functions , specified as names.dat , that is in the format : I am then to add these keyword pairs to a dictionary , which is the part I 'm stuck on . The code I have thus...
name : name2 , name : name3 , name2 : name4 , name3 : name5\n ( etc ) dictionary = dict ( ) database = open ( 'names.dat ' , ' r ' ) data = database.read ( ) data = data.rstrip ( '\n ' ) data = data.split ( ' , ' ) for item in range ( len ( data ) ) : dictionary.update ( data [ item-1 ] ) File `` MyName.py '' , line 7 ...
In Python , what is the easiest way to add a list consisting of keyword pairs to a dictionary ?
Python
I 'm trying to do some research on iOS and it involves attaching lldb to a process . I 'm able to do it with lldb console , however when I 'm trying to convert it to a python script , it stuck at `` process continue '' for the first time and never reach the commands at the end . Can anyone helps ? Thanks !
import lldbdebugger = lldb.SBDebugger.Create ( ) debugger.SetAsync ( False ) debugger.HandleCommand ( 'platform select remote-ios ' ) debugger.HandleCommand ( 'process connect connect : //localhost:1234 ' ) debugger.HandleCommand ( 'process continue ' ) # other commands
Python script stuck when trying to continue process in lldb
Python
I am currently trying to create a X by 3 series of graphs in matplotlib , I have done similar things recently , but this specific 2D form of metrics is really giving me a challenge on removing axis labels or setting the MaxNLocator.Currently , each sublot still tries to show the X labels and Y labels on their own . Usi...
plt.rcParams [ 'figure.figsize ' ] = [ 18 , 10 ] fig , ax = plt.subplots ( nrows=10 , ncols=3 ) for number , team in enumerate ( team_dict.keys ( ) ) : print ( number , team ) df = pd.DataFrame ( data=team_dict [ team ] ) axy = ax [ number // 3 ] [ number % 3 ] df = pd.pivot_table ( df , values='count_events ' , index=...
Ca n't hide subplot axis labels or set MaxNLocator in matplotlib
Python
Context : I am using shutil.rmtree ( delDir , ignore_errors = False , onerror = readOnlyErrorHandler ) to delete a directory tree that holds readonly files : Annoyence : PyLint ( inside VS Code ) marks the raise command inside my readOnlyErrorHandler function as 'The raise statement is not inside an except clause ' by ...
def readOnlyErrorHandler ( func , path , exc_info ) : import errno if func in ( os.rmdir , os.unlink , os.remove ) and exc_info [ 1 ] .errno == errno.EACCES : print ( f '' Retry ' { func.__name__ } ' after chmod 0o777 on ' { path } ' '' ) os.chmod ( path , 0o777 ) func ( path ) else : # marked as 'The raise statement i...
PyLint raises 'misplaced-bare-raise ' in error handler function for shutil.rmtree ( ... )
Python
Just now I saw a quiz on this page : The example answer isFrom the documentation I know that : min ( iterable [ , key=func ] ) - > valuemin ( a , b , c , ... [ , key=func ] ) - > valueWith a single iterable argument , return its smallest item.With two or more arguments , return the smallest argument.But why is min ( { ...
> > > x , y = ? ? ? > > > min ( x , y ) == min ( y , x ) False x , y = { 0 } , { 1 } min ( { 0,2 } ,1 ) # 1min ( 1 , { 0,2 } ) # 1min ( { 1 } , [ 2,3 ] ) # [ 2,3 ] min ( [ 2,3 ] ,1 ) # 1
Confusing about a Python min quiz
Python
When I run the following code I get an KeyError : ( ' a ' , 'occurred at index a ' ) . How can I apply this function , or something similar , over the Dataframe without encountering this issue ? Running python3.6 , pandas v0.22.0
import numpy as npimport pandas as pddef add ( a , b ) : return a + bdf = pd.DataFrame ( np.random.randn ( 3 , 3 ) , columns = [ ' a ' , ' b ' , ' c ' ] ) df.apply ( lambda x : add ( x [ ' a ' ] , x [ ' c ' ] ) )
Pandas apply function on dataframe over multiple columns
Python
This question is more about curiosity than utility . If I 'm writing a function that 's supposed to run for ever , for instance a daemon , how would Python handle it if I called the function again from the end of the function ? I 'm fairly sure that doing this in C would result in a stack overflow , but given the level...
def daemonLoop ( ) : # Declare locals # Do stuff daemonLoop ( )
Is it a sin to use infinite recursion for infinite loops in Python ?
Python
Is it possible to calculate a first order derivative using the aggregate framework ? For example , I have the data : I 'm trying to obtain an output like :
{ time_series : [ 10,20,40,70,110 ] } { derivative : [ 10,20,30,40 ] }
Compute first order derivative with MongoDB aggregation framework
Python
I really ca n't find this out . I tried to use itertools , tried all kind of looping , but still i ca n't achieve what I want . Here is what i need : I have list such as : This list is each time different , there can be 5 different items in it each time and what I need is to get something like this : I am really lost ....
list = [ ( `` car '' , 2 ) , ( `` plane '' , 3 ) , ( `` bike '' , 1 ) ] car1 , plane1 , bike1car1 , plane2 , bike1car1 , plane3 , bike1car2 , plane1 , bike1car2 , plane2 , bike1car2 , plane3 , bike1
Python : all possible combinations of `` dynamic '' list
Python
I have come across the KMP algorithm for substring searching and implemented it in python . Later , I found that the in operator can also be used for this problem and I decided to compare their performances . To my surprise , in was much faster than the KMP algorithm and I decided to take a closer look at in.I found th...
def lps ( pattern ) : start_ind = 0 lps_list = [ 0 ] for j in pattern [ 1 : ] : if ( j == pattern [ start_ind ] ) : lps_list.append ( start_ind ) start_ind += 1 else : start_ind = 0 lps_list.append ( start_ind ) return lps_list def kmp ( search , pattern ) : lps_list = lps ( pattern ) pat_ind = 0 for j in search : if (...
Why is substring searching using 'in ' operator , faster than using KMP algorithm ?
Python
I have learnt from PEP 3131 that non-ASCII identifiers were supported in Python , though it 's not considered best practice.However , I get this strange behaviour , where my identifier ( U+1D70F ) seems to be automatically converted to τ ( U+03C4 ) .Is that expected behaviour ? Why does this silent conversion occur ? D...
class Base ( object ) : def __init__ ( self ) : self . = 5 # defined with U+1D70Fa = Base ( ) print ( a . ) # 5 # ( U+1D70F ) print ( a.τ ) # 5 as well # ( U+03C4 ) ? another way to access it ? d = a.__dict__ # { ' τ ' : 5 } # ( U+03C4 ) ? seems convertedprint ( d [ ' τ ' ] ) # 5 # ( U+03C4 ) ? consistent with the conv...
Non-ASCII Python identifiers and reflectivity
Python
How does one pre-populate a Formish form ? The obvious method as per the documentation does n't seem right . Using one of the provided examples : If we pass this a valid request object : The output is a structure like this : However , pre-populating the form using defaults requires this : The dottedish package has a Do...
import formish , schemaishstructure = schemaish.Structure ( ) structure.add ( ' a ' , schemaish.String ( ) ) structure.add ( ' b ' , schemaish.Integer ( ) ) schema = schemaish.Structure ( ) schema.add ( 'myStruct ' , structure ) form = formish.Form ( schema , 'form ' ) form.validate ( request ) { 'myStruct ' : { ' a ' ...
How does one pre-populate a Python Formish form ?
Python
The code given to exec below will pass without compile errors , but will result in an run-time error at `` error '' statement : The error message is : The location information of only File `` < string > '' , line 4 , in main is not very useful , for example when trying the locate the origin of the code which can be fro...
globs = { } exec ( `` 'def main ( ) : print ( 'Hello Python ' ) error # Makes run-time error '' ' , globs ) globs [ 'main ' ] ( ) Traceback ( most recent call last ) : File `` C : \work\sandbox.py '' , line 11 , in globs [ 'main ' ] ( ) File `` < string > '' , line 4 , in main NameError : name 'error ' is not defined
How to give exec code meaningful location to show if exception ?
Python
I am trying to understand properly how slots work programmatically . Before coding anything , I am trying to understand it well by looking at the examples for alexa sdk for python.Specifically , I was trying to understand the basics in slots in the ColorPicker example ( I understood properly the hello_world and did som...
def whats_my_color_handler ( handler_input ) : `` '' '' Check if a favorite color has already been recorded in session attributes . If yes , provide the color to the user . If not , ask for favorite color. `` '' '' # type : ( HandlerInput ) - > Response if color_slot_key in handler_input.attributes_manager.session_attr...
Understanding slots and getting its values in Alexa Skills Kit
Python
I have made a Python 3 program to calculate pi for a school project , but it always stops at 16 decimal places . Is there a limit to the length of numbers in python ? If so is there a language that I could use that will let me continue ?
accuracy = int ( input ( `` accuracy : `` ) ) current = 2opperation = `` + '' number = 3count = 1for i in range ( accuracy ) : if opperation == `` - '' : number = number - ( 4/ ( current* ( current+1 ) * ( current+2 ) ) ) opperation = `` + '' elif opperation == `` + '' : number = number + ( 4/ ( current* ( current+1 ) ...
Are there number limitations in python ?
Python
Possible Duplicate : Single quotes vs. double quotes in Python I have seen that when i have to work with string in Python both of the following sintax are accepted : Is anyway there any difference ? Is it by any reason better use one solution rather than the other ? Cheers ,
mystring1 = `` here is my string 1 '' mystring2 = 'here is my string 2 '
python string good practise : ' vs ``
Python
Is there an uniform way of knowing if an iterable object will be consumed by the iteration ? Suppose you have a certain function crunch which asks for an iterable object for parameter , and uses it many times . Something like : ( note : merging together the two for loops is not an option ) .An issue arises if the funct...
def crunch ( vals ) : for v in vals : chomp ( v ) for v in vals : yum ( v ) crunch ( iter ( range ( 4 ) ) def crunch ( vals ) : vals = list ( vals ) for v in vals : chomp ( v ) for v in vals : yum ( v ) hugeList = list ( longDataStream ) crunch ( hugeList ) def crunch ( vals ) : if type ( vals ) is not list : vals = li...
Detecting if an iterator will be consumed
Python
I need to store settings for my Google App Engine project . Currently I have : And when I want to use it : This feels clumsy so is there a better way ( without using Django ) ?
class Settings ( db.Model ) : rate = db.IntegerProperty ( default=4 ) ... Settings.get_or_insert ( 'settings ' )
storing app settings on Google App Engine
Python
I have a list of elements from which I want to remove those elements whose count is less than or equal to 2 in all the list.For example : I want to remove ' a ' , 'd ' , ' f ' , ' g ' from A and store the rest in B so that the list becomes : I created a dictionary which will store all the count of elements and based on...
A = [ [ ' a ' , ' b ' , ' c ' ] , [ ' b ' , 'd ' ] , [ ' c ' , 'd ' , ' e ' ] , [ ' c ' , ' e ' , ' f ' ] , [ ' b ' , ' c ' , ' e ' , ' g ' ] ] B = [ [ ' b ' , ' c ' ] , [ ' b ' ] , [ ' c ' , ' e ' ] , [ ' c ' , ' e ' ] , [ ' b ' , ' c ' , ' e ' ] ] for i in range ( len ( A ) ) : for words in A [ i ] : word_count [ wor...
Deleting elements of a list based on a condition
Python
I came across an interesting expression in Ruby : It means that if a is not defined , the `` new '' value will be assigned to a ; otherwise , a will be the same as it is . It is useful when doing some DB query . If the value is set , I do n't want to fire another DB query.So I tried the similar mindset in Python : It f...
a ||= `` new '' a = a if a is not None else `` new '' myVar = myVar if 'myVar ' in locals ( ) and 'myVar ' in globals ( ) else `` new '' try : myVarexcept NameError : myVar = NonemyVar = myVar if myVar else `` new ''
Is there any expression in python that similar to ruby 's ||=
Python
I have about 500 graphs generated in Excel using VBA and I need to export them to pdf . These graphs have alternative text to make them accessible for blind people . When I use the VBA ( ExportAsFixedFormat ) to generate the pdf , the alternative text will be missed in the pdf . Is there a code in python or R to conver...
ActiveSheet.ExportAsFixedFormat Type : =xlTypePDF , Filename : =PdfFileName , _ Quality : =xlQualityStandard , IncludeDocProperties : =True , IgnorePrintAreas : =False , OpenAfterPublish : =False
How to export a graph with alternative text in Excel to PDF using Python or R ?
Python
I have two file demo.py and demo.kv.can someone help me ? 1 . +Add More add row dynamic.After fill value when i click on Total Value then it shows string like 151012.Do n't show 12+10+15=37.I am using code for it2 . Can anyone tell me how to put sum of value in Total value TextBox after fill value TextBox instead of cl...
test = `` for val in values : test = val [ 2 ] +test self.total_value.text = test from kivy.uix.screenmanager import Screenfrom kivy.app import Appfrom kivy.lang import Builderfrom kivy.core.window import Windowfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.properties import BooleanProperty , ListProperty , StringPr...
how to plus integer value in loop
Python
I am trying to implement an a* search algorithm in python on a 6*6 interconnected node grid , using networkx to organize nodes and matplotlib to display . I 've got it working so it finds the shortest path , but without the heuristic , it 's just brute force search- which is too costly . How can I assign x , y coordina...
import networkx as nxG=nx.Graph ( ) import matplotlib.pyplot as pltdef add_nodes ( ) : G.add_nodes_from ( [ 0 , 1 , 2 , 3 , 4 , 5 , \ 6 , 7 , 8 , 9 , 10 , 11 , \ 12 , 13 , 14 , 15 , 16 , 17 , \ 18 , 19 , 20 , 21 , 22 , 23 , \ 24 , 25 , 26 , 27 , 28 , 29 , \ 30 , 31 , 32 , 33 , 34 , 35 ] ) c = 0 for y in range ( 0,5 ) :...
Assigning x , y coords in networkx/python for a* search heuristic
Python
I have a 5D array ' a ' , of size ( 3,2,2,2,2 ) .What I want to do is rotate this 5D array by 180 degrees , but only in the last two dimensions , without their positions changed . So output [ 0,0,0 ] should look like this : What I have tried : The rot90 function apparently rotates the whole array.Note : I want to avoid...
import numpy as npa = np.arange ( 48 ) .reshape ( 3,2,2,2,2 ) a [ 0,0,0 ] : array ( [ [ 0 , 1 ] , [ 2 , 3 ] ] ) out [ 0,0,0 ] : array ( [ [ 3 , 2 ] , [ 1 , 0 ] ] ) out = np.rot90 ( a , 2 ) out [ 0,0,0 ] : array ( [ [ 40 , 41 ] , [ 42 , 43 ] ] )
Rotating a 5D array in the last 2 dimensions
Python
I have a multidimensionnal dict , I need to return a specific value.The result of the print is : My question is : Is there a way to return the value of `` Ammonia '' only , in `` DAP_Local '' ? Thank you !
ConsomRatio= { `` DAP_Local '' : [ ] , '' MAP11_52 '' : [ ] } ConsomRatio [ `` DAP_Local '' ] .append ( { `` Ammonia '' : '' 0.229 '' , `` Amine '' : '' 0.0007 '' } ) ConsomRatio [ `` MAP11_52 '' ] .append ( { `` Ammonia '' : '' 0.138 '' , `` Fuel '' : '' 0.003 '' } ) print ( ConsomRatio [ `` DAP_Local '' ] ) [ { 'Ammo...
Dicts in Python
Python
I like any comment to appear on its own line . I do n't like to put comments on the same line that code is on . In some languages you can write a comment block such as : I like that . I like how the comment block just keeps getting more lines as I add more text to it . I like how if I insert text at some arbitrary poin...
/** * I am a comment block . This comment block will be automatically expanded by the * IDE such that it can contain all of the text in this block . **/ # I am a comment block . This comment block will NOT be automatically expanded by # the IDE , because it does not recognize these two comment lines as being joined .
Auto expanding blocks of comments in emacs
Python
Linuxwindows.In Windows , I can easily to use a [ 1 ] and a [ 2 ] to get those two value.But in Linux , xpath //a [ 1 ] get those two link text together.This make the program not so compatible in those OS . I have to modify code on different OS.Is it a lxml module bug ? Any solution for this ?
> > > from lxml import etree > > > html= '' ' < td > < a href= '' > a1 < /a > < /td > ... < td > < a href= '' > a2 < /a > < /td > ... `` ' > > > p=etree.HTML ( html ) > > > a=p.xpath ( `` //a [ 1 ] '' ) > > > for i in a : ... print i.text ... a1a2 > > > html= '' ' < td > < a href= '' > a1 < /a > < /td > ... < td > < a ...
python lxml different result on windows and linux
Python
Windows sockets have some strange behavior when it comes to WSAECONNREFUSED ( which means backlog full or port not available , see https : //stackoverflow.com/a/10308338/851737 ) . If Windows detects one of these conditions , it retries ( up to ) two times with an interval of 0.5s . This means it takes at least 1 secon...
import errnoimport socketimport timePORT = 50123def main ( ) : s = socket.socket ( ) s.bind ( ( '127.0.0.1 ' , PORT ) ) s.listen ( 0 ) client = socket.socket ( ) client.connect ( ( '127.0.0.1 ' , PORT ) ) client2 = socket.socket ( ) start = time.time ( ) try : client2.connect ( ( '127.0.0.1 ' , PORT ) ) except socket.e...
Fast detection or simulation of WSAECONNREFUSED
Python
The integer 2 has an __add__ method : ... but calling it raises a SyntaxError : Why ca n't I use the __add__ method ?
> > > `` __add__ '' in dir ( 2 ) True > > > 2.__add__ ( 3 ) File `` < stdin > '' , line 1 2.__add__ ( 3 ) ^SyntaxError : invalid syntax
Why does n't 2.__add__ ( 3 ) work in Python ?
Python
Why can two functions with the same id value have differing attributes like __doc__ or __name__ ? Here 's a toy example : Which prints : I 've tried mixing in a call to copy.deepcopy ( not sure if the recursive copy is needed for functions or it is overkill ) but this does n't change anything .
some_dict = { } for i in range ( 2 ) : def fun ( self , *args ) : print i fun.__doc__ = `` I am function { } '' .format ( i ) fun.__name__ = `` function_ { } '' .format ( i ) some_dict [ `` function_ { } '' .format ( i ) ] = funmy_type = type ( `` my_type '' , ( object , ) , some_dict ) m = my_type ( ) print id ( m.fun...
Why can two functions with the same ` id ` have different attributes ?
Python
I have a task where I need to find the lowest Collatz sequence that contains more than 65 prime numbers in Python . For example , the Collatz sequence for 19 is : 19 , 58 , 29 , 88 , 44 , 22 , 11 , 34 , 17 , 52 , 26 , 13 , 40 , 20 , 10 , 5 , 16 , 8 , 4 , 2 , 1This sequence contains 7 prime numbers.I also need to use me...
lookup = { } def countTerms ( n ) : if n not in lookup : if n == 1 : lookup [ n ] = 1 elif not n % 2 : lookup [ n ] = countTerms ( n / 2 ) [ 0 ] + 1 else : lookup [ n ] = countTerms ( n*3 + 1 ) [ 0 ] + 1 return lookup [ n ] , n def is_prime ( a ) : for i in xrange ( 2 , a ) : if a % i==0 : # print a , `` is not a prime...
finding the lowest collatz sequence that gives more that 65 primes
Python
I have a test code which uses an FTP stub with pyftpdlib , which to my surprise failed in production . The reason for this is that proftpd returns the directory name in response to NLST . Here is the response from pyftpdlib FTP stub : Here is the response from proftpd : It 's easy enough to remove those directory names...
In [ 10 ] : local_conn.login ( 'user ' , '12345 ' ) Out [ 10 ] : '230 Login successful . 'In [ 11 ] : import ftplibIn [ 12 ] : local_conn = ftplib.FTP ( ) In [ 13 ] : local_conn.connect ( 'localhost ' , 2121 ) Out [ 13 ] : '220 pyftpdlib 1.4.0 ready . 'In [ 14 ] : local_conn.login ( 'user ' , '12345 ' ) Out [ 14 ] : '2...
List files with pyftp - proftpd vs. pyftpdlib behavior
Python
I have a Django app saving objects to the database and a celery task that periodically does some processing on some of those objects . The problem is that the user can delete an object after it has been selected by the celery task for processing , but before the celery task has actually finished processing and saving i...
def my_delete_view ( request , pk ) : thing = Thing.objects.get ( pk=pk ) thing.delete ( ) return HttpResponseRedirect ( 'yay ' ) @ app.taskdef my_periodic_task ( ) : things = get_things_for_processing ( ) # if the delete happens anywhere between here and the .save ( ) , we 're hosed for thing in things : process_thing...
How to update an object or bail if it has been deleted in Django
Python
I have the following simple data frameI 'm looking to display the strings which occur in both columns : Thanks
import pandas as pddf = pd.DataFrame ( { 'column_a ' : [ ' a ' , ' b ' , ' c ' , 'd ' , ' e ' ] , 'column_b ' : [ ' b ' , ' x ' , ' y ' , ' c ' , ' z ' ] } ) column_a column_b0 a b1 b x2 c y3 d c4 e z result = ( `` b '' , `` c '' )
Count instances of strings in multiple columns python
Python
I made a GUI file from pyqt designer , which i converted to .py file.but when i load that .py code in my IDE ( Pycharm and sublime text ) , and i try to run it , it runs without errors , but the physical aspect of GUI is n't loaded , i tried a custom code from the internet , which worked great , GUI shows up when i run...
from PyQt5 import QtCore , QtGui , QtWidgetsclass Ui_Form ( object ) : def setupUi ( self , Form ) : Form.setObjectName ( `` Form '' ) Form.resize ( 400 , 300 ) self.pushButton = QtWidgets.QPushButton ( Form ) self.pushButton.setGeometry ( QtCore.QRect ( 170 , 200 , 91 , 30 ) ) self.pushButton.setObjectName ( `` pushBu...
Unable to build GUI from the code from PyQt Designer
Python
Is it possible to access the tuple of choices passed to an argument ? If so , how do I go about itfor example if I have can I access the tuple ( 'here ' , 'there ' , 'anywhere ' ) ?
parser = argparse.ArgumentParser ( description='choose location ' ) parser.add_argument ( `` -- location '' , choices= ( 'here ' , 'there ' , 'anywhere ' ) ) args = parser.parse_args ( )
Accessing the choices passed to argument in argparser ?
Python
I 've just begun using dask , and I 'm still fundamentally confused how to do simple pandas tasks with multiple threads , or using a cluster . Let 's take pandas.merge ( ) with dask dataframes . Now , let 's say I were to run this on my laptop , with 4 cores . How do I assign 4 threads to this task ? It appears the cor...
import dask.dataframe as dddf1 = dd.read_csv ( `` file1.csv '' ) df2 = dd.read_csv ( `` file2.csv '' ) df3 = dd.merge ( df1 , df2 ) dask.set_options ( get=dask.threaded.get ) df3 = dd.merge ( df1 , df2 ) .compute ( ) dask.set_options ( get=dask.threaded.get ) df3 = dd.merge ( df1 , df2 ) .compute
How to execute a multi-threaded ` merge ( ) ` with dask ? How to use multiples cores via qsub ?
Python
I 'm sorry if inverse is not the preferred nomenclature , which may have hindered my searching . In any case , I 'm dealing with two sqlalchemy declarative classes , which is a many-to-many relationship . The first is Account , and the second is Collection . Users `` purchase '' collections , but I want to show the fir...
from sqlalchemy import *from sqlalchemy.orm import scoped_session , sessionmaker , relationfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base ( ) engine = create_engine ( 'sqlite : /// : memory : ' , echo=True ) Session = sessionmaker ( bind=engine ) account_to_collection_map = Table ( 'acco...
sqlalchemy many-to-many , but inverse ?
Python
Today I found thisI looked the documentation from sympy about those types , but it does n't say anything about why they exist . Is there a reason to have 3 special singleton classes for -1 , 0 and 1 ? Edit : I saw this at the SymPy online shell
> > > type ( 1 ) < class 'sympy.core.numbers.One ' > > > > type ( 0 ) < class 'sympy.core.numbers.Zero ' > > > > type ( -1 ) < class 'sympy.core.numbers.NegativeOne ' > > > > type ( 2 ) < class 'sympy.core.numbers.Integer ' >
Sympy classes Zero , One and NegativeOne , why they exist ?
Python
I would like to build a Python script that checks if a specific directory is open in nautilus . So far the best solution I have is to use wmctrl -lxp to list all windows , which gives me output like this : Then I check if the basename of the directory I 'm interested in is in window name of the nautilus.Nautilus window...
0x0323d584 0 1006 nautilus.Nautilus namek Downloads0x0325083a 0 1006 nautilus.Nautilus namek test0x04400003 0 25536 gvim.Gvim namek yolo_voc.py + ( ~/code/netharn/netharn/examples ) - GVIM4 def is_directory_open ( dpath ) : import ubelt as ub # pip install me ! https : //github.com/Erotemic/ubelt import platform from o...
Is it possible to get the directory of a specific nautilus window in a script ?
Python
I am trying to teach myself python and I wanted to start with learning how to do a monte carlo analysis ( I am a scientist by trade who uses MCA alot ) . I am trying to write a program in that will perform a montecarlo simulation of 7 variables to calculate the range of possible outcomes from a given formula.I am EXTRE...
from scipy.stats import *import numpy as npn = 10000for i in range ( n ) : Area = norm ( 200,50 ) Thickness = norm ( 100,25 ) NTG = norm ( .85 , .2 ) POR = norm ( .32 , .02 ) GS = norm ( .80 , .2 ) BG= norm ( .0024 , .0001 ) Feather = 1 return ( ( ( ( Area*Thickness*NTG*POR*GS ) /BG ) *43560 ) *Feather ) /1000000000Res...
Monte Carlo Analysis Python Oil and Gas Volumetrics