lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Basically , I 'm trying to do remove any lists that begin with the same value . For example , two of the below begin with the number 1 : Because the value 1 exists at the start of two of the lists -- I need to remove both so that the new list becomes : How can I do this ? I 've tried the below , but the output is : [ [... | a = [ [ 1,2 ] , [ 1,0 ] , [ 2,4 ] , [ 3,5 ] ] b = [ [ 2,4 ] , [ 3,5 ] ] def unique_by_first_n ( n , coll ) : seen = set ( ) for item in coll : compare = tuple ( item [ : n ] ) print compare # Keep only the first ` n ` elements in the set if compare not in seen : seen.add ( compare ) yield itema = [ [ 1,2 ] , [ 1,0 ] , ... | Removing dupes in list of lists in Python |
Python | I know that questions about rounding in python have been asked multiple times already , but the answers did not help me . I 'm looking for a method that is rounding a float number half up and returns a float number . The method should also accept a parameter that defines the decimal place to round to . I wrote a method... | def round_half_up ( number , dec_places ) : s = str ( number ) d = decimal.Decimal ( s ) .quantize ( decimal.Decimal ( 10 ) ** -dec_places , rounding=decimal.ROUND_HALF_UP ) return float ( d ) def round_half_up ( number , dec_places ) : d = decimal.Decimal ( number ) .quantize ( decimal.Decimal ( 10 ) ** -dec_places , ... | Python 3.x rounding half up |
Python | In Python 3.7 int ( x-1 ) == x is True for x = 5e+17Why is this so and how do I prevent this bug ? To reproduce , paste this into your Python console : ( I am using int because x is the result of a division and I need to parse it as int . ) | int ( 5e+17-1 ) == 5e+17 > True | Why is int ( x-1 ) == x True in Python 3.7 with some values of x ? |
Python | I wanted to work on a small project to challenge my computer vision and image processing skills . I came across a project where I want to remove the hidden marks from the image . Hidden here refers to the watermarks that are not easily visible in rgb space but when you convert into hsv or some other space the marks bec... | b , g , r = cv2.split ( img ) b = b//2 ; r = cv2.merge ( ( r , g , b ) ) cv2.imshow ( `` image '' , r ) | How to remove hidden marks from images using python opencv ? |
Python | I 'm a beginning programmer in python and have a question about my code I 'm writing : When I run this program I also get 9 , 15 21 as output . But these are not prime numbers . What is wrong with my code ? Thanks ! | number = int ( input ( `` Enter a random number : `` ) ) for num in range ( 1 , number + 1 ) : for i in range ( 2 , num ) : if ( num % i ) == 0 : break else : print ( num ) break | Prime Numbers python |
Python | If i run following on python2.7 console it giving me output as : While i am running same operation in python3.5.2I want to know why in python2.7.12 print statement giving me only 0.2 but in python3.5.2 print function giving me 0.19999999999999996 . | > > > 1.2 - 1.00.19999999999999996 > > > print 1.2 - 1.0 0.2 > > > 1.2 - 1.00.19999999999999996 > > > print ( 1.2 - 1.0 ) 0.19999999999999996 | Why does the print function in Python3 round a decimal number ? |
Python | I ’ m working with sympy on a symbolic jacobian matrix J of size QxQ . Each coefficient of this matrix contains Q symbols , from f [ 0 ] to f [ Q-1 ] . What I ’ d like to do is to substitute every symbol in every coefficient of J with known values g [ 0 ] to g [ Q-1 ] ( which are no more symbols ) . The fastest way I f... | for k in range ( Q ) : J = J.subs ( f [ k ] , g [ k ] ) import sympyimport numpy as npimport timeQ = 17f0 , f1 , f2 , f3 , f4 , f5 , f6 , f7 , f8 , f9 , f10 , f11 , f12 , f13 , f14 , f15 , f16 = \ sympy.symbols ( `` f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 '' ) f = [ f0 , f1 , f2 , f3 , f4 , f5 , f6 , ... | Slow substitution of symbolic matrix with sympy |
Python | I 'm getting a really weird problem with P4Python since I started implementing workspace awareness.The situation is as follows : I have a `` P4Commands '' module which inherits P4 and connects in the __init__ ( ) Then , I have respectively the following classes : P4UserP4WorkspaceP4ChangelistThe P4Commands module inher... | result = super ( P4Commands , self ) .run ( *args , **kwargs ) def run ( self , *args , **kwargs ) : # run whatever commands have to be run , with client temporarily set # to this instance 's client setting . with self.FUNCS.saved_context ( client=self.client ) as _ : return self.FUNCS.run ( *args , **kwargs ) | File ( s ) not on client |
Python | I 'm using Django and Neo4j together with neomodel as the OGM ( ORM for graphs ) . It 's working nicely but when it comes to testing , Neomodel does n't support the usual Django behavior with the relational databases . I mean that it does n't create a temporal Neo4j instance that is created at the beginning of testing ... | from time import sleepfrom subprocess import callfrom django.test.runner import DiscoverRunnerfrom py2neo import authenticateclass DiscoverRunner ( DiscoverRunner ) : def setup_databases ( self , *args , **kwargs ) : # Stop your development instance call ( `` sudo neo4j stop '' , shell=True ) # Sleep to ensure the serv... | Neo4j and Django testing |
Python | I would like to scrape a table from the Ligue 1 football website . Specifically the table which contains information on cards and referees . http : //www.ligue1.com/LFPStats/stats_arbitre ? competition=D1I am using the following code : This returns another table somewhere else in the html . I have tried to circumnaviga... | import requestsfrom bs4 import BeautifulSoupimport csvr=requests.get ( `` http : //www.ligue1.com/LFPStats/stats_arbitre ? competition=D1 '' ) soup= BeautifulSoup ( r.content , `` html.parser '' ) table=soup.find_all ( 'table ' ) < table > < thead > < tr > < th class= '' { sorter : false } hide position '' > Position <... | Ca n't Scrape a Specific Table using BeautifulSoup4 ( Python 3 ) |
Python | In numpy , I have an array that can be either 2-D or 3-D , and I would like to reduce it to 2-D while squaring each element . So I tried this and it does n't work : It returns this error : I suppose einsum does n't assume that when the ellipsis goes away in the right hand side , I want to sum over the ellipsis dimensio... | A = np.random.rand ( 5 , 3 , 3 ) np.einsum ( ' ... ij , ... ij- > ij ' , A , A ) ValueError : output has more dimensions than subscripts given in einstein sum , but no ' ... ' ellipsis provided to broadcast the extra dimensions . A = np.random.rand ( 5 , 3 , 3 ) np.einsum ( 'aij , aij- > ij ' , A , A ) A = np.random.ra... | Summing over ellipsis broadcast dimension in numpy.einsum |
Python | Consider we 've got a bunch of subtress that look like this : I 'm trying to figure how to code a merge function such as doing something like this : will produce : but doing something like this : would produce : Said otherwise , loading the subtrees in the same order will always produce the same tree but if you use the... | subtree1 = { `` id '' : `` root '' , `` children '' : [ { `` id '' : `` file '' , `` caption '' : `` File '' , `` children '' : [ ] } , { `` id '' : `` edit '' , `` caption '' : `` Edit '' , `` children '' : [ ] } , { `` id '' : `` tools '' , `` caption '' : `` Tools '' , `` children '' : [ { `` id '' : `` packages '' ... | How to create a tree from a list of subtrees ? |
Python | After reading this question , I noticed that S. Lott might have liked to use an “ ordered defaultdict ” , but it does n't exist . Now , I wonder : Why do we have so many dict classes in Python ? dictblist.sorteddictcollections.OrderedDictcollections.defaultdictweakref.WeakKeyDictionaryweakref.WeakValueDictionaryothers ... | dict ( initializer= [ ] , sorted=False , ordered=False , default=None , weak_keys=False , weak_values=False ) | Why are n't Python dicts unified ? |
Python | Is it possible to test methods inside interactive python and retain blank lines within them ? This gives the familiar errorSo , yes a workaround is to remove all blank lines inside functions . I 'd like to know if that were truly mandatory to be able to run in interactive mode/REPL.thanks | def f1 ( ) : import random import time time.sleep ( random.randint ( 1 , 4 ) ) IndentationError : unexpected indent | How to configure interactive python to allow blank lines inside methods |
Python | Assume I have the following DataFrameI need to return a second DataFrame that lists the number of occurrences of A and B by day . i.e.I have a feeling this involves `` groupby '' , but I dont know enough about it to get it into the format above ^ | dic = { `` Date '' : [ `` 04-Jan-16 '' , `` 04-Jan-16 '' , `` 04-Jan-16 '' , `` 05-Jan-16 '' , `` 05-Jan-16 '' ] , `` Col '' : [ ' A ' , ' A ' , ' B ' , ' A ' , ' B ' ] } df = pd.DataFrame ( dic ) df Col Date0 A 04-Jan-161 A 04-Jan-162 B 04-Jan-163 A 05-Jan-164 B 05-Jan-16 A BDate 04-Jan-16 2 105-Jan-16 1 1 | Pandas : return number of occurrences by date |
Python | I understand that given an iterable such asI can turn it into a list and slice off the ends at arbitrary points with , for exampleor reverse it withor combine the two withHowever , trying to accomplish this in a single operation produces in some results that puzzle me : Only after much trial and error , do I get what I... | > > > it = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] > > > it [ 1 : -2 ] [ 2 , 3 , 4 , 5 , 6 , 7 ] > > > it [ : :-1 ] [ 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ] > > > it [ 1 : -2 ] [ : :-1 ] [ 7 , 6 , 5 , 4 , 3 , 2 ] > > > it [ 1 : -2 : -1 ] [ ] > > > > it [ -1:2 : -1 ] [ 9 , 8 , 7 , 6 , 5 , 4 ] > > > > it [ -2:1 : -1 ] [ 8 , 7... | Mysterious interaction between Python 's slice bounds and `` stride '' |
Python | I 've been playing around with Cython in preparation for other work . I tried a simple test case and noticed something odd with the way my code performs for larger problem sizes . I created a simple min/max function that calculates the min and max of a 2D float32 array and compared it to running numpy.min ( a ) , numpy... | import numpycimport cythoncimport numpyDTYPE = numpy.float32ctypedef numpy.float32_t DTYPE_t @ cython.boundscheck ( False ) @ cython.wraparound ( False ) def minmax_float32 ( numpy.ndarray [ DTYPE_t , ndim=2 ] arr ) : cdef DTYPE_t min = arr [ 0 , 0 ] cdef DTYPE_t max = arr [ 0 , 0 ] cdef int row_max = arr.shape [ 0 ] c... | Cython vs numpy performance scaling |
Python | I recently made the switch from python 2 to python 3 . Python 3 documentation reads : `` Removed reload ( ) . Use imp.reload ( ) '' It does n't really say why though.This question describes how it 's done now in python 3 . Does anyone have any idea why it 's been removed from the built-ins and now requires imp or impor... | from imp import reload | Why was reload removed from python builtins in the switch to python3 ? |
Python | PrefaceI have a test where I 'm working with nested iterables ( by nested iterable I mean iterable with only iterables as elements ) . As a test cascade considerE.g . foo may be simple identity functionand contract is simply checks that flattened iterables have same elementsBut if some of nested_iterable elements is an... | from itertools import teefrom typing import ( Any , Iterable ) def foo ( nested_iterable : Iterable [ Iterable [ Any ] ] ) - > Any : ... def test_foo ( nested_iterable : Iterable [ Iterable [ Any ] ] ) - > None : original , target = tee ( nested_iterable ) # this does n't copy iterators elements result = foo ( target )... | deep copy nested iterable ( or improved itertools.tee for iterable of iterables ) |
Python | Let 's say I want to open a text file for reading using the following syntax : But if I detect that it ends with .gz , I would call gzip.open ( ) . If `` do something '' part is long and not convenient to write in a function ( e.g . it would create a nested function , which can not be serialized ) , what is the shortes... | with open ( fname , ' r ' ) as f : # do something pass if fname.endswith ( '.gz ' ) : with gzip.open ( fname , 'rt ' ) as f : # do something passelse : with open ( fname , ' r ' ) as f : # do something pass | python : `` with '' syntax for opening files with two functions |
Python | I 'm doing a bit more complex operation on a dataframe where I compare two rows which can be anywhere in the frame.Here 's an example : Now what I am doing here is that I have pairings of strings in A and B , for example a_c which I call AB . And I have the reverse pairing c_a as well . I sum over the numbers AW and BW... | import pandas as pdimport numpy as npD = { ' A ' : [ ' a ' , ' a ' , ' c ' , ' e ' , ' e ' , ' b ' , ' b ' ] , ' B ' : [ ' c ' , ' f ' , ' a ' , ' b ' , 'd ' , ' a ' , ' e ' ] \ , 'AW ' : [ 1,2,3,4,5,6,7 ] , 'BW ' : [ 10,20,30,40,50,60,70 ] } P = pd.DataFrame ( D ) P = P.sort_values ( [ ' A ' , ' B ' ] ) P [ 'AB ' ] = ... | Pandas : Get the only value of a series or nan if it does not exist |
Python | my very first day with Python.I like to filter on a trace file generated by C.Each double from C is formatted in the file bytwo hex strings representing 32 bit of the 64 double.e.g . 1234567890.3 ( C double ) inside file : How can I parse and combine it to further work with a Python float ? Thanks in advance | 0xb49333330x41d26580 | Converting from a C double transferred in two hex strings |
Python | I am using datetime in some Python udfs that I use in my pig script . So far so good . I use pig 12.0 on Cloudera 5.5However , I also need to use the pytz or dateutil packages as well and they dont seem to be part of a vanilla python install . Can I use them in my Pig udfs in some ways ? If so , how ? I think dateutil ... | import sys # I append the path to dateutil on my local windows machine . Is that correct ? sys.path.append ( ' C : /Users/me/AppData/Local/Continuum/Anaconda2/lib/site-packages ' ) from dateutil import tz 2016-08-30 09:56:06,572 [ main ] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1121 : Python Error . Traceback ( m... | Pig : is it possible to use pytz or dateutils for Python udfs ? |
Python | I tried it on virtualenv : | ( venv ) $ pip install Django==1.0.4Downloading/unpacking Django==1.0.4 Could not find a version that satisfies the requirement Django==1.0.4 ( from versions : ) No distributions matching the version for Django==1.0.4Storing complete log in /home/tokibito/.pip/pip.log | Why is Django 1.0.x not able to install from PyPI ? |
Python | BackgroundThe Python 3 documentation clearly describes how the metaclass of a class is determined : if no bases and no explicit metaclass are given , then type ( ) is used if an explicit metaclass is given and it is not an instance of type ( ) , then it is used directly as the metaclass if an instance of type ( ) is gi... | class MyMetaclass ( type ) : passdef metaclass_callable ( name , bases , namespace ) : print ( `` Called with '' , name ) return MyMetaclass ( name , bases , namespace ) class MyClass ( metaclass=metaclass_callable ) : passclass MyDerived ( MyClass ) : passprint ( type ( MyClass ) , type ( MyDerived ) ) | Why does the class definition 's metaclass keyword argument accept a callable ? |
Python | I want to enforce that all items in a list are of type x . What would be the best way to do this ? Currently I am doing an assert like the following : Where int is the type I 'm trying to enforce here . Is there a better way to do this ? | a = [ 1,2,3,4,5 ] assert len ( a ) == len ( [ i for i in a if isinstance ( i , int ) ] ) | How to check to make sure all items in a list are of a certain type |
Python | This dictionary corresponds with numbered nodes : Using two print statements , I want to print marked and unmarked nodes as follows : Marked nodes : 0 1 2 6 7Unmarked nodes : 3 4 5 8 9I want something close to : | { 0 : True , 1 : True , 2 : True , 3 : False , 4 : False , 5 : False , 6 : True , 7 : True , 8 : False , 9 : False } print ( `` Marked nodes : % d '' key in markedDict if markedDict [ key ] = True ) print ( `` Unmarked nodes : % d '' key in markedDict if markedDict [ key ] = False ) | How to print with inline if statement ? |
Python | There is a puzzle which I am writing code to solve that goes as follows.Consider a binary vector of length n that is initially all zeros . You choose a bit of the vector and set it to 1 . Now a process starts that sets the bit that is the greatest distance from any 1 bit to $ 1 $ ( or an arbitrary choice of furthest bi... | # ! /usr/bin/pythonfrom __future__ import divisionfrom math import *def findloc ( v ) : count = 0 maxcount = 0 id = -1 for i in xrange ( n ) : if ( v [ i ] == 0 ) : count += 1 if ( v [ i ] == 1 ) : if ( count > maxcount ) : maxcount = count id = i count = 0 # Deal with vector ending in 0s if ( 2*count > = maxcount and ... | Fast way to place bits for puzzle |
Python | I have text in my database . I send some text from xhr to my view . Function find does not find some unicode chars.I want to find selected text using : but sometimes variable 'selection ' contains a char like that : whereas in variable 'text ' there was : They are just different forms of the same thing . How to make .f... | text.find ( selection ) ę # in xhr unichr ( 281 ) ę # in db has two chars unichr ( 101 ) + unichr ( 808 ) | Python the same char not equals |
Python | I 'm playing around with generators and generator expressions and I 'm not completely sure that I understand how they work ( some reference material ) : So it looks like generator.send was ignored . That makes sense ( I guess ) because there is no explicit yield expression to catch the sent information ... However , I ... | > > > a = ( x for x in range ( 10 ) ) > > > next ( a ) 0 > > > next ( a ) 1 > > > a.send ( -1 ) 2 > > > next ( a ) 3 > > > a = ( ( yield x ) for x in range ( 10 ) ) > > > next ( a ) 0 > > > print next ( a ) None > > > print next ( a ) 1 > > > print next ( a ) None > > > a.send ( -1 ) # this send is ignored , Why ? ... ... | Attempting to understand yield as an expression |
Python | I am trying to do the following with a sed script but it 's taking too much time . Looks like something I 'm doing wrongly.Scenario : I 've student records ( > 1 million ) in students.txt.In This file ( each line ) 1st 10 characters are student ID and next 10 characters are contact number and so onstudents.txt 10000000... | while read -r pattern replacement ; do sed -i `` s/ $ pattern/ $ replacement/ '' students.txtdone < encrypted_contact_numbers.txt sed 's| *\ ( [ ^ ] *\ ) *\ ( [ ^ ] *\ ) . *|s/\1/\2/g| ' < encrypted_contact_numbers.txt |sed -f- students.txt > outfile.txt | SED or AWK script to replace multiple text |
Python | For a data analysis task , I want to find zero crossings in a numpy array , coming from a convolution with first a sobel-like kernel , and then a mexican hat kernel . Zero crossings allow me to detect edges in the data.Unfortunately , the data is somewhat noisy and I only want to find zero crossings with a minimal jump... | import numpy as nparr = np.array ( [ 12 , 15 , 9 , 8 , -1 , 1 , -12 , -10 , 10 ] ) > > > array ( [ 1 , 3 , 7 ] ) > > > array ( [ 3 , 7 ] ) zero_crossings = np.where ( np.diff ( np.sign ( np.trunc ( arr/10 ) ) ) ) [ 0 ] arr = np.array ( [ 12 , 15 , 9 , 8 , -1 , 1 , -12 , -10 , 10 ] ) arr_floored = np.trunc ( arr/10 ) > ... | Finding minimal jump zero crossings in numpy |
Python | Is there a method to print terminal formatted output to a variable ? I want that string ' b ' to a variable - so how to do it ? I am working with a text string from telnet . Thus I want to work with the string that would be printed to screen.So what I am looking for is something like this : Another example with a carri... | print ' a\bb ' -- > ' b ' simplify_string ( ' a\bb ' ) == > ' b ' simplify_string ( 'aaaaaaa\rbb ' ) == > 'bbaaaaa ' | How to print terminal formatted output to a variable |
Python | Guided by this answer I started to build up pipe for processing columns of dataframe based on its dtype . But after getting some unexpected output and some debugging i ended up with test dataframe and test dtype checking : OUTPUT : Almost everything is good , but this test code produces two questions : The most strange... | # Creating test dataframetest = pd.DataFrame ( { 'bool ' : [ False , True ] , 'int ' : [ -1,2 ] , 'float ' : [ -2.5 , 3.4 ] , 'compl ' : np.array ( [ 1-1j , 5 ] ) , 'dt ' : [ pd.Timestamp ( '2013-01-02 ' ) , pd.Timestamp ( '2016-10-20 ' ) ] , 'td ' : [ pd.Timestamp ( '2012-03-02 ' ) - pd.Timestamp ( '2016-10-20 ' ) , p... | Caveats while checking dtype in pandas DataFrame |
Python | Why is the code below termed 'age-old disapproved method ' of printing in the comment by 'Snakes and Coffee ' to Blender 's post of Print multiple arguments in python ? Does it have to do with the backend code/implementation of Python 2 or Python 3 ? | print ( `` Total score for `` + str ( name ) + `` is `` + str ( score ) ) | Why is print ( `` text '' + str ( var1 ) + `` more text '' + str ( var2 ) ) described as `` disapproved '' ? |
Python | Consider the following simple example class , which has a property that exposes a modified version of some internal data when called : The value.setter works fine for regular assignment , but of course breaks down for compound assignment : The desired behavior is that x.value += 5 should be equivalent to x.value = x._v... | class Foo ( object ) : def __init__ ( self , value , offset=0 ) : self._value = value self.offset = offset @ property def value ( self ) : return self._value + self.offset @ value.setter def value ( self , value ) : self._value = value > > > x = Foo ( 3 , 2 ) > > > x.value5 > > > x.value = 2 > > > x.value4 > > > x.valu... | Property setters for compound assignment ? |
Python | I have the following code : However , when I run python ./pypy/pypy/translator/goal/translate.py t.py I get the following error : There was actually more to the error but I thought only this last part was relevant . If you think more of it might be helpful , please comment and I will edit.In fact , I get another error ... | import sysdef entry_point ( argv ) : sys.exit ( 1 ) return 0def target ( *args ) : return entry_point , None ... [ translation : ERROR ] Exception : unexpected prebuilt constant : < built-in function exit > [ translation : ERROR ] Processing block : [ translation : ERROR ] block @ 9 is a < class 'pypy.objspace.flow.flo... | RPython sys methods do n't work |
Python | I 'm writing a passion program that will determine the best poker hand given hole cards and community cards . As an ace can go both ways in a straight , I 've coded this as [ 1 , 14 ] for a given 5 card combination.I understand recursion but implementing it is a different story for me . I 'm looking for a function that... | hand = [ [ 1 , 14 ] , 2 , 3 , [ 1 , 14 ] , 7 ] desired_output = [ [ 1 , 2 , 3 , 1 , 7 ] , [ 1 , 2 , 3 , 14 , 7 ] , [ 14 , 2 , 3 , 1 , 7 ] , [ 14 , 2 , 3 , 14 , 7 ] ] def split_first_ace ( hand ) : aces = [ True if isinstance ( x , list ) else False for x in hand ] for i , x in enumerate ( aces ) : if x : ranks_temp = h... | Split list recursively until flat |
Python | I have a log file that is formatted in the following way : I am attempting to run some stats over this dataset . I have the following code : I did not want to define a class for such a simple dataset , so I used a name tuple . When I attempt to run , I get this error : It appears that the lambda function is operating o... | datetimestring \t username \t transactionName \r\n import timeimport collectionsfile = open ( 'Log.txt ' , ' r ' ) TransactionData = collections.namedtuple ( 'TransactionData ' , [ 'transactionDate ' , 'user ' , 'transactionName ' ] ) transactions = list ( ) for line in file : fields = line.split ( '\t ' ) transactionD... | `` reduce '' function in python not work on `` namedtuple '' ? |
Python | When creating a BrowserView in Plone , I know that I may optionally configure a template with ZCML like so : Or alternatively in code : Is there any difference between the two approaches ? They both appear to yield the same result.Sub-question : I know there is a BrowserView class one can import , but conventionally ev... | < configure xmlns : browser= '' http : //namespaces.zope.org/browser '' > < browser : page … class= '' .foo.FooView '' template= '' foo.pt '' … / > < /configure > # foo.pyfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFilefrom zope.publisher.browser import BrowserPageclass FooView ( BrowserPage ) : ... | What is the difference between template in ZCML and ViewPageTemplateFile |
Python | Consider : I want to replace matches randomly with entries of a list repl . But when using lambda m : random.choice ( repl ) as a callback , it does n't replace \1 , \2 etc . with its captures any more , returning `` \1bla\2 '' as plain text.I 've tried to look up re.py on how they do it internally , so I might be able... | text = `` abcdef '' pattern = `` ( b|e ) cd ( b|e ) '' repl = [ r '' \1bla\2 '' , r '' \1blabla\2 '' ] text = re.sub ( pattern , lambda m : random.choice ( repl ) , text ) | How can I pass a callback to re.sub , but still inserting match captures ? |
Python | I have a web application with an associated API and database . I 'd like to use the same Django models in the API , but have it served separately by different processes so I can scale it independently . I also do n't need the API to serve static assets , or any of the other views . The complication is that the routes I... | http : //domain.com/normal/application/stuffhttp : //domain.com/api/different/stuff | django deploying separate web & api endpoints on heroku |
Python | Is it possible to create hyperlinks without leading and trailing spaces ? The following does n't work : The reason I 'm asking is I 'm working with Chinese text . Spaces are not used as word delimiters in Chinese . With the added spaces the text does n't look well formatted , for example : 没有空格就对了。versus 多了 空格 不好看。Any ... | re ` Structured ` _Text.. _ ` Structured ` : http : //docutils.sourceforge.net/docs/user/rst/quickstart.html | RestructuredText - Hyperlinks without leading and trailing spaces |
Python | I have a Python script that interfaces with an API . The script is started from a PHP page . I wrote both scripts , so I can change the code in either as appropriate.The Python script needs a username and password to interface with the API . My first inclination is to pass them to Python as CLI arguments : However , an... | < ? phpexec ( 'python someScript.py AzureDiamond hunter2 ' ) ; ? > $ ps | grep someScript1000 23295 2.0 0.2 116852 9252 pts/0 S+ 15:47 0:00 python someScript.py AzureDiamond hunter2 | Start process , hide arguments from ps |
Python | I 'm trying to pack and send columnar data over a socket connection . To speed it up , I thought about splitting the packing ( struct.pack ) to multiple processes . To avoid pickling both ways , I thought it might be better to have the packing processes send the data themselves , as it was said socket objects can be pi... | import socketfrom multiprocessing import Poolfrom struct import pack # Start and connect a sockets = socket.socket ( ) s.connect ( ( ip , port ) ) # Data to be packed and sent in this orderdata1 = 1 , 2 , 3 , 4data2 = 5 , 6 , 7 , 8data3 = 9 , 10 , 11 , 12 # Top level column packer/sender for mp.pooldef send_column ( co... | Sending over the same socket with multiprocessing.pool.map |
Python | Perhaps I am doing something wrong while z-normalizing my array . Can someone take a look at this and suggest what 's going on ? In R : In Python using numpy : Am I using numpy incorrectly ? | > data < - c ( 2.02 , 2.33 , 2.99 , 6.85 , 9.20 , 8.80 , 7.50 , 6.00 , 5.85 , 3.85 , 4.85 , 3.85 , 2.22 , 1.45 , 1.34 ) > data.mean < - mean ( data ) > data.sd < - sqrt ( var ( data ) ) > data.norm < - ( data - data.mean ) / data.sd > print ( data.norm ) [ 1 ] -0.9796808 -0.8622706 -0.6123005 0.8496459 1.7396910 1.5881... | Output values differ between R and Python ? |
Python | I see from here that I can pick out tests based on their mark like so : Let 's say I have a test decorated like so : I 'd like to do something like the following : That way I run test_Foo with the parameter of 'release ' but not the parameter of 'debug ' . Is there a way to do this ? I think I can do this by writing a ... | pytest -v -m webtest @ pytest.mark.parametrize ( 'platform , configuration ' , ( pytest.param ( 'win ' , 'release ' ) pytest.param ( 'win ' , 'debug ' ) ) ) def test_Foo ( self ) : pytest -v -m parameterize.configuration.release | Pytest select tests based on mark.parameterize value ? |
Python | I 'm running a Debian 10 stable x64 system with the dwm window manager , and I 'm using Python 3.7.3 . From what I can tell from some example code and the draw_text method itself , I should be able to draw text on the root window with code like this : This code runs without error , but no text is displayed . I 've also... | # ! /usr/bin/env python3import Xlibimport Xlib.displaydisplay = Xlib.display.Display ( ) screen = display.screen ( ) root = screen.rootgc = root.create_gc ( foreground = screen.white_pixel , background = screen.black_pixel ) root.draw_text ( gc , 1 , 1 , b '' Hello , world ! '' ) | How do I write text to the root window using Python 's Xlib ? |
Python | I wish to be able to perform python debugging using print ( ) or similar method where it prints the passed expression in addition to the usual output.For instance , for the following code : Current Output : Expected Output : Currently , the same can be achieved by manually adding the expression string , ( not so elegan... | print ( 42 + 42 ) print ( type ( list ) ) print ( datetime.now ( ) ) 84 < class 'type ' > 2019-08-15 22:43:57.805861 42 + 42 : 84type ( list ) : < class 'type ' > datetime.now ( ) : 2019-08-15 22:43:57.805861 print ( `` 42 + 42 : `` , 42 + 42 ) print ( `` type ( list ) : `` , type ( list ) ) print ( `` datetime.now ( )... | print ( ) method to print passed expression literally along with computed output for quick debugging |
Python | I 'm looking at an open source package ( MoviePy ) which adapts its functionality based on what packages are installed . For example , to resize an image , it will use the functionality provided by OpenCV , else PIL/pillow , else SciPy . If none are available , it will gracefully fallback to not support resizing.The se... | requires = [ 'decorator > =4.0.2 , < 5.0 ' , 'imageio > =2.1.2 , < 3.0 ' , 'tqdm > =4.11.2 , < 5.0 ' , 'numpy ' , ] optional_reqs = [ `` scipy > =0.19.0 , < 1.0 ; python_version ! = ' 3.3 ' '' , `` opencv-python > =3.0 , < 4.0 ; python_version ! = ' 2.7 ' '' , `` scikit-image > =0.13.0 , < 1.0 ; python_version > = ' 3.... | Can I use Environment Markers in tests_require in setup.py ? |
Python | HighLine is a Ruby library for easing console input and output . It provides methods that lets you request input and validate it . Is there something that provides functionality similar to it in Python ? To show what HighLine does see the following example : It asks `` Yes or no ? `` and lets the user input something .... | require 'highline/import'input = ask ( `` Yes or no ? `` ) do |q| q.responses [ : not_valid ] = `` Answer y or n for yes or no '' q.default = ' y ' q.validate = /\A [ yn ] \Z/iend Yes or no ? |y| EH ? ? ? Answer y or n for yes or no ? y | Is there a Python equivalent to HighLine ? |
Python | I want to replace those elements of list1 whose indices are stored in list indices by list2 elements . Following is the current code : Is it possible to write a one-liner for the above four lines using lambda function or list comprehension ? EDITlist1 contains float valueslist2 contains float valuesindices contain inte... | j=0for idx in indices : list1 [ idx ] = list2 [ j ] j+=1 | Python one liner to substitute a list indices |
Python | How can I easily create an object that can not be pickled for testing edge cases in my rpc code ? It needs to be : SimpleReliable ( not expected to break in future versions of python or pickle ) Cross platformEdit : The intended use looks something like this : | class TestRPCServer : def foo ( self ) : return MagicalUnpicklableObject ( ) def test ( ) : with run_rpc_server_and_connect_to_it ( ) as proxy : with nose.assert_raises ( pickle.PickleError ) : proxy.foo ( ) | Create object that can not be pickled |
Python | I 've recently stumbled over this expression : It evaluates to False , but I do n't understand why.True == False is False and False in ( False , ) is True , so both ( to me ) plausible possibilitiesandevaluate to True , as I would have expected.What is going wrong here ? | True == False in ( False , ) True == ( False in ( False , ) ) ( True == False ) in ( False , ) | How does operator binding work in this Python example ? |
Python | Recently , reading Python `` Functional Programming HOWTO '' , I came across a mentioned there test_generators.py standard module , where I found the following generator : It took me a while to understand how it works . It uses a mutable list values to store the yielded results of the iterators , and the N+1 iterator r... | # conjoin is a simple backtracking generator , named in honor of Icon 's # `` conjunction '' control structure . Pass a list of no-argument functions # that return iterable objects . Easiest to explain by example : assume the # function list [ x , y , z ] is passed . Then conjoin acts like : # # def g ( ) : # values = ... | Conjoin function made in functional style |
Python | As title , I creates the zip file from my Django backend server ( hosted on a Ubuntu 14.04.1 LTS ) using the python zipfile module : I managed to open it using my Mac in Finder , but no success using the SSZipArchive library . I have tried using the latest commit of master branch and also tag v1.0.1 and v0.4.0.Using v0... | zipfile.ZipFile ( dest_path , mode= ' w ' , compression=zipfile.ZIP_DEFLATED , allowZip64=True ) if ( unz64local_CheckCurrentFileCoherencyHeader ( s , & iSizeVar , & offset_local_extrafield , & size_local_extrafield ) ! =UNZ_OK ) return UNZ_BADZIPFILE ; ... -rw-r -- r -- 2.0 unx 1992 b- defN 26-Nov-15 14:59 < file_name... | Unable to unzip a large zip file ( 3.3GB ) in iOS9 using SSZipArchive |
Python | When I train a SVC with cross validation , cross_val_predict returns one class prediction for each element in X , so that y_pred.shape = ( 1000 , ) when m=1000.This makes sense , since cv=5 and therefore the SVC was trained and validated 5 times on different parts of X . In each of the five validations , predictions we... | y_pred = cross_val_predict ( svc , X , y , cv=5 , method='predict ' ) score = accuracy_score ( y , y_pred ) | Why is cross_val_predict not appropriate for measuring the generalisation error ? |
Python | Is there a built-in function that works like zip ( ) , but fills the results so that the length of the resulting list is the length of the longest input and fills the list from the left with e.g . None ? There is already an answer using zip_longest from itertools module and the corresponding question is very similar to... | header = [ `` title '' , `` firstname '' , `` lastname '' ] person_1 = [ `` Dr. '' , `` Joe '' , `` Doe '' ] person_2 = [ `` Mary '' , `` Poppins '' ] person_3 = [ `` Smith '' ] > > > dict ( magic_zip ( header , person_1 ) ) { 'title ' : 'Dr . ' , 'lastname ' : 'Doe ' , 'firstname ' : 'Joe ' } > > > dict ( magic_zip ( ... | zip ( ) -like built-in function filling unequal lengths from left with None value |
Python | I 'm running Spark Streaming with two different windows ( on window for training a model with SKLearn and the other for predicting values based on that model ) and I 'm wondering how I can avoid one window ( the `` slow '' training window ) to train a model , without `` blocking '' the `` fast '' prediction window.My s... | conf = SparkConf ( ) conf.setMaster ( `` local [ 4 ] '' ) sc = SparkContext ( conf=conf ) ssc = StreamingContext ( sc , 1 ) stream = ssc.socketTextStream ( `` localhost '' , 7000 ) import Custom_ModelContainer # # # Window 1 # # # # # # predict data based on model computed in window 2 # # # def predict ( time , rdd ) :... | How to avoid one Spark Streaming window blocking another window with both running some native Python code |
Python | Let 's say I want to create a list of ints using Python that consists of the cubes of the numbers 1 through 10 only if the cube is evenly divisible by four.I wrote this working line : My beef with this line of code is that it 's computing the cube of x twice . Is there more pythonic way to write this line ? Or is this ... | cube4 = [ x ** 3 for x in range ( 1 , 11 ) if ( x ** 3 ) % 4 == 0 ] | Is this list comprehension pythonic enough ? |
Python | I am looking for a regex pattern that will match third , fourth , ... occurrence of each character . Look below for clarification : For example I have the following string : I want to replace all the duplicated characters after the second occurrence . The output will be : Some regex patterns that I tried so far : Using... | 111aabbccxccybbzaa1 11-aabbccx -- y -- z -- - | Match and remove duplicated characters : Replace multiple ( 3+ ) non-consecutive occurrences |
Python | I am using Django purely for creating template ( no server ) .Here is the scheme I have : page1.htmlbase.htmlcode_to_make_template.pyThe directory structure looks like this : But when I run code_to_make_template.py I got this message : What 's the right way to do it ? | { % extends `` base.html '' % } { % block 'body ' % } < div class= '' container '' > < img src= '' ./images/ { { filename } } '' style= '' padding-top:100px ; padding-left:100px '' align= '' center '' width= '' 60 % '' heig < /div > { % endblock % } < ! DOCTYPE html > < html > < head > < meta http-equiv= '' content-typ... | How to use Django templating as is without server |
Python | Here 's some data from another question : What I would do first is to add quotes across all words , and then : Is there a smarter way to do this ? | positive negative neutral1 [ marvel , moral , bold , destiny ] [ ] [ view , should ] 2 [ beautiful ] [ complicated , need ] [ ] 3 [ celebrate ] [ crippling , addiction ] [ big ] import astdf = pd.read_clipboard ( sep='\s { 2 , } ' ) df = df.applymap ( ast.literal_eval ) | How do you read in a dataframe with lists using pd.read_clipboard ? |
Python | I strace 'd a simple script using perl and bash.Why does perl need the pseudorandom number generator for such a trivial script ? I would expect opening /dev/urandom only after the first use of random data.Edit : I also tested python and rubyWhy do perl and ruby open it with different modes ? | $ strace perl -e 'echo `` test '' ; ' 2 > & 1 | grep 'random'open ( `` /dev/urandom '' , O_RDONLY ) = 3 $ strace bash 'echo `` test '' ' 2 > & 1 | grep 'random ' $ $ strace python -c 'print `` test '' ' 2 > & 1 | grep random $ $ strace ruby -e 'print `` test\n '' ' 2 > & 1 | grep randomopen ( `` /dev/urandom '' , O_RDO... | why do perl , ruby use /dev/urandom |
Python | I have a list of dictionaries , and I need to get a list of the values from a given key from the dictionary ( all the dictionaries have those same key ) .For example , I have : I need to get 1 , 2 , 3.Of course , I can get it with : But I would like to get a nicer way to do so . | l = [ { `` key '' : 1 , `` Val1 '' : 'val1 from element 1 ' , `` Val2 '' : 'val2 from element 1 ' } , { `` key '' : 2 , `` Val1 '' : 'val1 from element 2 ' , `` Val2 '' : 'val2 from element 2 ' } , { `` key '' : 3 , `` Val1 '' : 'val1 from element 3 ' , `` Val2 '' : 'val2 from element 3 ' } ] v= [ ] for i in l : v.appe... | Get a list of values from a list of dictionaries ? |
Python | I know how to detect if my Python script 's stdout is being redirected ( > ) using sys.stdout.isatty ( ) but is there a way to discover what it 's being redirected to ? For example : Is there a way to discover the name somefile.txt on both Windows and Linux ? | python my.py > somefile.txt | Is there a way to find out the name of the file stdout is redirected to in Python |
Python | I have a dataset with ~300 points and 32 distinct labels and I want to evaluate a LinearSVR model by plotting its learning curve using grid search and LabelKFold validation.The code I have looks like this : My question is how to setup the cv attribute for the grid search and learning curve so that it will break my orig... | import numpy as npfrom sklearn import preprocessingfrom sklearn.svm import LinearSVRfrom sklearn.pipeline import Pipelinefrom sklearn.cross_validation import LabelKFoldfrom sklearn.grid_search import GridSearchCVfrom sklearn.learning_curve import learning_curve ... # get data ( x , y , labels ) ... C_space = np.logspac... | How to nest LabelKFold ? |
Python | Python 's print statement normally seems to print the repr ( ) of its input . Tuples do n't appear to be an exception : But then I stumbled across some strange behavior while messing around with CPython 's internals . In short : if you trick Python 2 into creating a self-referencing tuple , printing it directly behaves... | > > > print ( 1 , 2 , 3 ) ( 1 , 2 , 3 ) > > > print repr ( ( 1 , 2 , 3 ) ) ( 1 , 2 , 3 ) > > > print outer # refer to the link above ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (... | What method does Python 2 use to print tuples ? |
Python | The following code : produces for numpy 1.13.3However , if I change the 127 to a 126 , both return a np.int8 array . And if I change the 127 to a 128 both return a np.int16 array.Questions : Is this expected behaviour ? Why is it different for the two platforms for this one case ? | > > > import numpy as np > > > np.arange ( 2 ) .astype ( np.int8 ) * 127 # On Windowsarray ( [ 0 , 127 ] , dtype=int16 ) # On Linuxarray ( [ 0 , 127 ] , dtype=int8 ) | Multiplying a np.int8 array with 127 yields different numpy array types depending on platform |
Python | My goal is to have one cell in Jupyter notebook displaying multiple interactive widgets . Specifically , I would like to have four slider for cropping an image and then another separate slider for rotating this cropped image . Of course , both plots should be displayed when I run the code . Here is what I have.I can ha... | def image_crop ( a , b , c , d ) : img_slic=frame [ a : b , c : d ] plt.figure ( figsize= ( 8,8 ) ) plt.imshow ( img_slic , cmap='RdBu ' ) return a , b , c , dinteractive_plot = interactive ( image_crop , a = widgets.IntSlider ( min=0 , max=2000 , step=10 , value=500 , description='Vertical_Uppper ' ) , b = widgets.Int... | How to include multiple interactive widgets in the same cell in Jupyter notebook |
Python | I am writing a python wrapper to the Microsoft Dynamics Business Connector .net assembly.This is my code : This is my errors when running pytest : .net decompiler shows : P.S . The stackoverflow grader asks me to add more details : ) What else - obj = clr.AddRefrence works and I can see a Microsoft attribute in obj . B... | `` `` '' Implements wrapper for axapta bussiness connector . `` `` '' import pathlibfrom msl.loadlib import LoadLibraryimport clrDLL_PATH = pathlib.Path ( __file__ ) .parent / 'Microsoft.Dynamics.BusinessConnectorNet.dll'def test_msl_connector ( ) : `` '' '' Get Axapta object via msl-loadlib package . '' '' '' connecto... | Wrapping Microsoft Dynamics Business Connector .net assembly in python |
Python | I try to access the classmethod of a parent from within __init_subclass__ however that does n't seem to work.Suppose the following example code : which produces the following exception : The cls.__mro__ however shows that Foo is a part of it : ( < class '__main__.Bar ' > , < class '__main__.Foo ' > , < class 'object ' ... | class Foo : def __init_subclass__ ( cls ) : print ( 'init ' , cls , cls.__mro__ ) super ( cls ) .foo ( ) @ classmethod def foo ( cls ) : print ( 'foo ' ) class Bar ( Foo ) : pass AttributeError : 'super ' object has no attribute 'foo ' | Using ` super ( ) ` within ` __init_subclass__ ` does n't find parent 's classmethod |
Python | I was a happy man , having his own happy local pip index . One day I 've updated pip client and I 'm not happy anymore : But WHY ? I have SSL enabled on my server and my pip.conf file looks like this : How is 'secure and verifiable'/'insecure and unverifiable ' file defined ? How PIP distinguishes between them ? Finall... | Downloading/unpacking super_packageGetting page https : //my_server/index/super_package/URLs to search for versions for super_package : * https : //my_server/index/super_package/* https : //pypi.python.org/simple/super_package/Analyzing links from page https : //my_server/index/super_package/Skipping https : //my_serve... | In python PIP , how can I make files in my private pip index `` secure and verifiable '' ? |
Python | I have the following dataframe : I need to be able to keep track of when the latest maximum and minimum value occurred within a specific rolling window . For example if I were to use a rolling window period of 5 , then I would need an output like the following : All this shows is , what is the date of the latest maximu... | date value2014-01-20 102014-01-21 122014-01-22 132014-01-23 92014-01-24 72014-01-25 122014-01-26 11 date value rolling_max_date rolling_min_date2014-01-20 10 2014-01-20 2014-01-202014-01-21 12 2014-01-21 2014-01-202014-01-22 13 2014-01-22 2014-01-202014-01-23 9 2014-01-22 2014-01-232014-01-24 7 2014-01-22 2014-01-24201... | Most recent max/min value |
Python | I 've been boggling my head to make this array for some time but having no success doing it in a vectorized way.I need a function that takes in the 2d array size n and produces a 2d array of size ( n , n ) looking like this : ( and can take odd number arguments ) Any suggestions would be much appreciated , thanks ! | n = 6np.array ( [ [ 0,0,0,0,0,0 ] , [ 0,1,1,1,1,0 ] , [ 0,1,2,2,1,0 ] , [ 0,1,2,2,1,0 ] , [ 0,1,1,1,1,0 ] , [ 0,0,0,0,0,0 ] , | Build 2d pyramidal array - Python / NumPy |
Python | I 'm generating some pdfs using ReportLab in Django . I followed and experimented with the answer given to this question , and realised that the double-quotes therein do n't make sense : gives filename constant_-foo_bar-.pdfgives filename constant_foo_bar.pdfWhy is this ? Is it just to do with slug-esque sanitisation f... | response [ 'Content-Disposition ' ] = 'inline ; filename=constant_ '' % s_ % s '' .pdf'\ % ( 'foo ' , 'bar ' ) response [ 'Content-Disposition ' ] = 'inline ; filename=constant_ % s_ % s.pdf ' \ % ( 'foo ' , 'bar ' ) | why are python double-quotes converted to hyphen in filename ? |
Python | Hi I get a strange error message : Property user is corrupt in the datastoreCan you tell me what it means and what I should do ? Here 's the full traceEDIT : Here is my entire model . I 've not changed it for several deployments : EDIT 2 : By changing the variable PAGESIZE I can make the page load for the most recent e... | 2011-05-04 01:35:15.144Property user is corrupt in the datastore : Traceback ( most recent call last ) : File `` /base/python_runtime/python_lib/versions/1/google/appengine/api/datastore.py '' , line 958 , in _FromPb value = datastore_types.FromPropertyPb ( prop ) File `` /base/python_runtime/python_lib/versions/1/goog... | Property user is corrupt in the datastore : |
Python | I was searching for an algorithm to generate prime numbers . I found the following one done by Robert William Hanks . It is very efficient and better than the other algorithms but I can not understand the math behind it.What is the relation between the array of Trues values and the final prime numbers array ? | def primes ( n ) : `` '' '' Returns a list of primes < n `` '' '' lis = [ True ] * n for i in range ( 3 , int ( n**0.5 ) +1,2 ) : if lis [ i ] : lis [ i*i : :2*i ] = [ False ] *int ( ( n-i*i-1 ) / ( 2*i ) +1 ) return [ 2 ] + [ i for i in range ( 3 , n,2 ) if lis [ i ] ] | Prime numbers generator explanation ? |
Python | I know we can overload behavior of instances of a class , e.g . - We can change the result of print s : Can we change the result of print Sample ? | class Sample ( object ) : passs = Sample ( ) print s < __main__.Sample object at 0x026277D0 > print Sample < class '__main__.Sample ' > class Sample ( object ) : def __str__ ( self ) : return `` Instance of Sample '' s = Sample ( ) print sInstance of Sample | Can we overload behavior of class object |
Python | I 've written a script in python to reach the target page where each category has their avaiable item names in a website . My below script can get the product names from most of the links ( generated through roving category links and then subcategory links ) .The script can parse sub-category links revealed upon clicki... | import requestsfrom urllib.parse import urljoinfrom bs4 import BeautifulSouplink = `` https : //www.courts.com.sg/ '' res = requests.get ( link ) soup = BeautifulSoup ( res.text , '' lxml '' ) for item in soup.select ( `` .nav-dropdown li a '' ) : if `` # '' in item.get ( `` href '' ) : continue # kick out invalid link... | Trouble parsing product names out of some links with different depth |
Python | Let 's say you work with a wrapper object : This object implements __iter__ , because it passes any call to it to its member f , which implements it . Case in point : According to the documentation ( https : //docs.python.org/3/library/stdtypes.html # iterator-types ) , IterOrNotIter should thus be iterable.However , t... | class IterOrNotIter : def __init__ ( self ) : self.f = open ( '/tmp/toto.txt ' ) def __getattr__ ( self , item ) : try : return self.__getattribute__ ( item ) except AttributeError : return self.f.__getattribute__ ( item ) > > > x = IterOrNotIter ( ) > > > x.__iter__ ( ) .__next__ ( ) 'Whatever was in /tmp/toto.txt\n '... | How come an object that implements __iter__ is not recognized as iterable ? |
Python | Inspired by this earlier stack overflow question I have been considering how to randomly interleave iterables in python while preserving the order of elements within each iterable . For example : The original question asked to randomly interleave two lists , a and b , and the accepted solution was : However , this solu... | > > > def interleave ( *iterables ) : ... `` Return the source iterables randomly interleaved '' ... < insert magic here > > > > interleave ( xrange ( 1 , 5 ) , xrange ( 5 , 10 ) , xrange ( 10 , 15 ) ) [ 1 , 5 , 10 , 11 , 2 , 6 , 3 , 12 , 4 , 13 , 7 , 14 , 8 , 9 ] > > > c = [ x.pop ( 0 ) for x in random.sample ( [ a ] ... | Interleaving multiple iterables randomly while preserving their order in python |
Python | I have a large array with 1024 entries that have 7 bit values in range ( 14 , 86 ) This means there are multiple range of indices that have the same value.For example , I want to feed this map to a python program that would spew out the following : Some code to groupby mapped value is ready but I am having difficulty c... | consider the index range 741 to 795 . It maps to 14consider the index range 721 to 740 . It maps to 15consider the index range 796 to 815 . It maps to 15 if ( ( index > = 741 ) and ( index < = 795 ) ) return 14 ; if ( ( index > = 721 ) and ( index < = 740 ) ) return 15 ; if ( ( index > = 796 ) and ( index < = 815 ) ) r... | Compressing a sinewave table |
Python | This question is a follow up to my answer in Efficient way to compute the Vandermonde matrix.Here 's the setup : Now , I 'll compute the Vandermonde matrix in two different ways : And , Sanity check : These methods are identical , but their performance is not : So , the first method , despite requiring a transposition ... | x = np.arange ( 5000 ) # an integer arrayN = 4 m1 = ( x ** np.arange ( N ) [ : , None ] ) .T m2 = x [ : , None ] ** np.arange ( N ) np.array_equal ( m1 , m2 ) True % timeit m1 = ( x ** np.arange ( N ) [ : , None ] ) .T42.7 µs ± 271 ns per loop ( mean ± std . dev . of 7 runs , 10000 loops each ) % timeit m2 = x [ : , No... | Broadcasted NumPy arithmetic - why is one method so much more performant ? |
Python | In Python 3I have n't considered corner cases ( exponent < = 0 ) Why do n't we use the above-written code in-place of code computed using Divide and Conquer Technique , this code looks more simple and easy to understand ? Is this code less efficient by any means ? | def power ( base , exponent ) : if exponent == 1 : return base return base * power ( base , exponent - 1 ) | Finding Power Using Recursion |
Python | This is a follow up to this answer to my previous question Fastest approach to read thousands of images into one big numpy array.In chapter 2.3 `` Memory allocation of the ndarray '' , Travis Oliphant writes the following regarding how indexes are accessed in memory for C-ordered numpy arrays . ... to move through comp... | import numpy as npN = 512n = 500a = np.random.randint ( 0,255 , ( N , N ) ) def last_and_second_last ( ) : `` 'Store along the two last indexes '' ' imgs = np.empty ( ( n , N , N ) , dtype='uint16 ' ) for num in range ( n ) : imgs [ num , : , : ] = a return imgsdef second_and_third_last ( ) : `` 'Store along the two fi... | The accessing time of a numpy array is impacted much more by the last index compared to the second last |
Python | I want to maintain a Django model with a unique id for every combination of choices within the model . I would then like to be able to update the model with a new field and not have the previous unique id 's change . The id 's can be a hash or integer or anything.What 's the best way to achieve this ? Given the above e... | class MyModel ( models.Model ) : WINDOW_MIN = 5 WINDOW_MAX = 7 WINDOW_CHOICES = [ ( i , i ) for i in range ( WINDOW_MIN - 1 , WINDOW_MAX - 1 ) ] window = models.PositiveIntegerField ( 'Window ' , editable=True , default=WINDOW_MIN , choices=WINDOW_CHOICES ) is_live = models.BooleanField ( 'Live ' , editable=True , defa... | Using the Django ORM , How can you create a unique hash for all possible combinations |
Python | I 've been working on an R package which interfaces with Python via a simple server script and socket connections . I can test in on my own machine just fine , but I 'd like to test it on a Travis build as well ( I do n't want to go through the effort of setting up a Linux VM ) . To do this I would need a Python instal... | language : rr : - release - develcache : packagessudo : falsematrix : include : - python:2.7 - python:3.6 # Be strict when checking our packagewarnings_are_errors : true # System dependencies for HTTP callingr_binary_packages : - jsonlite - R6 pypath = Sys.which ( 'python ' ) if ( nchar ( pypath ) > 0 ) { py = PythonEn... | Installing both Python and R for a Travis build ? |
Python | I need to write a function that accepts a list of lists representing friends for each person and need to convert it into a dictionary . so an input of [ [ ' A ' , ' B ' ] , [ ' A ' , ' C ' ] , [ ' A ' , 'D ' ] , [ ' B ' , ' A ' ] , [ ' C ' , ' B ' ] , [ ' C ' , 'D ' ] , [ 'D ' , ' B ' ] , [ ' E ' ] ] should return { A ... | [ [ ' A ' , ' B ' ] , [ ' A ' , ' C ' ] , [ ' A ' , 'D ' ] , [ ' B ' , ' A ' ] , [ ' C ' , ' B ' ] , [ ' C ' , 'D ' ] , [ 'D ' , ' B ' ] , [ ' E ' ] ] { A : [ B , C , D ] , B : [ A ] , C : [ B , D ] , D : [ B ] , E : None } s= [ [ ' A ' , ' B ' ] , [ ' A ' , ' C ' ] , [ ' A ' , 'D ' ] , [ ' B ' , ' A ' ] , [ ' C ' , ' ... | Converting list of lists to a dictionary with multiple values for a key |
Python | I was looking at this and this threads , and though my question is not so different , it has a few differences . I have a dataframe full of floats , that I want to replace by strings . Say : To this table I want to replace by several criteria , but only the first replacement works : If I instead do the selection for th... | A B C A 0 1.5 13 B 0.5 100.2 7.3 C 1.3 34 0.01 df [ df < 1 ] = ' N ' # Worksdf [ ( df > 1 ) & ( df < 10 ) ] # = ' L ' # Does n't workdf [ ( df > 10 ) & ( df < 50 ) ] = 'M ' # Does n't workdf [ df > 50 ] = ' H ' # Does n't work ( ( df.applymap ( type ) ==float ) & ( df < 10 ) & ( df > 1 ) ) # Does n't work | Pandas : Selecting and modifying dataframe based on even more complex criteria |
Python | Above , I create a dict with a hash collision , and two slots occupied . How is that getitem handled for the integer 1 ? And how does the indexing manage to resolve the correct value for a complex literal indexing ? Python 2.7.12 / Linux . | > > > one_decimal = Decimal ( ' 1 ' ) > > > one_complex = complex ( 1,0 ) > > > d = { one_decimal : '1D ' , one_complex : '1C ' } > > > len ( d ) 2 > > > map ( hash , d ) [ 1 , 1 ] > > > d [ 1 ] '1D ' > > > d [ 1+0j ] '1C ' | Putting two keys with the same hash into a dict |
Python | Psychology experiments often require you to pseudo-randomize the trial order , so that the trials are apparently random , but you do n't get too many similar trials consecutively ( which could happen with a purely random ordering ) . Let 's say that the visual display on each trial has a colour and a size : And we can ... | display_list = [ ] colours = { 0 : 'red ' , 1 : 'blue ' , 2 : 'green ' , 3 : 'yellow ' } sizes = [ 1 ] * 20 + [ 2 ] * 20 + [ 3 ] * 20 + [ 4 ] * 20 + [ 5 ] * 20 + [ 6 ] * 20for i in range ( 120 ) : display_list.append ( { 'colour ' : colours [ i % 4 ] , 'size ' : sizes [ i ] } ) print ( display_list ) def consecutive_pr... | Sorting algorithm to keep equal values separated |
Python | I have some kind of verbose logic that I 'd like to compact down with some comprehensions.Essentially , I have a dict object that I 'm reading from which has 16 values in it that I 'm concerned with . I 'm getting the keys that I want with the following comprehension : The source dictionary kind of looks like this : I ... | [ `` I % d '' % ( i , ) for i in range ( 16 ) ] { `` I0 '' : [ 0,1,5,2 ] , `` I1 '' : [ 1,3,5,2 ] , `` I2 '' : [ 5,9,10,1 ] , ... } [ { `` I0 '' : 0 , `` I1 '' : 1 , `` I2 '' : 5 , ... } { `` I0 '' : 1 , `` I1 '' : 3 , `` I2 '' : 9 , ... } ... ] | Combined list and dict comprehension |
Python | I 'm trying to make a basic Skype bot using Skype4Py and have encountered a rather serious error . I am working on a 64 bit windows 7 with the 32bit Python 2.7.8. installed , along with the latest version of Skype4Py.My main demand is that the bot has an overview of 5 different Skype chats : four individual chats with ... | class SkypeBot ( object ) : def __init__ ( self ) : self.skype = Skype4Py.Skype ( Events=self ) self.skype.Attach ( ) self.active_chat = find_conference_chat ( ) def MessageStatus ( self , msg , status ) : if status == Skype4Py.cmsReceived : if msg.Chat.Name == self.active_chat.Name : msg.Chat.SendMessage ( respond_to_... | Skype4Py MessageStatus not firing consistently |
Python | In a current benchmark about mongodb drivers , we have noticed a huge difference in performance between python and .Net ( core or framework ) .And the a part of the difference can be explained by this in my opinion.We obtained the following results : We took a look to the memory allocation in C # and we noticed a ping ... | ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━━━┫┃ Ratio Duration/Document ┃ 24.82 ┃ 0.03 ┃ 0.001 ┃┃ Duration ( ms ) ┃ 49 638 ┃ 20 016 ┃ 0.40 ┃┃ Count ┃ 2000 ┃ 671 972 ┃ 336 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━... | How to reach the same performance with the C # mongo driver than PyMongo in python ? |
Python | Given a function f ( ) , a number x and an integer N , I want to compute the List : An obvious way to do this in Python is the following Python code : But I want to know if there is a better or faster , way to do this . | y = [ x , f ( x ) , f ( f ( x ) ) , ... , f ( f ... M times ... f ( f ( x ) ) ] y = [ x ] for i in range ( N-1 ) : y.append ( f ( y [ -1 ] ) ) | Iterated function in Python |
Python | I have a script that consumes command line arguments and I would like to implement two argument-passing schemes , namely : Typing the arguments out at the command line.Storing the argument list in a file , and passing the name of this file to the program via the command line.To that end I am passing the argument fromfi... | from argparse import ArgumentParserparser = ArgumentParser ( fromfile_prefix_chars= ' @ ' ) parser.add_argument ( 'filename ' , nargs= ' ? ' ) parser.add_argument ( ' -- foo ' , nargs= ' ? ' , default=1 ) parser.add_argument ( ' -- bar ' , nargs= ' ? ' , default=1 ) args = parser.parse_args ( ) print ( args ) -- foo2 -... | How can I pass command line arguments contained in a file and retain the name of that file ? |
Python | Before Python-3.3 , I detected that a module was loaded by a custom loader with hasattr ( mod , '__loader__ ' ) .After Python-3.3 , all modules have the __loader__ attribute regardless of being loaded by a custom loader.Python-2.7 , 3.2 : Python-3.3 : How do I detect that a module was loaded by a custom loader ? | > > > import xml > > > hasattr ( xml , '__loader__ ' ) False > > > import xml > > > hasattr ( xml , '__loader__ ' ) True > > > xml.__loader__ < _frozen_importlib.SourceFileLoader object at ... > | Python - How do you detect that a module has been loaded by custom loader ? |
Python | Python has a nice feature that gives the contents of an object , like all of it 's methods and existing variables , called dir ( ) . However when dir is called in a function it only looks at the scope of the function . So then calling dir ( ) in a function has a different value than calling it outside of one . For exam... | dir ( ) > [ '__builtins__ ' , '__doc__ ' , '__loader__ ' , '__name__ ' , '__package__ ' , '__spec__ ' ] def d ( ) : return dir ( ) d ( ) > [ ] | dir inside function |
Python | I have the following custom class : This class does exactly what i want for when i have multiple keys , but does n't do what i want for single keys.Let me demonstrate what my code outputs : But then : I want it to be : Here was my attempt to fix it to act the way i want ( which led to infinite recursion ) : | class MyArray ( OrderedDict ) : def __init__ ( self , *args ) : OrderedDict.__init__ ( self , *args ) def __getitem__ ( self , key ) : if not hasattr ( key , '__iter__ ' ) : return OrderedDict.__getitem__ ( self , key ) return MyArray ( ( k , self [ k ] ) for k in key ) x = MyArray ( ) x [ 0 ] = 3x [ 1 ] = 4x [ 2 ] = 5... | Custom OrderedDict that returns itself |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.