lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I 'm struggling to split text rows , based on variable delimiter , and preserve empty fields and quoted data.Examples : or as tab-delimited vesionShould both result in : So far , i 've tried : Using split , but clearly the quoted delimiters are not handled as desired.solutions using the csv library , but it tends to ha... | 1 , '' 2 '' , three , 'four , 4 ' , , '' 6\tsix '' 1\t '' 2 '' \tthree\t'four , 4'\t\t '' 6\tsix '' [ ' 1 ' , ' '' 2 '' ' , 'three ' , 'four , 4 ' , `` , `` 6\tsix '' ] s = ' 1 , '' 2 '' , three , \'four , 4\ ' , , '' 6\tsix '' 'wordchars = ( printables + ' \t\r\n ' ) .replace ( ' , ' , `` , 1 ) delimitedList ( OneOrMo... | Python delimited line split problems |
Python | Assume to have a object with unique name . Now you want to switch the name of two objects : Here is the layout : And I would like to do this : This throws an IntegrityError . Is there a way to switch these fields within one commit without this error ? | import sqlalchemy as saimport sqlalchemy.orm as ormfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base ( ) class MyObject ( Base ) : __tablename__ = 'my_objects ' id = sa.Column ( sa.Integer , primary_key=True ) name = sa.Column ( sa.Text , unique=True ) if __name__ == `` __main__ '' : engine... | How can I switch two fields of a unique row within one commit using SQLAlchemy ? |
Python | I am writing a function that is supposed to go through a .fasta file of DNA sequences and create a dictionary of nucleotide ( nt ) and dinucleotide ( dnt ) frequencies for each sequence in the file . I am then storing each dictionary in a list called `` frequency '' . This is the piece of code that is acting strange : ... | for fasta in seq_file : freq = { } dna = str ( fasta.seq ) for base1 in [ ' A ' , 'T ' , ' G ' , ' C ' ] : onefreq = float ( dna.count ( base1 ) ) / len ( dna ) freq [ base1 ] = onefreq for base2 in [ ' A ' , 'T ' , ' G ' , ' C ' ] : dinucleotide = base1 + base2 twofreq = float ( dna.count ( dinucleotide ) ) / ( len ( ... | Frequencies not adding up to one |
Python | Given a class A I can simply add an instancemethod a viaHowever , if I try to add another class B 's instancemethod b , i.e . A.b = B.b , the attempt at calling A ( ) .b ( ) yields a TypeError : unbound method b ( ) must be called with B instance as first argument ( got nothing instead ) ( while B ( ) .b ( ) does fine ... | def a ( self ) : passA.a = a A.a - > < unbound method A.a > A.b - > < unbound method B.b > # should be A.b , not B.b | How to monkeypatch one class 's instance method to another one ? |
Python | What I need is to : Apply a logistic regression classifier Report the per-class ROC using the AUC . Use the estimated probabilities of the logistic regression to guide the construction of the ROC . 5fold cross validation for the training your model.For this , my approach was to use this really nice tutorial : From his ... | df = pd.read_csv ( filepath_or_buffer='https : //archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data ' , header=None , sep= ' , ' ) df.columns= [ 'sepal_len ' , 'sepal_wid ' , 'petal_len ' , 'petal_wid ' , 'class ' ] df.dropna ( how= '' all '' , inplace=True ) # drops the empty line at file-enddf.tail ( ) ... | Using ROC AUC score with Logistic Regression and Iris Dataset |
Python | ProblemML data preparation for stock trading . I have 3-dim MultiIndex on a large DataFrame ( maybe n=800000 x f=20 ) . One index-dimension is date with about dt=1000 levels , the others identify m=800 different stocks ( with 20 features each , individual for each stock ) . So for each date , there are 800 x 20 differe... | import pandas as pddata = { ' x ' : [ 5,6,7,3,4,5,1,1,0,12,15,14 ] , ' y ' : [ 4,6,5,5,4,3,2,0,1,13,14,13 ] } dates = [ pd.to_datetime ( '2018-01-01 ' ) , pd.to_datetime ( '2018-01-02 ' ) , pd.to_datetime ( '2018-01-03 ' ) ] index = pd.MultiIndex.from_arrays ( [ [ 'alpha ' ] * 6 + [ 'beta ' ] * 6 , [ ' A ' ] * 3 + [ ' ... | pandas : Replicate / Broadcast single indexed DataFrame on MultiIndex DataFrame : HowTo and Memory Efficiency |
Python | I 'm having trouble running inference on a model in docker when the host has several cores . The model is exported via PyTorch 1.0 ONNX exporter : Starting the model server ( wrapped in Flask ) with a single core yields acceptable performance ( cpuset pins the process to specific cpus ) docker run -- rm -p 8081:8080 --... | torch.onnx.export ( pytorch_net , dummyseq , ONNX_MODEL_PATH ) Percentage of the requests served within a certain time ( ms ) 50 % 5 66 % 5 75 % 5 80 % 5 90 % 7 95 % 46 98 % 48 99 % 49 Percentage of the requests served within a certain time ( ms ) 50 % 9 66 % 12 75 % 14 80 % 18 90 % 62 95 % 66 98 % 69 99 % 69 100 % 77 ... | Caffe2 : Load ONNX model , and inference single threaded on multi-core host / docker |
Python | Given a function that depends on multiple variables , each with a certain probability distribution , how can I do a Monte Carlo analysis to obtain a probability distribution of the function . I 'd ideally like the solution to be high performing as the number of parameters or number of iterations increase.As an example ... | import numpy as npimport matplotlib.pyplot as pltsize = 1000gym = [ 30 , 30 , 35 , 35 , 35 , 35 , 35 , 35 , 40 , 40 , 40 , 45 , 45 ] left = 5right = 10mode = 9shower = np.random.triangular ( left , mode , right , size ) argument = np.random.choice ( [ 0 , 45 ] , size , p= [ 0.9 , 0.1 ] ) mu = 15sigma = 5 / 3dinner = np... | How can I do a Monte Carlo analysis on an equation ? |
Python | I recently had my website moved to a new server . I have some basic python scripts with access data in a MySQL database . On the old server we had no problems . On the new server : MySQLWorkbench can connect no trouble and perform all queriesThe same ( SELECT ) queries with python work 5 % of the time and the other 95 ... | query = `` SELECT * FROM wordpress.table ; '' conn = MySQLConnection ( **mysqlconfig ) cursor = conn.cursor ( ) cursor.execute ( query ) rows = cursor.fetchall ( ) total_rows = 100000interval = 10data = [ ] for n in range ( 0 , total_rows / interval ) : q = `` SELECT * FROM wordpress.table LIMIT % s OFFSET % s '' % ( i... | Python MySQL queries time out where MySQL workbench works fine |
Python | In Oracle , my data has been hashed by passing an integer into ` STANDARD_HASH ' as follows . How can I get the same hash value using Python ? Result in Oracle when an integer passed to STANDARD_HASH : Result in Python when a string is passed in : Maybe this information will also help . I can not change anything on the... | SELECT STANDARD_HASH ( 123 , 'SHA256 ' ) FROM DUAL ; # A0740C0829EC3314E5318E1F060266479AA31F8BBBC1868DA42B9E608F52A09F import hashlibhashlib.sha256 ( str.encode ( str ( 123 ) ) ) .hexdigest ( ) .upper ( ) # A665A45920422F9D417E4867EFDC4FB8A04A1F3FFF1FA07E998E86F7F7A27AE3 # I want to modify this function to get the has... | Hash an integer in Python to match Oracle 's STANDARD_HASH |
Python | How do I use string substitution in Psycopg2 to handle both NULL and non-NULL values ? For example : I need the first query to look like SELECT * FROM table WHERE col = 1 ; And the second to be the functional equivalent of SELECT * FROM table WHERE col IS NULL ; Is there a trick ? I have many columns that may be NULL o... | sql = 'SELECT * FROM table WHERE col = % s ; 'possible_params = [ 1 , None ] for x in possible_params : print cur.mogrify ( sql , ( x , ) ) | pyscopg2 select NULL values |
Python | My code : The code works as expected . But PEP 8 E211 is raised for the second , third and fourth line claiming whitespace before ' [ ' I do n't get it . How can I format this so that PEP 8 is satisfied ? | if 'certainField ' in myData [ 'meta ' ] [ 'loc ' ] : something = myData [ 'meta ' ] \ < - PEP8 E11 raised for this [ 'loc ' ] \ < - PEP8 E11 raised for this [ 'certainField ' ] \ < - PEP8 E11 raised for this [ 'thefield ' ] | PEP 8 E211 issue raised . Not sure why |
Python | I have a pandas dataframe with the following columns : Product nameNumber of product sold in New York ( let 's say 100 ) Number of product sold in California ( let 's say 50 ) Looks like this : I want to reshape the frame using the two location columns to create a new column like this : How does one achieve this with p... | Product New York CaliforniaWidget01 100 50 Product Location Total SoldWidget01 New York 100Widget01 California 50 | Merge columns and create new column with pandas |
Python | I am using django-import-export to process CSV files uploaded to my Django admin site.When I run Django on my local machine , all works fine.When I deploy my application to Heroku I start getting errors related to tmpfile access : I 've read up on what I can about Heroku ephemeral storage , it seems like this should wo... | Feb 24 14:35:12 test-staging app/web.3 : ERROR 2017-02-24 22:35:12,143 base 14 139687073408832 Internal Server Error : ... .Feb 24 14:35:12 test-staging app/web.3 : File `` /app/.heroku/python/lib/python2.7/site-packages/import_export/admin.py '' , line 163 , in process_import Feb 24 14:35:12 test-staging app/web.3 : d... | Tmpfile error with django-import-export on Heroku |
Python | I have a string like the following : I tried using CSV module and it did n't fit , cause i have n't found a way to ignore what 's quoted . Pyparsing looked like a better answer but i have n't found a way to declare all the grammars.Currently , i am using my old Perl script to parse it , but i want this written in Pytho... | < 118 > date=2010-05-09 , time=16:41:27 , device_id=FE-2KA3F09000049 , log_id=0400147717 , log_part=00 , type=statistics , subtype=n/a , pri=information , session_id=o49CedRc021772 , from= '' prvs=4745cd07e1=example @ example.org '' , mailer= '' mta '' , client_name= '' example.org , [ 194.177.17.24 ] '' , resolved=OK ... | Pyparsing CSV string with random quotes |
Python | I use the python-nautilus module , and I try to add a custom emblem ( an icon overlay ) , like that : But I did n't found anything about that.I 'm able to add an existing emblem like `` multimedia '' with this code : But I would like to add my own icon.Do you have an idea ? How can I do that ? Thank you in advance ! | import os.pathfrom gi.repository import Nautilus , GObjectclass OnituIconOverlayExtension ( GObject.GObject , Nautilus.InfoProvider ) : def __init__ ( self ) : pass def update_file_info ( self , file ) : if os.path.splitext ( file.get_name ( ) ) [ 1 ] == `` fileWithEmblem '' : file.add_emblem ( `` multimedia '' ) file.... | Python-nautilus : add custom emblems ( overlay icon ) |
Python | So I frequently write code following a pattern like this : etcI saw now on a different question a comment that explained how this approach creates a new list each time and it is better to mutate the existing list , like so : It 's the first time I 've seen this explicit recommendation and I 'm wondering what the implic... | _list = list ( range ( 10 ) ) # Or whatever_list = [ some_function ( x ) for x in _list ] _list = [ some_other_function ( x ) for x in _list ] _list [ : ] = [ some_function ( x ) for x in _list ] def some_function ( number : int ) : return number*10def main ( ) : _list1 = list ( range ( 10 ) ) _list2 = list ( range ( 1... | Python difference between mutating and re-assigning a list ( _list = and _list [ : ] = ) |
Python | It seems that the np.where function evaluates all the possible outcomes first , then it evaluates the condition later . This means that , in my case , it will evaluate square root of -5 , -4 , -3 , -2 , -1 even though it will not be used later on.My code runs and works . But my problem is the warning . I avoided using ... | import numpy as npc=np.arange ( 10 ) -5d=np.where ( c > =0 , np.sqrt ( c ) , c ) RuntimeWarning : invalid value encountered in sqrtd=np.where ( c > =0 , np.sqrt ( c ) , c ) | Numpy `` Where '' function can not avoid evaluate Sqrt ( negative ) |
Python | Out of the following two variants ( with or without plus-sign between ) of string literal concatenation : What 's the preferred way ? What 's the difference ? When should one or the other be used ? Should non of them ever be used , if so why ? Is join preferred ? Code : | > > > # variant 1 . Plus > > > ' A'+ ' B '' AB ' > > > # variant 2 . Just a blank space > > > ' A ' ' B '' AB ' > > > # They seems to be both equal > > > ' A'+ ' B ' == ' A ' ' B'True | Variants of string concatenation ? |
Python | The Story : I 'm currently in the process of unit-testing a function using hypothesis and a custom generation strategy trying to find a specific input to `` break '' my current solution . Here is how my test looks like : Basically , I 'm looking for possible inputs when answer ( ) function does not return 0 or 1 or 2.H... | from solution import answer # skipping mystrategy definition - not relevant @ given ( mystrategy ) def test ( l ) : assert answer ( l ) in { 0 , 1 , 2 } $ pytest test.py =========================================== test session starts ============================================ ... -- -- -- -- -- -- -- -- -- -- -- -- -... | Skipping falsifying examples in Hypothesis |
Python | I 'm compiling several different versions of Python for my system , and I 'd like to know where in the source the startup banner is defined so I can change it for each version . For example , when the interpreter starts it displaysI 'd like to change the string default to other things to signal which version I 'm using... | Python 3.3.1 ( default , Apr 28 2013 , 10:19:42 ) [ GCC 4.7.2 20121109 ( Red Hat 4.7.2-8 ) ] on linuxType `` help '' , `` copyright '' , `` credits '' or `` license '' for more information . > > > | Where is the Python startup banner defined ? |
Python | I use AbstractBaseUser together with CustomPermissionsMixin . CustomPermissionsMixin is kind of the same with django PermissionsMixin the difference is I changed related_name and related_query_name for user_permissions and groups so it wo n't clashing with django PermissionsMixin related_nameI have the same Student cla... | @ python_2_unicode_compatibleclass CustomPermissionsMixin ( models.Model ) : `` '' '' A mixin class that adds the fields and methods necessary to support Django 's Group and Permission model using the ModelBackend. `` '' '' is_superuser = models.BooleanField ( _ ( 'superuser status ' ) , default=False , help_text=_ ( '... | manytomany relation does not exist . It 's in a different schema |
Python | For someone who is new to python , I do n't understand how to remove an instance of a class from inside a recursive function.Consider this code of a k-d Tree : The important part is this : How can i delete the current instance ? The del self or self=None or my approach is NOT working | def remove ( self , bin , targetAxis=0 , parent=None ) : if not self : return None elif self.data.x == bin.x and self.data.y == bin.y : if self.rightNode : self.data = self.rightNode.findMin ( ( targetAxis+1 ) % KdSearch.DIMENSION ) self.rightNode = self.rightNode.remove ( self.data , ( targetAxis+1 ) % KdSearch.DIMENS... | Remove root from k-d-Tree in Python |
Python | The scipy.fftpack.rfft function returns the DFT as a vector of floats , alternating between the real and complex part . This means to multiply to DFTs together ( for convolution ) I will have to do the complex multiplication `` manually '' which seems quite tricky . This must be something people do often - I presume/ho... | import numpy as npimport scipy.fftpack as sfftX = np.random.normal ( size = 2000 ) Y = np.random.normal ( size = 2000 ) NZ = np.fft.irfft ( np.fft.rfft ( Y ) * np.fft.rfft ( X ) ) SZ = sfft.irfft ( sfft.rfft ( Y ) * sfft.rfft ( X ) ) # This multiplication is wrongNZarray ( [ -43.23961083 , 53.62608086 , 17.92013729 , .... | How should I multiply scipy.fftpack output vectors together ? |
Python | I feel like I 'm missing something obvious here ! outputs : Whereas surely it should output : What 's going wrong here ? | seq = { ' a ' : [ ' 1 ' ] , 'aa ' : [ ' 2 ' ] , 'aaa ' : [ ' 3 ' ] , 'aaaa ' : [ ' 4 ' ] , 'aaaaa ' : [ ' 5 ' ] } for s in seq : print ( s ) aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa | Looping seems to not follow sequence |
Python | Is there a way in Python 3.2 or later to define a class whose subclasses should be created using a specific metaclass without the class itself being created using that metaclass ? An example to demonstrate what I mean : Let 's say I want to create an Enum class whose subclasses can be used to define enum types . An enu... | class EnumMeta ( type ) : def __new__ ( mcs , what , bases , dict ) : cls = super ( ) .__new__ ( mcs , what , bases , { } ) cls._instances_by_value = { } for k , v in dict.items ( ) : if k.startswith ( '__ ' ) or k == 'get_by_value ' : setattr ( cls , k , v ) else : instance = cls ( k , v ) setattr ( cls , k , instance... | Use a metaclass only for subclasses |
Python | Can I add a member variable / method to a Python generator ? I want something along the following lines , so that I can `` peek '' at member variable j : Yes , I know that I can return i AND j every time . But I do n't want to do that . I want to peek at a local within the generator . | def foo ( ) : for i in range ( 10 ) : self.j = 10 - i yield igen = foo ( ) for k in gen : print gen.j print k | Add a member variable / method to a Python generator ? |
Python | I was debugging some code with generators and came to this question . Assume I have a generator functionand a function returning a generator : They surely return the same thing . Can there be any differences when using them interchangeably in Python code ? Is there any way to distinguish the two ( without inspect ) ? | def f ( x ) : yield x def g ( x ) : return f ( x ) | Difference between generators and functions returning generators |
Python | I have a list of lists of tuples , where every tuple is of equal length , and I need to convert the tuples to a Pandas dataframe in such a way that the columns of the dataframe are equal to the length of the tuples , and each tuple item is a row entry across the columns.I have consulted other questions on this topic ( ... | import pandas as pdtupList = [ [ ( 'commentID ' , 'commentText ' , 'date ' ) , ( '123456 ' , 'blahblahblah ' , '2019 ' ) ] , [ ( '45678 ' , 'hello world ' , '2018 ' ) , ( ' 0 ' , 'text ' , '2017 ' ) ] ] # Trying list comprehension from previous stack question : pd.DataFrame ( [ [ y for y in x ] for x in tupList ] ) 0 1... | List of LISTS of tuples to Pandas dataframe ? |
Python | In Python 3 , I need to test whether my variable has the type 'dict_items ' , so I tried something like that : But dict_items is not a known type . it is not defined in types module neither . How can I test an object has the type dict_items ( without consuming data ) ? | > > > d= { ' a':1 , ' b':2 } > > > d.items ( ) dict_items ( [ ( ' a ' , 1 ) , ( ' b ' , 2 ) ] ) > > > isinstance ( d.items ( ) , dict_items ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > NameError : name 'dict_items ' is not defined | How to check an object has the type 'dict_items ' ? |
Python | I 'm trying to add to the `` recently used '' files list from Python 3 on Ubuntu.I am able to successfully read the recently used file list like this : This prints out the same list of files I see when I look at `` Recent '' in Nautilus , or look at the `` Recently Used '' place in the file dialog of apps like GIMP.How... | from gi.repository import Gtkrecent_mgr = Gtk.RecentManager.get_default ( ) for item in recent_mgr.get_items ( ) : print ( item.get_uri ( ) ) recent_mgr.add_item ( 'file : ///home/laurence/foo/bar.txt ' ) | How does one add an item to GTK 's `` recently used '' file list from Python ? |
Python | I have written code to find out common files between two given folders ( paths ) accounting for all levels of sub folders if present.Please suggest if there is a more efficient method . It 's taking too long if folders with many levels of subfolders are given.and calling this function with paths , like shown below : I ... | def findCommonDeep ( self , path1 , path2 ) : commonfiles = [ ] for ( dirpath1 , dirname1 , filenames1 ) in os.walk ( path1 ) : for file in filenames1 : for ( dirpath2 , dirname2 , filenames2 ) in os.walk ( path2 ) : if ( file in filenames2 and isfile ( join ( dirpath2 , file ) ) ) : commonfiles.append ( file ) print (... | Efficient Method of finding common files between two given paths in Python |
Python | The source for the flask.json module contains the following line . What does '\\/ ' mean , and why is Flask checking this ? | _slash_escape = '\\/ ' not in _json.dumps ( '/ ' ) | Why is Flask checking ` '\\/ ' in json.dumps ( '/ ' ) ` in its json module ? |
Python | Given that the new Python 3.5 allows type hinting with type signatures I want to use the new feature , but I do n't know how to fully annotate a function with the following structure : What 's the correct signature ? | def yieldMoreIfA ( text : str ) : if text == `` A '' : yield text yield text return else : yield text return | What type signature do generators have in Python ? |
Python | When I was browsing Python HMAC module source code today I found out that it contains global variable _secret_backdoor_key . This variable is then checked to interrupt object initialization . The code looks like thisFull code is here . Does anyone know what is the reason for this variable ? Comment says it is there for... | # A unique object passed by HMAC.copy ( ) to the HMAC constructor , in order # that the latter return very quickly . HMAC ( `` '' ) in contrast is quite # expensive._secret_backdoor_key = [ ] class HMAC : `` '' '' RFC 2104 HMAC class . Also complies with RFC 4231 . This supports the API for Cryptographic Hash Functions... | What is the reason for _secret_backdoor_key variable in Python HMAC library source code ? |
Python | Consider the following code ( from here , with the number of tests increased ) : Using Python 2.6 ( Python 2.6.5 ( r265:79063 , Apr 16 2010 , 13:57:41 ) [ GCC 4.4.3 ] on linux2 ) , the times reported are : However , on the same machine using Python 3.1 ( Python 3.1.2 ( r312:79147 , Apr 15 2010 , 15:35:48 ) [ GCC 4.4.3 ... | from timeit import Timerdef find_invpow ( x , n ) : `` '' '' Finds the integer component of the n'th root of x , an integer such that y ** n < = x < ( y + 1 ) ** n. `` '' '' high = 1 while high ** n < x : high *= 2 low = high/2 while low < high : mid = ( low + high ) // 2 if low < mid and mid**n < x : low = mid elif hi... | Why is Python 3.1 slower than 2.6 for this code ? |
Python | I am currently working on a project written in C++ that leverages the CryptoAPI to perform a Diffie-Hellman key exchange . I 'm having a bit of trouble getting this to work as the eventual RC4 session key I get can not be used to encrypt the same text in Python ( using pycrypto ) .The C++ code to perform the Diffie-Hel... | # include < tchar.h > # include < windows.h > # include < wincrypt.h > # pragma comment ( lib , `` crypt32.lib '' ) // The key size , in bits. # define DHKEYSIZE 512// Prime in little-endian format.static const BYTE g_rgbPrime [ ] = { 0x91 , 0x02 , 0xc8 , 0x31 , 0xee , 0x36 , 0x07 , 0xec , 0xc2 , 0x24 , 0x37 , 0xf8 , 0... | Diffie-Hellman ( to RC4 ) with Wincrypt From Python |
Python | I want to display an animation in Jupyter using Matplotlib . Here is some basic example : When I run the code for the first time ( or after restarting the kernel ) I get what I want : However , when I run the very same code for the second time I get a leftover in the left bottom : I noticed that when I add % matplotlib... | import numpy as npimport matplotlib.pyplot as pltimport matplotlib.animation as animationfig , ax = plt.subplots ( ) line , = ax.plot ( np.random.rand ( 10 ) ) ax.set_ylim ( 0 , 1 ) def update ( data ) : line.set_ydata ( data ) return line , def data_gen ( ) : while True : yield np.random.rand ( 10 ) ani = animation.Fu... | How to remove a residual plot in Jupyter output after displaying a matplotlib animation ? |
Python | I 'm trying to calculate SHA1 hash values in Python against binary files for later comparison . To make sure things are working , I used several methods to check the validity of my result . And , I 'm glad I did . Powershell and Python return different values . 7zip 's SHA1 function agrees with Powershell 's results an... | import hashlibwith open ( `` C : \\Windows\\system32\\wbem\\wmiutils.dll '' , `` rb '' ) as f : print ( hashlib.sha1 ( f.read ( ) ) .hexdigest ( ) ) PS C : \ > Get-FileHash C : \Windows\System32\wbem\wmiutils.dll -Algorithm SHA1 Python : d25f5b57d3265843ed3a0e7b6681462e048b29a9Powershell : B8C757BA70F6B145AD191A1B09C22... | Why do I get a different SHA1 hash between Powershell and 32bit-Python on a system DLL ? |
Python | I 'd like to write a decorator that would limit the number of times a function can be executed , something along the following syntax : I think it 's possible to write this type of decorator , but I do n't know how . I think a function wo n't be this decorator 's first argument , right ? I 'd like a `` plain decorator ... | @ max_execs ( 5 ) def my_method ( *a , **k ) : # do something here pass | How are these type of python decorators written ? |
Python | I am writing an external script to run a mapreduce job via the Python mrjob module on my laptop ( not on Amazon Elastic Compute Cloud or any large cluster ) .I read from the mrjob documentation that I should use MRJob.make_runner ( ) to run a mapreduce job from a separate python script as follows.However , how do I spe... | mr_job = MRYourJob ( args= [ '-r ' , 'emr ' ] ) with mr_job.make_runner ( ) as runner : ... | How does one specify the input file for a runner from Python ? |
Python | Does anyone have an idea on how to write a function loading_values ( csvfilename ) that takes a string corresponding to the name of the data file and returns a list of tuples containing the subset name ( as a string ) and a list of floating point data values.the result should be something like this when the function is... | > > > stat = loading_values ( ` statistics.csv ` ) > > > stat [ ( 'Pressure ' , [ 31.52 , 20.3 , ... , 27.90 , 59.58 ] ) , ( 'Temp ' , [ 97.81 , 57.99 , ... , 57.80 , 64.64 ] ) , ( 'Range ' , [ 79.10 , 42.83 , ... , 68.84 , 26.88 ] ) ] f=open ( 'statistics.csv ' , ' r ' ) for c in f : numbers = c.split ( ' , ' ) number... | Loading data from a csv file and display in list of tuples |
Python | I want to do reproducible tests that use random numbers as inputs . I am used to invoke rng in Matlab and numpy.random.seed in Python . However , I noticed that the Notes section of seed 's help reads : This is a convenience , legacy function . The best practice is to not reseed a BitGenerator , rather to recreate a ne... | from numpy.random import MT19937from numpy.random import RandomState , SeedSequencers = RandomState ( MT19937 ( SeedSequence ( 123456789 ) ) ) # Later , you want to restart the streamrs = RandomState ( MT19937 ( SeedSequence ( 987654321 ) ) ) | Why using numpy.random.seed is not a good practice ? |
Python | I 'm attempting to calculate e^x using recursion , e^x = e^ ( x/2 ) *e^ ( x/2 ) , and the third order Maclaurin expansion for e^x and the script keeps returning 1 . I 'm not looking for a higher accuracy solution , just simply to understand where the script goes wrong : ) My thought is that with enough iterations it sh... | def exp ( x ) : if abs ( x ) < 0.0001 : return 1+x+x**2/2 else : y=exp ( x/2 ) return y*y | Calculating exp ( x ) with the use of recursion in Python |
Python | I am trying to understand iterator . I notice Python documentation considers iterator to be a functional-style construct . I do n't really understand it.Is n't it true that iterator has a state inside it . So when you call it.__next__ ( ) , you mutate the state of the iterator . As far as I know , mutating state of an ... | ( define tokens- > iterator ( lambda ls ( lambda ( ) ( if ( null ? ls ) '*eoi* ( let ( ( tok ( car ls ) ) ) ( set ! ls ( cdr ls ) ) tok ) ) ) ) ) ( define it ( tokens- > iterator 1 '+ 2 ) ) scheme @ ( guile-user ) > ( it ) $ 2 = 1scheme @ ( guile-user ) > ( it ) $ 3 = +scheme @ ( guile-user ) > ( it ) $ 4 = 2scheme @ (... | Why iterator is considered functional-style in the Python documentation ? |
Python | I realized there is a memory leak in one python script . Which occupied around 25MB first , and after 15 days it is more than 500 MB . I followed many different ways , and not able to get into the root of the problem as am a python newbie ... Finally , I got this following I set a break point , and after every iteratio... | objgraph.show_most_common_types ( limit=20 ) tuple 37674function 9156dict 3935list 1646wrapper_descriptor 1468weakref 888builtin_function_or_method 874classobj 684method_descriptor 551type 533instance 483Kind 470getset_descriptor 404ImmNodeSet 362module 342IdentitySetMulti 333PartRow 331member_descriptor 264cell 185Fon... | print all available tuples in python from a debugger |
Python | When map has different-length inputs , a fill value of None is used for the missing inputs : This is the same behavior as : What 's the reason map provides this behavior , and not the following ? …and is there an easy way to get the latter behavior either with some flavor of zip or map ? | > > > x = [ [ 1,2,3,4 ] , [ 5,6 ] ] > > > map ( lambda *x : x , *x ) [ ( 1 , 5 ) , ( 2 , 6 ) , ( 3 , None ) , ( 4 , None ) ] > > > import itertools > > > list ( itertools.izip_longest ( *x ) ) [ ( 1 , 5 ) , ( 2 , 6 ) , ( 3 , None ) , ( 4 , None ) ] > > > map ( lambda *x : x , *x ) [ ( 1 , 5 ) , ( 2 , 6 ) , ( 3 , ) , ( ... | Why does map work like izip_longest with fill=None ? |
Python | Last semester in college , my teacher in the Computer Languages class taught us the esoteric language named Whitespace . In the interest of learning the language better with a very busy schedule ( midterms ) , I wrote an interpreter and assembler in Python . An assembly language was designed to facilitate writing progr... | hold N Push the number onto the stackcopy Duplicate the top item on the stackcopy N Copy the nth item on the stack ( given by the argument ) onto the top of the stackswap Swap the top two items on the stackdrop Discard the top item on the stackdrop N Slide n items off the stack , keeping the top item add Additionsub Su... | Do you have suggestions for these assembly mnemonics ? |
Python | Possible Duplicate : accessing a python int literals methods In Python , everything is an object.But then again , why does n't the following snippet work ? However , this does work : What is the difference between n and 1 ? Is n't it a design failure that it does n't work ? For instance , it does work with string liter... | 1.__add__ ( 2 ) n = 1n.__add__ ( 2 ) `` one '' .__add__ ( `` two '' ) Console.WriteLine ( 100.ToString ( ) ) ; | Why does 1.__add__ ( 2 ) not work out ? |
Python | In a Python regular expression , I encounter this singular problem.Could you give instruction on the differences between re.findall ( ' ( ab|cd ) ' , string ) and re.findall ( ' ( ab|cd ) + ' , string ) ? Actual Output is : I 'm confused as to why does the second result does n't contain 'ab ' as well ? | import restring = 'abcdla'result = re.findall ( ' ( ab|cd ) ' , string ) result2 = re.findall ( ' ( ab|cd ) + ' , string ) print ( result ) print ( result2 ) [ 'ab ' , 'cd ' ] [ 'cd ' ] | re.findall ( ' ( ab|cd ) ' , string ) vs re.findall ( ' ( ab|cd ) + ' , string ) |
Python | Hi good people of StackOverflow . I 'm using pyzmq and I 've got some long-running processes , which led to a discovery that socket handles are being left open . I 've narrowed the offending code down to the following : pyzmq version is pyzmq-13.1.0Either there is a bug in pyzmq , or I 'm doing something incorrectly . ... | import zmquri = 'tcp : //127.0.0.1'sock_type = zmq.REQlinger = 250 # Observe output of lsof -p < pid > here and see no socket handlesctx = zmq.Context.instance ( ) sock = ctx.socket ( sock_type ) sock.setsockopt ( zmq.LINGER , linger ) port = sock.bind_to_random_port ( uri ) # Observe output of lsof -p < pid > here and... | socket handle leak in pyzmq ? |
Python | If I create a thread that all it does is connect to some process and get its top window , then the program hangs . I debugged it a little and it seems to get stuck in comtypes._compointer_base.from_params . This is the whole traceback : after typing step in pdb , it shows this and then freezes : It seems that the probl... | ... - > self.top_win = self.app.top_window ( ) c : \python27\lib\site-packages\pywinauto\application.py ( 1095 ) top_window ( ) - > backend=self.backend.name ) c : \python27\lib\site-packages\pywinauto\findwindows.py ( 197 ) find_elements ( ) - > cache_enable=True ) c : \python27\lib\site-packages\pywinauto\uia_element... | Using pywinauto.top_window ( ) hangs when using it with threads |
Python | I want to do some rolling window calculation in pandas which need to deal with two columns at the same time . I 'll take an simple instance to express the problem clearly : Is there any way without for loop in pandas to solve the problem ? Any help is appreciated | import pandas as pddf = pd.DataFrame ( { ' x ' : [ 1 , 2 , 3 , 2 , 1 , 5 , 4 , 6 , 7 , 9 ] , ' y ' : [ 4 , 3 , 4 , 6 , 5 , 9 , 1 , 3 , 1 , 2 ] } ) windowSize = 4result = [ ] for i in range ( 1 , len ( df ) +1 ) : if i < windowSize : result.append ( None ) else : x = df.x.iloc [ i-windowSize : i ] y = df.y.iloc [ i-wind... | How to access multi columns in the rolling operator ? |
Python | I can use \=expr in : s command . For example , to convert timestamps format inplace : But the functionality of built-in functions are so limited . To parse a timestamp , I 'd like to use python script like this : How to embed this py-expr into : s command ? Thanks ! | : % s/\v < \d { 10 } > /\=strftime ( ' % c ' , submatch ( 0 ) ) /g $ python > > > import datetime > > > d = 'Apr 11 2012 ' > > > datetime.datetime.strptime ( d , ' % b % d % Y ' ) .isoformat ( ) '2012-04-11T00:00:00 ' : % s/\v\w+ \d { 2 } \d { 4 } /\= { ? py-expr ? } /g | How to embed python expression into : s command in vim ? |
Python | I am trying to parse and evaluate expressions , given to me as input from a file , of the form : ( actually I also allow `` multibit access '' ( i.e . var [ X : Y ] ) but let 's ignore it for now ... ) Where var is an integer , and the [ ] indicates bit access.For example , for var = 0x9 , the first expression above sh... | var [ 3 ] = 0 and var [ 2 ] = 1var [ 0 ] = 1 and var [ 2 ] = 0 and var [ 3 ] = 1 ... # ! /usr/bin/env pythonfrom pyparsing import Word , alphas , nums , infixNotation , opAssocclass BoolAnd ( ) : def __init__ ( self , pattern ) : self.args = pattern [ 0 ] [ 0 : :2 ] def __bool__ ( self ) : return all ( bool ( a ) for a... | Python 's pyparsing : Implementing grammar to parse logical AND expression |
Python | Consider a histogram calculation of a numpy array that returns percentages : The above returns two arrays : perc containing the % ( i.e . percentages ) of values within each pair of consecutive edges [ ix ] and edges [ ix+1 ] out of the total.edges of length len ( hist ) +1Now , say that I want to filter perc and edges... | # 500 random numbers between 0 and 10,000values = np.random.uniform ( 0,10000,500 ) # Histogram using e.g . 200 bucketsperc , edges = np.histogram ( values , bins=200 , weights=np.zeros_like ( values ) + 100/values.size ) | Filtering histogram edges and counts |
Python | I would like to remove the first 3 characters from strings in a Dataframe column where the length of the string is > 4If else they should remain the same.E.gI can filter the strings by length : and slice the strings : But not sure how to put this together and apply it to my dataframeAny help would be appreciated . | bloomberg_ticker_yAIM9DJEM9 # ( should be M9 ) FAM9IXPM9 # ( should be M9 ) merged [ 'bloomberg_ticker_y ' ] .str.len ( ) > 4 merged [ 'bloomberg_ticker_y ' ] .str [ -2 : ] | Slicing Dataframe column based on length of strings |
Python | The following never prints anything in Python 3.6Instead , it just sits there and burns CPU . The issue seems to be that product never returns an iterator if it 's over an infinite space because it evaluates the full product first . This is surprising given that the product is supposed to be a generator.I would have ex... | from itertools import product , countfor f in product ( count ( ) , [ 1,2 ] ) : print ( f ) for tup in ( ( x , y ) for x in count ( ) for y in [ 1,2 ] ) : print ( tup ) for f in takewhile ( lambda x : True , count ( ) ) : print ( f ) | Does itertools.product evaluate its arguments lazily ? |
Python | Could you provide an example of using the high-level API Estimators with placeholders and feeding batches like for a basic use : How to do the same with Estimator API ? Estimator takes batch_size , steps , input_fuc or feed_fun as an argument of the fit function ( see doc https : //www.tensorflow.org/versions/master/ap... | for step in xrange ( max_steps ) : batch_of_inputs , batch_of_targets= get_batch_from_disk ( step ) # e.g.batches are stored as list where step is and index of the list feed_dict = { x : batch_of_inputs , y : batch_of_targets } _ , loss_value = sess.run ( [ train_op , loss ] , feed_dict=feed_dict ) | Tensorflow , feeding Estimator.fit ( batch ) |
Python | I would like to random shuffle a list so that each variable in the list when shuffled gets put in a new place in the list.What I am currently doing : With this method I shuffle the list but it is still possible to have a variable end up in the same place in this case ' b'.My desired outputcompletely shuffled listI appr... | list = [ ' a ' , ' b ' , ' c ' , 'd ' ] ; random.shuffle ( list ) list [ ' c ' , ' b ' , 'd ' , ' a ' ] [ ' c ' , ' a ' , 'd ' , ' b ' ] | Python : How to random shuffle a list where each variable will end up in a new place |
Python | I use tornado.testing to implement my tornado handlers ' unit test . The tests seems to be working . But I got below error for every test function.Does it matters ? How can I stop it ? | [ W 141027 19:13:25 autoreload:117 ] tornado.autoreload started more than once in the same process | Why I got tornado.autoreload started more than once in testing ? |
Python | I 'm having a difficult time to debug a problem in which the float nan in a list and nan in a numpy.array are handled differently when these are used in itertools.groupby : Given the following list and array : When I iterate over the list the contiguous nans are grouped : However if I use the array it puts successive n... | from itertools import groupbyimport numpy as nplst = [ np.nan , np.nan , np.nan , 0.16 , 1 , 0.16 , 0.9999 , 0.0001 , 0.16 , 0.101 , np.nan , 0.16 ] arr = np.array ( lst ) > > > for key , group in groupby ( lst ) : ... if np.isnan ( key ) : ... print ( key , list ( group ) , type ( key ) ) nan [ nan , nan , nan ] < cla... | Why can itertools.groupby group the NaNs in lists but not in numpy arrays |
Python | I wrote a program to read in Windows DNS debugging log , but inside always got some funny characters in the domain field . Below is one of the example : I want to replace all the \x.. with a ? I explicitly type \xc2 as follows works But its not working if I write as follow : re.sub ( '\\\x.. ' , ' ? ' , line ) How I ca... | ( 13 ) \xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d ( 5 ) example ( 3 ) com ( 0 ) ' line = ' ( 13 ) \xc2\xb5\xc2\xb1\xc2\xbe\xc3\xa2p\xc3\xb4\xc2\x8d ( 5 ) example ( 3 ) com ( 0 ) 're.sub ( '\\\xc2 ' , ' ? ' , line ) result : ' ( 13 ) ? \xb5 ? \xb1 ? \xbe\xc3\xa2p\xc3\xb4 ? \x8d ( 5 ) example ( 3 ) com ( 0 ) ' | python replace unicode characters |
Python | Question from Daily Coding Problem 210 as reproduced below : A Collatz sequence in mathematics can be defined as follows . Starting with any positive integer : It is conjectured that every such sequence eventually reaches the number 1 . Test this conjecture.Bonus : What input n < = 1000000 gives the longest sequence ? ... | if n is even , the next number in the sequence is n / 2if n is odd , the next number in the sequence is 3n + 1 def collatz ( n ) : sequenceLength = 0 while ( n > =1 ) : if ( n==1 ) : break # solution is found elif ( n % 2==0 ) : n = n/2 sequenceLength += 1 else : n = 3*n+1 sequenceLength += 1 return ( sequenceLength ) ... | How to write cache function or equivalent in Python ? |
Python | I 'm using Python 3 and I wanted to code a program that asks for multiple user inputs for a certain amount of time . Here is my attempt at that : The problem is , the code still waits for an input even if the time is up . I would like the loop to stop exactly when the time runs out . How do I do this ? Thank you ! | from threading import Timer # # def timeup ( ) : global your_time your_time = False return your_time # # timeout = 5your_Time = Truet = Timer ( timeout , timeup ) t.start ( ) # # while your_time == True : input ( ) t.cancel ( ) print ( 'Stop typing ! ' ) | Taking in multiple inputs for a fixed time |
Python | In another question I learnt how to expose a function returning a C++ object to Python by copying the object . Having to perform a copy does not seem optimal . How can I return the object without copying it ? i.e . how can I directly access the peaks returned by self.thisptr.getPeaks ( data ) in PyPeakDetection.getPeak... | # ifndef PEAKDETECTION_H # define PEAKDETECTION_H # include < string > # include < map > # include < vector > # include `` peak.hpp '' class PeakDetection { public : PeakDetection ( std : :map < std : :string , std : :string > config ) ; std : :vector < Peak > getPeaks ( std : :vector < float > & data ) ; private : flo... | How to expose a function returning a C++ object to Python without copying the object ? |
Python | I 've read a few other SO ( PythonScope and globals do n't need global ) but nothing seems to explain as explicitly as I would like and I 'm having trouble mentally sifting through whether or not PyDocs tells me the answer to my question : Now , understandably , andbut thenI thought , however , that things like += impl... | myList = [ 1 ] def foo ( ) : myList = myList + [ 2 , 3 ] def bar ( ) : myList.extend ( [ 2 , 3 ] ) def baz ( ) : myList += [ 2 , 3 ] > > > foo ( ) UnboundLocalError : local variable 'myList ' referenced before assignment bar ( ) # worksmyList # shows [ 1 , 2 , 3 ] > > > baz ( ) UnboundLocalError : local variable 'myLis... | Python += versus .extend ( ) inside a function on a global variable |
Python | I was trying to display the status of processing to the user on the front end when I was using StreamingHttpResponse.I was able to get the current status but it is being appended to the previous one.I want the response template to contain only the current yield . views.py output in the browser expected output1st : < p ... | from django.shortcuts import renderfrom django.http import StreamingHttpResponse , HttpResponseimport timedef f1 ( ) : x = 0 while x < 5 : time.sleep ( 1 ) x = x+1 code = `` '' '' < p > { } < /p > '' '' '' .format ( x ) yield codedef home ( request ) : return StreamingHttpResponse ( f1 ( ) ) < p > 1 < /p > < p > 2 < /p... | Render current status only on template in StreamingHttpResponse in Django |
Python | When you want to change the root screenmanager in kvlang you can do the following from within any screen : Or you can do the following if this button is located on the screen that is managed by the screen manager : However when you have a nested screen manager like this : I do n't know how to change the nested screen m... | Button : text : 'press me to change the screen of the root manager ' on_press : app.root.current = 'name_of_target_screen ' Button : text : 'press me to change the current screen ' on_press : root.manager.current = 'name_of_target_screen ' [ Root screen manager ] [ screen 1 ] [ screen 2 ] [ BoxLayout ] [ sidescreen ] [... | Kivy : How to access a nested screenmanager from within any screen in kvlang |
Python | I have a python application that I am trying to deploy with zappa . The root level of my directory has the application and a directory named helper . The structure looks like this : Within the helper directory there is an api.py file that is referenced in my app.py like soWhen I run the command to package and deploy us... | |-app.py|-zappa_settings.json|-helper |-api.py |-__init.py__ from helper import api | Zappa not packaging nested source directories |
Python | What would be the fastest way to search for a number ( eg . 12.31 ) in long sorted list and get the values one before and after my `` search '' value when the exact value is n't found ( eg . 11.12 and 12.03 in the list below ) ? Many thanks in advance . | long_list = [ 10.11 , 11.12 , 13.03 , 14.2 .. 12345.67 ] | search for before and after values in a long sorted list |
Python | I 've tried to apply the solution provided in this question to my real data : Selecting rows in a MultiIndexed dataframe . Somehow I can not get the results it should give . I 've attached both the dataframe to select from , as well as the result.What I need ; Rows 3 , 11 AND 12 should be returned ( when you add the 4 ... | df_test = pd.read_csv ( 'df_test.csv ' ) def find_window ( df ) : v = df.values s = np.vstack ( [ np.zeros ( ( 1 , v.shape [ 1 ] ) ) , v.cumsum ( 0 ) ] ) threshold = 0 r , c = np.triu_indices ( s.shape [ 0 ] , 1 ) d = ( c - r ) [ : , None ] e = s [ c ] - s [ r ] mask = ( e / d < threshold ) .all ( 1 ) rng = np.arange (... | Incorrect results when applying solution to real data |
Python | In the nautilus-python bindings , there is a file `` nautilus.defs '' . It contains stanzas likeorNow I can see what most of these do ( eg . that last one means that I can call the method `` get_mime_type '' on a `` FileInfo '' object ) . But I 'd like to know : what is this file , exactly ( ie . what do I search the w... | ( define-interface MenuProvider ( in-module `` Nautilus '' ) ( c-name `` NautilusMenuProvider '' ) ( gtype-id `` NAUTILUS_TYPE_MENU_PROVIDER '' ) ) ( define-method get_mime_type ( of-object `` NautilusFileInfo '' ) ( c-name `` nautilus_file_info_get_mime_type '' ) ( return-type `` char* '' ) ) | Python/C `` defs '' file - what is it ? |
Python | A lot of times I find myself writing something that looks like this : This is hideous . Is there a more elegant way to implement this kind of `` try things until one does n't exception '' logic ? It seems like this is the kind of thing that would come up a lot ; I 'm hoping there 's some language feature I do n't know ... | try : procedure_a ( ) except WrongProcedureError : try : procedure_b ( ) except WrongProcedureError : try : procedure_c ( ) except WrongProcedureError : give_up ( ) | Elegant alternative to long exception chains ? |
Python | Consider this code : I would expect the same output . However , with CPython 2.5 , 2.6 ( similarly in 3.2 ) I get : With PyPy 1.5.0 , I get the expected output : Which is the `` right '' output ? ( Or what should be the output according to the Python documentation ? ) Here is the bug report for CPython . | class Foo1 ( dict ) : def __getattr__ ( self , key ) : return self [ key ] def __setattr__ ( self , key , value ) : self [ key ] = valueclass Foo2 ( dict ) : __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__o1 = Foo1 ( ) o1.x = 42print ( o1 , o1.x ) o2 = Foo2 ( ) o2.x = 42print ( o2 , o2.x ) ( { ' x ' : 42 ... | Python : inconsistence in the way you define the function __setattr__ ? |
Python | Hello fellow programmers , I would like to change the min_num error message of a formset.My code creates a formset using an inlineformset_factory : In the template I render the non_form_errors : The min_num validation works as intended and shows the error message Please submit 1 or more forms. , when a user removes all... | formset_clazz = inlineformset_factory ( MyParentModel , MyModel , MyModelForm , can_delete=True , min_num=1 , validate_min=True ) formset = formset_clazz ( data=request.POST ) print ( formset._non_form_errors ) if formset.is_valid ( ) : print ( `` yay ! `` ) else : print ( `` nay ! `` ) return render ( request , `` myt... | Django : Change formset error message ( s ) |
Python | I am looking into ways of testing some code that acts on files , but I would like to write some tests that only rely on specific strings within the source file rather than having a specific file somewhere in the file system.I know that it is possible to provide a file-like stream interface to strings via io.StringIO.Th... | import io # 'abgdezhjiklmnxoprstufqyw'text = 'αβγδεζηθικλμνξoπρστυφχψω'with open ( 'test.txt ' , ' w ' ) as file_obj : file_obj.write ( text ) with open ( 'test.txt ' , ' r ' ) as file_obj : file_obj.seek ( 8 ) print ( file_obj.read ( 8 ) ) # εζηθικλμwith io.StringIO ( text ) as file_obj : file_obj.seek ( 8 ) print ( f... | How to emulate file opened in text mode in Python |
Python | I 've followed the Tensorflow Reading Data guide to get my app 's data in the form of TFRecords , and am using TFRecordReader in my input pipelines to read this data.I 'm now reading the guides on using skflow/tf.learn to build a simple regressor , but I ca n't see how to use my input data with these tools.In the follo... | Traceback ( most recent call last ) : File `` ... /tf.py '' , line 138 , in < module > run ( ) File `` ... /tf.py '' , line 86 , in run regressor.fit ( x , labels ) File `` ... /site-packages/tensorflow/contrib/learn/python/learn/estimators/base.py '' , line 218 , in fit self.batch_size ) File `` ... /site-packages/ten... | Using a Tensorflow input pipeline with skflow/tf learn |
Python | The -builtin option of SWIG has the advantage of being faster , and of being exempt of a bug with multiple inheritance.The setback is I ca n't set any attribute on the generated classes or any subclass : -I can extend a python builtin type like list , without hassle , by subclassing it : -However using the same approac... | class Thing ( list ) : passThing.myattr = 'anything ' # No problem class Thing ( SWIGBuiltinClass ) : passThing.myattr = 'anything'AttributeError : type object 'Thing ' has no attribute 'myattr ' | Extending SWIG builtin classes |
Python | Say I am looking at a particular date : How can I find : The date of the Monday right before my_date ( if my_date is n't a Monday ) The date of the closest Monday to my_dateIs there a way to round dates in datetime ? | from datetime import date , timedeltadays_to_substract = 65my_date = date.today ( ) -timedelta ( days=days_to_subtract ) | Rounding dates in Python |
Python | Using a given species of fp numbers , say float16 , it is straight forward to construct sums with totally wrong results . For example , using python/numpy : Here we have used cumsum to force naive summation . Left to its own devices numpy would have used a different order of summation , yielding a better answer : The a... | import numpy as npone = np.float16 ( 1 ) ope = np.nextafter ( one , one+one ) np.array ( ( ope , one , -one , -one ) ) .cumsum ( ) # array ( [ 1.001 , 2. , 1. , 0 . ] , dtype=float16 ) np.array ( ( ope , one , -one , -one ) ) .sum ( ) # 0.000977 np.full ( 10**4,10**-4 , np.float16 ) .cumsum ( ) # array ( [ 1.0e-04 , 2.... | With pairwise summation , how many terms do I need to get an appreciably wrong result ? |
Python | The following code generates a sample of size 100 from trunctated normal distributions with different intervals . Is there any effecient ( vectorised ) way of doing this ? | from scipy.stats import truncnormimport numpy as npsample= [ ] a_s=np.random.uniform ( 0,1 , size=100 ) b_s=a_s+0.2for i in range ( 100 ) : sample.append ( truncnorm.rvs ( a_s [ i ] , b_s [ i ] , size=100 ) ) print sample | Vectorised code for sampling from truncated normal distributions with different intervals |
Python | I 'm very new to Python and am exploring it 's use to allow users to build custom images . The idea is that the client would select a few options and the image would be created on the server then downloaded ( or used for other things on the server side ) .The image is composed of many images , most of which are small i... | from PIL import Imagebackground = Image.open ( `` Background.png '' ) foreground = Image.open ( `` Trim.png '' ) fire = Image.open ( `` Type_Fire_Large.png '' ) background = Image.alpha_composite ( background , foreground ) background.paste ( fire , ( 150 , 150 ) ) background.show ( ) | Produce a composed image with different sized layers with transparency |
Python | So I found this code inside Kotti : And I was wondering : What do the left-hand square brackets do ? I did some testing in a python shell , but I ca n't quite figure out the purpose of it.Bonus question : What does the lambda return ? I would guess a tuple of ( Boolean , self._children ) , but that 's probably wrong ..... | [ child ] = filter ( lambda ch : ch.name == path [ 0 ] , self._children ) | Python : Left-side bracket assignment |
Python | I am trying to retrieve certain fields within a .lua file . Initially I thought I could just split on commas but the second set of curly brackets ruins that . An example : So I would be looking for the following from the first line : '' ESPN Deportes '' ( 6th field ) , tv ( 9th ) , 936 ( 10th ) God help me ... or more ... | return { { 6163 , 0 , `` tv '' , false , { 1302 } , `` ESPN Deportes '' , `` ESPN Deportes es el '' , nil , '' tv '' , '' 936 '' , nil , '' 4x3 '' , mediaRestrictions= { `` m2g '' } } , { 57075 , 0 , `` tv '' , false , { 1302 } , `` Video Rola '' , `` Video \ '' Música Para Tus Ojos\ '' , uedes ver . `` , nil , '' tv '... | Python : parsing help needed ! |
Python | I am trying to establish a long running Pull subscription to a Google Cloud PubSub topic.I am using a code very similar to the example given in the documentation here , i.e . : The problem is that I 'm receiving the following traceback sometimes : I saw that this was referenced in another question but here I am asking ... | def receive_messages ( project , subscription_name ) : `` '' '' Receives messages from a pull subscription . '' '' '' subscriber = pubsub_v1.SubscriberClient ( ) subscription_path = subscriber.subscription_path ( project , subscription_name ) def callback ( message ) : print ( 'Received message : { } '.format ( message... | Google PubSub python client returning StatusCode.UNAVAILABLE |
Python | Is there any programming language ( or type system ) in which you could express the following Python-functions in a statically typed and type-safe way ( without having to use casts , runtime-checks etc ) ? # 1 : # 2 : | # My function - What would its type be ? def Apply ( x ) : return x ( x ) # Example usageprint Apply ( lambda _ : 42 ) white = Noneblack = Nonedef White ( ) : for x in xrange ( 1 , 10 ) : print ( `` White move # % s '' % x ) yield blackdef Black ( ) : for x in xrange ( 1 , 10 ) : print ( `` Black move # % s '' % x ) yi... | How to make these dynamically typed functions type-safe ? |
Python | I built simple text editor with some accessibility feature for screen reading software.I 'm using Python for .NET ( pythonnet ) to show a form containing a rich text box.When user press tab after a period it pop-ups a context menu with completions for selected element.Ok , it works fine with Python objects , but it doe... | import sysimport oslst = list ( ) names = jedi.names ( MySource ) names [ 0 ] .defined_names ( ) # works for sysnames [ 1 ] .defined_names ( ) # works for osnames [ 2 ] .defined_names ( ) # does n't work for lst instance of list ( ) . | python jedi : how to retrieve methods of instances ? |
Python | So apparently I ca n't do this in Python ( 2.7 ) : It made sense in my head , but well ... I could create a function : then I can do but not , for exampleSo what I am asking isis there a reason for not allowing this ? ( the first thing ) what is the closest thing that does work ? My current guess for # 2 : | x = ( 1 , 2 , ) ( a , b , c ) = ( *x , 3 ) make_tuple = lambda *elements : tuple ( elements ) ( c , a , b ) = make_tuple ( 3 , *x ) ( a , b , c ) = make_tuple ( *x , 3 ) ( a , b , c , d ) = make_tuple ( *x , *x ) y = [ 3 , 4 ] ( a , b , c , d ) = ( *x , *y , ) ( a , b , c ) = x + ( 3 , ) ( a , b , c , d ) = x + x ( a ,... | Python : why not ( a , b , c ) = ( *x , 3 ) |
Python | I have a list of weather forecasts that start with a similar prefix that I 'd like to remove . I 'd also like to capture the city names : Some Examples : If you have vacation or wedding plans in Phoenix , Tucson , Flagstaff , Salt Lake City , Park City , Denver , Estes Park , Colorado Springs , Pueblo , or Albuquerque ... | > > > text = 'If you have vacation or wedding plans in NYC , Boston , Manchester , Concord , Providence , or Portland ' > > > re.search ( r'^If you have vacation or wedding plans in ( ( \b\w+\b ) , ? ) + or ( \w+ ) ' , text ) .groups ( ) ( 'Providence , ' , 'Providence ' , 'Portland ' ) > > > | Python regex to capture a comma-delimited list of items |
Python | So in python I have the following code , taken from this answer : This opens the text and exports it to a png file just fine : But this includes whitespace beyond the whitespace outside of the frame . How would you go about cropping the image to export only the text , like a bounding box , like so ? | import matplotlib.pyplot as plt import sympy x = sympy.symbols ( ' x ' ) y = 1 + sympy.sin ( sympy.sqrt ( x**2 + 20 ) ) lat = sympy.latex ( y ) # add text plt.text ( 0 , 0.6 , r '' $ % s $ '' % lat , fontsize = 50 ) # hide axes fig = plt.gca ( ) fig.axes.get_xaxis ( ) .set_visible ( False ) fig.axes.get_yaxis ( ) .set_... | Matplotlib save only text without whitespace |
Python | I have a Flask application , being run in Apache , that relies on PyMySQL . The application provides a series of REST commands . It is running under Python 3.Without providing the entire source , the program is structured as : There are a few more REST calls - but they all essentially do the same thing ( ie - get a con... | # ! flask/bin/pythonimport jsonimport pymysqlfrom flask import * # Used to hopefully share the connection if the process is n't restartedmysql_connection = None # Gets the mysql_connection , or opens itGetStoreCnx ( ) : global mysql_connection if ( mysql_connection ! = None ) : store_connection_string = `` '' # Get the... | PyMySQL in Flask/Apache sometimes returning empty result |
Python | I have a cron job everyday to make a call to an API and fetch some data . For each row of the data I kick off a task queue to process the data ( which involves looking up data via further APIs ) . Once all this has finished my data does n't change for the next 24 hours so I memcache it.Is there a way of knowing when al... | class fetchdata ( webapp.RequestHandler ) : def get ( self ) : todaykey = str ( date.today ( ) ) memcache.delete ( todaykey ) topsyurl = 'http : //otter.topsy.com/search.json ? q=site : open.spotify.com/album & window=d & perpage=20 ' f = urllib.urlopen ( topsyurl ) response = f.read ( ) f.close ( ) d = simplejson.load... | Run function when task queue is empty on appengine |
Python | I build large lists of high-level objects while parsing a tree . However , after this step , I have to remove duplicates from the list and I found this new step very slow in Python 2 ( it was acceptable but still a little slow in Python 3 ) . However I know that distinct objects actually have a distinct id . For this r... | from fractions import Fractiona = Fraction ( 1,3 ) b = Fraction ( 1,3 ) | Removing duplicates in a Python list by id |
Python | I have a fixed amount of int arrays of the form : for example : where a and b can be ints from 0 to 2 , c and d can be 0 or 1 , and e can be ints from 0 to 2.Therefore there are : 3 * 3 * 2 * 2 * 3 : 108 possible arrays of this form.I would like to assign to each of those arrays a unique integer code from 0 to 107 . I ... | [ a , b , c , d , e ] [ 2,2,1,1,2 ] [ 0,0,0,0,1 ] and [ 1,0,0,0,0 ] | Encode array of integers into unique int |
Python | I created virtualenv , installed in it Django with after thatproduces Where all these packages are from ? How to get rid of them ? I worked a lot of time before with the same approach and the setup was clean.pip freeze showed installed only Django.I use Ubuntu 16.04 , Python 2.7.12 , virtualenv version 15 on my home an... | pip install django==1.9.8 pip freeze appdirs==1.4.0Django==1.9.8packaging==16.8pyparsing==2.1.10six==1.10.0 | pip freeze shows appdirs , packaging , pyparsing , six installed |
Python | In the typing module , both TypeVar and NewType require as a first positional argument , a string to be used as the created object 's __name__ attribute . What is the purpose of __name__ here ? Considering that this is a compulsory argument , I would expect it to be something essential . In PEP-484 where type hinting w... | T = TypeVar ( 'T ' , int , float , complex ) | Purpose of __name__ in TypeVar , NewType |
Python | I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules . The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background . Using S.Lotts book I decided to use his D... | class Die ( object ) : ' '' simulate a six-sided die `` 'def roll ( self ) : self.value=random.randrange ( 1,7 ) return self.valuedef getValue ( self ) : return self.value class Die ( ) : ' '' simulate a six-sided die `` 'def roll ( self ) : self.ban=random.randrange ( 1,7 ) return self.bandef getValue ( self ) : retur... | How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods ? |
Python | I wrote a command-line tool to execute git pull for multiple git repos using python asyncio . It works fine if all repos have ssh password-less login setup . It also works fine if only 1 repo needs password input . When multiple repos require password input , it seems to get deadlock.My implementation is very simple . ... | utils.exec_async_tasks ( utils.run_async ( path , cmds ) for path in repos.values ( ) ) async def run_async ( path : str , cmds : List [ str ] ) : `` '' '' Run ` cmds ` asynchronously in ` path ` directory `` '' '' process = await asyncio.create_subprocess_exec ( *cmds , stdout=asyncio.subprocess.PIPE , cwd=path ) stdo... | python asyncio gets deadlock if multiple stdin input is needed |
Python | In Python 2 If I have a list containing lists of variable lengths then I can do the following : In Python 3 None type is seemingly not accepted.Is there , in Python 3 , an as simple method for producing the same result . | a= [ [ 1,2,3 ] , [ 4,6 ] , [ 7,8,9 ] ] list ( map ( None , *a ) ) | Python - Transpose List of Lists of various lengths - 3.3 easiest method |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.