lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I was recently comparing the amount of memory occupied by a Python set to that occupied by a frozenset using Pympler : Why would a frozenset created from a set occupy a different amount of memory than one created from some other iterable ? Or is this just a quirk of how Pympler approximates the amount of memory occupie... | > > > from pympler.asizeof import asizeof > > > x = range ( 100 ) > > > s = set ( x ) > > > f0 = frozenset ( x ) > > > f1 = frozenset ( s ) > > > asizeof ( s ) 10824 > > > asizeof ( f0 ) 10824 > > > asizeof ( f1 ) 6728 > > > f0==f1True | memory occupied by set vs frozenset in Python 2.7 |
Python | I have four different lists . headers , descriptions , short_descriptions and misc . I want to combine these into all the possible ways to print out : like if i had ( i 'm skipping short_description and misc in this example for obvious reasons ) I want it to print out like : What would you say is the best/cleanest/most... | header\ndescription\nshort_description\nmisc headers = [ 'Hello there ' , 'Hi there ! ' ] description = [ ' I like pie ' , 'Ho ho ho ' ] ... Hello thereI like pie ... Hello thereHo ho ho ... Hi there ! I like pie ... Hi there ! Ho ho ho ... | Most efficent way to create all possible combinations of four lists in Python ? |
Python | I 'm trying to write a decorator that preserves the arguments of the functions it decorates . The motivation for doing this is to write a decorator that interacts nicely with pytest.fixtures.Suppose we have a function foo . It takes a single argument a.If we get the argument spec of fooWe frequently want to create a de... | def foo ( a ) : pass > > > inspect.getargspec ( foo ) ArgSpec ( args= [ ' a ' ] , varargs=None , keywords=None , defaults=None ) def identity_decorator ( wrapped ) : def wrapper ( *args , **kwargs ) : return wrapped ( *args , **kwargs ) return wrapper @ identity_decoratordef foo ( a ) : pass > > > inspect.getargspec ( ... | Python create decorator preserving function arguments |
Python | I have an array and I need to get the indices satisfying both where a condition is true , and where the same condition is false , e.g . : In my use case x is quite large , this code is called inside a loop , and profiling has revealed that np.where is actually the bottleneck . I 'm currently doing something analogous t... | x = np.random.rand ( 100000000 ) true_inds = np.where ( x < 0.5 ) false_inds = np.where ( x > = 0.5 ) | numpy np.where scan array once to get both sets of indices corresponding to T/F condition |
Python | I have a dictionary of dictionaries : And I want to convert it to : The requirement is that new_d [ key ] [ i ] and new_d [ another_key ] [ i ] should be in the same sub-dictionary of d.So I created new_d = { } and then : This gives me what I expected , but I am just wondering if there are some built-in functions for t... | d = { `` a '' : { `` x '' :1 , `` y '' :2 , `` z '' :3 } , `` b '' : { `` x '' :2 , `` y '' :3 , `` z '' :4 } , `` c '' : { `` x '' :3 , `` y '' :4 , `` z '' :5 } } new_d = { `` x '' : [ 1 , 2 , 3 ] , `` y '' : [ 2 , 3 , 4 ] , `` z '' : [ 3 , 4 , 5 ] } for key in d.values ( ) [ 0 ] .keys ( ) : new_d [ key ] = [ d.value... | Convert a dictionary of dictionaries to dictionary of lists |
Python | My IPython shell becomes sluggish after I instantiate a QApplication object . For example , even from a fresh start , the following code will make my shell sluggish enough where I have to restart it.As soon as that is submitted , my typing becomes lagged by 2 or 3 seconds . My computer is not fantastic , but I still ha... | from PyQt4 import QtGuiapp = QtGui.QApplication ( [ ] ) | QApplication instance causing python shell to be sluggish |
Python | I 'm developing a GUI with PySide and I create pixmap from images like this : This works perfectly when I run the program but when I test it with py.test this happens : It says that the pixmap is null , so it seems like the image was n't loaded properly.I really want to test my code and I ca n't find any information ab... | PHONE_IMAGE_PATH = `` resources/images/phone.png '' self.phone_null = QtGui.QPixmap ( GREY_DOT_PATH ) self.phone_null = self.phone_null.scaledToWidth ( 20 ) QPixmap : :scaleWidth : Pixmap is a null pixmap | Image assets wo n't load when using pytest |
Python | Adding seaborn figures to subplots is usually done by passing 'ax ' when creating the figure . For instance : This method , however , does n't apply to seaborn.palplot , which visualizes seaborn color palettes . My goal is to create a figure of different color palettes for scalable color comparison and presentation . T... | sns.kdeplot ( x , y , cmap=cmap , shade=True , cut=5 , ax=ax ) import numpy as npimport seaborn as snsimport matplotlib.pyplot as pltfig1 = plt.figure ( ) length , n_colors = 12 , 50 # amount of subplots and colors per subplotstart_colors = np.linspace ( 0 , 3 , length ) for i , start_color in enumerate ( start_colors ... | Add seaborn.palplot axes to existing figure for visualisation of different color palettes |
Python | Consider the following example : How could I make it so that an exception will be raised if I try to set a member that is not set in __init__ ? Code above wo n't fail when it is executed , but gives me a fun time to debug the problems.Like with str : Thanks ! | class A ( ) : def __init__ ( self ) : self.veryImportantSession = 1a = A ( ) a.veryImportantSession = None # ok # 200 lines belowa.veryImportantSessssionnnn = 2 # I wan na exception here ! ! It is typo ! > > > s = `` lol '' > > > s.a = 1Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module >... | How to protect againt typos when setting value for class members ? |
Python | I am curious why the following would output that there was a match : The newline is before the end of the string , yes ? Why is this matching ? | import refoo = 'test\n'match = re.search ( '^\w+ $ ' , foo ) if match == None : print `` It did not match '' else : print `` Match ! '' | Why does \w+ match a trailing newline ? |
Python | The following sorting method works perfectly.However the case sensitive related section of the lambdas vi.name if cs else vi.name.lower ( ) gets used 3 times which irks my repeated code gene.Out of interest , can the case aspect be set in advance somehow , but without making permenant changes to the name attribute or d... | def sort_view_items ( self ) : cs = self.settings.case_sensitive if self.settings.sort_by_file_name : sk = lambda vi : ( vi.name if cs else vi.name.lower ( ) , vi.group , vi.tab ) elif self.settings.sort_by_folder : sk = lambda vi : ( vi.folder , vi.name if cs else vi.name.lower ( ) ) elif self.settings.sort_by_syntax ... | Set part of a lambda function in advance to avoid repeated code |
Python | I 'm parsing a document that have some UTF-16 encoded string.I have a byte string that contains the following : When converting to utf-8 , I get the following output : The first two chars þÿ indicate it 's a BOM for UTF-16BE , as indicated on WikipediaBut , what I do n't understand is that if I try the UTF16 BOM like t... | my_var = b'\xc3\xbe\xc3\xbf\x004\x004\x000\x003\x006\x006\x000\x006\x00-\x001\x000\x000\x003\x008\x000\x006\x002\x002\x008\x005 ' print ( my_var.decode ( 'utf-8 ' ) ) # > þÿ44036606-10038062285 if value.startswith ( codecs.BOM_UTF16_BE ) print ( codecs.BOM_UTF16_BE ) # > b'\xfe\xff ' print ( my_var.decode ( 'utf-16 ' )... | Struggling with utf-16 encoding/decoding |
Python | My simulation needs to implementThis overflows for large x , i. e. I 'm getting the RuntimeWarning : overflow encountered in cosh warning . In principle , as logarithm decreases the number in question , in some range of x , cosh should overflow while log ( cosh ( ) ) should not . Is there any solution for that in NumPy... | np.log ( np.cosh ( x ) ) | Avoiding overflow in log ( cosh ( x ) ) |
Python | I m trying to execute several batch-scripts in a python loop . However the said bat-scripts contain cmd /K and thus do not `` terminate '' ( for lack of a better word ) . Therefore python calls the first script and waits forever ... Here is a pseudo-code that gives an idea of what I am trying to do : My question is : `... | import subprocessparams = [ MYSCRIPT , os.curdir ] for level in range ( 10 ) : subprocess.call ( params ) | loop over a batch script that does not terminate |
Python | I have a sentence and a list This indicates that 5th word in the sentence is a disease type . Now I need to get the starting and ending position of the 5th word . If I just do string search with 'cold ' it will give me the starting position of the `` cold '' which occurs first . | str = 'cold weather gives me cold ' tag = [ ' O ' , ' O ' , ' O ' , ' O ' , 'disease ' ] | Find the start and end position of a word in a string based on the index position of that word from a label list |
Python | While trying to plot a cumulative distribution function ( CDF ) using matplotlib 's hist function , the last point goes back to zero . I read some threads explaining that this is because of the histogram-like format , but could n't find a solution for my case.Here 's my code : which produces the following imageAs you c... | import matplotlib.pyplot as pltx = [ 7.845419,7.593756,7.706831,7.256211,7.147965 ] fig , ax=plt.subplots ( ) ax.hist ( x , cumulative=True , normed=1 , histtype='step ' , bins=100 , label= ( 'Label-1 ' ) , lw=2 ) ax.grid ( True ) ax.legend ( loc='upper left ' ) plt.show ( ) | Matplotlib CDF goes back to zero |
Python | ProblemHow can I dump a pickle object with its own dependencies ? The pickle object is generally generated from a notebook.I tried creating virtualenv for the notebook to track dependencies , however this way I do n't get only the imports of the pickle object but many more that 's used in other places of the applicatio... | apiPort : 8080 apiName : name-tagger model : model-repository.internal/model.pickle requirements : model-repository.internal/model.requirements predicterVersion : 1.0 | How to use requirements.txt or similar for a pickle object |
Python | I have the following function signature : I need the number of positional arguments . How can I return the number ( 2 ) of positional arguments ( x & s ) . The number of keyword arguments is not relevant . | # my signaturedef myfunction ( x , s , c=None , d=None ) : # some irrelevant function body | Count positional arguments in function signature |
Python | I am trying to compile a script utilizing multiprocessing into a Windows executable . At first I ran into the same issue as Why python executable opens new window instance when function by multiprocessing module is called on windows when I compiled it into an executable . Following the accepted answer I adjusted my scr... | from multiprocessing import freeze_support # my functionsif __name__ == `` __main__ '' : freeze_support ( ) # my script freeze_support ( ) p = multiprocessing.Process ( target=my_function , args= [ my_list ] ) p.start ( ) p1 = multiprocessing.Process ( target=my_function , args= [ my_list ] ) p1.start ( ) p.join ( ) p1... | Multiprocessing python within frozen script |
Python | The ProblemI 'm trying to use the Django ORM to do the equivalent of a SQL NOT IN clause , providing a list of IDs in a subselect to bring back a set of records from the logging table . I ca n't figure out if this is possible.The ModelWhat I 've TriedMy first attempt was to use exclude , but this does NOT to negate the... | class JobLog ( models.Model ) : job_number = models.BigIntegerField ( blank=True , null=True ) name = models.TextField ( blank=True , null=True ) username = models.TextField ( blank=True , null=True ) event = models.TextField ( blank=True , null=True ) time = models.DateTimeField ( blank=True , null=True ) query = ( Jo... | Django ORM : Equivalent of SQL ` NOT IN ` ? ` exclude ` and ` Q ` objects do not work |
Python | I would like to improve the way this code is written . Right now I have six methods that are almost copy-paste , only one line is changing . How can I make a generic method and depending on the property of the data input to change the calculations ? I was thinking to use functional programming to achieve that , but I a... | def margin_to_exchange_rate_sell ( data ) : j = data.to_JSON ( ) list_p = [ ] mid = midrate.get_midrate ( j [ `` fromCurrency '' ] [ 0 ] ) for idx , val in enumerate ( j [ 'toCurrency ' ] ) : try : mid_current = 1/get_key ( mid , j [ 'toCurrency ' ] [ idx ] ) bankMSell = float ( j [ 'sellMargin ' ] [ idx ] ) list_p.app... | How can I use functional programming to make a generic method in python ? |
Python | I am trying to create a matrix in a random way in the intervals [ -5 , -1 ] and [ 1,5 ] . How can I create a matrix taking into account the intervals ( no 0 values ) with random values ? I tried to do it with randint of numpy and with piecewise . In the first case it is not posible to indicate 2 intervals and in the se... | x=np.random.randint ( -5,5 , ( 2,3 ) ) np.piecewise ( x , [ x < = 1 , x > =-1 ] , [ np.random.randint ( -5 , -1 ) , np.random.randint ( 1,5 ) ] ) [ -2 , -3 , -1 1 , -2 , 3 ] | Generate a matrix without 0 values in a random way |
Python | I have a dataset that I want to map over using several Pyspark SQL Grouped Map UDFs , at different stages of a larger ETL process that runs on ephemeral clusters in AWS EMR . The Grouped Map API requires that the Pyspark dataframe be grouped prior to the apply , but I have no need to actually group keys.At the moment ,... | @ pandas_udf ( b_schema , PandasUDFType.GROUPED_MAP ) def transform ( a_partition ) : b = a_partition.drop ( `` pid '' , axis=1 ) # Some other transform stuff return b ( sql .read.parquet ( a_path ) .withColumn ( `` pid '' , spark_partition_id ( ) ) .groupBy ( `` pid '' ) .apply ( transform ) .write.parquet ( b_path ) ... | Pyspark SQL Pandas Grouped Map without GroupBy ? |
Python | Ok so I have two lists : I compare them in such a way so I get the following output : The basic is idea to go through each list and compare them . If they have an element in common remove that element . But only one of that element not all of them . If they do n't have an element in common leave it . Two identical list... | x = [ 1 , 2 , 3 , 4 ] y = [ 1 , 1 , 2 , 5 , 6 ] x = [ 3 , 4 ] y = [ 1 , 5 , 6 ] done = True while not done : done = False for x in xlist : for y in ylist : if x == y : xlist.remove ( x ) ylist.remove ( y ) done = False print xlist , ylist | Looking for more pythonic list comparison solution |
Python | When I run the following codeWhere myfile looks like this : I getWhen the expected output is a list of numbers : The corresponding command I run in the terminal isSo far , I have tried playing around with escaping and quoting in different ways , such as escaping slashes in the sed or adding extra quotation marks for gr... | from subprocess import call , check_output , Popen , PIPEgr = Popen ( [ `` grep '' , `` '^ > ' '' , myfile ] , stdout=PIPE ) sd = Popen ( [ `` sed '' , `` s/ . *len=// '' ] , stdin=gr.stdout ) gr.stdout.close ( ) out = sd.communicate ( ) [ 0 ] print out > name len=345sometexthere > name2 len=4523someothertexthere ... .... | Python subprocess communicate ( ) yields None , when list of number is expected |
Python | This question is based on this older question : 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 solution by Divakar is what I currently use for 2D arrays : Now , if I wanted to pass a 3D array , I need to modi... | In [ 122 ] : arr = np.array ( [ [ 1 , 3 , 7 ] , [ 4 , 9 , 8 ] ] ) ; arrOut [ 122 ] : array ( [ [ 1 , 3 , 7 ] , [ 4 , 9 , 8 ] ] ) In [ 127 ] : np.indices ( arr.shape ) Out [ 127 ] : array ( [ [ [ 0 , 0 , 0 ] , [ 1 , 1 , 1 ] ] , [ [ 0 , 1 , 2 ] , [ 0 , 1 , 2 ] ] ] ) array ( [ [ 0 , 0 , 1 ] , [ 0 , 1 , 3 ] , [ 0 , 2 , 7 ]... | Generalise slicing operation in a NumPy array |
Python | I 've just started using pyparsing this evening and I 've built a complex grammar which describes some sources I 'm working with very effectively . It was very easy and very powerful . However , I 'm having some trouble working with ParsedResults . I need to be able to iterate over nested tokens in the order that they ... | import pyparsing as ppword = pp.Word ( pp.alphas + ' , . ' ) ( 'word* ' ) direct_speech = pp.Suppress ( ' “ ' ) + pp.Group ( pp.OneOrMore ( word ) ) ( 'direct_speech* ' ) + pp.Suppress ( ' ” ' ) sentence = pp.Group ( pp.OneOrMore ( word | direct_speech ) ) ( 'sentence ' ) test_string = 'Lorem ipsum “ dolor sit ” amet ,... | ` pyparsing ` : iterating over ` ParsedResults ` |
Python | I 've noticed some strange behaviour that may or may not be specific to my system . ( lenovo t430 running windows 8 ) With this script : I get the following output ( what I would consider nominal ) with a browser open . However without a browser open I observe a severe per loop latency . Obviously this is counter-intui... | import timenow = time.time ( ) while True : then = now now = time.time ( ) dif = now - then print ( dif ) time.sleep ( 0.01 ) import timenow = time.time ( ) def newSleep ( mark , duration ) : count = 0 while time.time ( ) -mark < duration : count+=1 print ( count ) while True : then = now now = time.time ( ) dif = now ... | Why is time.sleep ( ) accuracy influenced by Chrome ? |
Python | I was playing around with different implementations of the Euclidean distance metric and I noticed that I get different results for Scipy , pure Python , and Java.Here 's how I compute the distance using Scipy ( = option 1 ) : here 's an implementation in Python I found in a forum ( option 2 ) : and lastly , here 's my... | distance = scipy.spatial.distance.euclidean ( sample , training_vector ) distance = math.sqrt ( sum ( [ ( a - b ) ** 2 for a , b in zip ( training_vector , sample ) ] ) ) public double distance ( int [ ] a , int [ ] b ) { assert a.length == b.length ; double squaredDistance = 0.0 ; for ( int i=0 ; i < a.length ; i++ ) ... | Euclidean distance , different results between Scipy , pure Python , and Java |
Python | Recently I tried compiling program something like this with GCC : and it ran just fine . When I inspected the stack frames the compiler optimized the program to use only one frame , by just jumping back to the beginning of the function and only replacing the arguments to f. And - the compiler was n't even running in op... | int f ( int i ) { if ( i < 0 ) { return 0 ; } return f ( i-1 ) ; f ( 100000 ) ; | Detecting Infinite recursion in Python or dynamic languages |
Python | I 'm trying to run rqscheduler with django-rq on Heroku with RedisToGo . I 've implemented django-rq as described in their readme ( https : //github.com/ui/django-rq ) .I have a worker that starts an rqworker , and another worker that starts up rqscheduler using the management command suggested in the readme . The rqwo... | redis.exceptions.ConnectionError : Error 111 connecting to localhost:6379 . Connection refused . RQ_QUEUES = { 'default ' : { 'HOST ' : 'localhost ' , 'PORT ' : 6379 , 'DB ' : 0 , 'PASSWORD ' : '***** ' , 'DEFAULT_TIMEOUT ' : 500 , } , 'high ' : { 'URL ' : os.getenv ( 'REDISTOGO_URL ' , 'redis : //localhost:6379/0 ' ) ... | RQScheduler on Heroku |
Python | So I am relatively new to python , and in order to learn , I have started writing a program that goes online to wikipedia , finds the first link in the overview section of a random article , follows that link and keeps going until it either enters a loop or finds the philosophy page ( as detailed here ) and then repeat... | user_agent = 'Mozilla/4.0 ( compatible ; MSIE 6.0 ; Windows NT ) ' values = { 'name ' : 'David Kavanagh ' , 'location ' : 'Belfast ' , 'language ' : 'Python ' } headers = { 'User-Agent ' : user_agent } encodes = urllib.urlencode ( values ) req = urllib2.Request ( url , encodes , headers ) page = urllib2.urlopen ( req )... | Wikipedia philosophy game diagram in python and R |
Python | I have some pandas.Series – s , below – that I want to one-hot-encode . I 've found through research that the ' b ' level is not important for my predictive modeling task . I can exclude it from my analysis like so : But when I go to transform a new series , one containing both ' b ' and a new level , 'd ' , I get an e... | import pandas as pdfrom sklearn.preprocessing import OneHotEncoders = pd.Series ( [ ' a ' , ' b ' , ' c ' ] ) .values.reshape ( -1 , 1 ) enc = OneHotEncoder ( drop= [ ' b ' ] , sparse=False , handle_unknown='error ' ) enc.fit_transform ( s ) # array ( [ [ 1. , 0 . ] , # [ 0. , 0 . ] , # [ 0. , 1 . ] ] ) enc.get_feature... | sklearn.preprocessing.OneHotEncoder : using drop and handle_unknown='ignore ' |
Python | I am a beginner at python . As most beginners , I am trying to make a text based rpg . I have finally gotten to the leveling up system and am at another roadblock . When the character levels up , they get to allot x skill points to a skill ( add x to a variable x times ) . two of these variables effect the health of th... | class Char : def __init__ ( self , x , y ) : self.str = x self.con = y self.hp = ( self.con + self.str ) / 2player = Char ( 20 , 20 ) def main ( dude ) : print ( `` strength : `` + str ( dude.str ) ) print ( `` constitution : `` + str ( dude.con ) ) print ( `` hp : `` + str ( dude.hp ) ) print ( `` -- -- -- '' ) action... | Variable X not updating when variables that should effect X change |
Python | I am working on a simple 2d game where many enemies continually spawn and chase the player or players in python + pygame . A problem I ran into , and one many people that have programmed this type of game have run into is that the enemies converge very quickly . I have made a temporary solution to this problem with a f... | def moveEnemy ( enemy , player , speed ) : a = player.left-enemy.left b = player.top-enemy.top r = speed/math.hypot ( a , b ) return enemy.move ( r*a , r*b ) def clump ( enemys ) : for p in range ( len ( enemys ) ) : for q in range ( len ( enemys ) -p-1 ) : a = enemys [ p ] b = enemys [ p+q+1 ] if abs ( a.left-b.left )... | directing a mass of enemies at once |
Python | The result of this comparison surprised me ( CPython 3.4 ) : My understanding of the the docs is that the left operand should be cast to float to match the type of the right operand : Python fully supports mixed arithmetic : when a binary arithmetic operator has operands of different numeric types , the operand with th... | > > > 9007199254740993 == 9007199254740993.0False > > > float ( 9007199254740993 ) == 9007199254740993.0True | Why does 9007199254740993 ! = 9007199254740993.0 ? |
Python | I was trying to create a module , where portal users could modify the associated partner data . But I get a security error that only admin users could modify configs . File `` ... /server/openerp/addons/base/res/res_config.py '' , line 541 , in execute raise openerp.exceptions.AccessError ( _ ( `` Only administrators c... | if uid ! = SUPERUSER_ID and not self.pool [ 'res.users ' ] .has_group ( cr , uid , 'base.group_erp_manager ' ) : raise openerp.exceptions.AccessError ( _ ( `` Only administrators can change the settings '' ) ) class Configuration ( models.TransientModel ) : _inherit = 'res.config.settings ' _name = 'portal_partner_conf... | How can a portal user modify his own partner data in Odoo 8 ? |
Python | I have two binary integers , x0 and x1 that are 8 bits ( so they span from 0 to 255 ) . This statement is always true about these numbers : x0 & x1 == 0 . Here is an example : So I need to do the following operation on these numbers . First , interpret these binary representations as ternary ( base-3 ) numbers , as fol... | bx0 = 100 # represented as 01100100 in binarybx1 = 129 # represented as 10000001 in binary tx0 = ternary ( bx0 ) # becomes 981 represented as 01100100 in ternarytx1 = ternary ( bx1 ) # becomes 2188 represented as 10000001 in ternary tx1_swap = swap ( tx1 ) # becomes 4376 , represented as 20000002 in ternary result = te... | How to merge two binary numbers into a ternary number |
Python | I 've seen this quite often : Why do some people use the default value of None for the the owner parameter ? This is even done in the Python docs : | def __get__ ( self , instance , owner=None ) : descr.__get__ ( self , obj , type=None ) -- > value | Why do people default owner parameter to None in __get__ ? |
Python | Different results for enchant library ( enchant 1.6.6 ) In MAC OSX 10.11.12 ( El Capitan ) : In Linux Ubuntu 14.04 LTS : Any ideas why I get different results and other alternatives in NLTK for `` suggest '' functionality ? MAC OSUbuntuIn my Ubuntu tried : But still same results | > > > import enchant > > > d = enchant.Dict ( `` en_US '' ) > > > d.suggest ( `` prfomnc '' ) [ 'performance ' , 'prominence ' , 'preform ' , 'perform ' ] > > > import enchant > > > d = enchant.Dict ( `` en_US '' ) > > > d.suggest ( `` prfomnc '' ) [ 'princedom ' , 'preferment ' , 'preform ' ] > > > enchant.list_dicts ... | Enchant dictionary across different platforms |
Python | Is sequence unpacking atomic ? e.g . : I 'm under the impression it is not.Edit : I meant atomicity in the context of multi-threading , i.e . whether the entire statement is indivisible , as atoms used to be . | ( a , b ) = ( c , d ) | Is sequence unpacking atomic ? |
Python | I want to process stock level-2 data in pandas . Suppose there are four kinds data in each row for simplicity : millis : timestamp , int64 last_price : the last trade price , float64 , ask_queue : the volume of ask side , a fixed size ( 200 ) array of int32bid_queue : the volume of bid side , a fixed size ( 200 ) array... | dtype = np.dtype ( [ ( 'millis ' , 'int64 ' ) , ( 'last_price ' , 'float64 ' ) , ( 'ask_queue ' , ( 'int32 ' , 200 ) ) , ( 'bid_queue ' , ( 'int32 ' , 200 ) ) ] ) In [ 17 ] : data = np.random.randint ( 0 , 100 , 1616 * 5 ) .view ( dtype ) % compute the average of ask_queue level 5 ~ 10In [ 18 ] : data [ 'ask_queue ' ] ... | Is there any elegant way to define a dataframe with column of dtype array ? |
Python | I want to perform bagging using python scikit-learn.I want to combine RFE ( ) , recursive feature selection algorithm.The step is like below.Make 30 subsets allowing redundant selection ( bagging ) Perform RFE for each data setGet output of each classificationfind top 5 features from each outputI tried to use BaggingCl... | cf1 = LinearSVC ( ) rfe = RFE ( estimator=cf1 ) bagging = BaggingClassifier ( rfe , n_estimators=30 ) bagging.fit ( trainx , trainy ) | Bagging ( bootstrap ) of RFE using python scikit-learn |
Python | Consider some given sequence and a window length , say the list ( so that ) and window length 3.I 'd like to take the sliding window sum of this sequence , but cyclically ; i.e. , to calculate the length-24 list : The best I could come up with , using collections.deque and Stupid Lambda Tricks , wasIs there something l... | a = [ 13 * i + 1 for i in range ( 24 ) ] In [ 61 ] : aOut [ 61 ] : [ 1 , 14 , 27 , 40 , ... , 287 , 300 ] [ sum ( [ 1 , 14 , 27 ] ) , sum ( [ 14 , 27 , 40 ] ) , ... , sum ( [ 287 , 300 , 1 ] ) , sum ( [ 300 , 1 , 14 ] ) ] d = collections.deque ( range ( 24 ) ) d.rotate ( 1 ) map ( lambda _ : d.rotate ( -1 ) or sum ( a ... | Cyclical Sliding Window Iteration |
Python | I was wondering if numpy could be used to build the most basic cube model where all cross-combinations and their computed value are stored.Let 's take the following example of data : And to be able to build something like : I 'm hoping that the usage of using something like meshgrid might get me 75 % there . Basically ... | AUTHOR BOOK YEAR SALESShakespeare Hamlet 2000 104.2Shakespeare Hamlet 2001 99.0Shakespeare Romeo 2000 27.0Shakespeare Romeo 2001 19.0Dante Inferno 2000 11.6Dante Inferno 2001 12.6 YEAR TOTALAUTHOR BOOK 2000 2001 ( ALL ) ( ALL ) 142.8 130.6 273.4Shakespeare ( ALL ) 131.2 118.0 249.2Dante ( ALL ) 11.6 12.6 24.2Shakespear... | Build a basic cube with numpy ? |
Python | One of the biggest challenges in tesseract OCR text recognition is the uneven illumination of images.I need an algorithm that can decide the image is containing uneven illuminations or not . Test Images I Attached the images of no illumination image , glare image ( white-spotted image ) and shadow containing image.If w... | def show_hist_v ( img_path ) : img = cv2.imread ( img_path ) hsv_img = cv2.cvtColor ( img , cv2.COLOR_BGR2HSV ) h , s , v = cv2.split ( hsv_img ) histr =cv2.calcHist ( v , [ 0 ] , None , [ 255 ] , [ 0,255 ] ) plt.plot ( histr ) plt.show ( ) low_threshold =np.count_nonzero ( v < 50 ) high_threshold =np.count_nonzero ( v... | Robust Algorithm to detect uneven illumination in images [ Detection Only Needed ] |
Python | I have a script that I want to execute both in Python3.5 and IronPython2.7.The script is originally written with Python3 in mind , so I have some nested loops similar to the code below : Now if I run this in IronPython2.7 I do n't get the same result because zip returns a list and not an iterator.To circumvent this pro... | myIter0 = iter ( [ 'foo ' , 'foo ' , 'bar ' , 'foo ' , 'spam ' , 'spam ' ] ) myIter1 = iter ( [ 'foo ' , 'bar ' , 'spam ' , 'foo ' , 'spam ' , 'bar ' ] ) myIter2 = iter ( [ 1,2,3,4,5,6 ] ) for a in myIter0 : for b , c in zip ( myIter1 , myIter2 ) : if a + b == 'foobar ' : print ( c ) break import sysif sys.version_info... | zip in IronPython 2.7 and Python3.5 |
Python | I have a large set of csv files ( file_1.csv , file_2.csv ) , separated by time period , that cant be fit into memory . Each file will be in the format mentioned below . Each file is about instrument logs that are consistent in their format . There are set of instruments which can emit different codes ( code ) at a giv... | | instrument | time | code | val || -- -- -- -- -- -- | -- -- -- | -- -- -- -- -- | -- -- -- -- -- -- -- -|| 10 | t1 | c1_at_t1 | v_of_c1_at_t1 || 10 | t1 | c2_at_t1 | v_of_c2_at_t1 || 10 | t2 | c1_at_t2 | v_of_c1_at_t2 || 10 | t2 | c3_at_t2 | v_of_c3_at_t2 || 11 | t1 | c4_at_t1 | v_of_c4_at_t1 || 11 | t1 | c5_at_t1 | ... | How to separate files using dask groupby on a column |
Python | I used Taylor expansion in image classification task . Basically , firstly , pixel vector is generated from RGB image , and each pixel values from pixel vector is going to approximated with Taylor series expansion of sin ( x ) . In tensorflow implementation , I tried possible of coding up this with tensorflow , and I s... | term = 2c = tf.constant ( [ 1 , -1/6 ] ) power = tf.constant ( [ 1 , 3 ] ) x = tf.keras.Input ( shape= ( 32 , 32 , 3 ) ) res = [ ] for x in range ( term ) : expansion = c * tf.math.pow ( tf.tile ( x [ ... , None ] , [ 1 , 1 , 1 , 1 , term ] ) , power ) m_ij = tf.math.cumsum ( expansion , axis=-1 ) res.append ( m_i ) | make input features map from expansion neurons for convolutional layer in keras |
Python | Now I have a numpy array , and a vector.I want to perform a contain operation between the array and the vector row wise . In other words , I want to check whether the first row [ 1 , 2 ] contain 2 , whether the second row [ 3 , 4 ] contain 5 . The expected output would look like : How could I implement this function ? ... | [ [ 1 2 ] [ 3 4 ] [ 2 5 ] ] [ 2 , 5 , 2 ] [ True , False , True ] | How to perform contain operation between a numpy array and a vector row-wise ? |
Python | I have a dataframe and want to eliminate duplicate rows , that have same values , but in different columns : Rows [ 1 ] , [ 2 ] have the values { x , y , e , f } , but they are arranged in a cross - i.e . if you would exchange columns c , d with a , b in row [ 2 ] you would have a duplicate . I want to drop these lines... | df = pd.DataFrame ( columns= [ ' a ' , ' b ' , ' c ' , 'd ' ] , index= [ ' 1 ' , ' 2 ' , ' 3 ' ] ) df.loc [ ' 1 ' ] = pd.Series ( { ' a ' : ' x ' , ' b ' : ' y ' , ' c ' : ' e ' , 'd ' : ' f ' } ) df.loc [ ' 2 ' ] = pd.Series ( { ' a ' : ' e ' , ' b ' : ' f ' , ' c ' : ' x ' , 'd ' : ' y ' } ) df.loc [ ' 3 ' ] = pd.Ser... | Pandas find Duplicates in cross values |
Python | I am using the arrays modules to store sizable numbers ( many gigabytes ) of unsigned 32 bit ints . Rather than using 4 bytes for each element , python is using 8 bytes , as indicated by array.itemsize , and verified by pympler.eg : I have a large number of elements , so I would benefit from storing them within 4 bytes... | > > > array ( `` L '' , range ( 10 ) ) .itemsize8 > > > np.array ( range ( 10 ) , dtype = np.uint32 ) .itemsize4 python3 -m timeit -s `` from array import array ; a = array ( ' L ' , range ( 1000 ) ) '' `` for i in range ( len ( a ) ) : a [ i ] '' 10000 loops , best of 3 : 51.4 usec per loop python3 -m timeit -s `` imp... | Can I force python array elements to have a specific size ? |
Python | I have the task of porting some python code to Scala for research purposes . Now I use the Apache Math3 commons library and am having difficulty with the MersenneTwister.In Python : In Scala : What am I missing here ? Both are MersenneTwister 's , and Int.MaxValue = 2147483647 = ( 2**31 ) - 1 | SEED = 1234567890PRIMARY_RNG = random.Random ( ) PRIMARY_RNG.seed ( SEED ) n = PRIMARY_RNG.randrange ( ( 2**31 ) - 1 ) # 1977150888 val Seed = 1234567890val PrimaryRNG = new MersenneTwister ( Seed ) val n = PrimaryRNG.nextInt ( Int.MaxValue ) //1328851649 | Java Apache Math3 MersenneTwister VS Python random |
Python | Since it 's my first time learning systems programming , I 'm having a hard time wrapping my head around the rules . Now , I got confused about memory leaks . Let 's consider an example . Say , Rust is throwing a pointer ( to a string ) which Python is gon na catch.In Rust , ( I 'm just sending the pointer of the CStri... | use std : :ffi : :CString ; pub extern fn do_something ( ) - > *const c_char { CString : :new ( some_string ) .unwrap ( ) .as_ptr ( ) } def call_rust ( ) : lib = ctypes.cdll.LoadLibrary ( rustLib ) lib.do_something.restype = ctypes.c_void_p c_pointer = lib.do_something ( ) some_string = ctypes.c_char_p ( c_pointer ) .v... | How to stop memory leaks when using ` as_ptr ( ) ` ? |
Python | I find it annoying that I ca n't clear a list . In this example : The second time I initialize a to a blank list , it creates a new instance of a list , which is in a different place in memory , so I ca n't use it to reference the first , not to mention it 's inefficient.The only way I can see of retaining the same poi... | a = [ ] a.append ( 1 ) a.append ( 2 ) a = [ ] for i in range ( len ( a ) ) : a.pop ( ) | Clearing a list |
Python | Say I have one large string and an array of substrings that when joined equal the large string ( with small differences ) .For example ( note the subtle differences between the strings ) : How can I best align the strings to produce a new set of sub strings from the original large_str ? For example : Additional InfoThe... | large_str = `` hello , this is a long string , that may be made up of multiple substrings that approximately match the original string '' sub_strs = [ `` hello , ths is a lng strin '' , `` , that ay be mad up of multiple '' , `` subsrings tat aproimately `` , `` match the orginal strng '' ] [ `` hello , this is a long ... | How can I find the best fit subsequences of a large string ? |
Python | I have a program written with Python 3.7.4 on Windows that opens web pages in a browser . It displays the default browser and gives the user the chance to change which browser they want to use to open programs with.The default browser is detected when the program is initialised using this technique : And links are open... | from winreg import HKEY_CURRENT_USER , OpenKey , QueryValueEximport webbroswerreg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'chrome_path = ' C : /Program Files ( x86 ) /Google/Chrome/Application/chrome.exe % s'firefox_path = ' C : /Program Files ( x86 ) /Mozilla Firefox/fire... | How to override the default browser selection in Windows 7 when opening webppages with Python |
Python | I have been working on my project Deep Learning Language Detection which is a network with these layers to recognise from 16 programming languages : And this is the code to produce the network : So my last language class is SQL and in the test phase , it can never predict SQL correctly and it scores 0 % on them . I tho... | # Setting up the modelgraph_in = Input ( shape= ( sequence_length , number_of_quantised_characters ) ) convs = [ ] for i in range ( 0 , len ( filter_sizes ) ) : conv = Conv1D ( filters=num_filters , kernel_size=filter_sizes [ i ] , padding='valid ' , activation='relu ' , strides=1 ) ( graph_in ) pool = MaxPooling1D ( p... | Keras network can never classify the last class |
Python | When I compile my code from setup.py , it ca n't find the C++11 include file < array > - but C++11 compiler features do work.When I paste the same command line that setup.py generates into my shell , it all compiles perfectly well ( ! ) Code demonstrating this behavior can be seen here and is also pasted below.Terminal... | $ python setup.py build_extrunning build_extbuilding 'simple ' extensioncreating buildcreating build/temp.macosx-10.6-intel-3.4/usr/bin/clang -fno-strict-aliasing -Werror=declaration-after-statement -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -Isrc -I/Library/Framew... | Cython build ca n't find C++11 STL files - but only when called from setup.py |
Python | I need to randomly pick an n-dimensional vector with length 1 . My best idea is to pick a random point in the sphere an normalize it : The only problem is the volume of an n-ball gets smaller as the dimension goes up , so using a uniform distribution from random.random takes very long for even small n like 17 . Is ther... | import randomdef point ( n ) : sq = 0 v = [ ] while len ( v ) < n : x = 1 - 2*random.random ( ) v.append ( x ) sq = sq + x*x if sq > 1 : sq = 0 v = [ ] l = sq** ( 0.5 ) return [ x / l for x in v ] | Computationally picking a random point on a n-sphere |
Python | My dataframe looks like this : and I want : ie I have only 1 column that values differs and I want to create a new dataframe with columns added when new values are observed . Is there an easy way to do this ? | pd.DataFrame ( [ [ `` t1 '' , '' d2 '' , '' e3 '' , '' r4 '' ] , [ `` t1 '' , '' d2 '' , '' e2 '' , '' r4 '' ] , [ `` t1 '' , '' d2 '' , '' e1 '' , '' r4 '' ] ] , columns= [ `` a '' , '' b '' , '' c '' , '' d '' ] ) pd.DataFrame ( [ [ `` t1 '' , '' d2 '' , '' e3 '' , '' r4 '' , '' e1 '' , '' e2 '' ] ] , columns= [ `` a... | Create a new column only if values differ |
Python | Using Cython , I am trying to convert a Python list to a Cython array , and vice versa . The Python list contains numbers from the range 0 - 255 , so I specify the type of the array as an unsigned char array . Here is my code to do the conversions : The problem lies in the fact that pieces of garbage data are generated... | from libc.stdlib cimport malloccdef to_array ( list pylist ) : cdef unsigned char *array array = < unsigned char * > malloc ( len ( pylist ) * sizeof ( unsigned char ) ) cdef long count = 0 for item in pylist : array [ count ] = item count += 1 return arraycdef to_list ( array ) : pylist = [ item for item in array ] re... | Extra elements in Python list |
Python | I 've had to do some introspection in python and it was n't pretty : To get something likeIn our debugging output.I 'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python ? | name = sys._getframe ( 1 ) .f_codename = `` % s : % d % s ( ) '' % ( os.path.split ( name.co_filename ) [ 1 ] , name.co_firstlineno , name.co_name ) foo.py:22 bar ( ) blah blah | How do I do monkeypatching in python ? |
Python | With Python 3.5 on OS X 10.10.4 , I get spurious ] characters in the output syslog messages . This can be seen with the following sample program : If I run this , I see syslog output like this : ( Note the spurious ] character after Test ) .If I change the formatter string slightly to remove the initial [ character , t... | # ! /usr/bin/env python3import loggingimport logging.handlerslogger = logging.getLogger ( 'test ' ) syslog_handler = logging.handlers.SysLogHandler ( address='/var/run/syslog ' ) syslog_formatter = logging.Formatter ( ' [ { process } ] { message } ' , style= ' { ' ) syslog_handler.setFormatter ( syslog_formatter ) logg... | Why do I get a spurious ' ] ' character in syslog messages with Python 's SysLogHandler on OS X ? |
Python | Hi I have following code snippet which gives KeyError . I have checked other links specifying make __init__ call to Ordered Dict which I have done . But still no luck.Error : | from collections import OrderedDictclass BaseExcelNode ( OrderedDict ) : def __init__ ( self ) : super ( BaseExcelNode , self ) .__init__ ( ) self.start_row = -1 self.end_row = -1 self.col_no = -1 def __getattr__ ( self , name ) : return self [ name ] def __setattr__ ( self , name , value ) : self [ name ] = valueBaseE... | KeyError : '_OrderedDict__root ? |
Python | I have written an extension module that uses C++ function pointers to store sequences of function calls . I want to 'run ' these call sequences in separate processes using python 's multiprocessing module ( there 's no shared state , so no synchronization issues ) .I need to know if function pointers ( not data pointer... | # include < list > # include < boost/assert.hpp > # include < boost/python.hpp > # include < boost/python/stl_iterator.hpp > # include < boost/foreach.hpp > /* * Some functions to be called */double funcA ( double d ) { return d ; } double funcB ( double d ) { return d + 3.14 ; } double funcC ( double d ) { return d - ... | Do function pointers remain valid across processes ? |
Python | I 've read about this cool new dictionary type , the transformdictI want to use it in my project , by initializing a new transform dict with regular dict : which succeeds but when I run this : I get : How would you suggest to execute the transform function on the parameter ( regular ) dict when creating the new transfo... | tran_d = TransformDict ( str.lower , { ' A':1 , ' B':2 } ) tran_d.keys ( ) [ ' A ' , ' B ' ] tran_d.keys ( ) == [ ' a ' , ' b ' ] | python - Executing transform function on parameter dict when creating new transformdict |
Python | BackgroundWe are working in Python3.4 / Django1.8.4 and we are witnessing a strange phenomenon with respect to our user model , and specifically the timezone field of this model.Every so often when we are making migrations the new migration file will include an operation to alter said timezone field , but all of the at... | choices= [ ( 'Africa/Abidjan ' , 'Africa/Abidjan ' ) , ( 'Africa/Accra ' , 'Africa/Accra ' ) , ( 'Africa/Addis_Ababa ' , 'Africa/Addis_Ababa ' ) , ... ] class MyUser ( models.Model ) : f_name = models.CharField ( max_length=32398 ) # Got ta accomodate those crazy south-eastern names haha l_name = models.CharField ( max... | Django detecting redundant migrations repetitively |
Python | How do we read a file ( non-blocking ) and print it to the standard output ( still non-blocking ) ? This is the esiest way I can think of but it leaves you with a feeling there must be a better way . Something exposing some LineReceiver - like line by line modification - functionality would be even more preferred . | from twisted.internet import stdio , protocolfrom twisted.protocols.basic import FileSenderfrom twisted.internet import reactorclass FileReader ( protocol.Protocol ) : def connectionMade ( self ) : fl = open ( 'myflie.txt ' , 'rb ' ) d = FileSender ( ) .beginFileTransfer ( fl , self.transport ) d.addBoth ( fl.close ) d... | Reading file to stdout with twisted |
Python | I have few experience with languages like Python , Perl and Ruby , but I have developed in Smalltalk from some time . There are some pretty basic Smalltalk classes which are very popular and cross-Smalltalk implementation : Which classes would be the equivalent or valid semantic replacements in Python , Perl and Ruby ?... | FileStreamReadWriteStreamSetDictionaryOrderedCollectionSortedCollectionBagIntervalArray | Collections and Stream classes equivalences between Smalltalk , Perl , Python and Ruby |
Python | I was wrestling with a weird `` UnboundLocalError : local variable referenced before assignment '' issue in a multi-submodule project I am working on and slimmed it down to this snippet ( using the logging module from standard library ) : Which has this output ( I tried python 2.7 and 3.3 ) : Apparently the presence of... | import loggingdef foo ( ) : logging.info ( 'foo ' ) def bar ( ) : logging.info ( 'bar ' ) if False : import logging.handlers # With these alternatives things work : # import logging.handlers as logginghandlers # from logging.handlers import SocketHandlerlogging.basicConfig ( level=logging.INFO ) foo ( ) bar ( ) INFO : ... | python import inside function hides existing variable |
Python | Update : I 've noticed that entities are saved ( and available at the Datastore Viewer ) when I save them using views ( and the create_object function ) . But when I use shell ( manage.py shell ) to create and save new entity it is n't commited to the storage ( but still can be seen in Tes.objects.all ( ) ) .I started ... | from django.db import modelsclass Tes ( models.Model ) : name = models.CharField ( max_length=150 ) import osimport syssys.path.append ( `` d : \\workspace\\project\\ '' ) os.environ [ 'DJANGO_SETTINGS_MODULE ' ] = 'settings'from testmodule.models import Test = Tes ( name= '' test '' ) t.save ( ) tes = Tes.objects.all ... | Saving entities in django-nonrel with google appengine |
Python | Is there a way to trick argparse into accepting arbitrary numeric arguments like HEAD ( 1 ) ? is equivalent to My current approach is to use parse_known_args ( ) and then handle the remainder , but I 'd wish there was something a tad more elegant . | head -5 test.txt head -n 5 test.txt | python argparse to handle arbitrary numeric options ( like HEAD ( 1 ) ) |
Python | I create a package connecting to other libraries ( livelossplot ) . It has a lot of optional dependencies ( deep learning frameworks ) , and I do n't want to force people to install them.Right now I use conditional imports , in the spirit of : However , it means that it imports big libraries , even if one does not inte... | try : from .keras_plot import PlotLossesKerasexcept ImportError : # import keras plot only if there is keras pass def function_using_keras ( ) : import keras ... from keras.callbacks import Callbackclass PlotLossesKeras ( Callback ) : ... | Conditional import in Python when creating an object inheriting from it |
Python | I am a little confused by the object model of Python . I have two classes , one inherits from the other.What I am trying to do is not to override the __init__ ( ) method , but to create an instance of atom that will have attributes symbol and identifier.Like this : Thus I want to be able to access Atom.identifier and A... | class Node ( ) : def __init__ ( identifier ) : self.identifier = identifierclass Atom ( Node ) : def __init__ ( symbol ) self.symbol = symbol Atom ( `` Fe '' , 1 ) # will create an atom with symbol `` Fe '' and identifier `` 1 '' | Understanding objects in Python |
Python | If i have dataset like this : If we sum that salary column then we will get 316000I really want to know how much person who named 'alexander , smith , etc ' ( in distinct ) makes in salary if we sum all of the salaries from its splitting name in this dataset ( that contains same string value ) .output : as we see the s... | id person_name salary0 [ alexander , william , smith ] 450001 [ smith , robert , gates ] 650002 [ bob , alexander ] 560003 [ robert , william ] 800004 [ alexander , gates ] 70000 group sum_salaryalexander 171000 # sum from id 0 + 2 + 4 ( which contain 'alexander ' ) william 125000 # sum from id 0 + 3smith 110000 # sum ... | pandas : Group by splitting string value in all rows ( a column ) and aggregation function |
Python | I am trying to create a schema for documents that have dependencies that reference fields higher up in the document . For example : What I 'm struggling with here is enforcing the dependency between build-steps.needs-some-package and packages.some-package . Whenever build-steps contains `` needs-some-package '' , packa... | document = { 'packages ' : { 'some-package ' : { 'version ' : 1 } } , 'build-steps ' : { 'needs-some-package ' : { 'foo ' : 'bar ' } , 'other-thing ' : { 'funky ' : 'stuff ' } } } other_document = { 'packages ' : { 'other-package ' : { 'version ' : 1 } } , 'build-steps ' : { 'other-thing ' : { 'funky ' : 'stuff ' } } }... | How can a Cerberus dependency reference a field higher up in the document ? |
Python | I am a former Excel power user repenting for his sins . I need help recreating a common calculation for me.I am trying to calculate the performance of a loan portfolio . In the numerator , I am calculating the cumulative total of losses . In the denominator , I need the original balance of the loans included in the cum... | | Loan | Origination | Balance | NCO Date | NCO | As of Date | Age ( Months ) | NCO Age ( Months ) || -- -- -- -- -| -- -- -- -- -- -- -| -- -- -- -- -| -- -- -- -- -- -| -- -- -| -- -- -- -- -- -- | -- -- -- -- -- -- -- | -- -- -- -- -- -- -- -- -- || Loan 1 | 1/31/2011 | 1000 | 1/31/2018 | 25 | 5/31/2019 | 100 | 84 |... | Conditional Cumulative Sums in Pandas |
Python | I have the following data structures in numpy : My goal is to take each entry i in b , find the x , y coordinates/index positions of all values in a that are < = i , then randomly select one of the values in that subset : This `` works '' , but I 'd like to vectorize the sampling operation ( i.e . replace the for loop ... | import numpy as npa = np.random.rand ( 267 , 173 ) # dense img matrixb = np.random.rand ( 199 ) # array of probability samples from random import randintfor i in b : l = np.argwhere ( a < = i ) # list of img coordinates where pixel < = i sample = l [ randint ( 0 , len ( l ) -1 ) ] # random selection from ` l ` | Numpy : Vectorize np.argwhere |
Python | The following is in python 2.7 with MySQLdb 1.2.3.I needed a class wrapper to add some attributes to objects which did n't support it ( classes with __slots__ and/or some class written in C ) so I came out with something like this : I was expecting that the dir ( ) builtin called on my instance of Wrapper should have r... | class Wrapper ( object ) : def __init__ ( self , obj ) : self._wrapped_obj = obj def __getattr__ ( self , obj ) : return getattr ( self._wrapped_obj , attr ) > > > from _mysql import connection > > > c = connection ( **connection_parameters ) > > > c < _mysql.connection open to '127.0.0.1 ' at a16920 > > > > > > > dir ... | What kind of python magic does dir ( ) perform with __getattr__ ? |
Python | Need help figuring out an 8-bit checksum . The data is 132byte vectors . I thought I had the checksum figured out as I am able to transfer ~30kb of data before I hit the last segment of data shown blow which the checksum fails on . Its off by one.Output : | d1 = [ 0x00 , 0x00 , 0xff , 0x00 , 0x00 , 0x44 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0xff , 0x00 , 0x10 , 0x11 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0xff , 0x00 , 0x10 , 0x12 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 , 0x00 , 0x70 ... | 8-bit checksum is off by one |
Python | I 'm trying to parse a webpage using lxml and I 'm having trouble trying to bring back all the text elements within a div . Here 's what I have so far ... As of now `` foo '' brings back an empty list [ ] . Other pages bring back some content , but not all of the content that is in tags within the < div > . Other pages... | import requestsfrom lxml import htmlpage = requests.get ( `` https : //www.goodeggs.com/sfbay/missionheirloom/seasonal-chicken-stew-16oz/53c68de974e06f020000073f '' , verify=False ) tree = html.fromstring ( page.text ) foo = tree.xpath ( '//section [ @ class= '' product-description '' ] /div [ @ class= '' description-b... | What am I doing wrong ? Parsing HTML using lxml |
Python | Hoping someone can help me here.I 'm very new to Python , and I 'm trying to work out what I 'm doing wrong.I 've already searched and found out that that Python variables can be linked so that changing one changes the other , and I have done numerous tests with the id ( ) function to get to grips with this concept . B... | > > > a = [ 0,0 ] > > > b = a [ : ] > > > print a is bFalse > > > b [ 0 ] =1 > > > print a [ 0,0 ] > > > print b [ 1,0 ] > > > a = [ [ 0,0 ] , [ 0,0 ] ] > > > b = a [ : ] > > > print a is bFalse > > > b [ 0 ] [ 0 ] =1 > > > print a [ [ 1 , 0 ] , [ 0 , 0 ] ] > > > print b [ [ 1 , 0 ] , [ 0 , 0 ] ] | Python : copying a list within a list |
Python | I am trying to use this code to find candidates for rsa by brute force it seems like it should work but it does n't can anyone help me out ? z = ( p − 1 ) ( q − 1 ) for the calculation of z is used prior to thiswith p = 47 and q = 59 , e = 17 and d = 157 but after the program runs it finds no matches but it should . | def gcd ( e , z ) : if z == 0 : return e else : return gcd ( z , e % z ) e = int ( input ( `` Please enter the first number : '' ) ) z = int ( input ( `` Please enter the second number : '' ) ) print ( `` The GCD of `` , e , '' and `` , z , '' is `` , gcd ( e , z ) ) d = 1while d < e : if d * e == 1 % z : print ( d , '... | Python gcd calulation of rsa |
Python | In python , how can I split a long list into a list of lists wherever I come across '- ' . For example , how can I convert : to Many thanks in advance . | [ ' 1 ' , ' a ' , ' b ' , ' -- - ' , ' 2 ' , ' c ' , 'd ' , ' -- - ' , ' 3 ' , '123 ' , ' e ' , ' -- - ' , ' 4 ' ] [ [ ' 1 ' , ' a ' , ' b ' ] , [ ' 2 ' , ' c ' , 'd ' ] , [ ' 3 ' , '123 ' , ' e ' ] , [ ' 4 ' ] ] | a list > a list of lists |
Python | I try to capture fragments of string that looks like % a , % b , etc . and replace them with some values . Additionally , I want to be able to escape % character by typing % % .In an example string % d % % f % x % % % g I want to match % d % % f % x % % % g ( % d , % x , % g ) .My regular expression looks like this : (... | ( ? : [ ^ % ] |^ ) ( ? : % % ) * ( % [ a-z ] ) > > > import re > > > pat = re.compile ( `` ( ? : [ ^ % ] |^ ) ( ? : % % ) * ( % [ a-z ] ) '' ) > > > pat.findall ( `` % d % % f % x % % % g '' ) [ ' % d ' , ' % x ' ] > > > pat.findall ( `` % d % % f % x % % % g '' ) [ ' % d ' , ' % x ' , ' % g ' ] | Previous group match in Python regex |
Python | We have numbers in a string like this : We want to sort this and return : ( only unique numbers ! ) How to do it in ONE line ? | numbers = `` 1534423543 '' `` 1,2,3,4,5 '' | sort numbers in one line |
Python | Let 's say we have a n x n matrix . Taking n=4 as example : This is what I want to achieve : When cut=1 , given from function parameter , the matrix becomes : When cut=3 : When cut=5 : As we can see , the diagonal is being cut like a forward-slash , everything under the first slash would be zeros out.I am using numpy '... | x x x xx x x xx x x xx x x x x x x xx x x xx x x xx x x 0 x x x xx x x 0x x 0 0x 0 0 0 x x 0 0x 0 0 00 0 0 00 0 0 0 | Zero out matrix higher diagonal using numpy |
Python | I hope this is n't a stupid question but I found some code where they imported classmethod and some code where they do n't so there is difference ? I 'm using python 3.6 but the code originally I think was for python 2.7 ( it used from __builtin__ import ) | import unittestfrom selenium import webdriverfrom builtins import classmethod # original code was from __builtin__ import classmethod class HomePageTest ( unittest.TestCase ) : @ classmethod def setUp ( cls ) : # create a new Firefox session cls.driver = webdriver.Firefox ( ) cls.driver.implicitly_wait ( 30 ) cls.drive... | Import or not to import classmethod ? |
Python | I enjoy python one liners with -c , but it is limited when indentation is needed.Any ideas ? | python -c `` for x in range ( 1,10 ) print x '' | How can I make this one-liner work in DOS ? |
Python | In addition to pre-existing warning categories , users can define their own warning classes , such as in the code below : When invoking Python , the -W flag controls how to filter warnings . But when I try to get it to ignore my freshly minted warning category , I 'm told the filter is ignored : How can I use the comma... | $ cat mwe.py # ! /usr/bin/env python3.5import warningsimport pprintclass ObnoxiousWarning ( UserWarning ) : passfor i in range ( 3 ) : print ( i ) warnings.warn ( `` I do n't like this . `` , ObnoxiousWarning ) $ python3.5 -W ignore : :ObnoxiousWarning ./mwe.pyInvalid -W option ignored : unknown warning category : 'Obn... | Filtering based on custom warning categories |
Python | Given this snippet of code : I would expect it to print [ 0 , 1 , 2 ] , but instead it prints [ 2 , 2 , 2 ] . Is there something fundamental I 'm missing about how lambdas work with scope ? | funcs = [ ] for x in range ( 3 ) : funcs.append ( lambda : x ) print [ f ( ) for f in funcs ] | Python lambdas and scoping |
Python | Referring to the Django Book , chapter 3 : What determines why one thing is included as a string , and another as regular variable ? Why admin.site.urls but not 'admin.site.urls ' ? All other includes are included as strings ... I see no logical pattern here . | from django.conf.urls import patterns , include , url # Uncomment the next two lines to enable the admin : # from django.contrib import admin # admin.autodiscover ( ) urlpatterns = patterns ( `` , # Examples : # url ( r'^ $ ' , 'mysite.views.home ' , name='home ' ) , # url ( r'^mysite/ ' , include ( 'mysite.foo.urls ' ... | Why do some includes in Django need strings , and others variable names ? |
Python | How can I make a function that will create a list , increasing the amount of numbers it contains each time to a specified value ? For example if the max was 4 , the list would containIt 's difficult to explain what I 'm looking for , but from the example I think you 'll understand ! Thanks | 1 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 , 4 | Create List With Numbers Getting Greater Each Time Python |
Python | I 'd like to sort a 2D list where each `` row '' is of size 2 , like that for exampleThese rows represent ranges in fact , so Its always [ a , b ] where a < = bI want to sort it exactly this way , each element of the list being a 2-list , I 'd have ( by order of priority ) : [ a1 , b1 ] compared to [ a2 , b2 ] What I f... | [ [ 2,5 ] , [ 2,3 ] , [ 10,11 ] ] 1 . If a1 < a2 do not permute 2 . If a1 > a2 permute 3 . If a1 == a2 then permute if ( b1 - a1 ) > ( b2 - a2 ) | Sorted function using compare function |
Python | I 'm trying to free myself of JMP for data analysis but can not determine the pandas equivalent of JMP 's Split Columns function . I 'm starting with the following DataFrame : I can handle some of the output scenarios of JMP 's function using the pivot_table function , but I 'm stumped on the case where the Vals column... | In [ 1 ] : df = pd.DataFrame ( { 'Level0 ' : [ 0,0,0,0,0,0,1,1,1,1,1,1 ] , 'Level1 ' : [ 0,1,0,1,0,1,0,1,0,1,0,1 ] , 'Vals ' : [ 1,3,2,4,1,6,7,5,3,3,2,8 ] } ) In [ 2 ] : dfOut [ 2 ] : Level0 Level1 Vals0 0 0 11 0 1 32 0 0 23 0 1 44 0 0 15 0 1 66 1 0 77 1 1 58 1 0 39 1 1 310 1 0 211 1 1 8 Level0 0 1Level1 0 1 0 10 1 3 7... | pandas DataFrame reshape by multiple column values |
Python | I have a list of lists over which I need to iterate 3 times ( 3 nested loops ) I can achieve this using product of product as followsThe output looks as followsIts a tuple of tuple . My questions areIs this a good approach ? If so , what is the bestway to unpack theoutput of the product val into 3 separate variables sa... | rangeList = [ [ -0.18,0.18 ] , [ 0.14,0.52 ] , [ 0.48,0.85 ] ] from itertools import productfor val in product ( product ( rangeList , rangeList ) , rangeList ) : print val ( ( [ -0.18 , 0.18 ] , [ -0.18 , 0.18 ] ) , [ -0.18 , 0.18 ] ) ( ( [ -0.18 , 0.18 ] , [ -0.18 , 0.18 ] ) , [ 0.14 , 0.52 ] ) ( ( [ -0.18 , 0.18 ] ,... | Python itertools : Best way to unpack product of product of list of lists |
Python | As I learn Python I have encountered some different styles . I am wondering what the difference between using `` else '' is as opposed to just putting code outside of the `` if '' statement . To further explain my question , here are two blocks of code below . I understand that this is returning False if x ! = 5 , but ... | x = 5if x == 5 : return Trueelse : return False x = 5if x == 5 : return Truereturn False | What is the difference between `` else : return True '' and just `` return True ? '' |
Python | I saw this example at pythontips . I do not understand the second line when defaultdict takes an argument `` tree '' and return a `` tree '' .After I run this code , I checked the type of some_dict | import collectionstree = lambda : collections.defaultdict ( tree ) some_dict = tree ( ) some_dict [ 'color ' ] [ 'favor ' ] = `` yellow '' # Works fine defaultdict ( < function < lambda > at 0x7f19ae634048 > , { 'color ' : defaultdict ( < function < lambda > at 0x7f19ae634048 > , { 'favor ' : 'yellow ' } ) } ) | do n't understand this lambda expression with defaultdict |
Python | I know that dicts and sets are n't ordered , so equal sets or dicts may print differently ( all tests with Python 3.6.1 ) : And I just realized that pprint ( “ pretty-print ” ) sorts dicts but not sets : It 's documentation also says `` Dictionaries are sorted by key before the display is computed '' . But why does n't... | > > > for obj in { 0 , 8 } , { 8 , 0 } , { 0:0 , 8:8 } , { 8:8 , 0:0 } : print ( obj ) { 0 , 8 } { 8 , 0 } { 0 : 0 , 8 : 8 } { 8 : 8 , 0 : 0 } > > > for obj in { 0 , 8 } , { 8 , 0 } , { 0:0 , 8:8 } , { 8:8 , 0:0 } : pprint.pprint ( obj ) { 0 , 8 } { 8 , 0 } { 0 : 0 , 8 : 8 } { 0 : 0 , 8 : 8 } | pprint sorting dicts but not sets ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.