lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I am taking a course on algorithms and data structures in Python 3 and my instructor recently introduced us to the binary search tree . However , I am having trouble understanding the deletion algorithm . Below is the implementation we were taught , however when I initially wrote my own rendition , I did not include a ... | def remove ( self , data ) : if self.root : self.root = self.remove_node ( data , self.root ) def remove_node ( self , data , node ) : if node is None : return node if data < node.data : node.leftChild = self.remove_node ( data , node.leftChild ) elif data > node.data : node.rightChild = self.remove_node ( data , node.... | Purpose of base case in binary search tree deletion |
Python | I 'm new to RNN , and I 'm trying to figure out the specifics of LSTM cells and they 're relation to TensorFlow : Colah GitHubDoes the GitHub website 's example uses the same LSTM cell compared to TensorFlow ? The only thing I got on the TensorFlow site was that basic LSTM cells uses the following architecture : Paper ... | tf.nn.rnn_cell.GRUCell.__init__ ( num_units , input_size=None , activation=tanh ) | Recurrent Neural Network ( RNN ) - Forget Layer , and TensorFlow |
Python | I 'm using pyinotify to track file changes and try to overload the module where this modified file.But unfortunately , not the module probably is not overloaded , the changes that I am not visible.And code file from the module aa.aaMaybe there is some other way , I need to change the code did not have to manually reloa... | import sysimport asyncioimport pyinotifyimport importlibfrom aiohttp import webfrom aa.aa import m_aaclass EventHandler ( pyinotify.ProcessEvent ) : def my_init ( self , loop=None ) : self.loop = loop if loop else asyncio.get_event_loop ( ) def process_IN_MODIFY ( self , event ) : pathname = event.pathname name = event... | How to overload modules when using python-asyncio ? |
Python | What I understood in the documentation of ‘ np.einsum ‘ is that a permutation string , would give a permutation of the axis in a vector . This is confirmed by the following experiment : But this I can not understand : I would expect ( 4 , 2 , 3 ) instead ... What 's wrong with my understanding ? | > > > M = np.arange ( 24 ) .reshape ( 2,3,4 ) > > > M.shape ( 2 , 3 , 4 ) > > > np.einsum ( 'ijk ' , M ) .shape ( 2 , 3 , 4 ) > > > np.einsum ( 'ikj ' , M ) .shape ( 2 , 4 , 3 ) > > > np.einsum ( 'jik ' , M ) .shape ( 3 , 2 , 4 ) > > > np.einsum ( 'kij ' , M ) .shape ( 3 , 4 , 2 ) | numpy einsum to get axes permutation |
Python | Consider the following code using numpy arrays which is very slow : How to rewrite the function to speed up the calculation ? ( np.size ( tx ) == 10000 and np.size ( ox ) == 100000 ) | # Intersection of an octree and a trajectorydef intersection ( octree , trajectory ) : # Initialize numpy arrays ox = octree.get ( `` x '' ) oy = octree.get ( `` y '' ) oz = octree.get ( `` z '' ) oe = octree.get ( `` extent '' ) /2 tx = trajectory.get ( `` x '' ) ty = trajectory.get ( `` y '' ) tz = trajectory.get ( `... | Speeding up a numpy loop in python ? |
Python | I 'm trying to understand the internals of the CPython garbage collector , specifically when the destructor is called . So far , the behavior is intuitive , but the following case trips me up : Disable the GC.Create an object , then remove a reference to it.The object is destroyed and the _____del_____ method is called... | import gcimport unittest_destroyed = Falseclass MyClass ( object ) : def __del__ ( self ) : global _destroyed _destroyed = Trueclass GarbageCollectionTest ( unittest.TestCase ) : def testExplicitGarbageCollection ( self ) : gc.disable ( ) ref = MyClass ( ) ref = None # The next test fails . # The object is automaticall... | Why is the destructor called when the CPython garbage collector is disabled ? |
Python | I was working on project euler problem 14 and as a first attempt I whipped up this brute-force solution : My question is about that lambda , I 'm usually reluctant to use them but I do n't know any elegant way to avoid it in this case . Is there something in functools or other to chain two callables , or any other neat... | def collatz ( n , memo= { 1 : [ 1 ] } ) : if n not in memo : memo [ n ] = [ n ] + collatz ( 3 * n + 1 if n % 2 else n // 2 ) return memo [ n ] def p014 ( ) : return max ( xrange ( 1 , 10**6 ) , key=lambda n : len ( collatz ( n ) ) ) | Python avoiding lambda for key which needs two callables ( function composition ) |
Python | I am having a problem when using simpson 's rule from scipy.integrate library . The Area calculated sometimes is negative even if all the numbers are positive and the values on the x-axis are increasing from left to right . For example : The result returned by simps ( y , x ) is -226271544.06562585 . Why is it negative... | from scipy.integrate import simpsx = [ 0.0 , 99.0 , 100.0 , 299.0 , 400.0 , 600.0 , 1700.0 , 3299.0 , 3300.0 , 3399.0 , 3400.0 , 3599.0 , 3699.0 , 3900.0 , 4000.0 , 4300.0 , 4400.0 , 4900.0 , 5000.0 , 5100.0 , 5300.0 , 5500.0 , 5700.0 , 5900.0 , 6100.0 , 6300.0 , 6600.0 , 6900.0 , 7200.0 , 7600.0 , 7799.0 , 8000.0 , 84... | Simpson 's Rule Integration Negative Area |
Python | I like to figure out the myth behind Python 's namespace packages by setuptools , and here is what I did test.Make a virtual environment by virtualenv.Find a namespaced package on PyPI.Install that package by pip install.Check the installed file hierarchy.The package I played with is zope.interface and it worked well w... | ~virenv/ ... /site-packages/zope.interface-3.8.0-py2.6-nspkg.pth /zope.interface-3.8.0-py2.6.egg-info/ /zope/ /interface/ / ... ~virenv/../site-packages/zope.interface- ... egg/ /zope/ /__init__.py /interface/ /EGG-INFO/ | How come I ca n't get the exactly result to *pip install* by manually *python setup.py install* ? |
Python | I recently stumbled upon Python 's NotImplemented builtin . After some reading I do get it 's purpose now , but I do n't see why it evaluates to True as a boolean . The following example makes it seem like some kind of cruel joke to me : My question is simple : Why does NotImplemented evaluate to True ? | > > > class A : ... def __eq__ ( self , other ) : ... return NotImplemented ... > > > > > > a = A ( ) > > > a == 1False > > > bool ( a.__eq__ ( 1 ) ) True | Why does NotImplemented evaluate to True ? |
Python | I have sets of stringsI want to find the intersection between these two sets but element equality defined as the followingbasically if the lcs is at least 80 % of the length of the string we consider this matching `` enough '' . I know passing custom comparators to sorting methods works something like this but I have n... | set_a = { 'abcd ' , 'efgh ' , 'ghij ' } set_b = { 'abce ' , 'efgk ' , 'ghij ' } def match ( string_a , string_b , threshold=0.8 ) : lcs_len = lcs ( string_a , item_set_b ) return ( lcs_len / max ( len ( string_a ) , len ( item_set_b ) ) ) > 0.8 | Set intersection with custom comparator ? |
Python | list = [ [ 1 , 'abc ' ] , [ 2 , 'bcd ' ] , [ 3 , 'cde ' ] ] I have a list that looks like above.I want to parse the list and try to get a list that only contains the second element of all lists.output = [ 'abc ' , 'bcd ' , 'cde ' ] I think I can do it by going over the whole list and add only the second element to a ne... | output = [ ] for i in list : output.append ( i [ 1 ] ) | Parsing elements from list of list of strings |
Python | I have recently stumbled over a seeming inconsistency in Python 's way of dealing with else clauses in different compound statements . Since Python is so well designed , I 'm sure that there is a good explanation , but I ca n't think of it.Consider the following : Here , do_something_else ( ) is only executed if condit... | if condition : do_something ( ) else : do_something_else ( ) try : do_something ( ) except someException : pass : else : do_something_else ( ) finally : cleanup ( ) for i in some_iterator : print ( i ) else : print ( `` Iterator is empty ! '' ) | Why does else behave differently in for/while statements as opposed to if/try statements ? |
Python | I am working on invoice management system in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page but whenever user logout and try to access home page but it is giving following error.i tried AnonymousUser.is_authenticated method but still not workin... | TypeError at /'AnonymousUser ' object is not iterable from django.shortcuts import renderfrom django.contrib.auth.mixins import LoginRequiredMixin , UserPassesTestMixinfrom django.views.generic import ( ListView , DetailView , CreateView , UpdateView , DeleteView ) from .models import Invoicelistdef home ( request ) : ... | how to check whether user is logged in or not |
Python | Simple regex question : I want to replace page numbers in a string with pagenumber + some number ( say , 10 ) . I figured I could capture a matched page number with a backreference , do an operation on it and use it as the replacement argument in re.sub.This works ( just passing the value ) : Yielding , of course , 'he... | def add_pages ( x ) : return xre.sub ( `` ( ? < =Page ) ( \d { 2 } ) '' , add_pages ( r '' \1 '' ) , 'here is Page 11 and here is Page 78\nthen there is Page 65 ' , re.MULTILINE ) def add_pages ( x ) : return int ( x ) +10re.sub ( `` ( ? < =Page ) ( \d { 2 } ) '' , add_pages ( r '' \1 '' ) , 'here is Page 11 and here i... | regex : getting backreference to number , adding to it |
Python | If I create a file , use lseek ( 2 ) to jump to a high position in the ( empty ) file , then write some valuable information there , I create a sparse file on Unix system ( probably depending on the file system I use , but let 's assume I 'm using a typical Unix file system like ext4 or similar , there this is the case... | $ pythonf = open ( 'sparse ' , ' w ' ) f.seek ( ( 1 < < 40 ) + 42 ) f.write ( 'foo ' ) f.seek ( ( 1 < < 40 ) * 2 ) f.write ( '\0 ' ) f.close ( ) $ du -h sparse 8.0K sparse | Sparse files : How to find contents |
Python | We run several Python virtual environments on our minions managed by salt.The name of the system is build by this schema : Example : The pillar data : For every virtualenv we have one linux user . Up to now we compute values like `` home '' like this : But it is redundant.How could we avoid copy+pasting { % set system_... | project_customer_stage supercms_favoritcustomer_p systems : - customer : favoritcustomer project : supercms stage : p - customer : favoritcustomer project : supercms stage : q { % for system in pillar.systems % } { % set system_name = system.project + ' _ ' + system.customer + ' _ ' + system.stage % } { % set system_ho... | SaltStack : Properties ( computed values ) for data from SLS files ? |
Python | By default , pickling a numpy view array loses the view relationship , even if the array base is pickled too . My situation is that I have some complex container objects which are pickled . And in some cases , some contained data are views in some others . Saving a independent array of each view is not only a loss of s... | import numpy as npimport cPickletmp = np.zeros ( 2 ) d1 = dict ( a=tmp , b=tmp [ : ] ) # d1 to be saved : b is a view on apickled = cPickle.dumps ( d1 ) d2 = cPickle.loads ( pickled ) # d2 reloaded copy of d1 containerprint 'd1 before : ' , d1d1 [ ' b ' ] [ : ] = 1print 'd1 after : ' , d1print 'd2 before : ' , d2d2 [ '... | Preserving numpy view when pickling |
Python | numpy arrays can be partially assigned using integer or boolean indices like this : However , even though x [ [ 2,4 ] ] is in lvalue in this context , the lvalue can not be assigned to another variable , because in this case the assignment is done by __setitem__ , whereas __getitem__ , when passed an integer or boolean... | import numpy as npx = np.arange ( 5 ) x [ [ 2,4 ] ] =0x # # array ( [ 0. , 0. , 1. , 0. , 1 . ] ) x [ [ True ] *2+ [ False ] *3 ] =2x # # array ( [ 2. , 2. , 1. , 0. , 1 . ] ) x = np.arange ( 5 ) y = x [ [ 2,4 ] ] y [ : ] = 1xarray ( [ 0. , 0. , 0. , 0. , 0 . ] ) | Getting a numpy array view with integer or boolean indexing |
Python | when comparing two strings in python , it works fine and when comparing a string object with a unicode object it fails as expected however when comparing a string object with a converted unicode ( unicode -- > str ) object it failsA Demo : Works as expected : Pretty much yeah : Not expected : Why does n't the third exa... | > > > if 's ' is 's ' : print `` Hurrah ! '' ... Hurrah ! > > > if 's ' is u 's ' : print `` Hurrah ! '' ... > > > if 's ' is str ( u's ' ) : print `` Hurrah ! '' ... > > > type ( 's ' ) < type 'str ' > > > > type ( str ( u's ' ) ) < type 'str ' > | Strange behavior when comparing unicode objects with string objects |
Python | I can not find an adequate explanation for this behavior.But : I understand that in the second case there is a closure , but I can not find a detailed description of what actually is and under what conditions should return the function locals ( ) . | > > > def a ( ) : ... foo = 0 ... print locals ( ) ... def b ( ) : ... print locals ( ) ... b ( ) > > > a ( ) { 'foo ' : 0 } { } > > > def a ( ) : ... foo = 0 ... print locals ( ) ... def b ( ) : foo ... print locals ( ) ... b ( ) > > > a ( ) { 'foo ' : 0 } { 'foo ' : 0 } | Python - locals ( ) and closure |
Python | I have lots of C/C++ classes to export to python using Swig . I 've noticed that by default , Swig does n't generate a __hash__ method for wrapped classes , so the default hash gets used , which is the id of the wrapper object ( i.e . its memory address or something like it ) . This means if I end up with two python ob... | % extend Foo { bool __eq__ ( const Foo & other ) { return $ self == & other ; } bool __ne__ ( const Foo & other ) { return $ self ! = & other ; } long __hash__ ( ) { return ( long ) $ self ; } // hash : just address of C struct } | Is there a way to extend all classes in swig/python ? |
Python | I am trying to get a better understanding of the following python code and why the author has used the `` AND '' statement in the return.further down the code ... I 've tried inspecting the resulting object that gets handed back to the caller , however I still do n't entirely understand how it works.It seems like this ... | def valid_password ( self , password ) : PASS_RE = re.compile ( r'^ . { 6,128 } $ ' ) return password and PASS_RE.match ( password ) if not self.valid_password ( self.password ) : params [ 'error_password ' ] = `` Please enter a valid password . '' def valid_email ( self , email ) : EMAIL_RE = re.compile ( r'^ [ \S ] +... | What is this `` and '' statement actually doing in the return ? |
Python | Python click allows specifying some command line options as `` feature switches '' . Example from the official documentation : As the name suggests , it is used for the case when there is several alternatives for some feature , and only one can be selected . The code above allows running the script asHowever , the same... | @ click.command ( ) @ click.option ( ' -- upper ' , 'transformation ' , flag_value='upper ' , default=True ) @ click.option ( ' -- lower ' , 'transformation ' , flag_value='lower ' ) def info ( transformation ) : click.echo ( getattr ( sys.platform , transformation ) ( ) ) $ test.py -- upperLINUX2 $ test.py -- lowerlin... | Prohibit passing several feature switches in python click |
Python | I 'm confused with the following three patterns , would someone explain it in more detail ? | # # IPython with Python 2.7.3In [ 62 ] : re.findall ( r ' [ a-z ] * ' , '' f233op '' ) Out [ 62 ] : [ ' f ' , `` , `` , `` , 'op ' , `` ] # # why does the last `` come out ? In [ 63 ] : re.findall ( r ' ( [ a-z ] ) * ' , '' f233op '' ) Out [ 63 ] : [ ' f ' , `` , `` , `` , ' p ' , `` ] # # why does the character ' o ' ... | Confusing with the usage of regex in Python |
Python | I 'm looping over some XML files and producing trees that I would like to store in a defaultdict ( list ) type . With each loop and the next child found will be stored in a separate part of the dictionary.So then repeating this for several files would result in nicely indexed results ; a set of trees that were in posit... | d = defaultdict ( list ) counter = 0for child in root.findall ( something ) : tree = ET.ElementTree ( something ) d [ int ( x ) ] .append ( tree ) counter += 1 for x in d : for y in d [ x ] : print ( y ) | Python : Joining and writing ( XML.etrees ) trees stored in a list |
Python | If you change a view of a numpy array , the original array is also altered . This is intended behaviour.However , if I take a view of such a view , and change that , then the original array is not altered : This implies to me that , when you take a view of a view , you actually get back a copy . Is this correct ? Why i... | arr = np.array ( [ 1,2,3 ] ) mask = np.array ( [ True , False , False ] ) arr [ mask ] = 0arr # Out : array ( [ 0 , 2 , 3 ] ) arr = np.array ( [ 1,2,3 ] ) mask_1 = np.array ( [ True , False , False ] ) mask_1_arr = arr [ mask_1 ] # Becomes : array ( [ 1 ] ) mask_2 = np.array ( [ True ] ) mask_1_arr [ mask_2 ] = 0arr # ... | View of a view of a numpy array is a copy ? |
Python | I am trying to create a script which clones a github repository into the current directory and then deletes the script which called it.The script is written in python 3.7.4 and is compiled into an exe.I 've tried using 'os.remove ( sys.argv [ 0 ] ) ' which works before compiling but will not work for my end application... | import osdef function : # codedef main ( ) : function ( ) os.remove ( sys.argv [ 0 ] ) | How to delete a .exe file written in python from within the .exe file ? |
Python | I 'm having difficulties with locating the source of the queries which I see in my database logs . I 'm using Django , so the actual queries are generated automatically which makes a simple `` grep '' ineffective.I 'm thinking of patching the database cursors to append the current stacktrace to the query , something li... | for conn in connections.all ( ) : with conn.cursor ( ) as c : ctype = type ( c.cursor ) orig_execute = ctype.execute def _patchedExecute ( self , query , params=None ) : query = query + ' -- ' + traceback.format_stack ( ) return orig_execute ( self , query , params ) ctype.execute = _patchedExecute orig_execute_many = ... | Recommended way to find the source of a query when using Django ? |
Python | Possible Duplicate : In python , how do I take the highest occurrence of something in a list , and sort it that way ? Hi all , I am looking for an easy way to sort a list by popularity and then remove duplicate elements.For example , given a list : I would then end up with a list like the following : | [ 8 , 8 , 1 , 1 , 5 , 8 , 9 ] [ 8 , 1 , 5 , 9 ] | Take a list , sort by popularity and then remove duplicates |
Python | I am using Keras and CNTK ( backend ) my code is like this : I call the above model several times as I change optimizer . like this : When the model.fit ( ) is called second time , out of memory error is showingI thought it is because the memory of the first run was not released from gpu , So I added this after model.f... | def run_han ( embeddings_index , fname , opt ) ... sentence_input = Input ( shape= ( MAX_SENT_LENGTH , ) , dtype='int32 ' ) embedded_sequences = embedding_layer ( sentence_input ) l_lstm = Bidirectional ( GRU ( GRU_UNITS , return_sequences=True , kernel_regularizer=l2_reg , implementation=GPU_IMPL ) ) ( embedded_sequen... | CNTK out of memory error when model.fit ( ) is called second time |
Python | What is the fastest way ( within the limits of sane pythonicity ) to count distinct values , across columns of the same dtype , for each row in a DataFrame ? Details : I have a DataFrame of categorical outcomes by subject ( in rows ) by day ( in columns ) , similar to something generated by the following.For example , ... | import numpy as npimport pandas as pddef genSampleData ( custCount , dayCount , discreteChoices ) : `` '' '' generate example dataset '' '' '' np.random.seed ( 123 ) return pd.concat ( [ pd.DataFrame ( { 'custId ' : np.array ( range ( 1 , int ( custCount ) +1 ) ) } ) , pd.DataFrame ( columns = np.array ( [ 'day % d ' %... | efficient count distinct across columns of DataFrame , grouped by rows |
Python | I searched online and could n't find anything about this that does what I want.I would like to save a numpy array as an image but instead of having a colorful image , I want a black and white representation of the pixel values in their corresponding grid location.For example : I would like to save this as an image ( .P... | import numpy as npx = np.array ( [ [ 1,2 ] , [ 3,4 ] ] ) print ( x ) # [ [ 1 2 ] # [ 3 4 ] ] | Get matrix image of numpy array values - Grid with pixel values inside ( not colors ) |
Python | Right code example : This is extension module draft . As simple as possible . It has an empty method table and initializer function copied from original docpage . It contains 2 ( two ) intentional errors : variable someConstant declared but never defined ; function some_function defined , but never called ; If compiled... | # include `` Python.h '' # include < string > extern const int someConstant ; void some_function ( ) { const char *begin = NULL ; const char *end = NULL ; std : :string s ( begin , end ) ; const int v = someConstant ; } static PyMethodDef _G_methods [ ] = { { NULL , NULL , 0 , NULL } /* Sentinel */ } ; PyMODINIT_FUNC i... | Python receives SIGSEGV while loading C++ written extension module |
Python | Here 's a working example : df.replace ( { ' , ' : ' . ' } ) raises an OverflowError because somewhere in the code the convert flag is set to True . I am not sure but it is probably because pandas is inferring that it only contain numbers.I read the data from an Excel workbook and I want to prevent this conversion when... | df = pd.DataFrame ( { ' A ' : [ -39882300000000000000 ] } , dtype='object ' ) | Is it possible to force pandas not to convert data type when using DataFrame.replace |
Python | ProblemSay you have n lists of integers , where each list only includes integers in the range from 1 to n. For example , for n = 4 , we might have : Now my question is : Can I tick off all the integers between 1 and n in those n lists but with the catch that once I find one number , I ca n't use that list anymore to fi... | a_1 = [ 1 , 2 ] a_2 = [ 3 ] a_3 = [ 4 , 1 , 1 ] a_4 = [ 2 , 3 ] a_1 = [ 1 , 2 ] a_2 = [ 3 , 3 , 5 ] a_3 = [ 4 ] a_4 = [ 5 ] a_5 = [ 3 , 4 , 5 ] import itertoolsdef fillRange ( lists ) : cartesian = itertools.product ( *lists ) return any ( [ sorted ( comb ) == range ( 1 , len ( lists ) + 1 ) for comb in cartesian ] ) | Improving algorithm that uses the cartesian product |
Python | Is there any reason why the next tuple is greater then the list ? | > > > t = ( 1 , 2 , 3 ) > > > l = [ 1 , 2 , 3 ] > > > t > lTrue > > > t < lFalse | Why a tuple is greater than a similar list ? |
Python | In Java I can invoke a class or method without importing it by referencing its fully qualified name : Similar syntax will obviously not work using Python : Good practice and PEP recommendations aside , can I do the same thing in Python ? | public class Example { void example ( ) { //Use BigDecimal without importing it new java.math.BigDecimal ( 1 ) ; } } class Example : def example ( self ) : # Fails print ( os.getcwd ( ) ) | How to invoke a Python method using its fully qualified name ? |
Python | I 'm trying to group the similar numbers into one tuple of the form ( number , frequency ) .How do I convert this list into the list below | l1= [ 2,2,2,5,5,7 ] l1= [ ( 2,3 ) , ( 5,2 ) , ( 7,1 ) ] | how to group elements in a list based on frequency into a tuple |
Python | As titled , the result of this function is not logical and I do n't understand what the function is doing.For example , here is some reproducible code : you can see from here : for figure 1 , which is audio above 5dB : for figure 2 , which is audio above 20dB : How can it be that audio above 20dB is more than audio abo... | # load sample audiofilename = librosa.util.example_audio_file ( ) audio , sr = librosa.load ( filename ) # get intervals which are non-silentinter_20 = librosa.effects.split ( audio , top_db=20 ) inter_5 = librosa.effects.split ( audio , top_db=5 ) # create audioabove_20 = np.zeros ( audio.shape ) above_5 = np.zeros ( ... | Return value of librosa.effect.Split is strange |
Python | I am trying the the training and evaluation example on the tensorflow website.Specifically , this part : It appears that if I add the batch normalization layer ( this line : x = layers.BatchNormalization ( ) ( x ) ) I get the following error : InvalidArgumentError : The second input must be a scalar , but it has shape ... | import numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layers ( x_train , y_train ) , ( x_test , y_test ) = keras.datasets.mnist.load_data ( ) x_train = x_train.reshape ( 60000 , 784 ) .astype ( 'float32 ' ) / 255x_test = x_test.reshape ( 10000 , 784 ) .astype ( 'float32 ' ) /... | Keras Batchnormalization and sample weights |
Python | I 'm currently using the blobstore to generate thumbnails for images , however , I like to store the dimensions of the thumbnail in the img tag , as it is good practise and helps speed up rendering and makes a partially loaded page look a bit nicer.How would I calculate the dimensions of a thumbnail generated by the bl... | from __future__ import divisiondef resized_size ( original_width , original_height , width , height ) : original_ratio = float ( original_width ) / float ( original_height ) resize_ratio = float ( width ) / float ( height ) if original_ratio > = resize_ratio : return int ( width ) , int ( round ( float ( width ) / floa... | App Engine : Calculating the dimensions of thumbnails to be generated by serving thumbnails from the blobstore |
Python | How should an iterable be unpacked into a mismatching number of variable ( s ) ? Too many values : can be ignored withNote : `` extended iterable unpacking '' since Python 3 only . About the underscore.How can the opposite case of too few data / more variables : be handled , specifically so that the remaining variables... | > > > one , two = [ 1,2,3 ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : too many values to unpack ( expected 2 ) > > > one , two , *_ = [ 1,2,3,4 ] > > > > > > one , two , three = [ 1,2 ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < modu... | Unpack value ( s ) into variable ( s ) or None ( ValueError : not enough values to unpack ) |
Python | Say I have a string of words : ' a b c d e f ' . I want to generate a list of multi-word terms from this string.Word order matters . The term ' f e d ' should n't be generated from the above example.Edit : Also , words should not be skipped . ' a c ' , or ' b d f ' should n't be generated.What I have right now : Prints... | doc = ' a b c d e f'terms= [ ] one_before = Nonetwo_before = Nonefor word in doc.split ( None ) : terms.append ( word ) if one_before : terms.append ( ' '.join ( [ one_before , word ] ) ) if two_before : terms.append ( ' '.join ( [ two_before , one_before , word ] ) ) two_before = one_before one_before = wordfor term i... | How do I generate multi-word terms recursively ? |
Python | I have the following python program : If I invoke the program like this : the output isBut if I invoke the program with foo as an argument : the output isQuestionHow can I get arg 's default value to become a list ? I 've triedI 've tried setting default= [ 'foo ' ] but that results in : | # ! /usr/bin/env pythonimport argparseparser = argparse.ArgumentParser ( ) parser.add_argument ( 'arg ' , choices= [ 'foo ' , 'bar ' , 'baz ' ] , default='foo ' , nargs='* ' ) args = parser.parse_args ( ) print ( args ) ./prog.py Namespace ( arg='foo ' ) ./prog.py foo Namespace ( arg= [ 'foo ' ] ) prog.py : error : arg... | Python argparse : type inconsistencies when combining 'choices ' , 'nargs ' and 'default ' |
Python | Just curious more than anything why python will allow me to update a slice of a list but not a string ? Is there a good reason for this ? ( I am sure there is . ) | > > > s = `` abc '' > > > s [ 1:2 ] ' b ' > > > s [ 1:3 ] 'bc ' > > > s [ 1:3 ] = `` aa '' > > > l = [ 1,2,3 ] > > > l [ 1:3 ] [ 2 , 3 ] > > > l [ 1:3 ] = [ 9,0 ] > > > l [ 1 , 9 , 0 ] | Why can I update a list slice but not a string slice in python ? |
Python | I think these 3 are logically equivalent , returning the set { 1 , 3 , 4 } : But when I try to check the performance of each in ipython ( v1.2.1 on python 3.4.0 ) , the timeit magic fails . What 's going on here ? Also fails in 2.7 . I ca n't reproduce this using the vanilla python timeit.timeit method . | set ( sum ( ( ( 1 , 3 ) , ( 4 , ) , ( 1 , ) ) , ( ) ) ) set ( sum ( [ [ 1 , 3 ] , [ 4 ] , [ 1 ] ] , [ ] ) ) functools.reduce ( operator.or_ , ( { 1 , 3 } , { 4 } , { 1 } ) , set ( ) ) In [ 1 ] : from operator import or_ ; from functools import reduceIn [ 2 ] : timeit set ( sum ( [ [ 1 , 3 ] , [ 4 ] , [ 1 ] ] , [ ] ) ) ... | Why timeit does n't work on my code snippet ? |
Python | Running some experiments with TensorFlow , want to look at the implementation of some functions just to see exactly how some things are done , started with the simple case of tf.train.GradientDescentOptimizer . Downloaded the zip of the full source code from github , ran some searches over the source tree , got to : Ok... | C : \tensorflow-master\tensorflow\python\training\gradient_descent.pyclass GradientDescentOptimizer ( optimizer.Optimizer ) : def _apply_dense ( self , grad , var ) : return training_ops.apply_gradient_descent ( C : \tensorflow-master\tensorflow\python\training\training_ops.pyfrom tensorflow.python.training import gen_... | Where is the code for gradient descent ? |
Python | I have a following code in python that at least for me produces strange results : This gives the result : It seems ok if I only try to access numpy element but when increasing this element the timings get strange ... Why is there such a difference in timings ? | import numpy as npimport timeita = np.random.rand ( 3,2 ) print timeit.timeit ( ' a [ 2,1 ] + 1 ' , 'from __main__ import a ' , number=1000000 ) print timeit.timeit ( ' a.item ( ( 2,1 ) ) + 1 ' , 'from __main__ import a ' , number=1000000 ) 0.5336301326750.103801012039 | Numpy item faster than operator [ ] |
Python | In python , it is possible to chain operators in this manner : Which is evaluated to With the only difference being that b is evaluated only once ( so , something more like t = eval ( b ) ; a op t and t op c ) .This is advantageous from the view point that it is very readable and more concise than the equivalent versio... | a op b op c a op b and b op c import timeit timeit.timeit ( `` a < = b < = c '' , setup= '' a , b , c=1,2,3 '' ) 0.1086414959972899timeit.timeit ( `` a < = b and b < = c '' , setup= '' a , b , c=1,2,3 '' ) 0.09434155100097996 timeit.timeit ( `` a < = b < = c < = d < = e < = f '' , setup= '' a , b , c , d , e , f=1,2,3,... | Why are chained operator expressions slower than their expanded equivalent ? |
Python | I 've created a script to scrape name and email address from a webpage . When I run my script I get the name accordingly but in case of email this is what I get aeccdcd7cfc0eedadcc783cdc1dc80cdc1c3 . The string that I get instead of email changes every time I run the script.Website linkI 've tried so far : Current outp... | import requestsfrom bs4 import BeautifulSoupurl = `` https : //www.seafoodsource.com/supplier-directory/Tri-Cor-Flexible-Packaging-Inc '' res = requests.get ( url , headers= { `` User-Agent '' : '' Mozilla/5.0 '' } ) soup = BeautifulSoup ( res.text , 'lxml ' ) name = soup.select_one ( `` [ class $ ='-supplier-view-main... | Ca n't get a certain item from a webpage using requests |
Python | I 'm attempting to upgrade to tensorflow version 1.0 but have come to find that I 'm not able to reproduce my earlier output because the random number generator seems to be different . I need to be able to reproduce my results so I always set the seed to a constant value.Output : I 'm running python v3.5.2 on windows x... | import tensorflow as tfwith tf.Graph ( ) .as_default ( ) : tf.set_random_seed ( 1 ) a = tf.get_variable ( ' a ' , 1 ) with tf.Session ( ) as sess : tf.global_variables_initializer ( ) .run ( ) print ( 'TensorFlow version : { 0 } '.format ( tf.__version__ ) ) print ( sess.run ( a ) ) TensorFlow version : 0.12.1 [ -0.397... | Random number generator differs between tensorflow 1.0.1 and 0.12.1 |
Python | I set the on_motion to handle EVT_MOTION . I want the mouse location for interactively generating a coordinate-specific image , but WxPython has a ~400ms delay in registering successive motion events . Which makes the interface sluggish.Why is EVT_MOTION so slow and how do I fix it ? I tried it in Ubuntu 11.10 and WinX... | def on_motion ( self , event ) : `` '' '' mouse in motion '' '' '' # pt = event.GetPosition ( ) self.mouseover_location = event.GetPosition ( ) self.t2 = time.time ( ) print `` delay '' , self.t2 - self.t1 self.t1 = self.t2delay 0.379776954651delay 0.00115919113159delay 0.421130895615delay 0.416938066483delay 0.3768489... | Why is WxPythons motion detection so slow ? |
Python | In my django application , I have a set of donation , which I want to make statistics on . For each donation , a person is linked with his email address.I want to compute for each month , the number of donors , that is the number of unique email addess.So far I have : This works well , I get a monthly report of all ema... | # filter all donations by monthtruncate_date = connection.ops.date_trunc_sql ( 'month ' , 'date ' ) qs = Donation.objects.extra ( { 'month ' : truncate_date } ) # group by months and annotate each with the count of emailsdonors = qs.values ( 'month ' ) .annotate ( count=Count ( 'email ' ) ) .order_by ( 'month ' ) | Django queryset group by and count distincts |
Python | Looking to sharpen my data science skills . I am practicing url data pulls from a sports site and the json file has multiple nested dictionaries . I would like to be able to pull this data to map my own custom form of the leaderboard in matplotlib , etc. , but am having a hard time getting the json to a workable df.The... | import pandas as pdimport urllib as ulimport jsonurl = `` https : //gripapi-static-pd.usopen.com/gripapi/leaderboard.json '' response = ul.request.urlopen ( url ) data = json.loads ( response.read ( ) ) print ( data ) | How to download a nested JSON into a pandas dataframe ? |
Python | I was attempting to create a neural network that utilizes reinforcement learning . I picked scikit-neuralnetwork as the library ( because it 's simple ) . It seems though , that fitting twice crashes Theano.Here 's the simplest code that causes the crash ( Note , it does n't matter what layers there are , nor does the ... | import numpy as npfrom sknn.mlp import Classifier , Layerclf = Classifier ( layers= [ Layer ( `` Softmax '' ) ] , learning_rate=0.001 , n_iter=1 ) clf.fit ( np.array ( [ [ 0 . ] ] ) , np.array ( [ [ 0 . ] ] ) ) # Initialize the network for learningX = np.array ( [ [ -1 . ] , [ 1 . ] ] ) Y = np.array ( [ [ 1 . ] , [ 0 .... | sknn - input dimension mismatch on second fit |
Python | I am tracing a python script like this : Some lines look like this : Unfortunately I have no clue where this code comes from.Is there a way to see the file name ( including the path ) of getEffectiveLevel ( ) ? Of course I could search through all installed python code for a method with this name , but I would like to ... | python -m trace -- ignore-dir= $ HOME/lib64 : $ HOME/lib : /usr -t bin/myscript.py -- - modulename : __init__ , funcname : getEffectiveLevel__init__.py ( 1325 ) : logger = self__init__.py ( 1326 ) : while logger : __init__.py ( 1327 ) : if logger.level : __init__.py ( 1329 ) : logger = logger.parent__init__.py ( 1326 )... | Python module `` trace '' : file path missing |
Python | I 'm working off this example : http : //numba.pydata.org/numba-doc/0.15.1/examples.html # multi-threadingand it states that : You should make sure inner_func is compiled at this point , because the compilation must happen on the main thread . This is the case in this example because we use jit ( ) .It seems in the exa... | import numba as nbimport numpy as npdef inner_func ( result , a , b ) : threadstate = savethread ( ) for i in range ( len ( result ) ) : result [ i ] = np.exp ( 2.1 * a [ i ] + 3.2 * b [ i ] ) restorethread ( threadstate ) signature = nb.void ( nb.double [ : ] , nb.double [ : ] , nb.double [ : ] ) inner_func_nb = nb.ji... | When does a numba function compile ? |
Python | I have some code like this : This could be in a single expression ... .but getSomeValue ( ) can only be called if var is True.So , when calling if var and var2 == getSomeValue ( ) , are both evaluated by the interpreter , or the evaluation stops at var if False ? Where I can find this information on python documentatio... | if var : if var2 == getSomeValue ( ) if var and var2 == getSomeValue ( ) : | `` if var and var2 == getSomeValue ( ) '' in python - if the first is false , is the second statement evaluated ? ' |
Python | I have found the following code in a project.What does the ! r part mean ? | def __repr__ ( self ) : return f '' user= { self.user ! r } , variant= { self.variant ! r } '' | What does ! r mean in Python ? |
Python | I want to modify how IPython handles import errors by default . When I prototype something in the IPython shell , I usually forget to first import os , re or whatever I need . The first few statements often follow this pattern : Sure , that 's my fault for having bad habits and , sure , in a script or real program that... | In [ 1 ] : os.path.exists ( `` ~/myfile.txt '' ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -NameError Traceback ( most recent call last ) < ipython-input-1-0ffb6014a804 > in < module > ( ) -- -- > 1 os.path.exists ( `` ~/myfile.txt '' ) NameError : na... | Make IPython Import What I Mean |
Python | Trying the very simple following example causes my computer to grind to a halt , so that I have to restart . Checking task manager shows hundreds of `` python.exe '' tasks : I am using a dual core cpu ( i5 2467m ) so I thought the above would be fine . I tried setting processes=1 , which causes a slightly different pro... | import mathfrom multiprocessing import Poolpool = Pool ( processes=2 ) print pool.map ( math.sqrt , [ 1,4,9,16 ] ) | Simple toy example using multiprocessing module crashes computer |
Python | FINAL UPDATEI emailed the author of the paper and as it turns out there was a mistake in the equation for sigma . I gave the best answer to pv because they did help answer the problem as stated.FIRST ATTEMPTI am trying to program a numerical representation of the function below : ,and the '+'/'- ' superscripts indicate... | import scipy as spimport numpy as npimport matplotlib.pyplot as pltfrom numpy import pifrom scipy.special import jv , iv , kv , jvp , ivp , kvpm = 11 # Mode numbernr = 2 # Index of refractionR = 1 # Radius of cylindereps = 10e-8def yv_imcut ( n , z ) : return -2/ ( pi* ( 1j ) **n ) *kv ( n , -1j*z ) + 2* ( 1j ) **n/pi ... | Programming function containing cut in negative imaginary axis |
Python | i want to add a 3rd column with tuples , where each list element from 'key ' is matched with its list index in 'hi ' - > e.g . that it looks like this.i know that i have to use the zip function , but i cant get thy syntax right.i think it should be something likebut this is somehow wrong | a= [ [ ' 1 ' , ' 2 ' ] , [ ' 3 ' , ' 4 ' ] ] b= [ [ ' 5 ' , ' 6 ' ] , [ ' 7 ' , ' 8 ' ] ] df14=pd.DataFrame ( { 'key ' : a , 'hi ' : b } ) key hi tup0 [ 1 , 2 ] [ 5 , 6 ] [ ( 1,5 ) , ( 2,6 ) ] 1 [ 3 , 4 ] [ 7 , 8 ] [ ( 3,7 ) , ( 4,8 ) ] for index , row in df14.iterrows ( ) : df14 [ 'tup ' ] =df14.key.apply ( lambda x :... | zip list elements in different dataframe columns |
Python | Given the following data : How can I produce at chart using matplotlib , that plots ' b ' column of df1 and on top of that , puts markers on same plot line , but using the index points from df2.The desired chart would look something like this : I looked at this answer but ca n't quite adapt it . The issue is that in th... | df1 a b c 1/1/2017 -162 1525 -41 1/2/2017 192 1530 86 1/3/2017 33 1520 -124 1/4/2017 173 1502 -108 1/5/2017 194 1495 -31 1/6/2017 -15 1520 -46 1/7/2017 52 1525 181 1/8/2017 -2 1530 -135 1/9/2017 37 1540 651/10/2017 197 1530 73df2 a1/3/2017 331/6/2017 -151/7/2017 521/8/2017 -21/9/2017 37 xs = df1 [ ' b ' ] ys = df2 [ ' ... | How to plot overlapping series using line and markers ? |
Python | I have a big legacy Python method which contains roughly twenty return statements.The method should not return None but it does so . It is repeatable in a simple test case.Up to now I used a debugger and stepped through the code line by line to find the matching return statement.But is there an easier way ? Is there a ... | def big_method ( arg1 , some_var ) : # ... . many returns if arg1 : return some_var # < -- -- -- # ... many returnsassert not big_method ( True , None ) is None Traceback ( most recent call last ) : File `` /home/modwork_vums_d/src/manyreturns.py '' , line 8 , in < module > assert not big_method ( True , None ) is None... | Debug where method returns None |
Python | I want to use multiprocessing on a model to get predictions using a data frame as input . I have the following code : The error I 'm getting is : I think the issue is with the fact that I 'm passing in a data frame as the second parameter to the pool.map function . Any advice or help would be appreciated . | def perform_model_predictions ( model , dataFrame , cores=4 ) : try : with Pool ( processes=cores ) as pool : result = pool.map ( model.predict , dataFrame ) return result # return model.predict ( dataFrame ) except AttributeError : logging.error ( `` AttributeError occurred '' , exc_info=True ) raise TypeError ( `` sp... | Multiprocessing on a model with data frame as input |
Python | Is there a reason why this does n't work in Python ? | if 1 ! = 1 or 2 ! = 2 : print 'Something is wrong ... ' | Why no python implicit line continuation on 'and ' , 'or ' , etc . ? |
Python | I 'd like to know where the module I 'm about to import is coming from . Is there a which command in python ? Example : | > > > which module_name/usr/lib/python2.6/site-packages/module_name.py | Is there a python equivalent to the Unix ` which ` command ? |
Python | This is the example form , I 'll try to explain it in words later.I have a list from breaking up a string ... saywhere b is criteria 1 and c is criteria 2I want to break it into a list like this : So I want to process the string such that when I go through it , if the item matches criteria 1 , open a new list , if item... | [ a , a , a , b , a , a , b , a , c , a , b , a , a , c , a , c , a ] [ a , a , a , [ b , a , a , [ b , a , c ] , a , [ b , a , a , c ] , a , c ] , a ] def sublist ( self , l ) : for line in list : if not b : self.data.append ( line ) else : sublist ( l [ line : ] ) # < -- -- - not sure how to recurse it . | How to process a string into layer of sublists |
Python | I discovered that numpy.sin behaves differently when the argument size is < = 8192 and when it is > 8192 . The difference is in both performance and values returned . Can someone explain this effect ? For example , let 's calculate sin ( pi/4 ) : After crossing the 8192 elements limit the calculations become more than ... | x = np.pi*0.25for n in range ( 8191 , 8195 ) : xx = np.repeat ( x , n ) % timeit np.sin ( xx ) print ( n , np.sin ( xx ) [ 0 ] ) 64.7 µs ± 194 ns per loop ( mean ± std . dev . of 7 runs , 10000 loops each ) 8191 0.707106781186547664.6 µs ± 166 ns per loop ( mean ± std . dev . of 7 runs , 10000 loops each ) 8192 0.70710... | Why does numpy.sin return a different result if the argument size is greater than 8192 ? |
Python | Is there a way to avoid this loop so optimize the code ? Note : dist_ and TLabels are both numpy arrays with the same shape ( t,1 ) | import numpy as npcLoss = 0dist_ = np.array ( [ 0,1,0,1,1,0,0,1,1,0 ] ) # just an example , longer in realityTLabels = np.array ( [ -1,1,1,1,1 , -1 , -1,1 , -1 , -1 ] ) # just an example , longer in realityt = float ( dist_.size ) for i in range ( len ( dist_ ) ) : labels = TLabels [ dist_ == dist_ [ i ] ] cLoss+= 1 - ... | NumPy : How to avoid this loop ? |
Python | I noticed some confusing behavior when indexing a flat numpy array with a list of tuples ( using python 2.7.8 and numpy 1.9.1 ) . My guess is that this is related to the maximum number of array dimensions ( which I believe is 32 ) , but I have n't been able to find the documentation . Is the list of tuples is being `` ... | > > > a = np.arange ( 100 ) > > > tuple_index = [ ( i , ) for i in a ] > > > a [ tuple_index ] # This works ( but maybe it should n't ) > > > a [ tuple_index [ :32 ] ] # This works too > > > a [ tuple_index [ :31 ] ] # This breaks for 2 < = i < 32Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in ... | Strange behavior of tuple indexing a numpy array |
Python | I 'm using scikit-learn 's RFECV class to perform feature selection . I 'm interested in identifying the relative importance of a bunch of variables . However , scikit-learn returns the same ranking ( 1 ) for multiple variables . This can also be seen in their example code : Is there a way I can make scikit-learn also ... | > > > from sklearn.datasets import make_friedman1 > > > from sklearn.feature_selection import RFECV > > > from sklearn.svm import SVR > > > X , y = make_friedman1 ( n_samples=50 , n_features=10 , random_state=0 ) > > > estimator = SVR ( kernel= '' linear '' ) > > > selector = RFECV ( estimator , step=1 , cv=5 ) > > > s... | scikit-learn feature ranking returns identical values |
Python | I stumbled upon a behaviour in python that I have a hard time understanding . This is the proof-of-concept code : The output of the above is : The behaviour of loop_one is surprising to me as I would expect it to behave as loop_two : el is an immutable value ( a string ) that changes at each loop , but lambda seems to ... | from functools import partialif __name__ == '__main__ ' : sequence = [ 'foo ' , 'bar ' , 'spam ' ] loop_one = lambda seq : [ lambda : el for el in seq ] no_op = lambda x : x loop_two = lambda seq : [ partial ( no_op , el ) for el in seq ] for func in ( loop_one , loop_two ) : print [ f ( ) for f in func ( sequence ) ] ... | Weird lambda behaviour in loops |
Python | Someone asked here why when putting 1 and True in a set only 1 is kept.This is of course because 1==True . But in which cases 1 is kept and in which cases True is kept ? Let 's see : passing a list to build the set instead of using the set notation : seems logical : set iterates on the inner list , and does n't add the... | > > > set ( [ True,1 ] ) { True } > > > set ( [ 1 , True ] ) { 1 } > > > { True,1 } { 1 } > > > { 1 , True } { True } | Order of insertion in sets ( when parsing { } ) |
Python | This is mostly a logical question , but the context is done in Django.In our Database we have Vertex and Line Classes , these form a ( neural ) network , but it is unordered and I ca n't change it , it 's a Legacy DatabaseNow , in the application , the user will be able to visually select TWO vertexes ( the green circl... | class Vertex ( models.Model ) code = models.AutoField ( primary_key=True ) lines = models.ManyToManyField ( 'Line ' , through='Vertex_Line ' ) class Line ( models.Model ) code = models.AutoField ( primary_key=True ) class Vertex_Line ( models.Model ) line = models.ForeignKey ( Line , on_delete=models.CASCADE ) vertex =... | Django finding paths between two vertexes in a graph |
Python | I have a GUI with a QDockwidget and I would like that the color of the title bar of the dock widgets changes color if the user hovers above it with the mouse cursor . I have a small test program below where the title bar changes color when the cursor is above it . However , it also changes color if the cursor is above ... | CSS = `` '' '' QDockWidget : :title { background-color : lightblue ; border : 1px solid black ; } QDockWidget : :title : hover { background : yellow ; } QMainWindow : :separator { background : palette ( Midlight ) ; } QMainWindow : :separator : hover { background : palette ( Mid ) ; } '' '' '' from PyQt5 import QtWidge... | Change QDocketWidget hover title bar color with CSS |
Python | I would like to use pandas and statsmodels to fit a linear model on subsets of a dataframe and return the predicted values . However , I am having trouble figuring out the right pandas idiom to use . Here is what I am trying to do : This raises the following error : The error makes sense in that I think .transform want... | import pandas as pdimport statsmodels.formula.api as smimport seaborn as snstips = sns.load_dataset ( `` tips '' ) def fit_predict ( df ) : m = sm.ols ( `` tip ~ total_bill '' , df ) .fit ( ) return pd.Series ( m.predict ( df ) , index=df.index ) tips [ `` predicted_tip '' ] = tips.groupby ( `` day '' ) .transform ( fi... | Can pandas groupby transform a DataFrame into a Series ? |
Python | The documentation reads : But it does n't tell me much how to get this filename back from the AST node . Or how is this filename parameter is used . Is it just a stub ? | ast.parse ( source , filename= ' < unknown > ' , mode='exec ' ) Equivalent to compile ( source , filename , mode , ast.PyCF_ONLY_AST ) .compile ( source , filename , mode [ , flags [ , dont_inherit ] ] ) The filename argument should give the file from which the code was read ; pass some recognizable value if it wasn ’ ... | What 's the use of the filename parameter of ast.parse ? |
Python | Why/how does this create a seemingly infinite loop ? Incorrectly , I assumed this would cause some form of a stack overflow type error . | i = 0def foo ( ) : global i i += 1 try : foo ( ) except RuntimeError : # This call recursively goes off toward infinity , apparently . foo ( ) foo ( ) print i | Why does this Python script create an infinite loop ? ( recursion ) |
Python | I use nose for test collection and I also want to use its doctest plugin . I have a module that needs a fixture in order to be importable . Therefore , I can not use nose 's module fixtures , since they are loaded from the module under test . Is there a way to specify module fixtures for nose-doctest outside of the mod... | ~/pckg/ __init__.py py3only.py ... ( other modules ) tests/ test_py3only.py def fancy_py3_func ( a : '' A function argument annotation ( python 3 only syntax ) '' ) : `` '' '' A function using fancy syntax doubling it 's input . > > > fancy_py3_func ( 4 ) 8 `` '' '' return a*2 import sys , unittestdef setup_module ( ) ... | nose-doctest module fixture before module is imported |
Python | I 'm learning to use python decorator.I realize the decorated function 'fun ' acts like a black box inside the decorator . I can choose to use fun ( ) or not at all inside new_fun . However , I do n't know whether I can break into 'fun ' and interact with fun 's local scope inside the new_fun ? e.g . I 'm trying to mak... | def my_dcrtr ( fun ) : def new_fun ( ) : return fun ( ) return new_fun def return_locals_rpc_decorator ( fun ) : def decorated_fun ( *args , **kw ) : local_args = fun ( *args , **kw ) # pickle the local_args and send it to server # server unpickle and doing the RPC # fetch back server results and unpickle to results re... | Python : Modify the internal behavior of a function by using decorator |
Python | I have an awesome little function that looks like this : The point of the function is that I can call it from anywhere with a message , and if my project config file is set to verbose mode , all the messages will be printed with a helpful prefix to show where it was called . Here 's an example of some output : The form... | def verbose_print ( message , *args , **kwargs ) : `` '' '' Prints ` message ` with a helpful prefix when in verbose mode Args : message ( str ) : The message to print . Can be a format string , e.g . ` A % s with some % s in it ` *args : Variables for the message format **kwargs : Keyword variables for the message for... | How can I get the name of the class of a bound method from the interpreter stack ? |
Python | I 'm running code to generate a mask of locations in B closer than some distance D to locations in A.For lists of A and B that are tens of thousands of locations long , this code takes a while . I 'm pretty sure there 's a way to vectorize this though to make it run much faster . Thank you . | N = [ [ 0 for j in range ( length_B ) ] for i in range ( length_A ) ] dSquared = D*Dfor i in range ( length_A ) : for j in range ( length_B ) : if ( ( A [ j ] [ 0 ] -B [ i ] [ 0 ] ) **2 + ( A [ j ] [ 1 ] -B [ i ] [ 1 ] ) **2 ) < = dSquared : N [ i ] [ j ] = 1 | Vectorize mask of squared euclidean distance in Python |
Python | I 'm trying to sanitize user input to prevent XSS injection using libxml 's HTML cleaner . When I input a string like this : I get this instead : I want to get rid of the < p > tag that surrounds all of my input.Here is the function that currently does the cleaning : On an unrelated note , the above code has one line :... | Normal text < b > Bold text < /b > < p > Normal text < b > Bold text < /b > < /p > from lxml.html import cleancleaner = clean.Cleaner ( scripts = True , javascript = True , allow_tags = None , ) def sanitize_html ( html ) : return cleaner.clean_html ( html ) | Libxml Cleaner adds unwanted < p > tag to HTML fragments |
Python | While trying to fine-tune some memory leaks in the Python bindings for some C/C++ functions I cam across some strange behavior pertaining to the garbage collection of Numpy arrays . I have created a couple of simplified cases in order to better explain the behavior . The code was run using the memory_profiler , the out... | # File deallocate_ndarray.py @ profiledef ndarray_deletion ( ) : import numpy as np from gc import collect buf = 'abcdefghijklmnopqrstuvwxyz ' * 10000 arr = np.frombuffer ( buf ) del arr del buf collect ( ) y = [ i**2 for i in xrange ( 10000 ) ] del y collect ( ) if __name__=='__main__ ' : ndarray_deletion ( ) Filename... | numpy.ndarray objects not garbage collected |
Python | I need to generate 1D array where repeated sequences of integers are separated by a random number of zeros.So far I am using next code for this : It works but looks very slow when I need a lot of long sequences . So , how can I optimize it ? | from random import normalvariateregular_sequence = np.array ( [ 1,2,3,4,5 ] , dtype=np.int ) n_iter = 10lag_mean = 10 # mean length of zeros sequencelag_sd = 1 # standard deviation of zeros sequence length # Sequence of lags lengthslag_seq = [ int ( round ( normalvariate ( lag_mean , lag_sd ) ) ) for x in range ( n_ite... | Generate 1d numpy with chunks of random length |
Python | I have a C FFI written in Rust , called src/lib.rs that looks like the following : This is my Cargo.toml in the project base folder : This is the Python code calling Rust , also put in the base folder : I have good reason to believe that the C code is correct , since the rle_values_size and rle_values refer to the same... | // compile with $ cargo buildextern crate libc ; use self : :libc : : { size_t , int32_t } ; use std : :cmp : :min ; use std : :slice ; # [ no_mangle ] pub extern `` C '' fn rle_new ( values_data : *const int32_t , values_length : size_t ) - > *mut Rle { let values = unsafe { slice : :from_raw_parts ( values_data , val... | Dereference FFI pointer in Python to get underlying array |
Python | I tried now for one hour and I do n't get the result I expect , so I need to ask you here : I have Emacs 24 installedI have Python 3.0 installedActually I try to parse a python output to a table via orgmode : I expect a table when I export the buffer to pdf/html.However this does not happen.Can anyone fix my code and t... | # +begin_src python : session : results output table : exports resultsprint ( `` |Example| '' ) print ( `` | -- -- -- -- | '' ) print ( `` |One example entry| '' ) # +end_src | Parse Python Output in OrgMode to a table |
Python | I want to dynamically create classes at runtime in python.For example , I want to replicate the code below : ... but I want the Foo1 , Foo2 , Foo classes to be created dynamically ( ie : during execution instead of on first-pass compile ) .One way to achieve this is with type ( ) , like so : I can also achieve it with ... | > > > class RefObj ( object ) : ... def __init__ ( self , ParentClassName ) : ... print `` Created RefObj with ties to % s '' % ParentClassName ... class Foo1 ( object ) : ... ref_obj = RefObj ( `` Foo1 '' ) ... class Foo2 ( object ) : ... ref_obj = RefObj ( `` Foo2 '' ) ... Created RefObj with ties to Foo1Created RefO... | What is the advantage in using ` exec ` over ` type ( ) ` when creating classes at runtime ? |
Python | I 'm applying a concordance command over each item in a list . It works fine , but when it does not find a match , it prints out No matches . I would like it to ignore those and only print out results for matches.absol is the variable that contains the listHere is the relevant part of the script : | def get_all_phrases_containing_tar_wrd ( target_word , tar_passage , left_margin = 10 , right_margin = 10 ) : Ellis = nltk.word_tokenize ( tar_passage ) text = nltk.Text ( Ellis ) c = nltk.ConcordanceIndex ( text.Ellis , key = lambda s : s.lower ( ) ) concordance_txt = ( [ text.Ellis [ map ( lambda x : x-5 if ( x-left_... | Stop concordance printing 'no matches ' in python |
Python | I 'm trying to create a grammar to parse some Excel-like formulas I have devised , where a special character in the beginning of a string signifies a different source . For example , $ can signify a string , so `` $ This is text '' would be treated as a string input in the program and & can signify a function , so & fo... | grammar = r '' 'start : instruction ? instruction : simple | funcSTARTSYMBOL : `` ! `` | '' # '' | '' $ '' | '' & '' | '' ~ '' SINGLESTR : ( LETTER+|DIGIT+| '' _ '' | '' `` ) *simple : STARTSYMBOL [ SINGLESTR ] ( WORDSEP SINGLESTR ) *ARGSEP : `` , , '' // argument separatorWORDSEP : `` , '' // word separatorCONDSEP : `... | How to setup a grammar that can handle ambiguity |
Python | This is hard to explain but I will try to represent this in a small example : number of payments : Since the first month starts with 11 in NDD then the first element of my list will be 11 , to compute the next element I take the first month ( 11 ) and subtract the first payment 1 and then the second element is 10 . Thi... | NDD = 11/1/2018 1 0 2 0 2 1 1 0 2 1 1 1 11 10 10 8 8 6 5 4 4 2 1 12 number_of_payments = [ 1 0 2 0 2 1 1 0 2 1 1 1 ] dates = [ ] dates.append ( NDD.month ) for i in range ( 1,12 ) : dates [ i ] = ( dates [ i-1 ] + 12 - number_of_payments [ i-1 ] ) % 12 dates = [ 11 10 10 8 8 6 5 4 4 2 1 12 ] 11/18 10/18 10/18 8/18 8/18... | Datetime manipulation with lists |
Python | OVERVIEW I got a set of possible valid chunks I can use to split a text ( if possible ) .How can i split a given text using these chunks such as the result will be optimized ( minimized ) in terms of the number of resulting chunks ? TEST SUITEQUESTIONHow could I solve this problem on python without using a brute-force ... | if __name__ == `` __main__ '' : import random import sys random.seed ( 1 ) # 1 ) Testing robustness examples = [ ] sys.stdout.write ( `` Testing correctness ... '' ) N = 50 large_number = `` 314159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460... | How to split text into chunks minimizing the solution ? |
Python | writing a general function that can iterate over any iterable returning now , next pairs.I have been thinking about the best way to write a function where the number of items in each tuple can be set . for example if it wasthe result would be : I am new to using timeit , so please point out if I doing anything wrong he... | def now_nxt ( iterable ) : iterator = iter ( iterable ) nxt = iterator.__next__ ( ) for x in iterator : now = nxt nxt = x yield ( now , nxt ) for i in now_nxt ( `` hello world '' ) : print ( i ) ( ' h ' , ' e ' ) ( ' e ' , ' l ' ) ( ' l ' , ' l ' ) ( ' l ' , ' o ' ) ( ' o ' , ' ' ) ( ' ' , ' w ' ) ( ' w ' , ' o ' ) ( '... | python now , next , n iteration |
Python | I have two similar codes that need to be parsed and I 'm not sure of the most pythonic way to accomplish this.Suppose I have two similar `` codes '' both codes end with $ $ otherthing and contain a number of values separated by -At first I thought of using functools.wrap to separate some of the common logic from the lo... | secret_code_1 = 'asdf|qwer-sdfg-wert $ $ otherthing'secret_code_2 = 'qwersdfg-qw|er $ $ otherthing ' from functools import wrapsdef parse_secret ( f ) : @ wraps ( f ) def wrapper ( code , *args ) : _code = code.split ( ' $ $ ' ) [ 0 ] return f ( code , *_code.split ( '- ' ) ) return wrapper @ parse_secretdef parse_code... | How to compose two functions whose outer function supplies arguments to the inner function |
Python | Let 's say i have a lot of functions in alotoffunc.py that is used by more than 1 type of object . Let 's say ObjectI and ObjectII and ObjectXI all uses some functions in alotoffunc.py . And each of the Object were using different set of functions but all the objects have the variable object.table.alotoffunc.py : And t... | def abc ( obj , x ) : return obj.table ( x ) * 2def efg ( obj , x ) : return obj.table ( x ) * obj.table ( x ) def hij ( obj , x , y ) : return obj.table ( x ) * obj.table ( y ) def klm ( obj , x , y ) : return obj.table ( x ) *2 - obj.table ( y ) import alotoffuncclass ObjectI : def abc ( self , x ) : return alotoffun... | Creating classes with a lot of imported functions here and there |
Python | In my latest series of questions , I asked about fooling around with the internals of argparse . Mostly , I want to change an attribute defined as : Since it is `` protected '' , I would like to check if this attribute exists and if it is a regular expression before I substitute in my own regex . e.g . : This fails wit... | class FooClass ( object ) : def __init__ ( self ) : self._this_is_a_re=re.compile ( `` foo '' ) import remyFoo=FooClass ( ) attr='_this_is_a_re'if ( hasattr ( myFoo , attr ) and isinstance ( getattr ( myFoo , attr ) , re.RegexObject ) : setattr ( myFoo , attr , re.compile ( `` bar '' ) ) | re.RegexObject does n't exist ( raises AttributeError ) |
Python | I am trying to wrap/monkey patch modules in python . I am trying to develop a a clean means of implementing this that does not interfere with any existing code . ProblemGiven a script that imports some CLASS from a MODULEI would like to replace MODULE with another _MODULE_ . Where _MODULE_ is a patch for the original M... | from MODULE import CLASS from overlay import MODULE # Switches MODULE for _MODULEfrom MODULE import CLASS # Original import now uses _MODULE_ | Python Overlays : A case for monkey Patching |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.