lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I am trying to upload a package on Pypi for linux and windows from github actionswith linux I get this result during windows installation the code for upload is that Any ideas how to upload distributions for linux and windows ? | Binary wheel 'xxx-cp36-cp36m-linux_x86_64.whl ' has an unsupported platform tag 'linux_x86_64 ' . InvalidDistribution : Can not find file ( or expand pattern ) : 'dist/* ' python setup.py sdist bdist_wheel twine upload dist/* -- verbose | Binary wheel ca n't be uploaded on pypi using twine |
Python | I have a column in a dataframe which is filled with booleans and i want to count how many times it changes from True to False . I can do this when I convert the booleans to 1 's and 0 's , then use df.diff and then divide that answer by 2My expected outcome would be The amount of times False came up is 3 | import pandas as pdd = { 'Col1 ' : [ True , True , True , False , False , False , True , True , True , True , False , False , False , True , True , False , False , True , ] } df = pd.DataFrame ( data=d ) print ( df ) 0 True1 True2 True3 False4 False5 False6 True7 True8 True9 True10 False11 False12 False13 True14 True15... | Counting the amount of times a boolean goes from True to False in a column |
Python | I am attempting to write a unit test for a function that calls the open method on a pathlib.Path . I am able to successfully mock the open method without issue , but verifying the function is having the correct behavior is difficult . See the sample code below : When I introspect mock_open and review the _mock_mock_cal... | def test_my_function ( self ) : with patch.object ( Path , 'open ' ) as mock_open : my_function ( *args ) # This function calls Path.open [ call ( mode= ' w ' ) , call ( ) .__enter__ ( ) , call ( ) .__enter__ ( ) .write ( ' < file contents > ' ) , call ( ) .__enter__ ( ) .flush ( ) , call ( ) .__exit__ ( None , None , ... | Mock/Test Calls to Path.open |
Python | I have a setup.py that needs to support both Python 2 and 3.The code currently works and is installable in Python 2.xIf I add the use_2to3 = True clause to my setup.py , then the module can be installed in Python 3 , however , doing a : Causes a failure as one of the tests uses the StringIO class , and the import line ... | python setup.py test from setuptools import setupsetup ( name='myproject ' , version= ' 1.0 ' , description='My Cool project ' , classifiers = [ 'Programming Language : : Python ' , 'Programming Language : : Python : : 3 ' , ] , py_modules= [ 'mymodule ' ] , test_suite='test_mymodule ' , zip_safe=False , use_2to3 = Tru... | Tests not being convered by 2to3 in setup.py ? |
Python | I have a basic many to many relationship of : Song to Playlist with PlaylistMember as the through modelNow I am displaying the songs in the playlist detail view using an inline View that is a subclass of TabularInline : To add multiple sounds I have to click on `` Add another Sound '' , and then find that sound on a po... | class PlaylistMemberInline ( TabularInline ) : model = PlaylistMember raw_id_fields = ( 'Sound ' , ) class PlaylistAdmin ( TranslatableAdmin ) : ... inlines = [ PlaylistMemberInline ] | Is there a django admin widget for adding multiple foreign keys with an inline through_model |
Python | I have to multiply two 2-D matrices , bob and tim , in Numpy Python 3.xbob.shape gives ( 2,4 ) tim.shape gives ( 7,4 ) This piece of code gives a 3-D matrix with a shape of ( 2,7,4 ) It gives the output I want . But , I was wondering if there was a more elegant/faster way to do this in numpy rather than me having to it... | np.array ( [ foo*tim for foo in bob ] ) | 3-D Matrix Multiplication in Numpy |
Python | I am writing a quite large Python application ; the application is actually to a large part a wrapping of several shared libraries written in C and C++ ( Qt ) . I am 'installing ' this without administrator rights , so everything including shared libraries , binary and also Python modules must be in non-standard locati... | # ! /bin/bashexport LD_LIBRARY_PATH /funny/path/lib : $ LD_LIBRARY_PATHexport PYTHONPATH /funn/path/python/lib : $ PYTHONPATH # exec python main.py | Distributing python application |
Python | I know how to secure endpoint in flask , and I want to do the same thing to swagger generated python server stub . I am wondering how I can integrate flask token authentication works for the swagger python server , so the endpoint will be secured . I could easily add token authentication decorator to endpoint in flask ... | from flask import Flask , request , jsonifyfrom flask_restplus import Api , Resourceapp = Flask ( __name__ ) authorizations = { 'apikey ' : { 'type ' : 'apiKey ' , 'in ' : 'header ' , 'name ' : ' X-API-KEY ' } , } api = Api ( app , security = 'apikey ' , authorizations=authorizations ) def token_required ( f ) : @ wrap... | any workaround to add token authorization decorator to endpoint at swagger python server stub |
Python | I 'm building a game using Kivy . I 'm encountering performance issues so I decided to profile the program.I tried to run it by : The application screen stays black . After several seconds , an exception crashes the program : Why is this happening , and how can I profile my Kivy application ? | python -m cProfile main.py Traceback ( most recent call last ) : File `` c : \python27\Lib\runpy.py '' , line 162 , in _run_module_as_main `` __main__ '' , fname , loader , pkg_name ) File `` c : \python27\Lib\runpy.py '' , line 72 , in _run_code exec code in run_globals File `` c : \python27\Lib\cProfile.py '' , line ... | How can I profile a Kivy application ? |
Python | When I run my python 3 program : results in 211^ ( -1 ) .But when I run the calculation in wolfram alpha I get the result I was expecting . I did some test outputs and the variables exp , p and q in the program are all the integer values I used in wolfram alpha.My goal is to derive a private key from a ( weakly ) encry... | exp = 211p = 199q = 337d = ( exp ** ( -1 ) ) % ( ( p - 1 ) * ( q - 1 ) ) | Python modulo result differs from wolfram alpha ? |
Python | I 've got a numpy array . What is the fastest way to compute all the permutations of orderings . What I mean is , given the first element in my array , I want a list of all the elements that sequentially follow it . Then given the second element , a list of all the elements that follow it.So given my list : b , c , & d... | x = np.array ( [ `` a '' , `` b '' , `` c '' , `` d '' ] ) [ [ `` a '' , '' b '' ] , [ `` a '' , '' c '' ] , [ `` a '' , '' d '' ] , [ `` b '' , '' c '' ] , [ `` b '' , '' d '' ] , [ `` c '' , '' d '' ] , ] im = np.vstack ( [ x ] *len ( x ) ) a = np.vstack ( ( [ im ] , [ im.T ] ) ) .Tresults = a [ np.triu_indices ( len... | efficiently compute ordering permutations in numpy array |
Python | I have two base classes , Foo and Bar , and a Worker class which expects objects that behave like Foo . Then I add another class that implements all relevant attributes and methods from Foo but I did n't manage to communicate this successfully to static type checking via mypy . Here 's a small example : Here Worker act... | class MyMeta ( type ) : passclass Bar ( metaclass=MyMeta ) : def bar ( self ) : passclass Foo : def __init__ ( self , x : int ) : self.x = x def foo ( self ) : passclass Worker : def __init__ ( self , obj : Foo ) : self.x = obj.x class FooBar ( Bar ) : `` '' '' Objects of this type are bar and they are foo-ish . '' '' ... | How to implement an interface in a way that is compatible with static type checks ? |
Python | I 'm working on a Django project but I think this is a pure Python unittest question.Normally , when you run tests , exceptions will be caught by the test runner and handled accordingly.For debugging purposes , I want to disable this behavior , i.e . so that : will break into the interactive Python shell on an exceptio... | python -i manage.py test | How can I get Python 's unittest to not catch exceptions ? |
Python | I am trying to convert an expression containing terms with various degrees of a symbolic variable z_s into a polynomial in python using sympy.Poly ( ) so that I can then extract the coefficients using .coeffs ( ) .The expression I have is a high-order polynomial with independent , symbolic variable z_s . For some reaso... | f = -1.29096669270427e-61*z_s**33 + 6.24438995041203e-59*z_s**32 - 6.41125090009095e-57*z_s**31 - 8.30852813320818e-55*z_s**30 + 5.84175807723288e-53*z_s**29 + 1.88577332997761e-50*z_s**28 + 9.46504910106607e-49*z_s**27 - 2.28903644846359e-46*z_s**26 - 4.63321594171589e-44*z_s**25 - 1.78254194888339e-42*z_s**24 + 6.434... | Why does Sympy cut off polynomial terms with small coefficients ? |
Python | I want to create unittests for my command line interfacebuild with the Python prompt-toolkit ( https : //github.com/jonathanslenders/python-prompt-toolkit ) .How can I emulate user interaction with the prompt-toolkit ? Is there a best practice for these unittests ? Example Code : | from os import pathfrom prompt_toolkit import promptdef csv ( ) : csv_path = prompt ( '\nselect csv > ' ) full_path = path.abspath ( csv_path ) return full_path | How to create unittests for python prompt toolkit ? |
Python | This question was already asked on Sublime Forum , but it seems no one can answer it . Maybe you can ? I 've got the same issue on Windows 7 and 8 , Sublime 2.0.1 x86 version : | Traceback ( most recent call last ) : File `` ./sublime_plugin.py '' , line 362 , in run_File `` ./myTestPlugin.py '' , line 8 , in runAttributeError : 'module ' object has no attribute 'argv ' | Why is `` sys.argv '' not available in Sublime API ? |
Python | [ I apologize for the inept title ; I could not come up with anything better . Suggestions for a better title are welcome . ] I want to implement an interface to HDF5 files that supports multiprocess-level concurrency through file-locking . The intended environment for this module is a Linux cluster accessing a shared ... | class LockedH5File ( object ) : def __init__ ( self , path , ... ) : ... with h5py.File ( path , ' r+ ' ) as h5handle : fcntl.flock ( fcntl.LOCK_EX ) yield h5handle # ( method returns ) | How to give with-statement-like functionality to class ? |
Python | I am currently working on a Django website . I would like to figure out how to make a post_save signal that is activated ONLY when I save from Django Admin.Right now , I have made a post_save function . This works for all intents and purposes , but another part of my code uses .save ( ) to update an Integer within the ... | @ receiver ( post_save , sender=Event ) def save_post ( sender , instance , **kwargs ) : if instance.books_read==True : book_organizer.organize_it ( instance ) post_save.connect ( save_post , sender=Event ) | Making Django Signals Specific To Admin Save ONLY |
Python | I have the following Pandas Series : But I want something like this : I want to calculate the percentages based on only the counts in each category of Pclass ( not the whole sum of counts ) . It would be great if thesepercentages are calculated using only the Count column.So far , what I did was I summed up the counts ... | CountPclass Survived 1 0 80 1 1362 0 97 1 873 0 372 1 119 Count PercentagePclass Survived 1 0 80 37.0 1 136 63.02 0 97 52.7 1 87 47.33 0 372 75.8 1 119 24.2 CountPclass 1 2161 2162 1842 1843 4913 491 80 / 216 * 100 = 37.0 % | Get percentages of a column based off of another column but with different categories |
Python | I want to have a `` compass heading '' ( I want to know the angle upon the north ) using a magnetometer . I have seen on several tutorials that first , I need to calibrate it . When I looked up on how to do it I saw graphics comparisons of magnetometer value with and without calibration.Here are the links I used : link... | def save_mag_values ( ) : f = open ( `` magnetometer.csv '' , '' w '' ) for i in range ( 10000 ) : value = sensor.magnetic f.write ( `` , '' .join ( map ( str , value ) ) ) f.write ( `` \n '' ) gnuplot > plot `` magnetometer.csv '' using 1:2 title `` XY '' pointsize 2 pointtype 7 , \ `` magnetometer.csv '' using 1:3 ti... | Calibration of magnetometer does n't give expected results |
Python | I am supposed to add a specific label to my CSV file based off conditions . The CSV file has 10 columns and the third , fourth , and fifth columns are the ones that affect the conditions the most and I add my label on the tenth column . I have code here which ended in an infinite loop : I do not know why it would end i... | import csvimport sysw = open ( sys.argv [ 1 ] , ' w ' ) r = open ( sys.argv [ 1 ] , ' r ' ) reader = csv.reader ( r ) writer = csv.writer ( w ) for row in reader : if row [ 2 ] or row [ 3 ] or row [ 4 ] == ' 0 ' : row [ 9 ] == 'Label ' writer.writerow ( row ) w.close ( ) r.close ( ) w = open ( sys.argv [ 1 ] , ' a ' ) | CSV Writing to File Difficulties |
Python | I installed Django-cms with the djangocms-installer script , and all works fine except that I get a bunch of RemovedInDjango18Warning warnings in the shell every time I start the server , do anything with manage.py , or even do a manage.py tab-autocomplete ( most annoying ) ! So thought I 'd silence the warnings , usin... | # in manage.py , just after ` import os ; import sys ` : import warningswarnings.filterwarnings ( `` ignore '' ) /Users/fran/.virtualenvs/dkde2015/lib/python2.7/site-packages/cms/publisher/manager.py:5 : RemovedInDjango18Warning : ` PublisherManager.get_query_set ` method should be renamed ` get_queryset ` . class Publ... | Ca n't silence warnings that django-cms produces |
Python | I am on Mac OS X 10.8.2When I try to find files with filenames that contain non-ASCII-characters I get no results although I know for sure that they are existing . Take for example the console inputI get no results . But if I try without the umlaut I getSo the file is definitely existing . If I rename the file replacin... | > find */Bärlauch* > find */B*rlauch*images/Bärlauch1.JPG > > > glob.glob ( '*/B*rlauch* ' ) [ 'images/Bärlauch1.JPG ' ] > > > glob.glob ( '*/Bärlauch* ' ) [ ] | Python 's glob module and unix ' find command do n't recognize non-ascii |
Python | I 'm using Python 2.7 and django-nonrel for running Django projects on Google app engine . I 'm using version 1.6 of the Google app engine SDK . I run python manage.py syncdb or python manage.py deploy . After the command completes I get the following message : Why do I get this message and is there any way to fix it ? | Exception AttributeError : `` 'NoneType ' object has no attribute 'mkstemp ' '' in < bound method DatastoreFileStub.__del__ of < google.appengine.api.datastore_file_stub.DatastoreFileStub object at 0x8a2422c > > ignored | Exception AttributeError message when using manage.py in django-nonrel for Google app engine |
Python | I am using this functionMy desired output which I want should beThe output of above function isIts generator expression and I was not able to expand it like I wanted | def convert_tuple ( self , listobj , fields= [ 'start ' , 'end ' , 'user ' ] ) : return [ ( getattr ( obj , field ) for field in fields ) for obj in listobj ] [ ( '2am ' , '5am ' , 'john ' ) , ( '3am ' , '5am ' , 'john1 ' ) , ( '3am ' , '5am ' , 'john2 ' ) ] [ genexp , genexp , genexp ] | Expanding tuples in list comprehension generator |
Python | I often use the idiom ' { var_name } '.format ( **vars ( some_class ) ) .However , when I use a property , I can not use this to get the properties value.Consider this program : Question : Is there a way to make a properties value accessible via **vars ( some_class ) ? | # ! /usr/bin/env pythonclass Foo ( object ) : def __init__ ( self ) : self._bar = None self.baz = 'baz here ' @ property def bar ( self ) : if not self._bar : # calculate some value ... self._bar = 'bar here ' return self._barif __name__ == '__main__ ' : foo = Foo ( ) # works : print ( ' { baz } '.format ( **vars ( foo... | Python : Making a read-only property accessible via **vars ( some_class ) |
Python | I 've been playing around with python for some time and decided to better my generalized understanding of programming languages by writing a custom script handler in python . I have so far successfully implemented a basic memory handler and hooked a memory address ordinate to printing to the screen . My question can be... | f0 ( x , y , z ) : =ax^by^cz # notes : separate addresses from data lest the loop of doom comethclass Interpreter : def __init__ ( self ) : self.memory = { } self.dictionary = { `` mov '' : self.mov , `` put '' : self.put , `` add '' : self.add , `` sub '' : self.sub , `` clr '' : self.clr , `` cpy '' : self.cpy , `` r... | Implementation of functions with very basic scripting |
Python | Given a list of ratings of players , I am required to partition the players ( ie ratings ) into two groups as fairly as possible . The goal is to minimize the difference between the teams ' cumulative rating . There are no constraints as to how I can split the players into the teams ( one team can have 2 players and th... | def partition ( ratings ) : set1 = [ ] set2 = [ ] sum_1 = 0 sum_2 = 0 for n in sorted ( ratings , reverse=True ) : if sum_1 < sum_2 : set1.append ( n ) sum_1 = sum_1 + n else : set2.append ( n ) sum_2 = sum_2 + n return ( set1 , set2 ) | Fair partitioning of elements of a list |
Python | After hours of trying I 've decided to give in and ask SO for help : ) I have two Django 1.6 sites running on Apache2 on Debian 7 . I have one vhost . I want the root domain for the vhost to go to one django site ( example : mydomain.com ) , and a separate alias for the second site ( example : mydomain.com/two ) .I can... | WSGIDaemonProcess test1 python-path=/usr/local/projects/project_one : /usr/local/virtualenvs/project/lib/python2.7/site-packages WSGIScriptAlias /one /usr/local/projects/project_one/project_one/wsgi.py < Location /one > WSGIProcessGroup test1 < /Location > WSGIDaemonProcess test2 python-path=/usr/local/projects/project... | Two separate django sites in WSGI ( root and /two ) |
Python | I wrote a virtual machine language to assembly translator for a computer systems course I 'm taking ( using the nand2tetris curriculum ) . I originally wrote it in Python , but since I 'm learning D , I thought I 'd translate it . D is fairly close to Python syntactically , so it was n't too difficult . I assumed that ... | auto outputfile = File ( `` foo.txt '' , '' w '' ) ; foreach ( str ; my_appender.data ) outputfile.write ( str ) ; auto outputfile = File ( `` foo.txt '' , '' w '' ) ; outputfile.write ( my_appender.data ) ; # ! /usr/bin/pythonimport sysoperations_dict = { `` add '' : '' + '' , `` sub '' : '' - '' , `` and '' : '' & ''... | Python faster than D ? ? IO operations seem to slow D down a lot ... what 's going on ? |
Python | I have for some time gotten pretty bad results using the tool keras , and have n't been suspisous about the tool that much.. But I am beginning to be a bit concerned now . I tried to see whether it could handle a simple XOR problem , and after 30000 epochs it still have n't solved it ... code : Here is part of my resul... | from keras.models import Sequentialfrom keras.layers.core import Dense , Activationfrom keras.optimizers import SGDimport numpy as npnp.random.seed ( 100 ) model = Sequential ( ) model.add ( Dense ( 2 , input_dim=2 ) ) model.add ( Activation ( 'tanh ' ) ) model.add ( Dense ( 1 , input_dim=2 ) ) model.add ( Activation (... | XOR not learned using keras v2.0 |
Python | I have a problem where I need to pass the index of an array to a function which I define inline . The function then gets passed as a parameter to another function which will eventually call it as a callback.The thing is , when the code gets called , the value of the index is all wrong . I eventually solved this by crea... | from __future__ import print_functionimport threadingdef works_as_expected ( ) : for i in range ( 10 ) : run_in_thread ( lambda : print ( 'the number is : { } '.format ( i ) ) ) def not_as_expected ( ) : for i in range ( 10 ) : run_later_in_thread ( lambda : print ( 'the number is : { } '.format ( i ) ) ) def run_in_th... | Odd threading behavior in python |
Python | I have a program with rapid animations which works perfectly under pygame , and for technical reasons , I need to do the same using only matplotlib or an other widespread module.The program structure is roughly : I have no low level matplotlib experience , but I think it is possible to do equivalent things with matplot... | pygame.init ( ) SURF = pygame.display.set_mode ( ( 500 , 500 ) ) arr = pygame.surfarray.pixels2d ( SURF ) # a view for numpy , as a 2D arraywhile ok : # modify some pixels of arr pygame.display.flip ( ) pygame.quit ( ) import pygame , numpy , timepygame.init ( ) size= ( 400,400 ) SURF = pygame.display.set_mode ( size )... | Matplotlib equivalent of pygame flip |
Python | I 'm using Twisted 16.1.1 and python 3.4 . On twisted 's documentation for version 16.1.1 , there is a tutorial that says ` from twisted.spread import pb ' . But when I try to import it it gives an exception . What am I doing wrong ? I 'm follwing this tutorial . This is my code : On /usr/lib64/python3.4/site-packages/... | Traceback ( most recent call last ) : File `` main.py '' , line 10 , in < module > from twisted.spread import pbImportError : can not import name 'pb ' from twisted.internet import reactorfrom twisted.spread import pbclass Echoer ( pb.Root ) : def remote_echo ( self , st ) : print ( 'echoing : ' , st ) return stif __na... | Can not import name 'pb ' |
Python | I know that I should use the access methods . I see in the datetime module that the class datetime inherits from date.I also see that datetime is able to access the members of date , as in __repr__ : I tried to subclass datetime to add some information to it and then write a similar __repr__ function : The debugger com... | class datetime ( date ) : < some other code here ... . > self = date.__new__ ( cls , year , month , day ) self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._tzinfo = tzinfo return self def __repr__ ( self ) : `` '' '' Convert to formal string , for repr ( ) . '' '' '' L ... | Why ca n't I access the private variables of the superclass in Python ? |
Python | I am trying to create a simple program that removes duplicate lines from a file . However , I am stuck . My goal is to ultimately remove all except 1 duplicate line , different from the suggested duplicate . So , I still have that data . I would also like to make it so , it takes in the same filename and outputs the sa... | input_file = `` input.txt '' output_file = `` input.txt '' seen_lines = set ( ) outfile = open ( output_file , `` w '' ) for line in open ( input_file , `` r '' ) : if line not in seen_lines : outfile.write ( line ) seen_lines.add ( line ) outfile.close ( ) I really love christmasKeep the change ya filthy animalPizza i... | How to remove duplicate lines |
Python | I came across a strange issue in Python when using global variables.I have two modules ( files ) : mod1.py and mod2.pymod1 tries to modify the global variable var defined in mod2 . But the var in mod2 and var in mod seems to be two different things . Thus , the result shows that such modification does not work.Here is ... | # code for mod2.pyglobal var var = 1 def fun_of_mod2 ( ) : print var # code for mod1.pyfrom mod2 import var , fun_of_mod2 global var # commenting out this line yields the same resultvar = 2 # I want to modify the value of var defined in mod2fun_of_mod2 ( ) # but it prints : 1 instead of 2 . Modification failed : - ( | Understanding global variable in Python |
Python | I 'm a 'python neophyte ' and trying to grasp the inner workings of the dictionary datatype . Last night I was attempting to use one as a control structure ( i.e . switch statement ) for keyboard input on an openGL program . The problem was that for some reason the dictionary kept evaluating ALL cases ( two in this ins... | def keyboard ( key ) : values = { 110 : discoMode ( ) , 27 : exit ( ) } values.get ( key , default ) ( ) | Python : Using a dictionary as switch not working |
Python | Following M. O'Neill 's great paper , I tried implementing some lazy , infinite versions of the Sieve of Eratosthenes in Python . I was surprised to find that the heap-based version , that the paper claims should run faster , was actually over two times slower for me.The paper contains two examples , one based on a dic... | from itertools import countdef dict_sieve ( ) : yield 2 yield 3 candidates = count ( 5 , 2 ) composites = { 9 : { 3 } } # map composites to their prime factors for candidate in candidates : try : factors = composites.pop ( candidate ) except KeyError : # if it 's not in the dict , it 's prime yield candidate composites... | `` The Genuine Sieve of Eratosthenes '' in Python - why is heapq slower than dict ? |
Python | In Python , the list class seems to be a subclass of collections.abc.Sequence ( which makes totally sense ) : But the list type does n't seem to inherit from Sequence : So , how does this issubclass ( list , Sequence ) is working ? How does it return True ? | from collections.abc import Sequenceissubclass ( list , Sequence ) # returns True dict.__mro__ # returns ( dict , object ) | How is the list class a subclass of collections.abc.Sequence in Python ? |
Python | I have a list in PythonThere are `` groupings '' of consecutive 1 's and 0 's . For my purposes , I am only interested in the consecutive 1 's . Let 's say if there is a solitary 1 , e.g . I would like it to be changed into a 0 . Similarly , if there are only pairs of 1 's , these should become 0s as well . e.g . shoul... | list1 = [ 0 , 0 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 1 ] ... 0 , 0 , 1 , 0 , 0 ... ... . 0 , 0 , 1 , 1 , 0 , 0 ... ... . 0 , 0 , 0 , 0 , 0 , 0 ... counter_list = [ ] for i in list1 : if i == 1 : counter_list = counter_list + 1 if len ( counter_list ) ==1 or len ( counter_list ) ==2 : # now ... | What is a Pythonic way to remove doubled duplicates in a list but allow triplets/greater ? |
Python | I have code with labdas , I have checked each time the function object is created it is different ( not reference to same object ) , but it does n't work as I would expect it . Is there any way how to or I should use a functor to do it even if I have constant data which I insert into lambda ` s body ? outputs : but I n... | pairs = [ ( 'abc ' , 'xyz ' ) , ( '123 ' , '987 ' ) , ( 'abc ' , '987 ' ) ] pairLambs = [ ] for p in pairs : pairLambs.append ( lambda : print ( p ) ) pairLambs [ 0 ] ( ) pairLambs [ 1 ] ( ) pairLambs [ 2 ] ( ) ( 'abc ' , '987 ' ) ( 'abc ' , '987 ' ) ( 'abc ' , '987 ' ) ( 'abc ' , 'xyz ' ) ( '123 ' , '987 ' ) ( 'abc ' ... | Python lambda as constant functor |
Python | I am trying to run a simple logistic regression function . I have 4 columns named x1 , x2 , x3 , and x4 . x4 has a column that has only zeros and ones . So , I am using this as my dependent variable . To predict the dependent variable , I am using the independent variables x1 , x2 , and x3 . Is my syntax off or how can... | import pandas as pdimport statsmodels.formula.api as smfdf = pd.DataFrame ( { 'x1 ' : [ 10 , 11 , 0 , 14 ] , 'x2 ' : [ 12 , 0 , 1 , 24 ] , 'x3 ' : [ 0 , 65 , 3 , 2 ] , 'x4 ' : [ 0 , 0 , 1 , 0 ] } ) model = smf.logit ( formula='x4 ~ x1 + x2 + x3 ' , data=df ) .fit ( ) print ( model ) statsmodels.tools.sm_exceptions.Perf... | Logistic Regression Using statsmodels.api with R syntax in Python |
Python | BackgroundI have a class in python that takes in a list of mutexes . It then sorts that list , and uses __enter__ ( ) and __exit__ ( ) to lock/unlock all of the mutexes in a specific order to prevent deadlocks.The class currently saves us a lot of hassle with potential deadlocks , as we can just invoke it in an RAII st... | self.lock = SuperLock ( list_of_locks ) # Lock all mutexes.with self.lock : # Issue calls to all hardware protected by these locks . self.lock = SuperLock ( list_of_locks ) # Lock all mutexes.with self.lock : # Issue calls to all hardware protected by these locks. # Lock the first half of the mutexes in SuperLock.list_... | Multiple ways to invoke context manager in python |
Python | I 'm working on a project that involves accessing data from a large list that 's kept in memory . Because the list is quite voluminous ( millions of lines ) I keep an eye on how much memory is being used . I use OS X so I keep Activity Monitor open as I create these lists.I 've noticed that the amount of memory used by... | import randomimport sysdef make_table1 ( size ) : list1 = size * [ ( float ( ) , float ( ) , float ( ) ) ] # initialize the list line = ( random.random ( ) , random.random ( ) , random.random ( ) ) for count in xrange ( 0 , size ) : # Now fill it list1 [ count ] = line return list1def make_table2 ( size ) : list1 = siz... | Python list anomalous memory usage |
Python | I have some code that looks like this : cache_info ( ) reports that there were two misses - yet I called the function with the same argument.It actually took some doing , but I figured out that it 's because in one instance I was using the keyword arg , and the other I was using a positional argument.But why ? | from functools import lru_cache @ lru_cache ( ) def get_cheese ( type ) : print ( ' { } ? We\ 're all out . '.format ( type ) ) return Noneget_cheese ( type='cheddar ' ) get_cheese ( 'cheddar ' ) print ( get_cheese.cache_info ( ) ) | Why does my LRU cache miss with the same argument ? |
Python | I have a set of python scripts that I would like to profile with kernprof https : //github.com/rkern/line_profiler but I also want to be able to run it during normal execution without kernprof . What is an elegant way of ignoring the undefined @ profile during execution without kernprof ? Or any other decorator.Example... | @ profile def hello ( ) : print ( 'Testing ' ) hello ( ) kernprof -l test.py python test.py Traceback ( most recent call last ) : File `` test.py '' , line 1 , in < module > @ profile NameError : name 'profile ' is not defined python -m cProfile -o profile_data.pyprof run_cli.pypyprof2calltree -i profile_data.pyprof & ... | How to make an optional decorator in Python |
Python | Using a list of channel IDs such as : channel_ids = [ 'UC6nSFpj9HTCZ5t-N3Ra3-HB ' , 'UC6nSFpjSEBUCZ5t-N3Ra3-HB ' , 'UC6nrst90rsd3Z5t-N3Ra3-HC ' , 'UC6nSFpjd329th0rt-tuTH3-HA ' ] I want to retrieve the 50 most recent video uploads for all those channels using the YouTube Data API v3 , using as few http requests and as l... | from apiclient.discovery import buildyoutube = build ( 'youtube ' , 'v3 ' , developerKey=key ) channel_ids = [ 'UC6nSFpj9HTCZ5t-N3Ra3-HB ' , 'UC6nSFpjSEBUCZ5t-N3Ra3-HB ' , 'UC6nrst90rsd3Z5t-N3Ra3-HC ' , 'UC6nSFpjd329th0rt-tuTH3-HA ' ] videos_by_channel = { } for channel_id in channel_ids : search_response = youtube.sea... | Most efficient way to retrieve recent uploads from multiple channels with YouTube API v3 |
Python | I am trying to add more than one picture on Shopify with the Python API however , I am not able to upload 2 pictures to one product . At this time only one picture is being uploaded . How I can add more than 1 picture to Shopify API ? | import shopify API_KEY = 'dsfsdsdsdsdsad'PASSWORD = 'sadsdasdasdas'shop_url = `` https : // % s : % s @ teststore.myshopify.com/admin '' % ( API_KEY , PASSWORD ) shopify.ShopifyResource.set_site ( shop_url ) path = `` audi.jpg '' path2 = `` audi2.jpg '' new_product = shopify.Product ( ) new_product.title = `` Audi pict... | Shopify API Python Multiple Pictures upload with Python API |
Python | I 'd like to get an NxM matrix where numbers in each row are random samples generated from different normal distributions ( same mean but different standard deviations ) . The following code works : However , this code is not quite efficient as there is a for loop involved . Is there a faster way to do this ? | import numpy as npmean = 0.0 # same meanstds = [ 1.0 , 2.0 , 3.0 ] # different stdsmatrix = np.random.random ( ( 3,10 ) ) for i , std in enumerate ( stds ) : matrix [ i ] = np.random.normal ( mean , std , matrix.shape [ 1 ] ) | Numpy array with different standard deviation per row |
Python | This is my first python program - Requirement : Read a file consisting of { adId UserId } in each line . For each adId , print the number of unique userIds.Here is my code , put together from reading the python docs . Could you give me feedback on how I can write this in more python-ish way ? CODE : Thanks . | import csvadDict = { } reader = csv.reader ( open ( `` some.csv '' ) , delimiter= ' ' ) for row in reader : adId = row [ 0 ] userId = row [ 1 ] if ( adId in adDict ) : adDict [ adId ] .add ( userId ) else : adDict [ adId ] = set ( userId ) for key , value in adDict.items ( ) : print ( key , ' , ' , len ( value ) ) | Is there a better , pythonic way to do this ? |
Python | I am learning Python and have been trying to make a deque . However , I get incorrect output and I am not sure why . My code is as follows : In this code I take in a list , I then want to create a queue with 5 list , 4 of which have a 0 in them at different locations , the result I want is : However , the result I get ... | p = [ 2 , 1 ] , [ 1 , 1 ] init_q= deque ( ) init_q.append ( p ) for i in range ( len ( p ) ) : for j in range ( len ( p [ i ] ) ) : temp = p [ i ] [ j ] p [ i ] [ j ] = 0 init_q.append ( p ) p [ i ] [ j ] = tempwhile init_q : print init_q.pop ( ) ( [ 2 , 1 ] , [ 1 , 1 ] ) ( [ 0 , 1 ] , [ 1 , 1 ] ) ( [ 2 , 0 ] , [ 1 , 1... | Python deque scope ? |
Python | I 'm just wondering if I could easily convert a mixed number ( entered as a number or a string ) into a floating point number or an integer . I 've looked at the fractions module but it seems like it could n't do what I want , or I did n't read well.Just wanted to know if something already exists before I write my own ... | convert ( 1 1/2 ) convert ( ' 1 1/2 ' ) | Is there a Python module where I could easily convert mixed fractions into a float ? |
Python | For every python package you can specify a list of classifiers . Among others there is a Topic classifier , that puts the package in the specified categories that can be browsed on PyPI.For example , numpy has the following topics : Is there a way to search by topic programmatically using pip search or other third-part... | Topic : : Software DevelopmentTopic : : Scientific/Engineering | Searching PyPI by topic |
Python | I ca n't work out why it 's so much faster to parse this file in Python 2.7 than in Python 3.6 . I 've found this pattern both on macOS and Arch-Linux independently . Can others replicate it ? Any explanation ? Warning : the code snippet writes a ~2GB fileTimings : Code for test.py : | $ python2 test.py 5.01580309868 $ python3 test.py 10.664075019994925 import osSEQ_LINE = 'ATCGN'* 80 + '\n'if not os.path.isfile ( 'many_medium.fa ' ) : with open ( 'many_medium.fa ' , ' w ' ) as out_f : for i in range ( 1000000 ) : out_f.write ( ' > { } \n'.format ( i ) ) for _ in range ( 5 ) : out_f.write ( SEQ_LINE ... | Why opening and iterating over file handle over twice as fast in Python 2 vs Python 3 ? |
Python | In particular I would like to call the Postgres levenshtein function.I would like to write the blaze query to return words similar to the word 'similar ' , ie the equivalent of : In Blaze this should look something likebut levenshtein is not defined in any module I am importing on the python side.Where/how do I get a l... | select word from wordtable where levenshtein ( word , 'similar ' ) < 3 ; db.wordtable.word [ levenshtein ( db.wordtable.word , 'similar ' ) < 3 ] | calling SQL functions from Blaze |
Python | I have a pandas DataFrame of the form : What I 'm trying to do is fill in the missing sequence_no per id/start_time combo . For example , the id/start_time pairing of 71 and 2018-10-17 20:12:43+00:00 , is missing sequence_no 114430 . For each added missing sequence_no , I also need average/interpolate the missing value... | id start_time sequence_no value0 71 2018-10-17 20:12:43+00:00 114428 31 71 2018-10-17 20:12:43+00:00 114429 32 71 2018-10-17 20:12:43+00:00 114431 793 71 2019-11-06 00:51:14+00:00 216009 1004 71 2019-11-06 00:51:14+00:00 216011 1505 71 2019-11-06 00:51:14+00:00 216013 1806 92 2019-12-01 00:51:14+00:00 114430 197 92 201... | Slow pandas DataFrame MultiIndex reindex |
Python | I have dozens of functions like 'foo ' , which all have different argument numbers and names . Is there a common way that I can get the return values of these functions and do just a single extra operation like pformat to them ? Yes I can just generate a new function like the following : But then the new function 'wrap... | def foo ( a , b , c = 0 ) : return a+b func = ... # func can be got using getattr by namedef wrapper ( *arg , **kw ) : data = func ( *arg , **kw ) return pprint.pformat ( data ) return wrapper -- - /home/jaime/cache/decorator-3.2.0/src/decorator.py 2010-05-22 23:53:46.000000000 +0800+++ decorator.py 2010-10-28 14:55:11... | Is it possible to modify the return value of a function without defining new function in python ? |
Python | Is it possible in python to directly raise an error in a ternary statement ? As in : Of course it is possible to do this with a simple if/elif/else statement . Thus I 'm asking specifically for a solution using a `` one-line '' ternary statement.Just for clarification : I know that ternary statements are not intended t... | import numpy as npy = np.random.rand ( 200 , 5 , 5 ) y = ( y [ : , None ] if y.ndim == 1 else y if y.ndim == 2 else raise ValueError ( ' ` y ` must be given as a 1D or 2D array . ' ) ) | Raise error in ternary statement in python , without using classic if/else syntax |
Python | I 'm very new to pandas , but I 've been reading about it and how much faster it is when dealing with big data.I managed to create a dataframe , and I now have a pandas dataframe that looks something like this : Columns 0 is author 's id and column 1 is the number of citations this author had on a publication ( -1 mean... | 0 10 1 141 2 -12 3 18173 3 294 3 255 3 26 3 17 3 -18 4 259 4 2410 4 211 4 -112 4 -113 5 2514 5 1 current_author=1hindex=0for index , row in df.iterrows ( ) : if row [ 0 ] ==current_author : if row [ 1 ] > hindex : hindex+=1 else : print `` author `` , current_author , '' has h-index : '' , hindex current_author+=1 hind... | Efficient way to Calculate h-index ( impact/productivity of author publication ) in pandas DataFrame |
Python | I have a list of integers , and I want to generate a list containing a list of all the continuous integers.I have the following which works , but seems like a poor way to do it : I 've seen other questions suggesting that itertools.groupby is an efficient way to do this , but I 'm not familiar with that function and I ... | # I have : full_list = [ 0,1,2,3,10,11,12,59 ] # I want : continuous_integers = [ [ 0,1,2,3 ] , [ 10,11,12 ] , [ 59 ] ] sub_list = [ ] continuous_list = [ ] for x in full_list : if sub_list == [ ] : sub_list.append ( x ) elif x-1 in sub_list : sub_list.append ( x ) else : continuous_list.append ( sub_list ) sub_list = ... | python return lists of continuous integers from list |
Python | I 'm implementing an observer-observable pattern in python : This is the Observable class : and this is an observer : The code works as expected.But I need the Observer to be destroyed ( i.e . when it goes unreferenced , it should remove itself from the list of observers in the Observable object ) .The problem is that ... | class Observable ( object ) : def __init__ ( self , value ) : self.value = value self.observers = [ ] def set ( self , value ) : old = self.value self.value = value self.notifyObservers ( old , self.value ) def get ( self ) : return self.value def addObserver ( self , o ) : self.observers.append ( o ) def removeObserve... | how to properly implement Observer in python when the observer is [ should be ] destroyed |
Python | I want to plot a histogram with binned data . dataPlotFigurehttp : //7xrn7f.com1.z0.glb.clouddn.com/16-3-9/18987922.jpg My aim adjust xtickslines ' positions which represent the extension of bar vertical edges like follows : http : //7xrn7f.com1.z0.glb.clouddn.com/16-3-9/5475187.jpg the xticklabels still locate in the ... | # # x_da : 1,2,3,4,5x_da = np.arange ( 1,1+5*1,1 ) # # bin setting bin_range = [ `` < 1 `` , '' 1 - 2 '' , '' 2 - 3 '' , '' 3 - 4 '' , '' > 4 '' ] # # Counts base on the bin ( Already st ) y_da = np.array ( [ 178,2301,2880,1686,1715 ] ) fig = plt.figure ( figsize= ( 5,3 ) ) ax = plt.subplot ( 111 ) plt.bar ( x_da , y_d... | Cleanest way to set xtickslabel in specific position |
Python | I have a data frameWhere I group the data by ID and want to know the 2 categories per ID with the highest score . I can see two solutions to that : or manually converting it to a list of tuples , sorting the tuples , removing for each ID except for two and then converting back to a dataframe . The first one should be w... | ID CAT SCORE0 0 0 83258041 0 1 1484405 ... ... ... ... 1999980 99999 0 46140371999981 99999 1 1818470 df2 = df.groupby ( 'ID ' ) .apply ( lambda g : g.nlargest ( 2 , columns='SCORE ' ) ) import numpy as npimport pandas as pdimport timedef create_df ( n=10**5 , categories=20 ) : np.random.seed ( 0 ) df = pd.DataFrame ( ... | Why is pandas nlargest slower than mine ? |
Python | I am trying numba in this code snippet With numba @ jit ( ) decorator this code run slower ! without jit : 3.16 secwith jit : 3.81 secjust to help understand better the purpose of this code : | from numba import jitimport numpy as npfrom time import timedb = np.array ( np.random.randint ( 2 , size= ( 400e3 , 4 ) ) , dtype=bool ) out = np.zeros ( ( int ( 400e3 ) , 1 ) ) @ jit ( ) def check_mask ( db , out , mask= [ 1 , 0 , 1 ] ) : for idx , line in enumerate ( db ) : target , vector = line [ 0 ] , line [ 1 : ]... | numba slower for numpy.bitwise_and on boolean arrays |
Python | What is the Pythonic way of summing the product of all combinations in a given list , such as : ( For this example I have taken all the two-element combinations , but it could have been different . ) | [ 1 , 2 , 3 , 4 ] -- > ( 1 * 2 ) + ( 1 * 3 ) + ( 1 * 4 ) + ( 2 * 3 ) + ( 2 * 4 ) + ( 3 * 4 ) = 35 | Sum of product of combinations in a list |
Python | I have the following numpy array : Is there a way to transform this array to a symmetric pandas Dataframe that contains the count of occurences for all possible combinations ? I expect something along the lines of this : | import numpy as nppair_array = np.array ( [ ( 205 , 254 ) , ( 205 , 382 ) , ( 254 , 382 ) , ( 18 , 69 ) , ( 205 , 382 ) , ( 31 , 183 ) , ( 31 , 267 ) , ( 31 , 382 ) , ( 183 , 267 ) , ( 183 , 382 ) ] ) print ( pair_array ) # [ [ 205 254 ] # [ 205 382 ] # [ 254 382 ] # [ 18 69 ] # [ 205 382 ] # [ 31 183 ] # [ 31 267 ] # ... | How can I convert a two column array to a matrix with counts of occurences ? |
Python | I was trying to find a fast way to sort strings in Python and the locale is a non-concern i.e . I just want to sort the array lexically according to the underlying bytes . This is perfect for something like radix sort . Here is my MWEAs you can see it took 6.8 seconds which is almost 10x slower than R 's radix sort bel... | import numpy as npimport timeit # randChar is workaround for MemoryError in mtrand.RandomState.choice # http : //stackoverflow.com/questions/25627161/how-to-solve-memory-error-in-mtrand-randomstate-choicedef randChar ( f , numGrp , N ) : things = [ f % x for x in range ( numGrp ) ] return [ things [ x ] for x in np.ran... | What is the fastest way to sort strings in Python if locale is a non-concern ? |
Python | This is in the Phoenix fork of wxPython.I 'm trying to run a couple threads in the interests of not blocking the GUI.Two of my threads work fine , but the other one never seem to hit its bound result function . I can tell that it 's running , it just does n't seem to properly post the event.Here 's the result function ... | def on_status_result ( self , event ) : if not self.panel.progress_bar.GetRange ( ) : self.panel.progress_bar.SetRange ( event.data.parcel_count ) self.panel.progress_bar.SetValue ( event.data.current_parcel ) self.panel.status_label.SetLabel ( event.data.message ) from wx.lib.pubsub.core import PublisherPUB = Publishe... | wxPython threads blocking |
Python | I 've been using django-pyodbc-azure for a while on Linux , along with pydobc , FreeTDS and unixODBC to connect Django to SQL Server 2014 . I ran into this problem with an application that had been working fine , and am having trouble debugging it . To reproduce the problem , I started a brand new Django app to keep th... | ( azuretest ) [ vagrant @ vagrant azuretest ] $ pip freezeDjango==1.8.6django-pyodbc-azure==1.8.3.0pyodbc==3.0.10 DATABASES = { 'default ' : { 'ENGINE ' : 'sql_server.pyodbc ' , 'HOST ' : 'myserver.com ' , 'PORT ' : '1433 ' , 'NAME ' : 'my_db ' , 'USER ' : 'my_db_user ' , 'PASSWORD ' : 'mypw ' , 'AUTOCOMMIT ' : True , ... | django-pyodbc-azure rollback error with previously working configuration - line 389 |
Python | I have a hover text that contains a long line ( about 200 characters ) . The problem is that it becomes a long rectangle through the whole figure and it is not possible to see the complete text because it cuts.My data is in a dataframe . I am plotting x and y and just adding a z variable that contains description in th... | fig = make_subplots ( rows=2 , cols=1 , column_widths= [ 1 ] , subplot_titles= [ `` A '' , `` B '' ] ) fig.add_trace ( go.Scatter ( x=df.varA , y=df.varB , hovertext = df.varC , marker=dict ( color='darkblue ' ) , mode = 'markers ' ) , row=1 , col=1 ) fig.add_trace ( go.Scatter ( x=df.varA , y=df.varB , hovertext = df.... | How to break a long line in a hover text Plotly ? |
Python | This code prints a false warning once per year , in the night of the clock shift ( central European summer time to central European time ) : How to make this code work even during this yearly one hour clock shift ? UpdateI care only for the age , not the datetime . | import osimport datetimenow = datetime.datetime.now ( ) age = now - datetime.datetime.fromtimestamp ( os.path.getmtime ( file_name ) ) if ( age.seconds + age.days * 24 * 3600 ) < -180 : print ( 'WARN : file has timestap from future ? : % s ' % age ) | getmtime ( ) vs datetime.now ( ) : |
Python | I have a number of series in a pandas dataframe representing rates observed yearly . For an experiment , I want some of these series ' rates to converge towards one of the other series ' rate in the last observed year.For example , say I have this data , and I decide column a is a meaningful target for column b to appr... | rate a b year 2006 0.393620 0.260998 2007 0.408620 0.2605272008 0.396732 0.257396 2009 0.418029 0.249123 2010 0.414246 0.253526 2011 0.415873 0.256586 2012 0.414616 0.253865 2013 0.408332 0.257504 2014 0.401821 0.259208 | numpy / scipy : Making one series converge towards another after a period of time |
Python | I hawe two DataFrame : Need to merge df1 and df2 to obtain the following results : | df1 = pd.DataFrame ( { 'date ' : [ '2017-01-01 ' , '2017-01-02 ' , '2017-01-03 ' , '2017-01-04 ' , '2017-01-05 ' ] , 'value ' : [ 1,1,1,1,1 ] } ) df2 = pd.DataFrame ( { 'date ' : [ '2017-01-04 ' , '2017-01-05 ' , '2017-01-06 ' , '2017-01-07 ' , '2017-01-08 ' ] , 'value ' : [ 2,2,2,2,2 ] } ) date value date value 2017-0... | Pandas dataframe merge with update data |
Python | For me all of the three works the same way , but just to confirm , do they provide anything different ? | > > from nltk.stem import WordNetLemmatizer as lm1 > > from nltk import WordNetLemmatizer as lm2 > > from nltk.stem.wordnet import WordNetLemmatizer as lm3 | Why are there different Lemmatizers in NLTK library ? |
Python | I am sorry if this is too easy but I ca n't figure out how to build this dictionary.I have a string for exampleand I want a dictionary with all palindromes pointing to a list of the following not-palindromes , soI found out that I can check if a word is a palindrome withand I can also split a string into words withbut ... | `` Bob and Anna are meeting at noon '' { `` Bob '' : [ `` and '' ] , `` Anna '' : [ `` are '' , `` meeting '' , `` at '' ] , `` noon '' : [ ] } word.lower ( ) == word.lower ( ) [ : :-1 ] string.split ( ) | dictionary with palindromes to non palindromes ? |
Python | I crawl a table from a web link and would like to rebuild a table by removing all script tags . Here are the source codes.How can I remove all different script tags ? Take the follow cell as an exampple , which includes the tag a , br and td.My expected result is : | response = requests.get ( url ) soup = BeautifulSoup ( response.text ) table = soup.find ( 'table ' ) for row in table.find_all ( 'tr ' ) : for col in row.find_all ( 'td ' ) : # remove all different script tags # col.replace_with ( `` ) # col.decompose ( ) # col.extract ( ) col = col.contents < td > < a href= '' http :... | How can I remove all different script tags in BeautifulSoup ? |
Python | I 've have a simple means to a daemon via a double fork : Or alternatively , this is what I had before , but I suspect that it 's not correct : I 'd like to get back the process id of the daemon in the grandparent process that it gets disconnected from . Is this possible while still using os.fork ( ) and os.execvp ( ) ... | try : child = os.fork ( ) if child > 0 : sys.exit ( 0 ) except OSError : print ( `` fork 1 failed '' ) sys.exit ( 1 ) try : child = os.fork ( ) if child > 0 : sys.exit ( 0 ) except OSError : print ( `` fork 2 failed '' ) sys.exit ( 1 ) os.execvp ( args [ 0 ] , args ) # what the daemon 's supposed to be doing child = os... | How to to get the pid of a daemon created by a double fork ? |
Python | Historically I have always used the following for reading files in python : Is this still the recommend approach ? Are there any drawbacks to using the following : Most of the references I found are using the with keyword for opening files for the convenience of not having to explicitly close the file . Is this applica... | with open ( `` file '' , `` r '' ) as f : for line in f : # do thing to line from pathlib import Pathpath = Path ( `` file '' ) for line in path.open ( ) : # do thing to line | Recommended way of closing files using pathlib module ? |
Python | Suppose you have : Is there a built in function that returns the most frequent element ? | arr = np.array ( [ 1,2,1,3,3,4 ] ) | Is there a `` freq '' function in numpy/python ? |
Python | When class is inherited from nothing , I have an object of instance type.However , when I have the same class inheriting from an object , the created object is type of A . What is the logic behind this ? Does this mean every class should inherit from object ? | > > > class A ( ) : pass ; > > > a = A ( ) > > > type ( a ) < type 'instance ' > > > > type ( a ) is AFalse > > > type ( A ) < type 'classobj ' > > > > class A ( object ) : pass ; > > > a = A ( ) > > > type ( a ) < class '__main__.A ' > > > > type ( a ) is ATrue > > > type ( A ) < type 'type ' > | Why does inheriting from object make a difference in Python ? |
Python | I made a function to clean up any HTML code/tags from strings in my dataframe . The function takes every value from the data frame , cleans it with the remove_html function , and returns a clean df . After converting the data frame to string values and cleaning it up I 'm attempting to convert where possible the values... | def clean_df ( df ) : df = df.astype ( str ) list_of_columns = list ( df.columns ) for col in list_of_columns : column = [ ] for row in list ( df [ col ] ) : column.append ( remove_html ( row ) ) try : return int ( row ) except ValueError : pass del df [ col ] df [ col ] = column return df | Issues with try/except , attempting to convert strings to integers in pandas data frame where possible |
Python | When I calculate third order moments of an matrix X with N rows and n columns , I usually use einsum : This works usually fine , but now I am working with bigger values , namely n = 120 and N = 100000 , and einsum returns the following error : ValueError : iterator is too largeThe alternative of doing 3 nested loops is... | M3 = sp.einsum ( 'ij , ik , il- > jkl ' , X , X , X ) /N | Alternatives to numpy einsum |
Python | I have a website server based on python ( cherrypy ) , and i need some help . I 'm sorry in advance if this question is too basic . I do n't have a vast of experience in this area so far.My main page is on http : //host:9090/home/static/index.html.I want to rewrite the address of above , and define the following addres... | cherrypy.config.update ( { 'server.socket_port ' : 9090 , 'server.socket_host ' : ' 0.0.0.0 ' } ) conf = { '/ ' : { 'tools.sessions.on ' : True , 'tools.staticdir.root ' : os.path.abspath ( os.getcwd ( ) ) } , '/static ' : { 'tools.staticdir.on ' : True , 'tools.staticdir.dir ' : './static/html ' } , '/js ' : { 'tools.... | Static URL in cherrypy |
Python | This is my instruction set simulator Python script : The file ass-2.asm contains the assembly language instructions to run : The output I expect is : The output and error I receive is : The problem appears to be in the runm function.I think 2 numbers should be loaded to a register before the function is called and they... | MEM_SIZE=100 ; reg= { ' a':0 , ' b':0 , ' c':0 , 'd':0 , ' e':0 , ' f':0 , 'sp':0 , 'acc':0 , 'pc':0 , 'ivec':0 , 'int':0 , 'timer':0 , 'halt ' : False } ; memory= [ 0 ] *MEM_SIZE ; def mov ( opr ) : reg [ opr [ 0 ] ] =reg [ opr [ 1 ] ] ; reg [ 'pc ' ] =reg [ 'pc ' ] +1 ; def movv ( opr ) : reg [ opr [ 0 ] ] =int ( opr... | Instruction set simulator written in Python fails |
Python | In Python , I have a string which is a comma separated list of values . e.g . ' 5,2,7,8,3,4 ' I need to add a new value onto the end and remove the first value , e.g . ' 5,22,7,814,3,4 ' - > '22,7,814,3,4,1'Currently , I do this as follows : This runs millions of times in my code and I 've identified it as a bottleneck... | mystr = ' 5,22,7,814,3,4'latestValue= ' 1'mylist = mystr.split ( ' , ' ) mystr = `` for i in range ( len ( mylist ) -1 ) : if i==0 : mystr += mylist [ i+1 ] if i > 0 : mystr += ' , '+mylist [ i+1 ] mystr += ' , '+latestValue | What is the most efficient way to concatenate two strings and remove everything before the first ' , ' in Python ? |
Python | What is the difference between Python class attributes and Java static attributes ? For example , in Pythonin JavaIn Python , a static attribute can be accessed using a reference to an instance ? | class Example : attribute = 3 public class Example { private static int attribute ; } | Static attributes ( Python vs Java ) |
Python | I 'm trying to create a live plot which updates as more data is available.The above code works . However , I 'm unable to interact with the window generated by plt.show ( ) How can I plot live data while still being able to interact with the plot window ? | import os , sysimport matplotlib.pyplot as pltimport timeimport randomdef live_plot ( ) : fig = plt.figure ( ) ax = fig.add_subplot ( 111 ) ax.set_xlabel ( 'Time ( s ) ' ) ax.set_ylabel ( 'Utilization ( % ) ' ) ax.set_ylim ( [ 0 , 100 ] ) ax.set_xlim ( left=0.0 ) plt.ion ( ) plt.show ( ) start_time = time.time ( ) trac... | Interacting with live matplotlib plot |
Python | I am going through a link about generators that someone posted . In the beginning he compares the two functions below . On his setup he showed a speed increase of 5 % with the generator . I 'm running windows XP , python 3.1.1 , and can not seem to duplicate the results . I keep showing the `` old way '' ( logs1 ) as b... | def logs1 ( ) : wwwlog = open ( `` big-access-log '' ) total = 0 for line in wwwlog : bytestr = line.rsplit ( None,1 ) [ 1 ] if bytestr ! = '- ' : total += int ( bytestr ) return totaldef logs2 ( ) : wwwlog = open ( `` big-access-log '' ) bytecolumn = ( line.rsplit ( None,1 ) [ 1 ] for line in wwwlog ) getbytes = ( int... | Generator speed in python 3 |
Python | I would like to have a few different versions of the same language in Django , customized for different countries ( e.g . locale/en , locale/en_CA , locale/en_US , etc. ) . If there is no language for specific country I would expect to use the default language version ( locale/en ) ) .Then in the settings file for each... | LANGUAGE_CODE = 'en'LANGUAGES = ( ( 'en ' , ugettext ( 'English ' ) ) , ) | How to maintain different country versions of same language in Django ? |
Python | I am looking for a way to automatically define neighbourhoods in cities as polygons on a graph . My definition of a neighbourhood has two parts : A block : An area inclosed between a number of streets , where the number of streets ( edges ) and intersections ( nodes ) is a minimum of three ( a triangle ) .A neighbourho... | import osmnx as oximport networkx as nximport matplotlib.pyplot as pltG = ox.graph_from_address ( 'Nørrebrogade 20 , Copenhagen Municipality ' , network_type='all ' , distance=500 ) def plot_cliques ( graph , number_of_nodes , degree ) : ug = ox.save_load.get_undirected ( graph ) cliques = nx.find_cliques ( ug ) clique... | Finding neighbourhoods ( cliques ) in street data ( a graph ) |
Python | I have a two column numpy array . I want to go through each row of the 2nd column , and take the difference between each set of 2 numbers ( 9.6-0 , 19.13-9.6 , etc ) . If the difference is > 15 , I want to insert a row of 0s for both columns . I really only need to end up with values in the first column ( I only need t... | [ [ 0.00 0.00 ] [ 1.85 9.60 ] [ 2.73 19.13 ] [ 0.30 28.70 ] [ 2.64 38.25 ] [ 2.29 47.77 ] [ 2.01 57.28 ] [ 2.61 66.82 ] [ 2.20 76.33 ] [ 2.49 85.85 ] [ 2.55 104.90 ] [ 2.65 114.47 ] [ 1.79 123.98 ] [ 2.86 133.55 ] ] [ [ 0.00 0.00 ] [ 1.85 9.60 ] [ 2.73 19.13 ] [ 0.30 28.70 ] [ 2.64 38.25 ] [ 2.29 47.77 ] [ 2.01 57.28 ]... | Inserting rows of zeros at specific places along the rows of a NumPy array |
Python | How can I remove the output buffering from Sublime Text 3 when I build a Python 3 script ? I would like real-time output.I am using Sublime Text 3 with the Anaconda plugin , Python 3.6 and Linux Mint 18 . When I run a simple script using control-b : I get an instant output in a separate window called 'Build output ' . ... | print ( 'hello ' ) from time import sleepcount = 0print ( 'starting ' ) while True : print ( ' { } hello'.format ( count ) ) count += 1 sleep ( 0.5 ) { `` shell_cmd '' : `` /usr/bin/env python3 -u $ { file } '' , `` selector '' : `` source.python '' , `` file_regex '' : `` ^ ( ... * ? ) : ( [ 0-9 ] * ) : ? ( [ 0-9 ] * ... | How to remove output buffering when running Python in Sublime Text 3 |
Python | In Python ( 2.7 ) I want to create a class of rational numbers which mimics the behavior of the Fraction class ( in module fractions ) but overrides the __repr__ method to match the result of __str__ . The original idea was only for my own tinkering , and just in order to have IDLE output look friendlier . But now I am... | class Q ( Fraction ) : def __repr__ ( self ) : return str ( self ) > > > Q ( 1,2 ) 1/2 > > > Q ( 1,2 ) + Q ( 1,3 ) Fraction ( 5 , 6 ) | Python : Can I have a subclass return instances of its own type for operators defined in a superclass ? |
Python | I got confused about the following behavior . When I have a dataframe like this : which looks as follows : I receive the expected error TypeError : can not do slice indexing on with these indexers [ 3 ] of type 'int'when I try the following slice using .loc : It is expected as I pass an integer as an index and not one ... | import pandas as pdimport numpy as npdf = pd.DataFrame ( np.random.randn ( 6 , 4 ) , columns=list ( 'ABCD ' ) , index=list ( 'bcdefg ' ) ) A B C Db -0.907325 0.211740 0.150066 -0.240011c -0.307543 0.691359 -0.179995 -0.334836d 1.280978 0.469956 -0.912541 0.487357e 1.447153 -0.087224 -0.176256 1.319822f 0.660994 -0.2891... | Why does .loc behave differently depending on whether values are printed or assigned ? |
Python | I am trying to install django-oauth2-provider in Django . After installing and configuring settings.py , during migrations , I am getting the error like : django.core.exceptions.AppRegistryNotReady : Apps are n't loaded yet.settings.pyError Traceback : | INSTALLED_APPS = [ 'django.contrib.admin ' , 'django.contrib.auth ' , 'django.contrib.contenttypes ' , 'django.contrib.sessions ' , 'django.contrib.messages ' , 'django.contrib.staticfiles ' , 'rest_framework ' , 'hello_api ' , 'rest_framework.authtoken ' , 'provider ' , 'provider.oauth2 ' , ] MIDDLEWARE = [ 'django.mi... | Getting error : django.core.exceptions.AppRegistryNotReady : Apps are n't loaded yet while installing oauth2 provider in django rest framework |
Python | So here 's my dilema ... I 'm writing a script that reads all .png files from a folder and then converts them to a number of different dimensions which I have specified in a list . Everything works as it should except it quits after handling one image . Here is my code : The following will be returned if the target fol... | sizeFormats = [ `` 1024x1024 '' , `` 114x114 '' , `` 40x40 '' , `` 58x58 '' , `` 60x60 '' , `` 640x1136 '' , `` 640x960 '' ] def resizeImages ( ) : widthList = [ ] heightList = [ ] resizedHeight = 0resizedWidth = 0 # targetPath is the path to the folder that contains the imagesfolderToResizeContents = os.listdir ( targ... | How to loop through one element of a zip ( ) function twice - Python |
Python | In models.py I have : In my app both serve.py and models.py call : Is that double import going to instantiate the db twice and potentially cause a problem ? | ... db = SQLAlchemy ( app ) class User ( db.Document ) : ... from models import User | In Python , importing twice with class instantiation ? |
Python | At first glance I liked very much the `` Batches '' feature in Celery because I need to group an amount of IDs before calling an API ( otherwise I may be kicked out ) .Unfortunately , when testing a little bit , batch tasks do n't seem to play well with the rest of the Canvas primitives , in this case , chains . For ex... | @ a.task ( base=Batches , flush_every=10 , flush_interval=5 ) def get_price ( requests ) : for request in requests : a.backend.mark_as_done ( request.id , 42 , request=request ) print `` filter_by_price `` + str ( [ r.args [ 0 ] for r in requests ] ) @ a.taskdef completed ( ) : print ( `` complete '' ) chain ( get_pric... | Celery chain not working with batches |
Python | Let 's say I have 2 stringsandto make these strings as similar as possible , given that I can only remove characters I shoulddelete the last C from the first stringdelete the last A and the last B from the second string , so that they becomeWhat would be an efficient algorithm to find out which characters to remove fro... | AAABBBCCCCC AAAABBBBCCCC AAABBBCCCC | making two strings into one |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.