lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | According to this primer on subclassing ndarray , the __array_finalize__ method is guaranteed to be called , no matter if the subclass is instantiated directly , casted as a view or created from a template.In particular , when calling the constructor explicitly , the order of methods called is __new__ - > __array_final... | class Frame ( np.ndarray ) : def __new__ ( cls , input_array , title='unnamed ' ) : print 'calling Frame.__new__ with title { } '.format ( title ) self = input_array.view ( Frame ) # does not call __new__ or __init__ print 'creation of self done , setting self.title ... ' self.title = title return self def __array_fina... | Subclassing numpy.ndarray - why is __array_finalize__ not being called twice here ? |
Python | I have a config class that has the config for my Flask app . Most of the config options are picked up , but the secret_key remains unset , and so using the session raises an error . Why is n't the config fully imported ? app.py : config.py : When I access a view that uses the session , I get this error : | app = Flask ( __name__ ) app.config.from_object ( 'config.BaseConfig ' ) class BaseConfig ( object ) : DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite : ///test.db ' SQLALCHEMY_TRACK_MODIFICATIONS = False secret_key = '122332 ' RuntimeError : the session is unavailable because no secret key was set . Set the secret_key ... | Flask does n't get secret_key config from config object |
Python | I tried searching for something similar , and the closest thing I could find was this which helped me to extract and manipulate the data , but now I ca n't figure out how to re-plot the histogram . I have some array of voltages , and I have first plotted a histogram of occurrences of those voltages . I want to instead ... | import numpyimport matplotlib.pyplot as pyplotmydata = numpy.random.normal ( -15 , 1 , 500 ) # this seems to have to be 'uneven ' on either side of 0 , otherwise the code looks fine . FYI , my actual data is all positivepyplot.figure ( 1 ) hist1 = pyplot.hist ( mydata , bins=50 , alpha=0.5 , label='set 1 ' , color='red... | Python histograms : Manually normalising counts and re-plotting as histogram |
Python | I have the following code that reads an image with opencv and displays it : I want to generate some random images by using keras so I define this generator : but , when I use it in this way : I get this error : And it seems obvious to me : RGB , an image , of course it is 3 dimension ! What am I missing here ? The docu... | import cv2 , matplotlib.pyplot as pltimg = cv2.imread ( 'imgs_soccer/soccer_10.jpg ' , cv2.IMREAD_COLOR ) img = cv2.resize ( img , ( 128 , 128 ) ) plt.imshow ( img ) plt.show ( ) image_gen = ImageDataGenerator ( rotation_range=15 , width_shift_range=0.1 , height_shift_range=0.1 , shear_range=0.01 , zoom_range= [ 0.9 , ... | ImageDataGenerator : how to add the 4th dimension to a numpy array ? |
Python | For understanding what I 'm trying to achieve : printing delayed text in another view ... I 'm trying to make this sublime text 3 plugin run properly I want to call multiple method of my class using the edit passed in parameter of my run method as so : And I try to use it later on another method , but when I execute th... | # sample code , nothing realclass MyCommandClass ( sublime_plugin.TextCommand ) : myEdit = None def run ( self , edit ) : self.myEdit = edit # stuff self.myMethod ( ) def myMethod ( self ) : # use self.myEdit ... | Save the edit when running a Sublime Text 3 plugin |
Python | Before you think that it 's duplicated ( there are many question asking how to split long strings without breaking words ) take in mind that my problem is a bit different : order is not important and I 've to fit the words in order to use every line as much as possible.I 've a unordered set of words and I want to combi... | def compose ( words ) : result = `` `` .join ( words ) if len ( result ) > 253 : pass # this should not happen ! return result words = `` a bc def ghil mno pq r st uv '' limit = 5 # max 5 characters # This is good because it 's the shortest possible list , # but I do n't know how could I get it # Note : order is not im... | Splitting long string without breaking words fulfilling lines |
Python | According to the performance tip from Yahoo : When users request a page , it can take anywhere from 200 to 500ms for the backend server to stitch together the HTML page . During this time , the browser is idle as it waits for the data to arrive . In PHP you have the function flush ( ) . It allows you to send your parti... | ... < ! -- css , js -- > < /head > < ? php flush ( ) ; ? > < body > ... < ! -- content -- > | Is there a function in Django / Python similar to PHP flush ( ) that lets me send part of the HTTP response to clients ? |
Python | I have seen a pattern repeated a couple times in my team 's code , it looks like thisI was wondering if there is a function somewhere ( I have looked around but have n't been able to find it ) that would do something like thisSo , this function I am looking for , would receive an iterable and a function , and return tw... | numbers = [ 1 , 2 , 3 , 4 ] even_numbers = [ n for n in numbers if n % 2 == 0 ] odd_numbers = [ n for n in numbers if n % 2 ! = 0 ] numbers = [ 1 , 2 , 3 , 4 ] even_numbers , odd_numbers = fork ( numbers , lambda x : x % 2 == 0 ) | Is there a way to `` fork '' a list in two based on a condition |
Python | I have been studying examples from the profile documentation and I have come to the workflow when I runThis gives me some general stats of the number of calls made and so on . Mind you , it is rather cryptic : I heaviliy use numpy inside myFunc ( like numpy.sum , * and the like ) but I can not find those calls in the s... | import cProfile as profileimport pstatspr = profile.Profile ( ) pr.runcall ( myFunc , args , kwargs ) st = pstats.Stats ( pr ) st.print_stats ( ) # and other methods like print_callees , print_callers , etc . | Python profiling : time spent on each line of function |
Python | I 'm trying to use group by to create a new dataframe , but I need the multi index to be consistent . Regardless of whether the sub category exists , I 'd like it to be created like the following : With output that looks like : But I 'd like it to look likeI read different data that then adds a column in this format so... | import pandas as pddf = pd.DataFrame ( { 'Cat 1 ' : [ ' A ' , ' A ' , ' A ' , ' B ' , ' B ' , ' B ' , ' B ' , ' C ' , ' C ' , ' C ' , ' C ' , ' C ' , 'D ' ] , 'Cat 2 ' : [ ' A ' , ' B ' , ' A ' , ' B ' , ' B ' , ' B ' , ' A ' , ' B ' , ' B ' , ' B ' , ' B ' , ' B ' , ' A ' ] , 'Num ' : [ 1,1,1,1,1,1,1,1,1,1,1,1,1 ] } )... | Pandas Groupby Consistent levels even if empty |
Python | I am using sphinx with the pngmath extension to document my code that has a lot of mathematical expressions . Doing that in a *.rst file is working just fine.a \times b becomes : However , if I try the same inside a *.py file for example in a module documentation like so : I end up with Furthermore no amsmath functiona... | `` `` '' a \times b '' '' '' | How to enable math in sphinx ? |
Python | I need a way to reverse my key values pairing . Let me illustrate my requirements.I want the above to be converted to the following : | dict = { 1 : ( a , b ) , 2 : ( c , d ) , 3 : ( e , f ) } dict = { 1 : ( e , f ) , 2 : ( c , d ) , 3 : ( a , b ) } | Reverse key value pairing in python dictionary |
Python | I 'm currently using BeautifulSoup4 with Python 2.7 and trying to instantiate a new tag , with a certain class attribute . I know how to use attributes such as style : However , if I try to do this with the class reserved word , I get an error ( invalid syntax ) .I have also tried with 'class'= ' ... ' , but this is al... | div = soup.new_tag ( 'div ' , style='padding-left : 10px ' , attr2= ' ... ' , ... ) div = soup.new_tag ( 'div ' , class='left_padded ' , attr2= ' ... ' , ... ) # Throws error div = soup.new_tag ( 'div ' , attr2= ' ... ' , ... ) div [ 'class ' ] = 'left_padded ' | How can I specify a class attribute in new_tag ( ) ? |
Python | Python Tutorial 4.7.1 . Default Argument Values states the following : Important warning : The default value is evaluated only once . This makes a difference when the default is a mutable object such as a list , dictionary , or instances of most classes . For example , the following function accumulates the arguments p... | def f ( a , L= [ ] ) : L.append ( a ) return Lprint f ( 1 ) print f ( 2 ) print f ( 3 ) [ 1 ] [ 1 , 2 ] [ 1 , 2 , 3 ] | Python function : Optional argument evaluated once ? |
Python | Ok , I know this question has been asked a lot of times already , but I do n't get this working : I try to use xkcd-style in matplotlib on Ubuntu 16.04 LTS 64-bit with python 2.7.12 64-bit and I use sample code from matplotlib.org/xkcd/examples ( see below ) , but I still get this ! What I 've done yetinstall matplotli... | from matplotlib import pyplot as pltimport numpy as npplt.xkcd ( ) fig = plt.figure ( ) ax = fig.add_subplot ( 1 , 1 , 1 ) ax.spines [ 'right ' ] .set_color ( 'none ' ) ax.spines [ 'top ' ] .set_color ( 'none ' ) plt.xticks ( [ ] ) plt.yticks ( [ ] ) ax.set_ylim ( [ -30 , 10 ] ) data = np.ones ( 100 ) data [ 70 : ] -= ... | matplotlib 's xkcd ( ) not working |
Python | For some reason the order of the covariates seems to matter with a LogisticRegression classifier in scikit-learn , which seems odd to me . I have 9 covariates and a binary output , and when I change the order of the columns and call fit ( ) and then call predict_proba ( ) the output is different . Toy example belowThe ... | logit_model = LogisticRegression ( C=1e9 , tol=1e-15 ) logit_model.fit ( df [ 'column_2 ' , 'column_1 ' ] , df [ 'target ' ] ) logit_model.predict_proba ( df [ 'column_2 ' , 'column_1 ' ] ) array ( [ [ 0.27387109 , 0.72612891 ] .. ] ) logit_model.fit ( df [ 'column_1 ' , 'column_2 ' ] , df [ 'target ' ] ) logit_model.p... | LogisticRegression scikit learn covariate ( column ) order matters on training |
Python | I have a Django 1.8 application whose initial migration relies on django-interval-field like this : I 've since migrated this field to use Django 's built-in DurationField , and I 'm not using this module anymore , but I need to keep it in requirements.txt in order for my migrations to run.However , this module throws ... | import interval.fieldsmigrations.CreateModel ( name='Item ' , fields= [ ... ( 'estimated_time ' , interval.fields.IntervalField ( null=True , blank=True ) ) , | Removing a Django migration that depends on custom field from an old module |
Python | In PHP one can use the function preg_match with the flag PREG_OFFSET_CAPTURE in order to search a regex patter within a string and know what follows and what comes first . For example , given the string aaa bbb ccc ddd eee fff , I 'd like to match-split r'ddd ' and have : How to do this in python ? Thanks | before = 'aaa bbb ccc 'match = 'ddd'after = ' eee fff ' | Python regex search AND split |
Python | I am trying to implement a scan loop in theano , which given a tensor will use a `` moving slice '' of the input . It does n't have to actually be a moving slice , it can be a preprocessed tensor to another tensor that represents the moving slice.Essentially : where | -- -- -- -| is the input for each iteration.I am tr... | [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ] | -- -- -- -| ( first iteration ) | -- -- -- -| ( second iteration ) | -- -- -- -| ( third iteration ) ... ... ... | -- -- -- -| ( last iteration ) | Overlapping iteration over theano tensor |
Python | As part of a large piece of code , I need to call the ( simplified ) function example ( pasted below ) multiple ( hundreds of thousands of ) times , with different arguments . As such , I need this module to run quickly.The main issue with the module seems to be the multiple nested loops . However , I am not sure if th... | import numpy as npimport mathcimport numpy as npcimport cythonDTYPE = np.floatctypedef np.float_t DTYPE_tcdef extern from `` math.h '' : double log ( double x ) nogil double exp ( double x ) nogil double pow ( double x , double y ) nogildef example ( double [ : :1 ] xbg_PSF_compressed , double [ : :1 ] theta , double [... | Nested loop optimization in cython : is there a faster way to setup this code example ? |
Python | I want to have a dialog window where some buttons close the dialog and others do n't . The way I do this is by using the response signal from the Gtk.Dialog to call emit_stop_by_name ( 'response ' ) on the dialog . ( If someone knows of a better way of doing this , that might preempt the whole rest of this question . )... | from gi.repository import Gtkxml = `` '' '' < interface > < object class= '' GtkDialog '' id= '' dialog1 '' > < signal name= '' response '' handler= '' on_response '' / > < child internal-child= '' vbox '' > < object class= '' GtkBox '' id= '' dialog-vbox1 '' > < child internal-child= '' action_area '' > < object class... | Dialog breaks when using GtkBuilder to automatically connect signals , but works when manually connecting signals |
Python | Below is an example I got from someone 's blog about python closure.I run it in python 2.7 and get a output different from my expect.My expected output is : 0 , 2 , 4But the output is : 4 , 4 , 4Is there anyone could help to explain it ? Thank you in advance . | flist = [ ] for i in xrange ( 3 ) : def func ( x ) : return x*i flist.append ( func ) for f in flist : print f ( 2 ) | About python closure |
Python | When running my tests I am getting the following traceback.__init__.pytest_routes.pyIt appears that the get_context_variable function call is where the error is coming from . I also receive this error if I try and use assert_template_used . Having a rather difficult time finding any resolution to this . | in get_context_variableraise RuntimeError ( `` Signals not supported '' ) RuntimeError : Signals not supported from flask_testing import TestCasefrom app import create_app , dbclass BaseTest ( TestCase ) : BASE_URL = 'http : //localhost:5000/ ' def create_app ( self ) : return create_app ( 'testing ' ) def setUp ( self... | Flask-Testing signals not supported error |
Python | Good day , I have a dataframe where I want to isolate a part of the string for each row for that column . The problem I am having is that each row needs to have a substring of a different length , specifically I want to keep the string only up until the first occurs of `` . '' ( a period ) plus the next two letters . E... | import pandas as pdx = [ [ 34 , 'Sydney.Au123XX ' ] , [ 30 , 'Delhi.As1q ' ] , [ 16 , 'New York.US3qqa ' ] ] x = pd.DataFrame ( x ) x.columns = [ `` a '' , `` b '' ] # now I want to substring each row based on where `` . '' occurs. # I have tried the following : y = x [ `` b '' ] .str.slice ( stop = x [ `` b '' ] .str.... | Pandas - substring each row with a different length |
Python | We are usingWe have written a CustomDataBaseScheduler to schedule task , which schedules the task perfectly on time . We are running CeleryBeat Process as init script , but celeryBeat consumes Full memory of the system i.e . 24GB in a day . I tried to run pmap on celerybeat Process , but it shows [ anon ] has took the ... | django-celery==3.1.10celery==3.1.20python 2.7.13 | CeleryBeat Process consumes all OS memory |
Python | I got the meaning of | ( pipe special character ) in regex , Python.It matches either 1st or 2nd . ex : a|b Matches either a or b.My question : What if I want to match is a with case sensitive and b with case insensitive in above example ? ex : I want to search Pune in the way I have written in above statement s i.e Pu... | s = `` Welcome to PuNe , Maharashtra '' result1 = re.search ( `` punnee|MaHaRaShTrA '' , s ) result2 = re.search ( `` pune|maharashtra '' , s ) result3 = re.search ( `` PuNe|MaHaRaShTrA '' , s ) result4 = re.search ( `` P|MaHaRaShTrA '' , s ) result1 = re.search ( `` pune|MaHaRaShTrA '' , s1 , re.IGNORECASE ) | restrict 1 word as case sensitive and other as case insensitive in python regex | ( pipe ) |
Python | I wa n't to test the type of key when use __setitem__ . But strangely I found some part of code be omitted when use mutiple keys . Here is my test class : When use one key it 's ok : when use two keys , result is correct , but why nothing be printed outI 'm new in python any suggestion will appreciated! | class foo ( ) : def __init__ ( self ) : self.data= [ [ 1,2 ] , [ 3,4 ] , [ 5,6 ] ] def __getitem__ ( self , key ) : return self.data [ key ] def __setitem__ ( self , key , value ) : print ( 'Key is { 0 } , type of key is { 1 } '.format ( key , type ( key ) ) ) self.data [ key ] = valuef = foo ( ) > > > f [ 1 ] = [ 0,0 ... | Strange thing when Python __setitem__ use multiple key |
Python | I would need help to implement an algorithm allowing the generation of building plans , that I 've recently stumbled on while reading Professor Kostas Terzidis ' latest publication : Permutation Design : Buildings , Texts and Contexts ( 2014 ) .CONTEXTConsider a site ( b ) that is divided into a grid system ( a ) .Let ... | from random import shufflen_col , n_row = 7 , 5to_skip = [ 0 , 1 , 21 , 22 , 23 , 24 , 28 , 29 , 30 , 31 ] site = [ i for i in range ( n_col * n_row ) if i not in to_skip ] fitness , grid = [ [ None if i in to_skip else [ ] for i in range ( n_col * n_row ) ] for e in range ( 2 ) ] n = 2k = ( n_col * n_row ) - len ( to_... | How to re-order units based on their degree of desirable neighborhood ? ( in Processing ) |
Python | How can I simulate a python interactive session using input from a file and save what would be a transcript ? In other words , if I have a file sample.py : I want to get sample.py.out that looks like this ( python banner omitted ) : I 've tried feeding stdin to python , twitter 's suggestions were 'bash script ' with n... | # # this is a python script # def foo ( x , y ) : return x+ya=1b=2c=foo ( a , b ) c > > > # ... # this is a python script ... # ... def foo ( x , y ) : ... return x+y ... > > > a=1 > > > b=2 > > > > > > c=foo ( a , b ) > > > > > > c3 > > > | Simulate interactive python session |
Python | I have a Django application which uses the Django template system to generate its ( non-HTML ) output , in addition the the web UI . There 's a set of pages where a user can create a template for a report , adding { { } } tags for variable substitution , and an extra templatetag library to format things nicely.However ... | t = Template ( component_template ) self.output_content = t.render ( component_context ) unknown variable 'ffsdfd ' on line 33 of templatetemplate syntax error on line 22 of template engine = Engine ( string_if_invalid= '' ! ! MISSING_VARIABLE ! ! `` , dirs=settings.TEMPLATES [ 0 ] [ 'DIRS ' ] , context_processors=sett... | django template engine with error checking ? |
Python | I want to use the common pattern to apply a function to every column in a Pandas DataFrame , but the function should work conditional on the column data type.Sounds simple enough . But I found a weird behavior in testing for the data type and I can not find anywhere in the docs or googling the reason for it.Consider th... | import pandas as pdtoydf = pd.DataFrame ( dict ( A = [ 1 , 2 , 3 ] , B = [ 1.1 , 1.2 , 1.3 ] , C = [ ' 1 ' , ' 2 ' , ' 3 ' ] , D = [ True , True , False ] ) ) def dtype_fn ( the_col ) : print ( the_col ) return ( the_col.dtype ) toydf.apply ( dtype_fn ) toydf.apply ( dtype_fn ) 0 11 22 3Name : A , dtype : object0 1.11 ... | Applying function to columns of a Pandas DataFrame , conditional on data type |
Python | There 's something that 's bothering me about imports in packages.Imagine I have the following directory structure : Inside mod1.py I have the following code to import mod2.py : I have a main.py file in the directory containing pack that imports pack/sub1/mod1.pyHow does mod1.py have access to pack ? pack is not in the... | pack├── __init__.py├── sub1│ ├── __init__.py│ └── mod1.py└── sub2 ├── __init__.py └── mod2.py # mod1.pyimport pack.sub2.mod2pack.sub2.mod2.helloworld ( ) | How are absolute imports possible from within a subpackage ? |
Python | I 've read about new Python `` keywords '' async and await . However they are neither really keywords nor reserved in a namespace.In the example I would expect True and SyntaxError for a keyword.So , what exactly is async in Python ? How it works ? | > > > import keyword > > > keyword.iskeyword ( `` async '' ) False > > > asyncTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'async ' is not defined | What is async in Python ? |
Python | I was trying to separate the elements from a multiline string : My aim is to get a list lst such that : My attempt so far is this : How to fix the regex ? UpdateTest datasets | lines = `` 'c0 c1 c2 c3 c4 c50 10 100.5 [ 1.5 , 2 ] [ [ 10 , 10.4 ] , [ c , 10 , eee ] ] [ [ a , bg ] , [ 5.5 , ddd , edd ] ] 100.51 20 200.5 [ 2.5 , 2 ] [ [ 20 , 20.4 ] , [ d , 20 , eee ] ] [ [ a , bg ] , [ 7.5 , udd , edd ] ] 200.5 '' ' # first value is indexlst [ 0 ] = [ 'c0 ' , 'c1 ' , 'c2 ' , 'c3 ' , 'c4 ' , 'c5 '... | Advanced Python Regex : how to evaluate and extract nested lists and numbers from a multiline string ? |
Python | Here is my code : Problem : print ( title ) prints `` [ ] '' , empty list . I expect this to print `` Nabucco '' . The XPath expression is from Chrome inspector `` Copy XPath '' function . Why is n't this working ? Is there a disagreement between lxml and Chrome 's xpath engine ? Or am I missing something ? I am somewh... | from lxml import htmlimport requestspage = requests.get ( 'https : //en.wikipedia.org/wiki/Nabucco ' ) tree = html.fromstring ( page.content ) title = tree.xpath ( '//* [ @ id= '' mw-content-text '' ] /table [ 1 ] /tbody/tr [ 1 ] /th/i ' ) print ( title ) | Why lxml is n't finding xpath given by Chrome inspector ? |
Python | What happens is that if your code raises a runtime exception and that your completion does n't work , you have no idea why because traceback is n't printed . Try this very short code to see what I mean : the program should crash on line c = 2+ '' ddda '' , obviously you 're adding a string and an int , which simply doe... | import cmdclass App ( cmd.Cmd ) : def complete_foo ( self , *arg ) : # Uncommenting this line will silently crash the progrm # making it hard to debug . # Is there a way to force the program to crash ? c = 2 + `` ddda '' return `` d dzpo idz dza dpaoi '' .split ( `` `` ) def do_foo ( self , *args ) : print `` foo '' Ap... | How can I make my program properly crash when using the cmd python module ? |
Python | I 've got many thousands of lines of python code that has python2.7+ style string formatting ( e.g . without indices in the { } s ) I need to run this code under python2.6 and python2.6 requires the indices.I 'm wondering if anyone knows of a painless way allow python2.6 to run this code . It 'd be great if there was a... | `` { } { } '' .format ( 'foo ' , 'bar ' ) `` { 0 } { 1 } '' .format ( 'foo ' , 'bar ' ) | String formatting without index in python2.6 |
Python | I am sampling from a multivariate normal using numpy as follows.It gives me the following warning . RuntimeWarning : covariance is not positive-semidefinite.The matrix is clearly PSD . However , when I use a np.float64 array , it works fine . I need the covariance matrix to be np.float32 . What am I doing wrong ? | mu = [ 0 , 0 ] cov = np.array ( [ [ 1 , 0.5 ] , [ 0.5 , 1 ] ] ) .astype ( np.float32 ) np.random.multivariate_normal ( mu , cov ) | Confusing behavior of np.random.multivariate_normal |
Python | I would like to use the collections.Counter class to count emojis in a string . It generally works fine , however , when I introduce colored emojis the color component of the emoji is separated from the emoji like so : How can I make the most_common ( ) function return something like this instead : I 'm using Python 3.... | > > > import collections > > > emoji_string = `` '' > > > emoji_counter = collections.Counter ( emoji_string ) > > > emoji_counter.most_common ( ) [ ( `` , 5 ) , ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) ] [ ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) , ( `` , 1 ) ] | Using collections.Counter to count emojis with different colors |
Python | I have an issue related to Cryptography package in Python . Can you please help in resolving these , if possible ? ( tried a lot , but couldnt figure out the exact solution ) The python code which initiates this error : Value of `` Salt '' is getting displayed in 100 % of the cases . If Line3 gets executed successfully... | print ( `` Salt : % s '' % salt ) server_key = pyelliptic.ECC ( curve= '' prime256v1 '' ) # -- -- - > > Line2print ( `` Server_key : % s '' % server_key ) # -- -- - > > Line3server_key_id = base64.urlsafe_b64encode ( server_key.get_pubkey ( ) [ 1 : ] ) http_ece.keys [ server_key_id ] = server_keyhttp_ece.labels [ serve... | 'EntryPoint ' object has no attribute 'resolve ' when using Google Compute Engine |
Python | I have a dataframe 'work ' with non consecutive index , here an example : i need to extract from this dataframe new dataframes containing only rows where the index is consecutive , so in this case my goal is to getmaintaining all the columns.Can anyone help me ? Thanks ! | Index Column1 Column24464 10.5 12.74465 11.3 12.84466 10.3 22.85123 11.3 21.85124 10.6 22.45323 18.6 23.5 DF_1.index= [ 4464,4465,4466 ] DF_2.index= [ 5123,5124 ] DF_3.index= [ 5323 ] | How to split a dataframe based on consecutive index ? |
Python | Why is n't it possible to use `` await '' in f-strings ? Is there any way to coerce f-strings into evaluating the format expressions in the context of a coroutine function ? | $ python3 Python 3.6.0 ( default , Mar 4 2017 , 12:32:37 ) [ GCC 4.2.1 Compatible Apple LLVM 8.0.0 ( clang-800.0.42.1 ) ] on darwinType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information. > > > async def a ( ) : return 1 ... > > > async def b ( ) : return 'The return value of await a ( )... | Why is n't it possible to use `` await '' in f-strings ? |
Python | Could someone explain to me how to determine the running time in Big Θ notation for these ? I 've read quite a few things but still have no idea where to begin . In filter , I think it is Θ ( n^2 ) because it checks each element in list of size n with the predicate function f with n recursive calls so n*n. revfilter_be... | def filter ( f , lst ) : if lst == [ ] : return [ ] if f ( lst [ 0 ] ) : return [ lst [ 0 ] ] + filter ( f , lst [ 1 : ] ) return filter ( f , lst [ 1 : ] ) def my_reverse ( lst ) : # Reverse the list def reverse_helper ( x , y ) : if x == [ ] : return y return reverse_helper ( x [ 1 : ] , [ x [ 0 ] ] + y ) return reve... | Running time using Big Θ notation |
Python | My QuestionI am looking for a way to stop request processing in a Tool without raising an exception . In other words : I want to stop the request befor it gets to the specified controller and return a 2xx status code ? BackgroundWe want our application to support CORS and therefore the preflight request . The idea was ... | class CORSTool ( cherrypy.Tool ) : def __init__ ( self ) : cherrypy.Tool.__init__ ( self , 'before_handler ' , self.insert_cors_header , priority=40 ) cherrypy.request.hooks.attach ( 'before_handler ' , self.insert_cors_header , priority=40 ) def _setup ( self ) : cherrypy.Tool._setup ( self ) def insert_cors_header ( ... | Stop request processing in CherryPy and return 200 response from a tool |
Python | Is there a more sensible way of doing this ? I want to make a new list by summing over the indices of a lot of other lists . I 'm fairly new to programming and this seems like a very clunky method ! | list1 = [ 1,2,3,4,5 ] list2 = [ 1,1,1,4,1 ] list3 = [ 1,22,3,1,5 ] list4 = [ 1,2,5,4,5 ] ... list100 = [ 4,5,6,7,8 ] i = 0while i < len ( list1 ) : mynewlist [ i ] = list1 [ i ] +list2 [ i ] +list3 [ i ] +list4 [ i ] + ... list100 [ i ] i = i+1 | Summing over lists in python - is there a better way ? |
Python | I am new to tensorflow and neural network . I started a project which is about detecting errors in persian texts . I used the code in this address and developed the code in here . please check the code because I can not put all the code here.What I want to do is to give several persian sentences to the model for traini... | x_text , y = data_helpers.load_data_labels ( datasets ) # Build vocabularymax_document_length = max ( [ len ( x.split ( `` `` ) ) for x in x_text ] ) vocab_processor = learn.preprocessing.VocabularyProcessor ( max_document_length ) x = np.array ( list ( vocab_processor.fit_transform ( x_text ) ) ) vocab_path = os.path.... | Tensorflow can not restore vocabulary in evaluation process |
Python | Pip install of urllib3 is hanging on `` Caching due to etag '' . I 'm building an AWS chalice project that does n't let you specify -- no-cache-dir , so I need to fix the issue without that command . Any ideas ? Using Python 3.6.5 and Pip 10.0.1 in a virtual environment.Edit : Based on one of the comments , curl -vvv h... | ( partnerdb-virtualenv ) C : \Windows\SysWOW64\partnerdb-project > pip install urllib3 -vvvConfig variable 'Py_DEBUG ' is unset , Python ABI tag may be incorrectConfig variable 'WITH_PYMALLOC ' is unset , Python ABI tag may be incorrectCreated temporary directory : C : \Users\Matt\AppData\Local\Temp\pip-ephem-wheel-cac... | pip install urllib3 hanging on `` Caching due to etag '' |
Python | The Custom Graphs API of Dask seems to support only functions returning one output key/value.For example , the following dependency could not be easily represented as a Dask graph : This can be worked around by storing a tuple under a `` composite '' key ( e.g . `` B_C '' in this case ) and then splitting it by getitem... | B - > D / \A- - > F \ / C - > E | Does Dask support functions with multiple outputs in Custom Graphs ? |
Python | I ran this : Before asking here , I restarted my python shell and tried it online too and got the same result.I thought a dictionary with one more element will either give same bytes as output or more , than the one containing one less element . Any idea what am I doing wrong ? | import sysdiii = { 'key1':1 , 'key2':2 , 'key3':1 , 'key4':2 , 'key5':1 , 'key6':2 , 'key7':1 } print sys.getsizeof ( diii ) # output : 1048diii = { 'key1':1 , 'key2':2 , 'key3':1 , 'key4':2 , 'key5':1 , 'key6':2 , 'key7':1 , 'key8':2 } print sys.getsizeof ( diii ) # output : 664 | Dictionary size reduces upon increasing one element |
Python | I am currently solving a mathematical problem in which I need to count the number of reduced proper fractions with both numerator and denominator more more than 1000000 ( 10^6 ) .I have code that works fine for small numbers ; the example given ( value=8 ) gives the correct ( given ) answer 21.But this code seems to be... | import mathdef is_prime ( n ) : if n == 2 : return True if n % 2 == 0 or n < = 1 : return False sqr = int ( math.sqrt ( n ) ) + 1 for divisor in range ( 3 , sqr , 2 ) : if n % divisor == 0 : return False return Truedef get_divisors ( n ) : liste = [ 1 ] if n % 2 == 0 : liste.append ( 2 ) for divisor in range ( 3 , n+1 ... | How to count the number of reduced proper fractions fast enough ? |
Python | I see a couple examples of how to set the orientation of a text box , but not cell in a text box . I see how to format other things , like bold : but not vertically oriented text . | bold_format = workbook.add_format ( { 'bold ' : True } ) worksheet.write ( 'A1 ' , `` something '' , bold_format ) | Orient text in cell to vertical with XlsxWriter ? |
Python | I am working on some legacy code ( created by someone in love with spaghetti code ) that has over 150 getters and over 150 setters . The getters look like this : I would love to take the contents of each of these Getters and put them into a decorator /closure or some other method to make this code easier to maintain . ... | def GetLoadFee ( self ) : r_str = `` '' if len ( self._LoadFee ) > 20 : r_str = self._LoadFee [ :20 ] else : r_str = self._LoadFee.strip ( ) return r_str.strip ( ) def GetCurrency ( self ) : r_str = `` '' if len ( self._Currency ) > 3 : r_str = self._Currency [ :3 ] else : r_str = self._Currency.strip ( ) return r_str.... | How do I refactor 100s of Class Methods in Python ? |
Python | I 'm really sorry to bother you with an AttributeError , but I just ca n't figure out what 's wrong with my code though I worked through many solved question regarding AttributeErrors.This is my code : If I execute it , I get the following error message : The funny issue - to my opinion - is that `` entry1 '' is absolu... | class Base : def __init__ ( self ) : self.window = gtk.Window ( gtk.WINDOW_TOPLEVEL ) self.window.set_position ( gtk.WIN_POS_CENTER ) self.window.set_size_request ( 500,500*9/16 ) self.window.set_title ( `` pattern_executer '' ) self.button1 = gtk.Button ( `` E x i t `` ) self.button1.connect ( `` clicked '' , self.clo... | AttributeError in callback function |
Python | I 'm having trouble propagating custom_properties like color into my google chart through the python layer gviz_api.I would like to create a bar chart with individually colored bars such as in the example here : https : //developers.google.com/chart/interactive/docs/gallery/barchart # BarStylesBut I ca n't figure out h... | import gviz_apidef main ( ) : # Creating the data description = { `` test '' : ( `` string '' , `` Test name '' ) , `` duration '' : ( `` number '' , `` Duration '' ) } data = [ dict ( test= '' test A '' , duration=1000 , custom_properties= { `` role '' : '' color : green '' } ) , { `` test '' : `` test B '' , `` durat... | Feed google charts custom properties like color through gviz_api |
Python | I am trying to create documentation automatically from the code for all the URLs supported by my application . We are using completely client side MVC , hence each URL that is supported is essentially a REST API for the UI . Is there a easy way to generate the documentation from these URLs ? I wrote this small module a... | from django.core.management.base import BaseCommandfrom django.conf import settingsclass Command ( BaseCommand ) : ' '' Generates documentation for the URLs . For each URL includes the documentation fromthe callback implementing the URL and prints the default arguments along with the URL pattern and name '' ' def handl... | Automatically document my REST API |
Python | I am trying to add two pandas Series together . The first Series is very large and has a MultiIndex . The index of the second series is a small subset of the index of the first.Using the regular Series.add function takes about 9 seconds the first time , and 2 seconds on subsequent tries ( maybe because pandas optimizes... | df1 = pd.DataFrame ( np.ones ( ( 1000,5000 ) ) , dtype=int ) .stack ( ) df1 = pd.DataFrame ( df1 , columns = [ 'total ' ] ) df2 = pd.concat ( [ df1.iloc [ 50:55 ] , df1.iloc [ 2000:2005 ] ] ) # df2 is tiny subset of df1 starttime = time.time ( ) df1.total.add ( df2.total , fill_value=0 ) .sum ( ) print `` Method 1 took... | Faster alternative to Series.add function in pandas |
Python | I have a plot which consists of great number of lines . At each step the colours of lines should get updated in the animation , but doing a for loop on lines seems to be really costly . Is there any better way to do that ? Here is my code : Plus I could n't make it to work with animation artist ! I used draw . What is ... | import numpy as nplines= [ ] from matplotlib import pyplot as pltimport matplotlib.animation as animation # initial plotfig=plt.figure ( ) ax=plt.subplot ( 1,1,1 ) for i in range ( 10 ) : lines.append ( [ ] ) for j in range ( 10 ) : lines [ i ] .append ( ax.plot ( [ i , j ] , color= ' 0.8 ' ) ) lines=np.asarray ( lines... | Animation based on only updating colours in a plot |
Python | I am trying to follow the tutorial here to implement a custom inference pipeline for feature preprocessing . It uses the python sklearn sdk to bring in custom preprocessing pipeline from a script . For example : However I ca n't find a way to send multiple files . The reason I need multiple files is because I have a cu... | from sagemaker.sklearn.estimator import SKLearnscript_path = 'preprocessing.py'sklearn_preprocessor = SKLearn ( entry_point=script_path , role=role , train_instance_type= '' ml.c4.xlarge '' , sagemaker_session=sagemaker_session ) | AWS Sagemaker SKlearn entry point allow multiple script |
Python | I have been using this excellent decorator for memoization , which I found on the web ( shown here with the Fibonacci sequence as an example ) : Now I 'd like to understand the inner workings a bit better , I have not found answers by reading up on decorators or parameter handling in Python.Why is the cache dictionary ... | def memoize ( f ) : cache= { } def memf ( *x ) : if x not in cache : cache [ x ] = f ( *x ) return cache [ x ] return memf @ memoizedef fib ( n ) : if n==1 or n==0 : return 1 return fib ( n-2 ) + fib ( n-1 ) print fib ( 969 ) | Understanding parameter handling in a python memoization decorator |
Python | I 'm looking for a way to expose filtering functionality at my workplace to other developers and optionally customers.Problemi want to implement a simple query language over my data ( python dicts ) based on user defined filters exposed to my other developers and later on to our customers.the language should be simple ... | db = [ { 'first ' : 'john ' , 'last ' : 'doe ' , 'likes ' : [ 'cookies ' , 'http ' ] } , { 'first ' : 'jane ' , 'last ' : 'doe ' , 'likes ' : [ 'cookies ' , 'donuts ' ] } , { 'first ' : 'danny ' , 'last ' : 'foo ' , 'likes ' : [ 'http ' , 'donuts ' ] } , ] query = ' ( first == `` john '' or last == `` doe '' ) and like... | implement query language on python |
Python | I have a very large pandas dataframe and I would like to create a column that contains the time in seconds since the epoch for a ISO-8601 format date string.I originally used the standard Python libraries for this but the result is quite slow . I have tried to replace this by using the POSIX c library functions strptim... | % load_ext cythonmagic % % cythonfrom posix.types cimport time_tcimport numpy as npimport numpy as npimport timecdef extern from `` sys/time.h '' nogil : struct tm : int tm_sec int tm_min int tm_hour int tm_mday int tm_mon int tm_year int tm_wday int tm_yday int tm_isdst time_t mktime ( tm *timeptr ) char *strptime ( c... | Converting string date to epoch time not working with Cython and POSIX C libraries |
Python | Assume we need to call fortran function , which returns some values , in python program . I found out that rewriting fortran code in such way : and calling it in python in such way : gives us working result . Can I call fortran function in other way , cause I think the first way is a bit clumsy ? | subroutine pow2 ( in_x , out_x ) implicit none real , intent ( in ) : : in_x ! f2py real , intent ( in , out ) : : out_x real , intent ( out ) : : out_x out_x = in_x ** 2 returnend import modulenamea = 2.0b = 0.0b = modulename.pow2 ( a , b ) | making python and fortran friends |
Python | I have many possible arguments from argparse that I want to pass to a function . If the variable has n't been set , I want the method to use its default variable . However , handling which arguments have been set and which have n't is tedious : It seems like I should be able to do something like this : But this gives a... | import argparsedef my_func ( a = 1 , b = 2 ) : return a+bif __name__ == `` __main__ '' : parser = argparse.ArgumentParser ( description='Get the numeric values . ' ) parser.add_argument ( '-a ' , type=int ) parser.add_argument ( '-b ' , type=int ) args = parser.parse_args ( ) if not args.a is None and not args.b is Non... | Conditional passing of arguments to methods in python |
Python | am trying to use lxml to read html from a string and then try to find all img tags , update the image src 's attribute and add hyper link around each image found so this , will be thisthe problem am facing is two , first am using etree.HTML to load the html string , which for some reason is adding html tag and body tag... | < img src= '' old-value '' / > < a href= '' '' > < img src= '' new-value '' / > < /a > tree = etree.HTML ( self.content ) imgs = tree.xpath ( './/img ' ) thm = `` new-value '' for img in imgs : img.set ( 'src ' , thm ) a = etree.Element ( ' a ' , href= '' # '' ) img.insert ( 0 , a ) < html > < body > < p > < img src= '... | lxml python load html string without header and body and add element around targeted elements |
Python | I was wondering what happens to methods declared on a metaclass . I expected that if you declare a method on a metaclass , it will end up being a classmethod , however , the behavior is different . ExampleHowever , if I try to define a metaclass and give it a method foo , it seems to work the same for the class , not f... | > > > class A ( object ) : ... @ classmethod ... def foo ( cls ) : ... print `` foo '' ... > > > a=A ( ) > > > a.foo ( ) foo > > > A.foo ( ) foo > > > class Meta ( type ) : ... def foo ( self ) : ... print `` foo '' ... > > > class A ( object ) : ... __metaclass__=Meta ... def __init__ ( self ) : ... print `` hello '' ... | methods of metaclasses on class instances |
Python | This code produces a different output in Python 2 and Python 3.The output for Python 2 is : For Python 3 it is : Why is this working this way ? How are Python 2 descriptors different from Python 3 descriptors ? This makes also no sense , because http : //docs.python.org/release/3.0.1/reference/datamodel.html # invoking... | class Descriptor ( object ) : def __get__ ( self , instance , owner ) : print ( 'read ' ) return 1 def __set__ ( self , instance , value ) : print ( 'write ' ) def __delete__ ( self , instance ) : print ( 'del ' ) class C ( ) : a = Descriptor ( ) c = C ( ) c.a c.a = 3del c.ac.aprint ( 'finished ' ) readreadfinished rea... | Python descriptors not working in Python 2.7 |
Python | I have a Julia module I need to interface with from my python codebase . For that I am using pyjulia like so.However , this slows down everything since Julia needs to compile the module I am using.The module I use exports 1 function and internally uses ForwardDiff for some calculations . It calculates derivatives of a ... | import juliaj = julia.Julia ( ) j.include ( './simulation/n-dof/dynamics.jl ' ) j.using ( `` Dynamics '' ) print ( j.sim ( [ 1,2,3 ] , [ 1,2,3 ] ) ) module Dynamics function sim ( a , b ) return 1 end export simend | Cache Julia module for faster startup and usage in Python |
Python | I 'm trying to use gradient_override_map with Tensorflow 2.0 . There is an example in the documentation , which I will use as the example here as well.In 2.0 , GradientTape can be used to compute gradients as follows : There is also the tf.custom_gradient decorator , which can be used to define the gradient for a new f... | import tensorflow as tfprint ( tf.version.VERSION ) # 2.0.0-alpha0x = tf.Variable ( 5.0 ) with tf.GradientTape ( ) as tape : s_1 = tf.square ( x ) print ( tape.gradient ( s_1 , x ) ) import tensorflow as tfprint ( tf.version.VERSION ) # 2.0.0-alpha @ tf.custom_gradientdef log1pexp ( x ) : e = tf.exp ( x ) def grad ( dy... | How to use gradient_override_map in Tensorflow 2.0 ? |
Python | If I have two strings of equal length like the following : Is there an efficient way to align the two such that the most letters as possible line up as shown below ? The only way I can think of doing this is brute force by editing the strings and then iterating through and comparing . | 'aaaaabbbbbccccc '' bbbebcccccddddd ' 'aaaaabbbbbccccc -- -- - '' -- -- -bbbebcccccddddd ' | Rough string alignment in python |
Python | I have a couple of celery tasks that are included in my Django tests . Unfortunately exceptions are not thrown when tasks are invoked via .delay ( ) . I am setting CELERY_ALWAYS_EAGER to True.tasks.pytests.pyOutputWhen removing the .delay the test exits with an error as excpected : Versions | import celeryapp as app @ app.task ( ) def exception_task ( ) : print 'CELERY_ALWAYS_EAGER : ' , app.conf [ 'CELERY_ALWAYS_EAGER ' ] raise Exception ( 'foo ' ) def test_exception_in_task ( self ) : from tasks import exception_task exception_task.delay ( ) CELERY_ALWAYS_EAGER : True. -- -- -- -- -- -- -- -- -- -- -- -- ... | Celery tasks not throwing exception in Django Tests |
Python | I want to use nox in my project managed with poetry.What is not going well is that installing dev dependency in nox session.I have the noxfile.py as shown below : How can I install dev dependency in nox session ? | import noxfrom nox.sessions import Sessionfrom pathlib import Path__dir__ = Path ( __file__ ) .parent.absolute ( ) @ nox.session ( python=PYTHON ) def test ( session : Session ) : session.install ( str ( __dir__ ) ) # I want to use dev dependency here session.run ( `` pytest '' ) | How to use nox with poetry ? |
Python | Is there a null propagation operator ( `` null-aware member access '' operator ) in Python so I could write something likeas in C # , VB.NET and TypeScript , instead of | var = object ? .children ? .grandchildren ? .property var = None if not myobject\ or not myobject.children\ or not myobject.children.grandchildren\ else myobject.children.grandchildren.property | None propagation in Python chained attribute access |
Python | I need to randomly separate a data frame into two disjoint sets by the attribute 'ids ' . For example , consider the following data frame : I need to get two ( randomly separated with some fraction size ) dataframes with no intersecting values of ids.I know how to solve it in 'non-pandasian ' way : get the unique value... | df=Out [ 470 ] : 0 1 2 3 ids0 17.0 18.0 16.0 15.0 13.01 18.0 16.0 15.0 15.0 13.02 16.0 15.0 15.0 16.0 13.0131 12.0 8.0 21.0 19.0 14.0132 8.0 21.0 19.0 20.0 14.0133 21.0 19.0 20.0 9.0 14.0248 NaN NaN 12.0 11.0 17.0249 NaN 12.0 11.0 10.0 17.0250 12.0 11.0 10.0 NaN 17.0287 3.0 3.0 1.0 8.0 20.0288 3.0 1.0 8.0 3.0 20.0289 1... | random sampling with Pandas data frame disjoint groups |
Python | I have two lists of dictionaries.The subtraction of a and b should be updated in foo : Now I tried this with two loops and the zip-function : I get a TypeError : 'float ' object is not iterable . Where 's my mistake ? | foo = [ { 'Tom ' : 8.2 } , { 'Bob ' : 16.7 } , { 'Mike ' : 11.6 } ] bar = [ { 'Tom ' : 4.2 } , { 'Bob ' : 6.7 } , { 'Mike ' : 10.2 } ] foo = [ { 'Tom ' : 4.0 } , { 'Bob ' : 10.0 } , { 'Mike ' : 1.4 } ] def sub ( a , b ) : for mydict , mydictcorr in zip ( a , b ) : { k : [ x-y for x , y in mydict [ k ] , mydictcorr [ k ... | Subtract values from list of dictionaries from another list of dictionaries |
Python | I 'd like to achieve the following : ... creating keys recursively.After scratching my head for a while , I 've come up with this : | foodict [ 'foo.bar.baz ' ] = 'foo ' { 'foo ' : { 'bar ' : { 'baz ' : 'foo ' } } } } class Config ( dict ) : def __init__ ( self , *args , **kwargs ) : self.super = super ( Config , self ) self.update ( *args , **kwargs ) def __setitem__ ( self , keys , value ) : keys = keys.split ( ' . ' ) keys.reverse ( ) config = Con... | Set Python dict items recursively , when given a compound key 'foo.bar.baz ' |
Python | I have the following dataframe where I would like to print the unique values of the color column.df.colors.unique ( ) would work fine if there was n't the [ yellow , red ] row . As it is I keep getting the TypeError : unhashable type : 'list ' error which is understandable.Is there a way to still get the unique values ... | df = pd.DataFrame ( { 'colors ' : [ 'green ' , 'green ' , 'purple ' , [ 'yellow , red ' ] , 'orange ' ] , 'names ' : [ 'Terry ' , 'Nor ' , 'Franck ' , 'Pete ' , 'Agnes ' ] } ) Output : colors names0 green Terry1 green Nor2 purple Franck3 [ yellow , red ] Pete4 orange Agnes df = df [ ~df.colors.str.contains ( ' , ' , na... | How to get unique values of a dataframe column when there are lists - python |
Python | I wanted to use NumPy in a Fibonacci question because of its efficiency in matrix multiplication . You know that there is a method for finding Fibonacci numbers with the matrix [ [ 1 , 1 ] , [ 1 , 0 ] ] .I wrote some very simple code but after increasing n , the matrix is starting to give negative numbers.What could be... | import numpydef fib ( n ) : return ( numpy.matrix ( `` 1 1 ; 1 0 '' ) **n ) .item ( 1 ) print fib ( 90 ) # Gives -1581614984 | Numpy matrix exponentiation gives negative value |
Python | I have a QGraphicsScene containing some simple objects ( in this simplified example circles ) that I want to change into other objects ( here squares ) when selected . More specifically I 'd like to have parent objects which do n't draw themselves , they are drawn by their child objects , and under various circumstance... | from PySide import QtCore , QtGuiclass SceneObject ( QtGui.QGraphicsItem ) : def __init__ ( self , scene ) : QtGui.QGraphicsItem.__init__ ( self , scene = scene ) self.setFlag ( QtGui.QGraphicsItem.ItemIsSelectable , True ) self.setFlag ( QtGui.QGraphicsItem.ItemHasNoContents , True ) self.updateContents ( ) def update... | QGraphicsScene changing objects when selected |
Python | From the Python 's documentation of the chr built-in function , the maximum value that chr accepts is 1114111 ( in decimal ) or 0x10FFFF ( in base 16 ) . And in factMy first question is the following , why exactly that number ? The second question is : if this number changes , is it possible to know from a Python comma... | > > > chr ( 1114112 ) Traceback ( most recent call last ) : File `` < pyshell # 20 > '' , line 1 , in < module > chr ( 1114112 ) ValueError : chr ( ) arg not in range ( 0x110000 ) | Is it possible to know the maximum number accepted by chr using Python ? |
Python | In this answer https : //stackoverflow.com/a/27680814/3456281 , the following construct is presentedwhich actually prints `` Stopped . '' and breaks ( tested with Python 3.4.1 ) .Why ? ! Why is if IndexError even legal ? Why does a [ 2 ] not raise an IndexError with no try ... except around ? | a= [ 1,2 ] while True : if IndexError : print ( `` Stopped . '' ) break print ( a [ 2 ] ) | Why does ` if Exception ` work in Python |
Python | I am running the following function to profile a BigQuery query : And , I get something like the following : Initialize BQClient : 0.0007 | ExecuteQuery : 0.2854 | FetchResults : 1.0659 | PrintRecords : 0.0958 | Total : 1.4478 | FromCache : TrueI am running this on a GCP machine and it is only fetching ONE result in lo... | # q = `` SELECT * FROM bqtable LIMIT 1 '' 'def run_query ( q ) : t0 = time.time ( ) client = bigquery.Client ( ) t1 = time.time ( ) res = client.query ( q ) t2 = time.time ( ) results = res.result ( ) t3 = time.time ( ) records = [ _ for _ in results ] t4 = time.time ( ) print ( records [ 0 ] ) print ( `` Initialize BQ... | What 's causing so much overhead in Google BigQuery query ? |
Python | When I execute this code in python 2.6I get [ 1 , 2 , 3 ] as expected . But when I execute this one ( I think it is equivalent to previous ) I get an error messageWhy these two lines of code do not give the same result ? | reduce ( lambda x , y : x+ [ y ] , [ 1,2,3 ] , [ ] ) reduce ( lambda x , y : x.append ( y ) , [ 1,2,3 ] , [ ] ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` < stdin > '' , line 1 , in < lambda > AttributeError : 'NoneType ' object has no attribute 'append ' | Strange reduce behaviour |
Python | please help with this case : Result : Why does the list have empty elements ? | m = re.split ( ' ( [ A-Z ] [ a-z ] + ) ' , 'PeopleRobots ' ) print ( m ) [ `` , 'People ' , `` , 'Robots ' , `` ] | re.split ( ) gives empty elements in list |
Python | When answering this question ( and having read this answer to a similar question ) , I thought that I knew how Python caches regexes.But then I thought I 'd test it , comparing two scenarios : a single compilation of a simple regex , then 10 applications of that compiled regex.10 applications of an uncompiled regex ( w... | > > > import timeit > > > timeit.timeit ( setup= '' import re '' , ... stmt= ' r=re.compile ( r '' \w+ '' ) \nfor i in range ( 10 ) : \n r.search ( `` jkdhf `` ) ' ) 18.547793477671938 > > > timeit.timeit ( setup= '' import re '' , ... stmt='for i in range ( 10 ) : \n re.search ( r '' \w+ '' , '' jkdhf `` ) ' ) 106.478... | Why are uncompiled , repeatedly used regexes so much slower in Python 3 ? |
Python | There is a famous Python exampleI have several questions . The first one is B calls A and C calls A so I expect A to appear twice . The second question is about the order . | class A ( object ) : def go ( self ) : print ( `` go A go ! `` ) class B ( A ) : def go ( self ) : super ( B , self ) .go ( ) print ( `` go B go ! `` ) class C ( A ) : def go ( self ) : super ( C , self ) .go ( ) print ( `` go C go ! `` ) class D ( B , C ) : def go ( self ) : super ( D , self ) .go ( ) print ( `` go D ... | Python class inheritance call order |
Python | I 'm trying to create a shortcut through python that will launch a file in another program with an argument . E.g : The code I 've tried messing with : But i get an error thrown my way : I 've tried different formats of the string and google does n't seem to know the solution to this problem | `` C : \file.exe '' `` C : \folder\file.ext '' argument from win32com.client import Dispatchimport osshell = Dispatch ( `` WScript.Shell '' ) shortcut = shell.CreateShortCut ( path ) shortcut.Targetpath = r ' '' C : \file.exe '' `` C : \folder\file.ext '' 'shortcut.Arguments = argumentshortcut.WorkingDirectory = `` C :... | Python , create shortcut with two paths and argument |
Python | I have a list of counters in python : How do I find the count of each Counter element . Counter gives me an error of unhashable type . Another way I thought is to iterate through the list in a nested for-loop , checking if each counter is equal to any other counter in the list and increment a dictionary accordingly . I... | [ Counter ( { 12.011 : 30.0 , 15.999 : 2.0 } ) , Counter ( { 12.011 : 12.0 , 15.999 : 2.0 } ) , ... Counter ( { 12.011 : 40.0 , 15.999 : 5.0 , 79.904 : 5.0 } ) ] | Comparing list of Counters in Python |
Python | Some satellite based earth observation products provide latitude/longitude information while others provide the X/Y coordinates within a given grid projection ( and there are also some having both , see example ) . My approach in the second case is to set up a Basemap map which has the same parameters ( projection , el... | import numpy as npfrom mpl_toolkits.basemap import Basemapm=Basemap ( resolution= ' h ' , projection='spstere ' , ellps='WGS84 ' , boundinglat=-60 , lon_0=180 , lat_ts=-71 ) x_crn=np.array ( [ -2259300 , -1981500 , -2259300 , -1981500 ] ) # upper left , upper right , lower left , lower righty_crn=np.array ( [ 1236000 ,... | Why are Basemap south polar stereographic map projection coordinates not agreeing with those of data sets in the same projection ? |
Python | I am not quite sure this is possible ( or something similar ) in python . I want to access a method ( or another object ) of a class from an object that is an attribute of such class . Consider the following code : so that b as an object attribute of class A , can refer to a method or attribute of A ? Or similarly , is... | class A ( ) : def __init__ ( self ) : self.b = B ( ) self.c = C ( ) def print_owner ( self ) : print ( 'owner ' ) class B ( ) : def __init__ ( self ) : pass def call_owner ( self ) : self.owner ( ) .print_owner ( ) | Is it possible to refer to the owner class that an object belongs to as an attribute ? |
Python | Total python beginner here.I have the following function , which checks if a string derived from certain inputs exists in a text file . It loops through each line of the text file , to see if an exact match is found.I have to break out of looping , immediately after the match is found , to avoid needless looping.Here i... | def DateZoneCity_downloaded_previously ( Order_Date , ZoneCity ) : # function to check if a given DateZoneCity # combination had already been completely downloaded string_to_match = Order_Date.strftime ( ' % Y/ % m/ % d ' ) + `` - '' + ZoneCity [ 0 ] + `` - '' + ZoneCity [ 1 ] with open ( Record_File ) as download_stat... | Pythonic way to break out of loop |
Python | I 'm looking at a case like this : It works , but is there a better way to do this ? | def parse_item ( self , response ) : item = MetrocItem ( ) def ver ( string ) : if string : return string else : return 'null ' item [ 'latitude ' ] = ver ( response.xpath ( '//input [ @ id= '' latitude '' ] / @ value ' ) .extract_first ( ) ) | Is it a bad programing practice to put a function inside a class method ? |
Python | I am trying to figure out what combination of clothing customers are buying together . I can figure out the exact combination , but the problem I ca n't figure out is the count that includes the combination + others.For example , I have : This should result in : The best I can do is unique combinations : I tried : But ... | Cust_num Item RevCust1 Shirt1 $ 40Cust1 Shirt2 $ 40Cust1 Shorts1 $ 40Cust2 Shirt1 $ 40Cust2 Shorts1 $ 40 Combo CountShirt1 , Shirt2 , Shorts1 1Shirt1 , Shorts1 2 Combo CountShirt1 , Shirt2 , Shorts1 1Shirt1 , Shorts1 1 df = df.pivot ( index='Cust_num ' , columns='Item ' ) .sum ( ) df [ df.notnull ( ) ] = `` x '' df = d... | How to use Pandas to get the count of every combination inclusive |
Python | I want to get date and specific item in a text using regular expression in python 3 . Below is an example : In the example above , I would like to get all line after 'success line ' . Here desired output : This is want I 've tried : I do n't know what the proper way to get result . I 've tried this to get the line : Ho... | text = `` '190219 7:05:30 line1 fail line1 this is the 1st fail line2 fail line2 this is the 2nd fail line3 success line3 this is the 1st success process line3 this process need 3sec200219 9:10:10 line1 fail line1 this is the 1st fail line2 success line2 this is the 1st success process line2 this process need 4sec line... | How to extract lines after specific words ? |
Python | I always thought iterating over a file-like in Python would be equivalent to calling its readline method in a loop , but today I found a situation where that is not true . Specifically , I have a Popen 'd process p wherehangs ( presumably because p waits for input ; both stdin and stdout are pipes to my Python process ... | list ( itertools.takewhile ( lambda x : x ! = `` \n '' , p.stdout ) ) list ( itertools.takewhile ( lambda x : x ! = `` \n '' , iter ( p.stdout.readline , `` '' ) ) ) | Difference between iterating over a file-like and calling readline |
Python | Let 's say I have a NumPy array : At each index , I want to find the distance to nearest zero value . If the position is a zero itself then return zero as a distance . Afterward , we are only interested in distances to the nearest zero that is to the right of the current position . The super naive approach would be som... | x = np.array ( [ 0 , 1 , 2 , 0 , 4 , 5 , 6 , 7 , 0 , 0 ] ) out = np.full ( x.shape [ 0 ] , x.shape [ 0 ] -1 ) for i in range ( x.shape [ 0 ] ) : j = 0 while i + j < x.shape [ 0 ] : if x [ i+j ] == 0 : break j += 1 out [ i ] = j array ( [ 0 , 2 , 1 , 0 , 4 , 3 , 2 , 1 , 0 , 0 ] ) | Find Distance to Nearest Zero in NumPy Array |
Python | I am playing with the Titanic dataset , and trying to produce a pair plot of numeric variables against categorical variables . I can use Seaborn 's catplot to graph a plot of one numeric variable against one categorical variable : However , if I try to use PairGrid to graph numeric variables against categorical variabl... | import seaborn as snssns.catplot ( data=train , x='Fare ' , y='Sex ' ) x_vars = [ 'Fare ' ] y_vars = [ 'Sex ' ] g = sns.PairGrid ( train , x_vars=x_vars , y_vars=y_vars ) g.map ( sns.catplot ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -TypeError Trace... | Seaborn catplot combined with PairGrid |
Python | Consider the following ... What is special about [ ] ? I would expect this to raise a SyntaxError too . Why does n't it ? I 've observed this behavior in Python2 and Python3 . | In [ 1 ] : del [ ] In [ 2 ] : del { } File `` < ipython-input-2-24ce3265f213 > '' , line 1SyntaxError : ca n't delete literalIn [ 3 ] : del `` '' File `` < ipython-input-3-95fcb133aa75 > '' , line 1SyntaxError : ca n't delete literalIn [ 4 ] : del [ `` A '' ] File `` < ipython-input-5-d41e712d0c77 > '' , line 1SyntaxEr... | What is special about deleting an empty list ? |
Python | How can I watch standard output and standard error of a long-running subprocess simultaneously , processing each line as soon as it is generated by the subprocess ? I do n't mind using Python3.6 's async tools to make what I expect to be non-blocking async loops over each of the two streams , but that does n't seem to ... | import asynciofrom asyncio.subprocess import PIPEfrom datetime import datetimeasync def run ( cmd ) : p = await asyncio.create_subprocess_shell ( cmd , stdout=PIPE , stderr=PIPE ) async for f in p.stdout : print ( datetime.now ( ) , f.decode ( ) .strip ( ) ) async for f in p.stderr : print ( datetime.now ( ) , `` E : '... | Watch stdout and stderr of a subprocess simultaneously |
Python | Sometimes it looks reasonable to use __init__ as initialization method for already existing object , i.e . : As alternative to this implementation I see the following : It seems to me as over-complication of code . Is there any guideline on this situation ? | class A ( ) : def __init__ ( self , x ) : self.x = x def set_state_from_file ( self , file ) : x = parse_file ( file ) self.__init__ ( x ) class A ( ) : def __init__ ( self , x ) : self.init ( x ) def init ( self , x ) : self.x = x def set_state_from_file ( self , file ) : x = parse_file ( file ) self.init ( x ) | May __init__ be used as normal method for initialization , not as constructor ? |
Python | Adding headers with unicode_literals enabled seems to fail with Nginx , uWSGI and a simple Flask app : The app is available directly for debug purpose or through Nginx - > uWSGI - > Flask and works well.When I use a browser to connect directly to the app , I 've got a login dialog and theWWW-Authenticate header is corr... | # -*- coding : utf-8 -*-from __future__ import unicode_literalsfrom flask import Flask , make_responseapp = Flask ( 'test ' ) @ app.route ( '/ ' ) def index ( ) : response = make_response ( ) response.status_code = 401 response.headers = { 'WWW-Authenticate ' : 'Basic realm= '' test '' ' } # Fail # response.headers = {... | Add headers in a Flask app with unicode_literals |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.