lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I am working on a project where I have to use a combination of numeric and text data in a neural network to make predictions of a system 's availability for the next hour . Instead of trying to use separate neural networks and doing something weird/unclear ( to me ) at the end to produce the desired output , I decided ... | # LSTM Module for performance metricsinput = Input ( shape= ( shape [ 1 ] , shape [ 2 ] ) ) lstm1 = Bidirectional ( LSTM ( units=lstm_layer_count , activation='tanh ' , return_sequences=True , input_shape=shape ) ) ( input ) dropout1 = Dropout ( rate=0.2 ) ( lstm1 ) lstm2 = Bidirectional ( LSTM ( units=lstm_layer_count... | Training on sequences of sentences using Keras |
Python | I 'm using AE socket API and I have done the following test : App Engine instance : 0:00:04.022290 and 0:00:04.209410Local Python environment : 0:00:00.509000 and 0:00:00.511000 I 've started to do some testing after I noticed that a single request took about 400ms to 500ms . The server that is answering the request is... | class TestHandler ( webapp.RequestHandler ) : def get ( self ) : size = 1024 * 4 start = datetime.datetime.now ( ) for _ in range ( 10 ) : sock = socket.socket ( socket.AF_INET , socket.SOCK_STREAM ) sock.connect ( ( 'some.ip.here ' , 12345 ) ) sock.send ( 'some dummy data ' ) data = `` newData = 'dummy ' while newData... | App Engine Socket API factor 8 slower than native python |
Python | I need to draw a punchcard with matplotlib which seem to not have such a function.So I have coded the following one : However it does not exactly work as expected . If it is evaluated on the following example : we obtain the following result : You can notice there are a lot of empty vertical space between the circles ,... | import matplotlib.pyplot as pltimport numpy as npdef draw_punchcard ( infos , ax1=range ( 7 ) , ax2=range ( 24 ) , ax1_ticks= [ 'Monday ' , 'Tuesday ' , 'Wednesday ' , 'Thursday ' , 'Friday ' , 'Saturday ' , 'Sunday ' ] , ax2_ticks=range ( 24 ) , ax1_label='Day ' , ax2_label='Hour ' ) : `` '' '' Construct a punchcard .... | Matplotlib : How to remove the vertical space when displaying circles on a grid ? |
Python | I 've installed django using the pip command ( pip install Django ) , but i ca n't run it using the py command , as it ca n't find the module . I can only make it works using 'python ' command.Here is a summary of the screenshot I have atttachedIt also looks like django works only with 3.6.1 . Is there any way to set b... | $ python -- versionPython 3.6.1 $ py -- versionPython 3.6.0 | Why do python and py commands run different python 3 versions ? |
Python | So I 'm using the django-jcrop plugin to crop an image . Inside my HTML file I have this line : When this is passed , I get the following error : { { ratio } } is passed correctly outside of the tag , and gives the correct intended value , 400x400 . When I remove the single quotes from the max_size= ' { { ratio } } ' I... | < img src= '' { % cropped_thumbnail order 'cropping ' max_size= ' { { ratio } } ' % } '' > TemplateSyntaxError : max_size must match INTxINT TemplateSyntaxError : Could not parse the remainder : ' { { ' from ' { { ' | Django - Tag inside a Template tag |
Python | I have 3 dimensional array of integers ( ~4000 x 6000 x 3 ) that I need to classify in a particular way . I 'm hoping for something like a k-means clustering method , but instead of inputting the number of clusters I would like to input the maximum radius of a cluster.Said another way , given a sphere of a defined size... | import numpy as nprandomArray = np.random.rand ( 10,10,3 ) *500Out [ 8 ] : array ( [ [ [ 256.68932025 , 153.07151992 , 196.19477623 ] , [ 48.05542231 , 346.1289173 , 327.44694932 ] , [ 427.87340594 , 197.26882283 , 402.41558648 ] , [ 192.50462233 , 408.31800086 , 81.66016443 ] , [ 64.15373494 , 34.96971099 , 446.553624... | distance based classification |
Python | Are Python Empty Immutables Singletons ? If you review the CPython implementation of builtin types , you 'll find comments on all the immutable builtin objects that their empty versions are singletons . This would make a lot of sense as Python could avoid wasting memory on redundant items that would never change in pla... | /* The empty frozenset is a singleton */ > > > g = frozenset ( ) > > > f = frozenset ( ' a ' ) - frozenset ( ' a ' ) > > > ffrozenset ( [ ] ) > > > f is gFalse > > > id ( f ) 279262312 > > > id ( g ) 114734544 | Are Python Empty Immutables Singletons ? |
Python | I wrote an adaptive color thresholding function in Python ( because OpenCV 's cv2.adaptiveThreshold did n't fit my needs ) and it is way too slow . I 've made it as efficient as I can , but it still takes almost 500 ms on a 1280x720 image.I would greatly appreciate any suggestions that will make this function more effi... | def bilateral_adaptive_threshold ( img , ksize=20 , C=0 , mode='floor ' , true_value=255 , false_value=0 ) : mask = np.full ( img.shape , false_value , dtype=np.int16 ) left_thresh = np.zeros_like ( img , dtype=np.float32 ) # Store the right-side average of each pixel here right_thresh = np.zeros_like ( img , dtype=np.... | Python : How to make this color thresholding function more efficient |
Python | I learnt that in some immutable classes , __new__ may return an existing instance - this is what the int , str and tuple types sometimes do for small values . But why do the following two snippets differ in the behavior ? With a space at the end : Without a space : Why does the space bring the difference ? | > > > a = 'string ' > > > b = 'string ' > > > a is bFalse > > > c = 'string ' > > > d = 'string ' > > > c is dTrue | Python string with space and without space at the end and immutability |
Python | I was playing with couchdb and the recommended `` couchdbkit '' python package . I felt it was a bit slow and decided to do some measurements . If i did n't do something wrong , then using the popular `` requests '' package is more than 10 times faster than going through couchdbkit . Why ? Here is the timing script i u... | from time import time as nowfrom pprint import pprintclass Timer : def __init__ ( self ) : self.current = now ( ) def __call__ ( self , msg ) : snap = now ( ) duration = snap - self.current self.current = snap pprint ( `` % .3f duration -- % s '' % ( duration , msg ) ) def requests ( num ) : t = Timer ( ) import reques... | couchdbkit 10x slower than requests ? |
Python | I 'm seeing non-deterministic behavior when trying to select a pseudo-random element from sets , even though the RNG is seeded ( example code shown below ) . Why is this happening , and should I expect other Python data types to show similar behavior ? Notes : I 've only tested this on Python 2.7 , but it 's been repro... | import random '' ' Class contains a large set of pseudo-random numbers . ' '' class bigSet : def __init__ ( self ) : self.a = set ( ) for n in range ( 2000 ) : self.a.add ( random.random ( ) ) return '' ' Main test function . ' '' def randTest ( ) : `` ' Seed the PRNG. `` ' random.seed ( 0 ) `` ' Create sets of bigSet ... | Seeded Python RNG showing non-deterministic behavior with sets |
Python | For each element in a randomized array of 2D indices ( with potential duplicates ) , I want to `` +=1 '' to the corresponding grid in a 2D zero array . However , I do n't know how to optimize the computation . Using the standard for loop , as shown here , The runtime can be quite significant : Is there a way to vectori... | def interadd ( ) : U = 100 input = np.random.random ( size= ( 5000,2 ) ) * U idx = np.floor ( input ) .astype ( np.int ) grids = np.zeros ( ( U , U ) ) for i in range ( len ( input ) ) : grids [ idx [ i,0 ] , idx [ i,1 ] ] += 1 return grids > > timeit ( interadd , number=5000 ) 43.69953393936157 | Vectorize iterative addition in NumPy arrays |
Python | I am pickling , compressing , and saving python objects . I want to be able to double-check that that the object I saved is the exact same object that is returned after decompression and depickling . I thought there was an error in my code , but when I boiled the problem down to a reproducible example I found that pyth... | class fubar ( object ) : passprint ( fubar ( ) == fubar ( ) ) # False | Python does not consider equivalent objects to be equivalent |
Python | The scope of the variables created in a with statement is outside the with block ( refer : Variable defined with with-statement available outside of with-block ? ) . But when I run the following code : The output shows that Foo.__del__ is called before printing foo ( at # line 1 above ) : My question is , why is Foo.__... | class Foo : def __init__ ( self ) : print `` __int__ ( ) called . '' def __del__ ( self ) : print `` __del__ ( ) called . '' def __enter__ ( self ) : print `` __enter__ ( ) called . '' return `` returned_test_str '' def __exit__ ( self , exc , value , tb ) : print `` __exit__ ( ) called . '' def close ( self ) : print ... | Why is __del__ called at the end of a with block ? |
Python | i have dataframe with each row having a list value.i have to do a calculate a score with one row and against all the other rowsFor eg : repeat step 2,3 between id 0 and id 1,2,3 , similarly for all the ids.and create a N x N dataframe ; such as this : Right now my code has just one for loop : Is there a better way to d... | id list_of_value0 [ ' a ' , ' b ' , ' c ' ] 1 [ 'd ' , ' b ' , ' c ' ] 2 [ ' a ' , ' b ' , ' c ' ] 3 [ ' a ' , ' b ' , ' c ' ] Step 1 : Take value of id 0 : [ ' a ' , ' b ' , ' c ' ] , Step 2 : find the intersection between id 0 and id 1 , resultant = [ ' b ' , ' c ' ] Step 3 : Score Calculation = > resultant.size / id... | create a NxN matrix from one column pandas |
Python | If I try to load the d3.js library into my jupyter notebook it works fine with version 3.x . I can then go to the chrome console and the d3 object is available.If I do the same with version 4.x it is not available even though it is displayed in the sources tab of the chrome developer tools.What am I doing wrong ? | from IPython.core.display import display , HTMLHTML ( ' < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js '' > < /script > ' ) from IPython.core.display import display , HTMLHTML ( ' < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js '' > < /script > ' ) | d3.js Loading version 3 vs version 4 in Jupyter Notebook |
Python | I have a collection of images with a circle drawn as a white outline . However , I want to fill the complete circle with white color . What is a fast way to do it ? The following is the sample of the image : I have tried using nested loops to achieve this , but it takes a lot of time , and I have around 1.5 million ima... | roundRobinIndex = 0new_image = np.zeros ( ( img_w , img_h ) ) for row in range ( 540 ) : for column in range ( 800 ) : if image [ row , column ] == 255 : roundRobinIndex = ( roundRobinIndex + 1 ) % 2 if roundRobinIndex == 1 : new_image [ row , column ] = 255 | Filling an outlined circle |
Python | Using the functionality in pyviz , it 's easy to generate an hvplot/panel interactive dashboard for a gridded xarray dataset , like this air temperature data example : which automatically creates a slider for the time dimension : If I take a look at the object created : I can see that a DiscreteSlider widget was create... | import xarray as xrimport hvplot.xarrayimport panel as pnairtemps = xr.tutorial.load_dataset ( 'air_temperature ' ) atemp = airtemps.air [ :10 , : , : ] mesh = atemp.hvplot ( groupby='time ' ) row = pn.Row ( mesh ) display ( row ) print ( row ) Row [ 0 ] Row [ 0 ] HoloViews ( DynamicMap ) [ 1 ] WidgetBox [ 0 ] Discrete... | What is the best way to change the widget type in an hvplot/holoviews/panel object ? |
Python | I have a list like thislets call this list as 'years_list'When I did groupby year , I got the desired output : Then , I slightly changed my implementation like this , I have just added a dict , but the output is different , I could n't find out why . Please help me to find what the dict is doing actually . ( Python 2.7... | [ u'201003 ' , u'200403 ' , u'200803 ' , u'200503 ' , u'201303 ' , u'200903 ' , u'200603 ' , u'201203 ' , u'200303 ' , u'200703 ' , u'201103 ' ] group_by_yrs_list = groupby ( years_list , key = lambda year_month : year_month [ : -2 ] ) for k , v in group_by_yrs_list : print k , list ( v ) 2010 [ u'201003 ' ] 2004 [ u'2... | difference between dict ( groupby ) and groupby |
Python | hello im trying to achieve this raw query with sqlalchemy : so far i get the result i want with this raw query but i want to be able to .paginate them so i could keep working properlywith my other queries what i did was this : fairly simple and i got what i wanted , i belive i have to do something likebut im not gettin... | SELECT m.* , SUM ( case when f.monkey = m.id then 1 else 0 end ) as friendsFROM monkey as mLEFT JOIN friendship as f ON m.id = f.monkeyGROUP BY m.id , m.nameorder by friends desc monkeys = models.Monkey.query.order_by ( models.Monkey.name ) .paginate ( page , 5 , False ) monkeys = models.Monkey.query.join ( models.Frie... | from raw sql to flask-sqlalchemy |
Python | I have a pandas dataframe like below : I want to create a new `` z_gauss '' column by applying a convolution ( numpy.convolve ) with a gaussian filter on vectors ( column z ) corresponding to a group of rows in my dataframe with the same `` profile_index '' .I 've tried to do something like data [ `` z_gauss '' ] = dat... | profile_index point_index z x y0 0 1 -0.885429 297903.323027 6.669492e+061 0 2 -0.820151 297904.117752 6.669492e+062 0 3 -0.729671 297904.912476 6.669491e+063 0 4 -0.649332 297905.707201 6.669490e+064 1 1 -0.692186 297906.501926 6.669490e+065 1 2 -0.885429 297903.323027 6.669492e+066 1 3 -0.820151 297904.117752 6.66949... | Pandas apply convolve by group of rows |
Python | I am trying to understand and solve the following problem : Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot . Aman , their friend has been helping them out . But as it goes , Sameer and Arpit have got bored of problems involving factorials . Reason be... | ExampleInput:32 55 1121 71Output:2106Constraints:1 < = T < = 10001 < P < = 2*10^91 < = N < = 2*10^9Abs ( N-P ) < = 1000 def factorial ( c ) : n1=1n2=2num=1while num ! =c : n1= ( n1 ) * ( n2 ) n2+=1 num+=1return n1for i in range ( int ( raw_input ( ) ) ) : n , p=map ( int , raw_input ( ) .split ( ) ) print factorial ( n... | Boring Factorials in python |
Python | PEP 8 states : Imports are always put at the top of the file , just after any module comments and docstrings , and before module globals and constants.However if the class/method/function that I am importing is only used by a child process , surely it is more efficient to do the import when it is needed ? My code is ba... | p = multiprocessing.Process ( target=main , args= ( dump_file , ) ) p.start ( ) p.join ( ) print u '' Process ended with exitcode : { } '' .format ( p.exitcode ) if os.path.getsize ( dump_file ) > 0 : blc = BugLogClient ( listener='http : //21.18.25.06:8888/bugLog/listeners/bugLogListenerREST.cfm ' , appName='main ' ) ... | Using multiprocessing in Python , what is the correct approach for import statements ? |
Python | Tl ; dr is bold-faced text.I 'm working with an image dataset that comes with boolean `` one-hot '' image annotations ( Celeba to be specific ) . The annotations encode facial features like bald , male , young . Now I want to make a custom one-hot list ( to test my GAN model ) . I want to provide a literate interface .... | Arched_Eyebrows Attractive Bags_Under_Eyes Bald Bangs Chubby Male Wearing_Necktie Young [ 0 . 0 . 0 . 1 . 0 . 1 . 0 . 0 . 1 . ] import numpy as npheader = ( `` Arched_Eyebrows Attractive Bags_Under_Eyes `` `` Bald Bangs Chubby Male Wearing_Necktie Young '' ) NUM_CLASSES = len ( header.split ( ) ) # 9 binary_label = np.... | Literate way to index a list where each element has an interpretation ? |
Python | I am trying to have pexepct stdout logs via logger that I have defined . Below is the codeWith above code , logger is printing what pexepct is sending commands on the console but I am not getting response of pexpect . Is there a way I can log pexpect response too via loggerBelow is the outputWaiting for response | import loggingimport pexpectimport reimport time # this will be the method called by the pexpect object to logdef _write ( *args , **kwargs ) : content = args [ 0 ] # let 's ignore other params , pexpect only use one arg AFAIK if content in [ ' ' , `` , '\n ' , '\r ' , '\r\n ' ] : return # do n't log empty lines for eo... | Not able to print pexpect response via python logger |
Python | I have a Python code that creates a report for a data frame from Reddit , and converts it to simple HTML and then email 's it out . Below is the code : The email that is received is very simple in format . I wanted that email to look good so wrote a HTML code with header image logo etc using HTML Tables inline CSS , in... | # Clean all the Dataframestest_clean = clean ( test_test_df ) brand_clean = clean ( brands_df ) competitor_clean = clean ( competitors_df ) # Convert to HTMLtest_html = test_clean.render ( ) brand_html = brand_clean.render ( ) competitor_html = competitor_clean.render ( ) # In [ 27 ] : brand_clean # # Email Integration... | How do I integrate a HTML code in a Python Script ? |
Python | I have an equation system like the following : For this specific system , I know that a nontrivial solution ( s ) only exists if p1 == p2 , which is .However , how can I determine this in the general case using Sympy ? For this example , my implementation is as follows : The result is If I set the result isIs there som... | from sympy import Matrix , symbols , pprint , lcm , latexfrom sympy.solvers import solve_linear_systemtop_matrix = Matrix.zeros ( 8,7 ) p1 = symbols ( `` p1 '' ) p2 = symbols ( `` p2 '' ) top_matrix [ 0,0 ] = 1top_matrix [ 0,1 ] = -1top_matrix [ 1,1 ] = ( 1-p1 ) top_matrix [ 1,2 ] = -1top_matrix [ 2,2 ] = 1top_matrix [... | Symbolic solution of equation system using Sympy with trivial solutions depending on symbols |
Python | In twisted 's sourcecode , many docstrings contain formats like this : L { xxx } or C { xxx } or a line begin with an ' @ ' , what 's their meanings ? for example , in twisted/internet/interfaces.py : L { IPullProducer } , C { resumeProducing } , @ type producer ? By the way , are these formats a part of standard pytho... | def registerProducer ( producer , streaming ) : `` '' '' Register to receive data from a producer . ... For L { IPullProducer } providers , C { resumeProducing } will be called once each time data is required . ... @ type producer : L { IProducer } provider ... @ return : C { None } `` '' '' | What 's meaning of these formats in twisted 's docstring ? |
Python | The python language reference states in section 7.4 : For an except clause with an expression , that expression is evaluated , and the clause matches the exception if the resulting object is “ compatible ” with the exception . An object is compatible with an exception if it is the class or a base class of the exception... | print isinstance ( AssertionError ( ) , object ) # prints Truetry : raise AssertionError ( ) except object : # This block should execute but it never does . print 'Caught exception ' | Why does n't except object catch everything in Python ? |
Python | I 've been using arrays lately and really missing Python 's `` in '' operator.e.g . : I 've made up for it a little bit by creating a `` ThereExists-Object '' function , like so : e.g . : obviously I could define another function for this as well ... but I 'd like to know if there 's some syntactical sugar that I 'm un... | if ( `` hello '' in [ `` hello '' , `` there '' , `` sup '' ] ) : print `` this prints : ) '' function ThereExists-Object ( [ System.Management.Automation.ScriptBlock ] $ sb ) { return ( $ input | where $ sb ) -as [ bool ] } New-Alias -Name ThereExists -Value ThereExists-Object if ( $ arrayOfStuff | thereexists { $ _ -... | Powershell equivalent to Python `` in '' ? |
Python | I have data ( mostly a series of numpy arrays ) that I want to convert into text that can be copied/pasted/emailed etc.. I created the following formula which does this.My issue is that the string it produces is longer than it needs to be because it only uses a subset of letters , numbers , and symbols . If I was able ... | def convert_to_ascii85 ( x ) : p = pickle.dumps ( x ) p = zlib.compress ( p ) return b64.b85encode ( p ) | Compress data into smallest amount of text ? |
Python | I have a list of dictionaries . Each Dictionary has an integer key and tuple value . I would like to sum all the elements located at a certain position of the tuple.Example : I know i could do something like : Is there a more pythonic way of doing this ? Thanks | myList = [ { 1000 : ( `` a '' ,10 ) } , { 1001 : ( `` b '' ,20 ) } , { 1003 : ( `` c '' ,30 ) } , { 1000 : ( `` d '' ,40 ) } ] sum = 0for i in myList : for i in myList : temp = i.keys ( ) sum += i [ temp [ 0 ] ] [ 1 ] print sum | Python List of Dictionaries [ int : tuple ] Sum |
Python | I modified sys.modules [ __name__ ] to a class Hello , like this : Then , I imported hello.py in another python file test.py like : But , I got an error said `` AttributeError : 'NoneType ' object has no attribute 'time ' '' when I run python test.py.It seemed that hello.py could not import the time module.I really did... | # hello.pyimport sysimport timeclass Hello : def print_time ( self ) : print 'hello , current time is : ' , time.time ( ) sys.modules [ __name__ ] = Hello ( ) # test.pyimport hellohello.print_time ( ) | can not find time module when changed sys.modules [ __name__ ] |
Python | In python2.7 , following the pympler example : This is the first code after the imports . It results inI get the same error when I try to initialize a SummaryTracker object.It looks like a bug in Pympler , but the fact that I ca n't find any mentions of it contradicts this . According to the official documentation , ``... | from anotherfile import somefunction , somecustomclassfrom os import path , listdirimport pandas as pdimport gcfrom pympler import tracker , muppy , summaryall_objects = muppy.get_objects ( ) print 'all objects : ' , len ( all_objects ) sum1 = summary.summarize ( all_objects ) summary.print_ ( sum1 ) /usr/bin/python2.7... | pympler raises TypeError |
Python | Using DataArray objects in xarray what is the best way to find all cells that have values ! = 0.For example in pandas I would do My specific example I 'm trying to look at 3 dimensional brain imaging data.Looking at the documentation for xarray.DataArray.where it seems I want something like this : But I still get array... | df.loc [ df.col1 > 0 ] first_image_xarray.shape ( 140 , 140 , 96 ) dims = [ ' x ' , ' y ' , ' z ' ] first_image_xarray.where ( first_image_xarray.y + first_image_xarray.x > 0 , drop = True ) [ : ,0,0 ] < xarray.DataArray ( x : 140 ) > array ( [ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , ... | Sparse DataArray Xarray search |
Python | How can I concatenate two items when yielding from a function in python ? The base case : What if I want to yield both the number and its square number**2However doing itertools.chain.from_iterable ( [ generator1 , generator2 ] ) from the outside gives the expected result . | import itertoolsdef test ( ) : for number in range ( 0,10 ) : yield numberlist ( test ( ) ) # [ 0 ... 9 ] import itertoolsdef test ( ) : for number in range ( 0,10 ) : yield itertools.chain.from_iterable ( [ number , number*2 ] ) list ( test ( ) ) # [ 0,0,1,1,2,4,3,9 , ... ] pretended # < itertools.chain at 0x135decfd0... | Concatenate while yielding |
Python | In python ( tested on 2.7.6 ) all variables arestatically bound to a scope at compile time . This process is welldescribed in http : //www.python.org/dev/peps/pep-0227/ andhttp : //docs.python.org/2.7/reference/executionmodel.htmlIt is explicitly stated that `` If a name binding operation occursanywhere within a code b... | x = 1def f ( ) : print x x = 2 print x > > > f ( ) Traceback ( most recent call last ) : File `` < pyshell # 46 > '' , line 1 , in < module > f ( ) File `` < pyshell # 45 > '' , line 2 , in f print xUnboundLocalError : local variable ' x ' referenced before assignment x = 1class C ( ) : y = x + 10 x = 2 def __init__ ( ... | Why static binding works differently for class and function ? |
Python | I want to write a function which returns a list of functions . As a MWE , here 's my attempt at function that gives three functions that add 0 , 1 , and 2 to an input number : Contrary to my expectation , each function ends up using the last value taken by i. I 've experienced similar behavior when e.g . a list is used... | def foo ( ) : result = [ ] for i in range ( 3 ) : temp = lambda x : x + i print ( temp ( 42 ) ) # prints 42 , 43 , 44 result.append ( temp ) return resultfor f in foo ( ) : print ( f ( 42 ) ) # prints 44 , 44 , 44 | How can I return a function that uses the value of a variable ? |
Python | I am plotting journey time for a series of roads at hourly resolution , with data over a few weeks . I can plot using unix time , but that is n't very intuitive . This is 7 days worth of data . I used a function to manipulate the time field in order to give the date and hour : However , this results in ggplot throwing ... | def plot_time ( time ) : return time.strftime ( ' % Y- % m- % d- % H ' ) ValueError : invalid literal for float ( ) : 2016-04-13-00 | ggplot python handling time data over many weeks at hourly resolution |
Python | Consider this sample python code . It reads from stdin and writes to a file . Suppose I want to modify this same program to write to stdout instead . Then , I 'll have to replace each instance of f.write ( ) with sys.stdout.write ( ) . But that would be too tedious . I want to know if there is a way to specify f as an ... | import sysarg1 = sys.argv [ 1 ] f = open ( arg1 , ' w ' ) f.write ( ' < html > < head > < title > < /title > < /head > < body > ' ) for line in sys.stdin : f.write ( `` < p > '' ) f.write ( line ) f.write ( `` < /p > '' ) f.write ( `` < /body > < /html > '' ) f.close ( ) | Is it possible to have an alias for sys.stdout in python ? |
Python | I am currently doing a merge over a set of variables that I 'd like to parallelize . My code looks something like this : Ordinarily , to speed up long loops , I would replace the for m in mergelist with something like ... .But since I 'm using the star to unpack the tuple , it 's not clear to me how to map this correct... | mergelist = [ ( 'leftfile1 ' , 'rightfile1 ' , 'leftvarname1 ' , 'outputname1 ' ) , ( 'leftfile1 ' , 'rightfile1 ' , 'leftvarname2 ' , 'outputname2 ' ) ( 'leftfile2 ' , 'rightfile2 ' , 'leftvarname3 ' , 'outputname3 ' ) ] def merger ( leftfile , rightfile , leftvarname , outvarname ) : do_the_mergefor m in mergelist : ... | How to use a map with *args to unpack a tuple in a python function call |
Python | Given an array : And given its indices : How would I be able to stack them neatly one against the other to form a new 2D array ? This is what I 'd like : This is my current solution : It works , but is there something shorter/more elegant to carry this operation out ? | arr = np.array ( [ [ 1 , 3 , 7 ] , [ 4 , 9 , 8 ] ] ) ; arrarray ( [ [ 1 , 3 , 7 ] , [ 4 , 9 , 8 ] ] ) np.indices ( arr.shape ) array ( [ [ [ 0 , 0 , 0 ] , [ 1 , 1 , 1 ] ] , [ [ 0 , 1 , 2 ] , [ 0 , 1 , 2 ] ] ] ) array ( [ [ 0 , 0 , 1 ] , [ 0 , 1 , 3 ] , [ 0 , 2 , 7 ] , [ 1 , 0 , 4 ] , [ 1 , 1 , 9 ] , [ 1 , 2 , 8 ] ] ) d... | Create a 2D array from another array and its indices with NumPy |
Python | In a project I 'm working in I need to cover a Tornado service with Behave so I want to start an instance of my tornado service before running each scenario.Naively trying to run the loop as part before all seems to lock the excecution : So it 's probably not what I need . | from tornado import ioloopfrom tornadoadapter.applications import APPLICATIONdef before_all ( context ) : print `` Service running on port 8000 '' APPLICATION.listen ( 8000 ) ioloop.IOLoop.instance ( ) .start ( ) | How to run Tornado IO Loop during Behave environment setup |
Python | I have a client app that interacts with a web service to retrieve account information . There 's a requirement that the user is notified if they mistyped the username/password . I 'm modifying the web service to return something to my client to provide a hint to the user that there 's an error in input.How do I correct... | from flask.ext.httpauth import HTTPBasicAuthaccounts = [ [ `` user0 '' , `` password0 '' ] , [ `` user1 '' , `` password1 '' ] , ] @ app.route ( '/accountlist ' ) @ auth.login_requireddef accountlist ( ) username = auth.username ( ) ; if ... : # check if accounts does not have the given username # notify the sender tha... | How to implement `` Incorrect username/password '' hint for a webservice using Flask HTTP Auth ? |
Python | i 've started using pdb through gud in emacs 23.3 , how can i hook command messages sent to the debugger from the buffer ? i wrote the advice below for use with gdb , in order to persist comint 's ring , but ca n't find an equivalent function to hook for pdb . i 'm using python-mode.el as my major mode.thanks . | ( defadvice gdb-send-item ( before gdb-save-history first nil activate ) `` write input ring on quit '' ( if ( equal ( type-of item ) 'string ) ; avoid problems with 'unprintable ' structures sent to this function.. ( if ( string-match `` ^q\\ ( u\\|ui\\|uit\\ ) ? $ '' item ) ( progn ( comint-write-input-ring ) ( messa... | how do i hook commands sent to pdb through gud ? |
Python | I have a jpeg from where I want to crop a portion containing graph ( the one in the bottom portion ) .As of now I used this code to achieve the same : But I achieved this by guessing the x1 , y1 , x2 , y2 multiple times to arrive at this ( guess work ) .Image before cropping : Image after cropping : I 'm totally novice... | from PIL import Imageimg = Image.open ( r 'D : \aakash\graph2.jpg ' ) area = ( 20 , 320 , 1040 , 590 ) img2 = img.crop ( area ) # img.show ( ) img2.show ( ) | How to crop multiple rectangles or squares from JPEG ? |
Python | I 'm sorting a list of dicts by a key : some of the dicts have name set to None , and Python 2 places None values before any other , so they 're placed at the front of the sorted list . A naive fix would bebut , obviously , that would not work for any non-Latin names.What is a nice and Pythonic way of sorting a list co... | groups = sorted ( groups , key=lambda a : a [ 'name ' ] ) groups = sorted ( groups , key=lambda a : a [ 'name ' ] or 'zzzz ' ) | How do I sort a list with `` Nones last '' |
Python | In Clojure I can do something like this : instead of doing this : This is called threading in Clojure terminology and helps getting rid of a lot of parentheses.In Python if I try to use functional constructs like map , any , or filter I have to nest them to each other . Is there a construct in Python with which I can d... | ( - > path clojure.java.io/resource slurp read-string ) ( read-string ( slurp ( clojure.java.io/resource path ) ) ) | Is there something like the threading macro from Clojure in Python ? |
Python | I have a txt file with data in this format . The first 3 lines repeat over and over.I would like to output the data in a table format , for example : I am struggling to set the headers and just loop over the data . What I have tried so far is : The output from that is Not really what I am looking for . | name=1grade=Aclass=Bname=2grade=Dclass=A name | grade | class1 | A | B2 | D | A def myfile ( filename ) : with open ( file1 ) as f : for line in f : yield line.strip ( ) .split ( '=',1 ) def pprint_df ( dframe ) : print ( tabulate ( dframe , headers= '' keys '' , tablefmt= '' psql '' , showindex=False , ) ) # f = pd.Da... | Read file of repeated `` key=value '' pairs into DataFrame |
Python | Maybe I 'm missing the obvious.I have a pandas dataframe that looks like this : I 'd like to use the groupby function to count the number of appearances of each element in the categories column , so here the result would beHowever when I try using a groupby function , pandas counts the occurrences of the entire list in... | id product categories 0 Silmarillion [ 'Book ' , 'Fantasy ' ] 1 Headphones [ 'Electronic ' , 'Material ' ] 2 Dune [ 'Book ' , 'Sci-Fi ' ] Book 2Fantasy 1Electronic 1Material 1Sci-Fi 1 | Pandas : Use groupby on each element of list |
Python | Context : I 'm using a fully convolutional network to perform image segmentation . Typically , the input is an RGB image shape = [ 512 , 256 ] and the target is a 2 channels binary mask defining the annotated regions ( 2nd channel is the opposite of the fist channel ) .Question : I have the same CNN implementation usin... | import tensorflow as tftf.reset_default_graph ( ) x = inputs = tf.placeholder ( tf.float32 , shape= [ None , shape [ 1 ] , shape [ 0 ] , 3 ] ) targets = tf.placeholder ( tf.float32 , shape= [ None , shape [ 1 ] , shape [ 0 ] , 2 ] ) for d in range ( 4 ) : x = tf.layers.conv2d ( x , filters=np.exp2 ( d+4 ) , kernel_size... | Deep Learning implementation in Tensorflow or Keras give drastic different results |
Python | I am using Ubuntu 14.04 LTS . I tried Polipo , but it kept refusing Firefox 's connections even if I added myself as allowedClient and hours of researching with no solution . So instead , I installed Privoxy and I verified it work with Firefox by going to the Tor website and it said Congrats this browser is configured ... | 2016-07-14 02:43:34 [ scrapy ] INFO : Enabled downloader middlewares : [ 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware ' , 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware ' , 'myProject.middlewares.RandomUserAgentMiddleware ' , 'myProject.middlewares.ProxyMiddleware ' , 'scrapy.downl... | Scrapy gets NoneType Error when using Privoxy Proxy for Tor |
Python | I have a list of particular words ( 'tokens ' ) and need to find all of them ( if any of them are present ) in plain texts . I prefer using Pandas , to load text and perform the search . I 'm using pandas as my collection of short text are timestamped and it is quite easy to organise these short text in a single data s... | twitts0 today is a great day for BWM1 prices of german cars increased2 Japan introduced a new model of Toyota3 German car makers , such as BMW , Audi and VW mo ... list_of_car_makers = [ 'BMW ' , 'Audi ' , 'Mercedes ' , 'Toyota ' , 'Honda ' , 'VW ' ] twitts cars_mentioned0 today is a great day for BMW [ BMW ] 1 prices ... | Searching for all matches in texts with Pandas |
Python | I have a Django 1.9.6 site deployed to Heroku . When DEBUG=False I was getting a server error ( 500 ) . The logs contained no useful information , so I tried running it with DEBUG=True . Now it works fine . I think the issue may be tied to my scss file processing , which really confuses me and I was struggling with . I... | BASE_DIR = os.path.dirname ( os.path.dirname ( os.path.abspath ( __file__ ) ) ) STATIC_URL = '/static/'STATIC_ROOT = os.path.join ( BASE_DIR , 'staticfiles ' ) MEDIA_URL = `` /media/ '' MEDIA_ROOT = os.path.join ( BASE_DIR , `` media/ '' ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder ' ,... | Ca n't use django-compress with Heroku |
Python | I am following the following gensim tutorial to transform my word2vec model to tensor.Link to the tutorial : https : //radimrehurek.com/gensim/scripts/word2vec2tensor.htmlMore specifically , I ran the following commandHowever , I get the following error for the above command.When I use model.wv.save_word2vec_format ( m... | python -m gensim.scripts.word2vec2tensor -i C : \Users\Emi\Desktop\word2vec\model_name -o C : \Users\Emi\Desktop\word2vec UnicodeDecodeError : 'utf-8 ' codec ca n't decode byte 0x80 in position 0 : invalid start byte ValueError : invalid vector on line 1 ( is this really the text format ? ) | How to use word2vec2tensor in gensim ? |
Python | I used opencv 's minAreaRect to deskew the mnist digits.It worked well for most of the digits but , in some cases the minAreaRect was not detected correctly and it lead to further skewing of the digits.Images with which this code worked : Input image : minAreaRect Image : deskewed image : But , for this the did n't wor... | import numpy as npimport cv2image=cv2.imread ( 'MNIST/mnist_png/testing/9/73.png ' ) # for 4 # # 5032,6780 # 8527,2436,1391gray=cv2.cvtColor ( image , cv2.COLOR_BGR2GRAY ) # # for 9 problem with 4665,8998,73,7gray=cv2.bitwise_not ( gray ) Gblur=cv2.blur ( gray , ( 5,5 ) ) thresh=cv2.threshold ( Gblur,0,255 , cv2.THRESH... | Deskewing MNIST dataset images using minAreaRect ( ) of opencv |
Python | Is it pythonic to mimic method overloading as found in statically typed languages ? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types.Here is an example : | class EmployeeCollection ( object ) : @ staticmethod def find ( value ) : if isinstance ( value , str ) : # find employee by name and return elif isinstance ( value , int ) : # find employee by employee number and return else : raise TypeError ( ) | Is it Pythonic to mimic method overloading ? |
Python | python 3.7.3 , rpy2 3.2.0 , the following code : from rpy2 import robjectsWhat 's going on ? This looks like standard procedure for rypy2 , and indeed how we used it under python 2.Same issue applies for any kind of rpy2 import : import rpy2.robjects.tests etc . | Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > File `` .virtualenvs/flask3/lib/python3.7/site-packages/rpy2/robjects/__init__.py '' , line 14 , in < module > import rpy2.rinterface as rinterface File `` .virtualenvs/flask3/lib/python3.7/site-packages/rpy2/rinterface.py '' , line 6 ,... | rpy2 3.2.0 on python 3.7 issues w/ importing robjects |
Python | I am hitting an obscure problem ( bug ? ) with my Python3 QML program.I implemented a QAbstractListModel with a custom get method to get to the underlying QObject items . The moment I try to get the same Python QObject at two different places in QML I get : The get method looks like this : And the model like this : The... | TypeError : unable to convert a Python 'QMyItem ' object to a C++ 'QObject* ' instance @ pyqtSlot ( int , result=QMyItem ) def get ( self , row ) : return self._items [ row ] ComboBox { model : mymodel textRole : 'name ' onActivated : mymodel.item = model.get ( index ) onModelChanged : currentIndex = getCurrentIndex ( ... | Access Python QObject from QML fails to convert on second call |
Python | I 'm trying to have a rotated text in matplotlib . unfortunately the rotation seems to be in the display coordinate system , and not in the data coordinate system . that is : will give a line that will be in a 45 deg in the data coordinate system , but the accompanied text will be in a 45 deg in the display coordinate ... | import numpy as npimport matplotlib.pyplot as pltfig = plt.figure ( ) ax = fig.add_axes ( [ 0.15 , 0.1 , 0.8 , 0.8 ] ) t = np.arange ( 0.0 , 1.0 , 0.01 ) line , = ax.plot ( t , t , color='blue ' , lw=2 ) ax.text ( 0.51,0.51 , '' test label '' , rotation=45 ) plt.show ( ) | keeps text rotated in data coordinate system after resizing ? |
Python | Pytest 's output for failed asserts is much more informative and useful than the default in Python . I would like to leverage this when normally running my Python program , not just when executing tests . Is there a way to , from within my script , overwrite Python 's assert behavior to use pytest to print the stacktra... | def test_foo ( ) : foo = 12 bar = 42 assert foo == barif __name__ == '__main__ ' : test_foo ( ) $ python script/pytest_assert.pyTraceback ( most recent call last ) : File `` script/pytest_assert.py '' , line 8 , in < module > test_foo ( ) File `` script/pytest_assert.py '' , line 4 , in test_foo assert foo == barAssert... | Can I patch Python 's assert to get the output that py.test provides ? |
Python | I 've just written a small recursive programme to generate all the possible subdivisions of a list : I 've brute forced this and it 's taken me a long time to figure out . I 'm wondering what this is called , as I 'm sure there is a name for it.In general I 'm wondering how to learn this stuff from a mathematical point... | def subdivisions ( ls ) : yield [ ls ] if len ( ls ) > 1 : for i in range ( 1 , len ( ls ) ) : for lhs in subdivisions ( ls [ : i ] ) : yield lhs + [ ls [ i : ] ] > > > for x in subdivisions ( 'abcd ' ) : print x ... [ 'abcd ' ] [ ' a ' , 'bcd ' ] [ 'ab ' , 'cd ' ] [ ' a ' , ' b ' , 'cd ' ] [ 'abc ' , 'd ' ] [ ' a ' , ... | All possible subdivisions of a list |
Python | I am trying to download the html of a page that is requested through a javascript action when you click a link in the browser . I can download the first page because it has a general URL : But there are links along the bottom of the page that are numbers ( 1 to 10 ) . So if you click on one , it goes to , for example ,... | http : //www.locationary.com/stats/hotzone.jsp ? hz=1 http : //www.locationary.com/stats/hotzone.jsp ? ACTION_TOKEN=hotzone_jsp $ JspView $ NumericAction & inPageNumber=2 import urllibimport urllib2import cookielibimport reURL = `` def load ( url ) : data = urllib.urlencode ( { `` inUserName '' : '' email '' , `` inUse... | Download html in python ? |
Python | I have a list of items aprox 60,000 items - i would like to send queries to the database to check if they exist and if they do return some computed results . I run an ordinary query , while iterating through the list one-by-one , the query has been running for the last 4 days . I thought i could use the threading modul... | if __name__ == '__main__ ' : for ra , dec in candidates : t = threading.Thread ( target=search_sl , args= ( ra , dec , q ) ) t.start ( ) t.join ( ) | python , how to incrementally create Threads |
Python | I am doing a Kernel Density Estimation in Python and getting the contours and paths as shown below . ( here is my sample data : https : //pastebin.com/193PUhQf ) .There is a similar way to get the contours using R , which is described here : http : //bl.ocks.org/diegovalle/5166482Question : how can I achieve the same o... | from numpy import *from math import *import numpy as npimport matplotlib.pyplot as pltfrom scipy import statsx_2d = [ ] y_2d = [ ] data = { } data [ 'nodes ' ] = [ ] # here is the sample data : # https : //pastebin.com/193PUhQfX = [ ... .. ] for Picker in xrange ( 0 , len ( X ) ) : x_2d.append ( X [ Picker ] [ 0 ] ) y_... | python KDE get contours and paths into specific json format leaflet-friendly |
Python | I know someone explain why when I createequal unicode strings in Python 2.7they do not point to the same location in memoryAs in `` normal '' stringsok that was what I expected , but why ? how ? | > > > a1 = ' a ' > > > a2 = ' a ' > > > a1 is a2True > > > ua1 = u ' a ' > > > ua2 = u ' a ' > > > ua1 is ua2False | memory location in unicode strings |
Python | Some libraries like numpy , pandas or even python lists implement fancy indexing for its objects . This means I can do things like : If I want to offer this functionality in my class I could try to overload the __getitem__ and the __setitem__ methods : but I do n't see how this could work as 1:3 is not a valid variable... | obj [ 1:3 , : ] class Example ( object ) : def __getitem__ ( self , x ) : pass | Implementing fancy indexing in a class |
Python | Is it possible to apply code from imported module to module which import it ? For example , I have module Debug where defined some decorator for debugging , for example : What 's the idea : It 's would be useful if I can justand all functions from current module will wrapped with decorator.Is it possible ? | def debug_func ( f ) : def wrapper ( *func_args , **func_kwargs ) : print ( f ( *func_args , **func_kwargs ) ) return wrapper import Debug | Python introspection |
Python | Assume I have a list of this type : I want to find each index for which the value is the same for the n following indices.I can do it ( laboriously ) this way : Prints : Is there a better way to do this ? | # 0 1 2 3 4 5 6 7 8 9 10 11 -- list indexli= [ -1 , -1 , 2 , 2 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 ] def sub_seq ( li , n ) : ans= { } for x in set ( li ) : ans [ x ] = [ i for i , e in enumerate ( li [ : -n+1 ] ) if all ( x==y for y in li [ i : i+n ] ) ] ans= { k : v for k , v in ans.items ( ) if v } return ansli= [ -1... | Sequence of elements in a list satisfying a condition |
Python | I am using the python urllib2 library for opening URL , and what I want is to get the complete header info of the request . When I use response.info I only get this : I am expecting the complete info as given by live_http_headers ( add-on for firefox ) , e.g : My request function is : Is it possible to achieve the desi... | Date : Mon , 15 Aug 2011 12:00:42 GMTServer : Apache/2.2.0 ( Unix ) Last-Modified : Tue , 01 May 2001 18:40:33 GMTETag : `` 13ef600-141-897e4a40 '' Accept-Ranges : bytesContent-Length : 321Connection : closeContent-Type : text/html http : //www.yellowpages.com.mt/Malta-Web/127151.aspxGET /Malta-Web/127151.aspx HTTP/1.1... | how can I get complete header info from urlib2 request ? |
Python | With this code we have two instances of callable class , one is decorated and one is plain : I wonder if it is somehow supported to use the @ decorator syntax on a callable for just one instance - as opposed to decorating the class / method , which would apply to every instance . According to this popular answer , the ... | def decorator ( fn ) : def wrapper ( *args , **kwargs ) : print 'With sour cream and chives ! ' , return fn ( *args , **kwargs ) return wrapperclass Potato ( object ) : def __call__ ( self ) : print 'Potato @ { } called'.format ( id ( self ) ) spud = Potato ( ) fancy_spud = decorator ( Potato ( ) ) > > > spud ( ) Potat... | How can I decorate an instance of a callable class ? |
Python | I wonder , where does the function Read_Edgelist store the original id 's from the the edge list ? or under which attribute name ? Assume that I am reading an edge list like : where the numbers 1,2,3 are the ids ( or names ) of the nodes . Where does the iGraph ( python version ) stores these ids ? I tried retrieving t... | 1 22 1 1 3 | Initial node 's ids when creating graph from edge list |
Python | This prints What is the difference between _ value_ and value ? | from enum import Enumclass Type ( Enum ) : a = 1 b = 2print Type.a.value , Type.a._value_ 1 1 | python enum.Enum _value_ vs value |
Python | I am seeing the following phenomenon , could n't seem to figure it out , and did n't find anything with some search through archives : if I type in : I will get : However , if I type in : Then I will get : ( The first one only has one backslash on the r'\n ' whereas the second one has two backslashes in a row on the r'... | > > > if re.search ( r'\n ' , r'this\nis\nit ' ) : < br > ... print 'found it ! ' < br > ... else : < br > ... print `` did n't find it '' < br > ... did n't find it ! > > > if re.search ( r'\\n ' , r'this\nis\nit ' ) : < br > ... print 'found it ! ' < br > ... else : < br > ... print `` did n't find it '' < br > ... f... | python `` re '' package , strange phenomenon with `` raw '' string |
Python | There is a strange behavior of map when using Python 's multiprocessing.Pool . In the example below a pool of 4 processors will work on 28 tasks . This should take seven passes , each taking 4 seconds.However , it takes 8 passes . In the first six passes all processors are engaged . In the 7th pass only two tasks are c... | import timeimport multiprocessingfrom multiprocessing import Poolimport datetimedef f ( values ) : now = str ( datetime.datetime.now ( ) ) proc_id = str ( multiprocessing.current_process ( ) ) print ( proc_id+ ' '+now ) a=values**2 time.sleep ( 4 ) return a if __name__ == '__main__ ' : p = Pool ( 4 ) # number of proces... | python multiprocessing map mishandling of last processes |
Python | As stated in scipy lecture notes , this will not work as expected : But why ? How does being a view affect this behavior ? | a = np.random.randint ( 0 , 10 , ( 1000 , 1000 ) ) a += a.Tassert np.allclose ( a , a.T ) | Numpy : Why does n't ' a += a.T ' work ? |
Python | In particular , it outputs : Why ? | > > > dis.dis ( None ) 22 0 LOAD_FAST 0 ( x ) 3 LOAD_CONST 1 ( None ) 6 COMPARE_OP 8 ( is ) 9 POP_JUMP_IF_FALSE 23 23 12 LOAD_GLOBAL 1 ( distb ) 15 CALL_FUNCTION 0 18 POP_TOP 24 19 LOAD_CONST 1 ( None ) 22 RETURN_VALUE 25 > > 23 LOAD_GLOBAL 2 ( isinstance ) 26 LOAD_FAST 0 ( x ) 29 LOAD_GLOBAL 3 ( types ) 32 LOAD_ATTR 4... | Why does dis.dis ( None ) return output ? |
Python | I want to find the offset between two arrays of timestamps . They could represent , let 's say , the onset of beeps in two audio tracks.Note : There may be extra or missing onsets in either track.I found some information about cross-correlation ( e.g . https : //dsp.stackexchange.com/questions/736/how-do-i-implement-cr... | import numpy as nprfft = np.fft.rfftirfft = np.fft.irffttrack_1 = np.array ( [ ... , 5.2 , 5.5 , 7.0 , ... ] ) # The onset in track_2 at 8.0 is `` extra , '' it has no # corresponding onset in track_1track_2 = np.array ( [ ... , 7.2 , 7.45 , 8.0 , 9.0 , ... ] ) frequency = 44100num_samples = 10 * frequencywave_1 = np.z... | Does it make sense to use cross-correlation on arrays of timestamps ? |
Python | This question is in continue to a previous question I 've asked.I 've trained an LSTM model to predict a binary class ( 1 or 0 ) for batches of 100 samples with 3 features each , i.e : the shape of the data is ( m , 100 , 3 ) , where m is the number of batches.Data : Target : Model code : For the training stage , the m... | [ [ [ 1,2,3 ] , [ 1,2,3 ] ... 100 sampels ] , [ [ 1,2,3 ] , [ 1,2,3 ] ... 100 sampels ] , ... avaialble batches in the training data ] [ [ 1 ] [ 0 ] ... ] def build_model ( num_samples , num_features , is_training ) : model = Sequential ( ) opt = optimizers.Adam ( lr=0.0005 , beta_1=0.9 , beta_2=0.999 , epsilon=1e-08 ,... | LSTM - Making predictions on partial sequence |
Python | I ca n't understand why the following code behaves a particular way , which is described below : Why does repr ( MyClass2 ) says abc.MyClass2 ( which is by the way not true ) ? Thank you ! | from abc import ABCMeta class PackageClass ( object ) : __metaclass__ = ABCMeta class MyClass1 ( PackageClass ) : passMyClass2 = type ( 'MyClass2 ' , ( PackageClass , ) , { } ) print MyClass1print MyClass2 > > > < class '__main__.MyClass1 ' > > > > < class 'abc.MyClass2 ' > | Python inheritance , metaclasses and type ( ) function |
Python | I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations . I have used Matlab ( and SML-NJ ) for years , and am very comfortable in the functional environment without side effects ( barring I/O ) , but am a little reluctant about the side effects in Python . Can people share their... | lofls = [ [ ] ] * 4 # an accident waiting to happen ! lofls [ 0 ] .append ( 7 ) # not what I was expecting ... print lofls # gives [ [ 7 ] , [ 7 ] , [ 7 ] , [ 7 ] ] # instead , I should have done this ( I think ) lofls = [ [ ] for x in range ( 4 ) ] lofls [ 0 ] .append ( 7 ) # only appends to the first listprint lofls ... | side effect gotchas in python/numpy ? horror stories and narrow escapes wanted |
Python | I 'm working on an application that must support client-server connections . In order to do that , I 'm using the module of tornado that allows me to create WebSockets . I intend to be always in operation , at least the server-side . So I am very worried about the performance and memory usage of each of the objects cre... | # ! /usr/bin/env pythonimport tornado.httpserverimport tornado.websocketimport tornado.ioloopimport tornado.webimport gc , sysimport resourceclass WSHandler ( tornado.websocket.WebSocketHandler ) : def open ( self ) : print 'new connection ' self.write_message ( `` h '' ) def check_origin ( self , origin ) : return Tru... | python - When are WebSocketHandler and TornadoWebSocketClient completely deleted ? |
Python | I have a dummy example of an iterator container below ( the real one reads a file too large to fit in memory ) : This allows me to iterate over the value more than once so that I can implement something like this : How do I check in the normalise function that I am being passed an iterator container rather than a norma... | class DummyIterator : def __init__ ( self , max_value ) : self.max_value = max_value def __iter__ ( self ) : for i in range ( self.max_value ) : yield idef regular_dummy_iterator ( max_value ) : for i in range ( max_value ) : yield i def normalise ( data ) : total = sum ( i for i in data ) for val in data : yield val /... | How do I check if an iterator is actually an iterator container ? |
Python | If I have `` a.py '' and another file `` b.py '' It would appear that Python simply does not allow circular dependencies . Normally I guess you would alter the code such that the two classes actually can resolve themselves without importing one another directly . Perhaps by consolidating their reference to one another ... | from google.appengine.ext import dbclass A ( db.Model ) : db.ReferenceProperty ( b.B ) ... other stuff from google.appengine.ext import dbclass B ( db.Model ) : db.ReferenceProperty ( a.A ) ... other stuff | How should I deal with a circular import in Google App Engine ? |
Python | I 'd like to compare multiple objects and return True only if all objects are not equal among themselves . I tried using the code below , but it does n't work . If obj1 and obj3 are equal and obj2 and obj3 are not equal , the result is True.I have more than 3 objects to compare . Using the code below is out of question... | obj1 ! = obj2 ! = obj3 all ( [ obj1 ! = obj2 , obj1 ! = obj3 , obj2 ! = obj3 ] ) | Python : determining whether any item in sequence is equal to any other |
Python | Finally block runs just before the return statement in the try block , as shown in the below example - returns False instead of True : Similarly , the following code returns value set in the Finally block : However , for variable assignment without return statement in the finally block , why does value of variable upda... | > > > def bool_return ( ) : ... try : ... return True ... finally : ... return False ... > > > bool_return ( ) False > > > def num_return ( ) : ... try : ... x=100 ... return x ... finally : ... x=90 ... return x ... > > > num_return ( ) 90 > > > def num_return ( ) : ... try : ... x=100 ... return x ... finally : ... x... | Finally always runs just before the return in try block , then why update in finally block not affect value of variable returned by try block ? |
Python | I am trying to sort a list of tuples like these : The sorted list should be : So , here 1st the list should be sorted based on tuple [ 1 ] in descending order , then if the tuple values ( tuple [ 1 ] ) match like forApple , Banana & Pineapple - list should be further sorted based on tuple [ 0 ] in ascending order.I hav... | [ ( 'Pineapple ' , 1 ) , ( 'Orange ' , 3 ) , ( 'Banana ' , 1 ) , ( 'Apple ' , 1 ) , ( 'Cherry ' , 2 ) ] [ ( 'Orange ' , 3 ) , ( 'Cherry ' , 2 ) , ( 'Apple ' , 1 ) , ( 'Banana ' , 1 ) , ( 'Pineapple ' , 1 ) ] top_n.sort ( key = operator.itemgetter ( 1 , 0 ) , reverse = True ) # Output : [ ( Orange , 3 ) , ( Cherry , 2 )... | Sort at various levels in Python |
Python | I have a data frame that looks like this : Basically what I want to do is replace the value of the one hot encoded elements with the value from the `` value '' column and then delete the `` value '' column . The resulting data frame should be like this : | df = pd.DataFrame ( { `` value '' : [ 4 , 5 , 3 ] , `` item1 '' : [ 0 , 1 , 0 ] , `` item2 '' : [ 1 , 0 , 0 ] , `` item3 '' : [ 0 , 0 , 1 ] } ) df value item1 item2 item30 4 0 1 01 5 1 0 02 3 0 0 1 df_out = pd.DataFrame ( { `` item1 '' : [ 0 , 5 , 0 ] , `` item2 '' : [ 4 , 0 , 0 ] , `` item3 '' : [ 0 , 0 , 3 ] } ) item... | Replace ones in binary columns with values from another column |
Python | The Python Cookbook suggests the following tree structure for a `` typical library package '' : You 'll notice that the examples/ are not part of the actual package , which resides under projectname/projectname/ ( that 's where you 'll find the top-level __init__.py of the package ) .Well , examples/helloworld.py obvio... | projectname/ README.txt Doc/ documentation.txt projectname/ __init__.py foo.py bar.py utils/ __init__.py spam.py grok.py examples/ helloworld.py import osimport syssys.path.insert ( 0 , os.path.abspath ( '.. ' ) ) | How to include examples or test programs in a package ? |
Python | I 'm trying to parse this datetime string , without success yet , how can I get it ? | d = '2014-05-01 18:10:38-04:00'datetime.datetime.strptime ( d , ' % Y- % m- % d % H : % M : % S- % Z ' ) ValueError : time data '2014-05-01 18:10:38-04:00 ' does not match format ' % Y- % m- % d % H : % M : % S % Z ' | Python 2.7 how parse a date with format 2014-05-01 18:10:38-04:00 |
Python | I have the following toy grammar in Pyparsing : However , running this program will infinitely recurse , which is n't what I wanted . Rather , I wanted my grammar to be able to handle nested phrases so that the above program would resolve to something equivalent to the below : I attempted to modify the definitions for ... | import pyparsing as ppor_tok = `` or '' and_tok = `` and '' lparen = pp.Suppress ( `` ( `` ) rparen = pp.Suppress ( `` ) '' ) Word = pp.Word ( pp.alphas ) ( `` Word '' ) Phrase = pp.Forward ( ) And_Phrase = pp.Group ( pp.delimitedList ( Phrase , and_tok ) ) ( `` And_Phrase '' ) Or_Phrase = pp.Group ( pp.delimitedList (... | Nesting delimited lists in pyparsing without causing infinite recursion ? |
Python | I have a data in a text file that contains `` Test DATA_g004 , Test DATA_g003 , Test DATA_g001 , Test DATA_g002 '' .Is it possible to sort it without the word `` Test DATA_ '' so the data will be sorted like g001 , g002 , g003 etc ? I tried the .split ( `` Test DATA_ '' ) method but it does n't work . | def readFile ( ) : # try block will execute if the text file is found try : fileName = open ( `` test.txt '' , ' r ' ) data = fileName.read ( ) .split ( `` \n '' ) data.sort ( key=alphaNum_Key ) # alternative sort function print ( data ) # catch block will execute if no text file is found except IOError : print ( `` Er... | How to split a mixed string with numbers |
Python | I 've just begun playing around with Python 's Data Classes , and I would like confirm that I am declaring Class Variables in the proper way . Using regular python classesUsing python Data ClassThe class variable I am referring to is raise_amount . Is this a properly declared class variable using Data Classes ? Or is t... | class Employee : raise_amount = .05 def __init__ ( self , fname , lname , pay ) : self.fname = fname self.lname = lname self.pay = pay @ dataclassclass Employee : fname : str lname : str pay : int raise_amount = .05 | Proper way to create class variable in Data Class |
Python | Using tflite and getting properties of interpreter like : What does 'quantization ' : ( 0.003921568859368563 , 0 ) mean ? | print ( interpreter.get_input_details ( ) ) [ { 'name ' : 'input_1_1 ' , 'index ' : 47 , 'shape ' : array ( [ 1 , 128 , 128 , 3 ] , dtype=int32 ) , 'dtype ' : < class 'numpy.uint8 ' > , 'quantization ' : ( 0.003921568859368563 , 0 ) } ] | What does 'quantization ' mean in interpreter.get_input_details ( ) ? |
Python | As a simple example , assume a utility method , which accepts a python object input_obj , and out_type , a python type to convert ( typecast ) the object into-ExamplesThe method only supports objects of specific types like str , list , tuple , and then checks if that can be converted to the out_type specified.This is t... | def convert_obj ( input_obj , out_type ) : convert_obj ( ' 2 ' , 'int ' ) # returns 2convert_obj ( [ 1,2,3 ] , 'tuple ' ) # returns ( 1,2,3 ) supported_conversions = { tuple : [ str , list , set ] , str : [ tuple , float , list , long , int , set ] , float : [ str , long , int ] , list : [ tuple , str , set ] , long : ... | Find which other python types can an object be converted to ? |
Python | I occasionally spend a considerable amount of time tracking down brainfarts in my code ... while I normally run pylint against it , there are some things that slip past pylint . The easiest problem for me to overlook is this ... Neither pylint nor Python bark about this ... is there a python code-checking tool that can... | # normally , variable is populated from parsed text , so it 's not predictablevariable = 'fOoBaR'if variable.lower == 'foobar ' : # ^^^^^ < -- -- -- -- -- -- -- -- -- should be .lower ( ) do_something ( ) | Python code checker for comparing a function as an attribute |
Python | I am attempting to take a list of objects , and turn that list into a dict . The dict values would be each object in the list , and the dict keys would be a value found in each object.Here is some code representing what im doing : Now that code works , but its a bit ugly , and a bit slow . Could anyone give an example ... | class SomeClass ( object ) : def __init__ ( self , name ) : self.name = nameobject_list = [ SomeClass ( name= ' a ' ) , SomeClass ( name= ' b ' ) , SomeClass ( name= ' c ' ) , SomeClass ( name='d ' ) , SomeClass ( name= ' e ' ) , ] object_dict = { } for an_object in object_list : object_dict [ an_object.name ] = an_obj... | Best way to turn a list into a dict , where the keys are a value of each object ? |
Python | I was wondering if it is possible to insert something in .bashrc or .vimrc so that whenever I create a new Python file via vim it automatically creates a file with this already inserted before I edit it : A vast majority of my Python scripts use those lines , and if there is a way to include those for every newly creat... | # ! /usr/bin/env pythonimport sysif __name__ == '__main__ ' : | Bash or vim alias/command to use a certain template when creating Python files ? |
Python | I 'm porting a MATLAB code to Python 3.5.1 and I found a float round-off issue.In MATLAB , the following number is rounded up to the 6th decimal place : In Python , on the other hand , the following number is rounded off to the 6th decimal place : Interestingly enough , if the number is '-67.6000625 ' , then it is roun... | fprintf ( 1 , ' % f ' , -67.6640625 ) ; -67.664063 print ( ' % f ' % -67.6640625 ) -67.664062 print ( ' % f ' % -67.6000625 ) -67.600063 | Round-off / round-up criteria in Python |
Python | I am attempting to using part of a regular expression as input for a later part of the regular expression . What I have so far ( which fails the assertions ) : Breaking this down , the first digit ( s ) signify how many digits should be matched afterward . In the first assertion , I get a 3 , as the first character , w... | import reregex = re.compile ( r '' ( ? P < length > \d+ ) ( \d ) { ( ? P=length ) } '' ) assert bool ( regex.match ( `` 3123 '' ) ) is Trueassert bool ( regex.match ( `` 100123456789 '' ) ) is True subpattern 1 max_repeat 1 4294967295 in category category_digitsubpattern 2 in category category_digitliteral 123groupref ... | Using a regular expression backreference as part of the regular expression in Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.