lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Can someone explain why inheriting from unparameterized and parameterized Callable : when passed to mypy raises errors for both Foo and Bar : | from typing import Callablefrom typing import NoReturnfrom typing import TypeVarT = TypeVar ( 'T ' , str , int ) C = Callable [ [ T ] , NoReturn ] class Foo ( Callable ) : def __call__ ( self , t : T ) : passclass Bar ( C ) : def __call__ ( self , t : T ) : pass tmp.py:13 : error : Invalid base classtmp.py:19 : error :... | Callable is invalid base class ? |
Python | I have this code ( main function in my c++ python module ) : I have been getting warningI 'd like to migrate to numpy api 1.7 : How should I modify my function to replicate result in new version of c-api ? Can you direct me to any example ? | static PyObject* FMM ( PyObject* self , PyObject* args ) { PyObject *model_obj ; PyObject *time_obj ; PyObject *accepted_obj ; PyObject *lat_obj ; PyObject *lon_obj ; PyObject *h_obj ; int N ; if ( ! PyArg_ParseTuple ( args , `` OOOOOOi '' , & model_obj , & time_obj , & accepted_obj , & lat_obj , & lon_obj , & h_obj , ... | Migrating to numpy api 1.7 |
Python | When we have a 1D numpy array , we can sort it the following way : Note : I know I can do this using np.sort ; Obviously , I need the sorting indices for a different array - this is just a simple example . Now we can continue to my actual question..I tried to apply the same approach for a 2D array : This result looks g... | > > > temp = np.random.randint ( 1,10 , 10 ) > > > temparray ( [ 5 , 1 , 1 , 9 , 5 , 2 , 8 , 7 , 3 , 9 ] ) > > > sort_inds = np.argsort ( temp ) > > > sort_indsarray ( [ 1 , 2 , 5 , 8 , 0 , 4 , 7 , 6 , 3 , 9 ] , dtype=int64 ) > > > temp [ sort_inds ] array ( [ 1 , 1 , 2 , 3 , 5 , 5 , 7 , 8 , 9 , 9 ] ) > > > d = np.rand... | Sorting 2D numpy array using indices returned from np.argsort ( ) |
Python | I 'm working on a non-bare repository with pygit2This is successful , but when I perform a git status , I got this : And after a git reset -- hard , everything is fixed.Is there a way to update correctly the index with pygit ? | index = repo.indexindex.read ( ) # write in test/test.txtindex.add ( 'test/test.txt ' ) treeid = index.write_tree ( ) repo.create_commit ( 'HEAD ' , author , committer , 'test commit ' , treeid , [ repo.head.oid ] ) # On branch master # Changes to be committed : # ( use `` git reset HEAD < file > ... '' to unstage ) # ... | Untracked dirs on commit with pygit2 |
Python | The full error is : The full error log is : I get this error when I build the program with pyinstaller -F main.py The program works perfectly fine when I run the code in Visual Studio Code.I tried installing tinycss2 with pip install But it was already installed.My project imports are : | FileNotFoundError : [ Errno 2 ] No such file or directory : ' C : \\Users\\grossj\\AppData\\Local\\Temp\\_MEI143642\\tinycss2\\VERSION ' [ 21148 ] Failed to execute script main Traceback ( most recent call last ) : File `` main.py '' , line 11 , in < module > File `` < frozen importlib._bootstrap > '' , line 983 , in _... | FileNotFoundError : [ Errno 2 ] No such file or directory : 'tinycss2\\VERSION ' |
Python | I have a function that receives some arguments , plus some optional arguments . In it , the action taken is dependent upon whether the optional argument c was filled : If c is not passed , then this works fine . However , in my context , if c is passed , it will always be a numpy array . And comparing numpy arrays to N... | def func ( a , b , c = None ) : doStuff ( ) if c ! = None : doOtherStuff ( ) FutureWarning : comparison to ` None ` will result in an elementwise object comparison in the future . | FutureWarning when comparing a NumPy object to `` None '' |
Python | I have an N-dimensional array . I want to expand it to an ( N+1 ) -dimensional array by putting the values of the final dimension in the diagonal.For example , using explicit looping : which is a 5×3×3 array.My actual arrays are large and I would like to avoid explicit looping ( hiding the looping in map instead of a l... | In [ 197 ] : M = arange ( 5*3 ) .reshape ( 5 , 3 ) In [ 198 ] : numpy.dstack ( [ numpy.diag ( M [ i , : ] ) for i in range ( M.shape [ 0 ] ) ] ) .TOut [ 198 ] : array ( [ [ [ 0 , 0 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 0 , 2 ] ] , [ [ 3 , 0 , 0 ] , [ 0 , 4 , 0 ] , [ 0 , 0 , 5 ] ] , [ [ 6 , 0 , 0 ] , [ 0 , 7 , 0 ] , [ 0 , 0 , 8... | Construct ( N+1 ) -dimensional diagonal matrix from values in N-dimensional array |
Python | I just came across this idiom in some open-source Python , and I choked on my drink.Rather than : or even : the code read : I can see this is the same result , but is this a typical idiom in Python ? If so , is it some performance hack that runs fast ? Or is it just a once-off that needs a code review ? | if isUp : return `` Up '' else : return `` Down '' return `` Up '' if isUp else `` Down '' return isUp and `` Up '' or `` Down '' | Is this idiom pythonic ? ( someBool and `` True Result '' or `` False Result '' ) |
Python | [ Edit : Read accepted answer first . The long investigation below stems from a subtle blunder in the timing measurement . ] I often need to process extremely large ( 100GB+ ) text/CSV-like files containing highly redundant data that can not practically be stored on disk uncompressed . I rely heavily on external compre... | # ! /usr/bin/env python3from shlex import quotefrom subprocess import Popen , PIPEfrom time import perf_counterBYTE_COUNT = 3_000_000_000UNQUOTED_HEAD_CMD = [ `` head '' , `` -c '' , str ( BYTE_COUNT ) , `` /dev/zero '' ] UNQUOTED_GREP_CMD = [ `` grep '' , `` Arbitrary string which will not be found . `` ] QUOTED_SHELL... | Achieving shell-like pipeline performance in Python |
Python | Possible Duplicate : Python FAQ : “ How fast are exceptions ? ” I remember reading that Python implements a `` Better to seek forgiveness than to ask permission '' philosophy with regards to exceptions . According to the author , this meant Python code should use a lot of try - except clauses , rather than trying to de... | try : fb_social_auth = UserSocialAuth.objects.get ( user=self , provider='facebook ' ) user_dict [ 'facebook_id ' ] = fb_social_auth.uidexcept ObjectDoesNotExist : user_dict [ 'facebook_id ' ] = Nonetry : fs_social_auth = UserSocialAuth.objects.get ( user=self , provider='foursquare ' ) user_dict [ 'foursquare_id ' ] =... | Python -- efficiency of caught exceptions |
Python | In GTK2 , I enjoyed building a gui in the interpreter ( ipython or plain python ) `` on the fly '' and seeing the changes in real time like this : Which will result in showing a window to which I could add objects.I 'm changing to Gtk3 in part because it is the future and in part because I sometimes use Glade which now... | > > > import gtk > > > win = gtk.Window ( ) > > > win.connect ( 'delete-event ' , gtk.main_quit ) 10L > > > win.show_all ( ) > > > from gi.repository import Gtk > > > win = Gtk.Window ( ) > > > win.connect ( 'delete-event ' , Gtk.main_quit ) 13L > > > win.show_all ( ) > > > Gtk.main ( ) > > > win.show_now ( ) | Window does n't show in python interpreter in GTK3 without Gtk.main ( ) |
Python | I am presented with a list made entirely of tuples , such as : How can I split lst into as many lists as there are colours ? In this case , 3 listsI just need to be able to work with these lists later , so I do n't want to just output them to screen . Details about the listI know that every element of lst is strictly a... | lst = [ ( `` hello '' , `` Blue '' ) , ( `` hi '' , `` Red '' ) , ( `` hey '' , `` Blue '' ) , ( `` yo '' , `` Green '' ) ] [ ( `` hello '' , `` Blue '' ) , ( `` hey '' , `` Blue '' ) ] [ ( `` hi '' , `` Red '' ) ] [ ( `` yo '' , `` Green '' ) ] | Splitting a list of tuples to several lists by the same tuple items |
Python | I have the following code.The 'do something ' is complicated to explain but I replaced it with the affectation n = p.How can I write this explicitly ? More specifically , if k is in the set { p*K , ... , ( p+1 ) *K-1 } for p = 0 to N , then do something . How can I do it in a code ? | for k in range ( ( N + 1 ) * K ) : if k > = 0 and k < = K-1 : # do something # n = 0 elif k > = K and k < = 2*K-1 : # do something # n = 1 elif k > = 2*K and k < = 3*K-1 : # do something # n = 2 ... ... | How to write this algorithm in a python code ? |
Python | What is the best way to test the script myscript ? From SO research , it seems the only answer I 've found is to write a test in tests called test_myscript and use something likein my test case to run the script and then test the results . Is there a better way ? Or any other suggestions for different ways ? And should... | myproject/ bin/ myscript mypackage/ __init__.py core.py tests/ __init__.py test_mypackage.py setup.py import subprocessprocess = subprocess.Popen ( 'myscript arg1 arg2 ' ) print process.communicate ( ) | Testing python package bin scripts best practice |
Python | I have a dataframe with monthly records for different IDs , and I need to do some analysis only on the IDs that have multiple months of records.How would I filter out the rows of ID that only appear once and keep those with multiple rows and get a result likeI 've looked at some other pages that mention using something... | ID Month Metric1 Metric21 2018-01-01 4 3 1 2018-02-01 3 22 2018-02-01 1 53 2018-01-01 4 23 2018-02-01 6 34 2018-01-01 3 1 ID Month Metric1 Metric21 2018-01-01 4 3 1 2018-02-01 3 23 2018-01-01 4 23 2018-02-01 6 3 df = df [ df.groupby ( 'ID ' ) .ID.transform ( len ) > 1 ] | Remove rows from Pandas dataframe where value only appears once |
Python | I tried to compare these two snippets and see how many iterations could be done in one second . Turns out that Julia achieves 2.5 million iterations whereas Python 4 million . Is n't Julia supposed to be quicker . Or maybe these two snippets are not equivalent ? Python : Julia : | t1 = time.time ( ) i = 0while True : i += 1 if time.time ( ) - t1 > = 1 : break function f ( ) i = 0 t1 = now ( ) while true i += 1 if now ( ) - t1 > = Base.Dates.Millisecond ( 1000 ) break end end return iend | Python vs Julia speed comparison |
Python | Due to an astronomically atrocious bug on PyQt4 , I need to fire a mousePressEvent artificially on a QWebView as a last breath of hope . For some obscure reason , QWebView 's linkClicked and urlChanged signals do not pass a QUrl when the clicked link has Javascript involved ( It does not work on Youtube videos , for ex... | class CQWebView ( QtWebKit.QWebView ) : def mousePressEvent ( self , event ) : if type ( event ) == QtGui.QMouseEvent : if event.button ( ) == QtCore.Qt.LeftButton : # FIRE A QtCore.Qt.MiddleButton EVENT HERE , # SO THAT I CAN GET THE BLOODY LINK AFTERWARDS . elif event.button ( ) == QtCore.Qt.MiddleButton : self.emit ... | Is it possible to trigger a mousePressEvent artificially on a QWebView ? |
Python | I 'm trying to teach myself about how python bytecode works so I can do some stuff with manipulating functions ' code ( just for fun , not for real usage ) so I started with some simple examples , such as : The bytecode is* : So it makes sense to me that 124 is the LOAD_FAST bytecode , and the name of the object being ... | def f ( x ) : return x + 3/x ( 124 , 0 , 0 , 100 , 1 , 0 , 124 , 0 , 0 , 20 , 23 , 83 ) > > > dis.dis ( f ) 2 0 LOAD_FAST 0 ( x ) 3 LOAD_CONST 1 ( 3 ) 6 LOAD_FAST 0 ( x ) 9 BINARY_DIVIDE 10 BINARY_ADD 11 RETURN_VALUE > > > list ( f.__code__.co_code ) [ 124 , 0 , 100 , 1 , 124 , 0 , 27 , 0 , 23 , 0 , 83 , 0 ] | What do the zeros in python function bytecode mean ? |
Python | I would like to encode an IP address in as short a string as possible using all the printable characters . According to https : //en.wikipedia.org/wiki/ASCII # Printable_characters these are codes 20hex to 7Ehex.For example : In order to make decoding easy I also need the length of the encoding always to be the same . ... | shorten ( `` 172.45.1.33 '' ) -- > `` ^.1 9 '' maybe . # This is needed because ipaddress expects character strings and not byte strings for textual IP address representations from __future__ import unicode_literalsimport ipaddressimport base64 # Taken from http : //stackoverflow.com/a/20793663/2179021def to_bytes ( n ... | Encode IP address using all printable characters in Python 2.7.x |
Python | I am so new on Image Processing and what I 'm trying to do is clearing the noise from captchas ; For captchas , I have different types of them : For the first one what I did is : Firstly , I converted every pixel that is not black to the black . Then , I found a pattern that is a noise from the image and deleted it . F... | def delete ( searcher , h2 , w2 ) : h = h2 w = w2 search = searcher search = search.convert ( `` RGBA '' ) herear = np.asarray ( search ) bigar = np.asarray ( imgCropped ) hereary , herearx = herear.shape [ :2 ] bigary , bigarx = bigar.shape [ :2 ] stopx = bigarx - herearx + 1 stopy = bigary - hereary + 1 pix = imgCrop... | Python Image Processing on Captcha how to remove noise |
Python | Here are two example Django models . Pay special attention to the has_pet method.The problem here is that the has_pet method always generates a query . If you do something like this.Then you will actually be doing an extra query just to check if one person has a pet . That is a big problem if you have to check multiple... | class Person ( models.Model ) : name = models.CharField ( max_length=255 ) def has_pet ( self ) : return bool ( self.pets.all ( ) .only ( 'id ' ) ) class Pet ( models.Model ) : name = models.CharField ( max_length=255 ) owner = models.ForeignKey ( Person , blank=True , null=True , related_name= '' pets '' ) p = Person.... | How to reduce queries in django model has_relation method ? |
Python | Python question . I 'm generating a large array of objects , which I only need to make a small random sample . Actually generating the objects in question takes a while , so I wonder if it would be possible to somehow skip over those objects that do n't need generating and only explicitly create those objects that have... | a = createHugeArray ( ) s = random.sample ( a , len ( a ) *0.001 ) a = createArrayGenerator ( ) s = random.sample ( a , len ( a ) *0.001 ) | Lazily sample random results in python |
Python | I 've written an R function that calls gdal_calc.py to calculate the pixel-wise minimum value across a RasterStack ( series of input raster files ) . I 've done this because it 's much faster than raster : :min for large rasters . The function works well for up to 23 files , but throws a warning when passing 24 or more... | gdal_min < - function ( infile , outfile , return_raster=FALSE , overwrite=FALSE ) { require ( rgdal ) if ( return_raster ) require ( raster ) # infile : The multiband raster file ( or a vector of paths to multiple # raster files ) for which to calculate cell minima . # outfile : Path to raster output file . # return_r... | gdal_calc amin fails when passing more than 23 input files |
Python | I 'm trying to overload some methods of the string builtin.I know there is no really legitimate use-case for this , but the behavior still bugs me so I would like to get an explanation of what is happening here : Using Python2 , and the forbiddenfruit module.As you can see , the __repr__ function as been successfully o... | > > > from forbiddenfruit import curse > > > curse ( str , '__repr__ ' , lambda self : 'bar ' ) > > > 'foo '' foo ' > > > 'foo'.__repr__ ( ) 'bar ' > > > 'foo '' bar ' | Python overload primitives |
Python | When running this code with python myscript.py from Windows console cmd.exe ( i.e . outside of Sublime Text ) , it works : CaféWhen running it inside Sublime Text 2 with CTRL+B , it fails : Either like this ( by default ) : print d [ 'mykey ' ] [ 'readme ' ] UnicodeEncodeError : 'ascii ' codec ca n't encode character u... | # coding : utf8import jsond = json.loads ( `` '' '' { `` mykey '' : { `` readme '' : `` Café '' } } '' '' '' ) print d [ 'mykey ' ] [ 'readme ' ] { `` cmd '' : [ `` python '' , `` -u '' , `` $ file '' ] , '' file_regex '' : `` ^ [ ] *File \ '' ( ... * ? ) \ '' , line ( [ 0-9 ] * ) '' , '' selector '' : `` source.python... | Printing utf8 strings in Sublime Text 's console with Windows |
Python | I am using Python to convert some files to a binary format , but I 've run into an odd snare.ProblemCodeResultObviously the expected size would be 25 , but it appears to be interpreting the first byte ( B ) as a 4-byte integer of some kind . It will also write out a 4-byte integer instead of a byte.Work-aroundA work-ar... | import structs = struct.Struct ( 'Bffffff ' ) print s.size 28 import structs1 = struct.Struct ( ' B ' ) s2 = struct.Struct ( 'ffffff ' ) print s1.size + s2.size 25 | Python struct.Struct.size returning unexpected value |
Python | I 'm having a issue when using pydev for testing where my tests keep hanging . I 've dug into the issue and know what the root cause is . I 've provided samples of the code below that can be used to reproduce the issue . I 'm mainly testing on Centos 6.3 , python 2.7 , eclipse juno , pydev 2.7.1 , however the issue als... | for t in threading.enumerate ( ) : if t.getName ( ) ! = 'MainThread ' : t.join ( ) Thread : < bound method _MainThread.getName of < _MainThread ( MainThread , started 140268135126784 ) > > Thread : < bound method ThreadClass.getName of < ThreadClass ( Thread A , started 140268006471424 ) > > Thread : < bound method Thr... | Pydev PyUnit issue when using thread.join to ensure all threads are joined |
Python | I run : It says it 's making all sorts of stuff , but then the resulting directory ( build/bdist.macosx-10.10-x86_64 ) is empty . Where did my wheel roll away to ? t EditI now see that I 'm trying to look at the temp output . When I specify -d , sure enough , there 's a wheel in the designated location . Does -d have a... | python3 setup.py bdist_wheel -- universal running bdist_wheelrunning buildrunning build_pyrunning egg_infowriting dependency_links to rosapi_launcher.egg-info/dependency_links.txtwriting top-level names to rosapi_launcher.egg-info/top_level.txtwriting rosapi_launcher.egg-info/PKG-INFOwriting requirements to rosapi_laun... | I try to build a universal wheel , but it rolls away |
Python | I 'm reading a big file with hundreds of thousands of number pairs representing the edges of a graph . I want to build 2 lists as I go : one with the forward edges and one with the reversed . Currently I 'm doing an explicit for loop , because I need to do some pre-processing on the lines I read . However , I 'm wonder... | with open ( 'SCC.txt ' ) as data : for line in data : line = line.rstrip ( ) if line : edge_list.append ( ( int ( line.rstrip ( ) .split ( ) [ 0 ] ) , int ( line.rstrip ( ) .split ( ) [ 1 ] ) ) ) reversed_edge_list.append ( ( int ( line.rstrip ( ) .split ( ) [ 1 ] ) , int ( line.rstrip ( ) .split ( ) [ 0 ] ) ) ) | Build 2 lists in one go while reading from file , pythonically |
Python | I 'm trying to do something similar to the following : When I drop into the debugger , I 'd like for the exception instance e to be in my local scope . However , if I run this script , I find that this is not the case : Why is e not defined ? I 'm currently using print statements to find out the attributes of e , but I... | try : 1/0except ZeroDivisionError as e : import ipdb ; ipdb.set_trace ( ) Kurts-MacBook-Pro-2 : Scratch kurtpeek $ python debug_exception.py -- Return -- None > /Users/kurtpeek/Documents/Scratch/debug_exception.py ( 4 ) < module > ( ) 2 1/0 3 except ZeroDivisionError as e : -- -- > 4 import ipdb ; ipdb.set_trace ( ) ip... | In Python , how to drop into the debugger in an except block and have access to the exception instance ? |
Python | Assume I 'm going to write a Python script that catches the KeyboardInterrupt exception to be able to get terminated by the user using Ctrl+C safelyHowever , I ca n't put all critical actions ( like file writes ) into the catch block because it relies on local variables and to make sure a subsequent Ctrl+C does not bre... | try : with open ( `` file.txt '' , `` w '' ) as f : for i in range ( 1000000 ) : # imagine something useful that takes very long instead data = str ( data ** ( data ** data ) ) try : pass finally : # ensure that this code is not interrupted to prevent file corruption : f.write ( data ) except KeyboardInterrupt : print ... | Does finally ensure some code gets run atomically , no matter what ? |
Python | I have a string as follows where I need to remove similar consecutive words.My output should look as follows.I am using the following python code to do it.However , my code is O ( n² ) and really inefficient as I have a huge dataset . I am wondering if there is a more efficient way of doing this in Python.I am happy to... | mystring = `` my friend 's new new new new and old old cats are running running in the street '' myoutput = `` my friend 's new and old cats are running in the street '' mylist = [ ] for i , w in enumerate ( mystring.split ( ) ) : for n , l in enumerate ( mystring.split ( ) ) : if l ! = w and i == n-1 : mylist.append (... | How to remove consecutive identical words from a string in python |
Python | I 'm trying to listen for MediaKey events under Gnome 3 ( Gnome Shell ) . All the examples I find refer to using DBus to connect to org.gnome.SettingsDaemon.MediaKeys . This service does n't seem to exist on my platform . I 'm trying to do this using Python via GObject-Introspection . The examples say do something like... | from gi.reposiotry import Gioconnection = Gio.bus_get_sync ( Gio.BusType.SESSION , None ) proxy = Gio.DBusProxy.new_sync ( connection , 0 , None , 'org.gnome.SettingsDaemon ' , '/org/gnome/SettingsDaemon/MediaKeys ' , 'org.gnome.SettingsDaemon.MediaKeys ' , None ) | How do you listen for Mediakey events under gnome 3 using python ? |
Python | I have a java app and a python launcher for it . The java app locks a file to avoid multiple startups using this code : The python launcher tries to lock on the same file with fcntl and it can . Two java processes ca n't do this and neither two python processes can lock exclusively on the same file . But a java and a p... | java.nio.channels.FileLock lock = lockWrapper.getChannel ( ) .tryLock ( ) ; if ( lock == null ) { logger.info ( `` Anotheris already running '' ) ; } lock.release ( ) ; staticLock = lockWrapper.getChannel ( ) .lock ( ) ; lockfile =open ( lockfilename , ' w+ ' ) portalocker.lock ( lockfile , portalocker.LOCK_EX| portalo... | Java and python processes can exclusive lock the same file on linux |
Python | There is a drastic performance hit when using a keyfunc in heapq.nlargest : I expected a small extra cost , perhaps something like 30 % - not 400 % . This degradation seems to be reproducible over a few different data sizes . You can see in the source code there is a special-case handling for if key is None , but other... | > > > from random import random > > > from heapq import nlargest > > > data = [ random ( ) for _ in range ( 1234567 ) ] > > > % timeit nlargest ( 10 , data ) 30.2 ms ± 1.19 ms per loop ( mean ± std . dev . of 7 runs , 10 loops each ) > > > % timeit nlargest ( 10 , data , key=lambda n : n ) 159 ms ± 6.32 ms per loop ( m... | Why is using a key function so much slower ? |
Python | Using app engine 's search API , I tried to search the queries which contain , , = , ( , etc.It returns the following error : Why ? Does the search API support these characters ? | Failed to parse query `` engines ( Modular ) '' Traceback ( most recent call last ) : File `` /base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py '' , line 1505 , in __call__ rv = self.router.dispatch ( request , response ) File `` /base/python27_runtime/python27_lib/versions/third_party/web... | Search API returns QueryError when Query contains ' , ' ( Comma ) or = or ( ) |
Python | FactoryBoy seem to always create the instances in the default database . But I have the following problem.The code is pointing to the global database . I have n't found a way to specify the database within the factory : | cpses = CanonPerson.objects.filter ( persons__vpd=6 , persons__country= '' United States '' ) .using ( `` global '' ) class CanonPersonFactory ( django_factory.DjangoModelFactory ) : class Meta : model = CanonPerson django_get_or_create = ( 'name_first ' , 'p_id ' ) p_id = 1 name_first = factory.Sequence ( lambda n : `... | How to specify the database for Factory Boy ? |
Python | I 'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration . Something like this : The argument to the decorator is completely separate from the argument to the function it 's wrapping . I 've looked at quite a few examples but I 'm not qu... | @ cacheable ( '/path/to/cache/file ' ) def my_function ( a , b , c ) : return 'something ' | Python : decorator specific argument ( unrelated to wrapped function ) ? |
Python | I 'd like to be able to use % cd `` default_dir '' and % matplotlib whenever I call ipython from my terminal . I tried writing this in a .py file in .ipython/profile_default/startup/file.py but it results in the following error : | [ TerminalIPythonApp ] WARNING | Unknown error in handling startup files : File `` /Users/ < name > /Dropbox/.ipython/profile_default/startup/startup.py '' , line 18 % cd `` ~/Dropbox/ '' ^SyntaxError : invalid syntax | How can I configure IPython to issue the same `` magic '' commands at every startup ? |
Python | We already know that Function arguments used to have the limit of 255 explicitly passed arguments . However , this behaviour is changed now and since Python-3.7 there 's no limit except sys.maxsize which is actually the limit of python 's containers . But what about the local variables ? We basically can not add local ... | In [ 142 ] : def bar ( ) : ... : exec ( ' k=10 ' ) ... : print ( f '' locals : { locals ( ) } '' ) ... : print ( k ) ... : g = 100 ... : ... : In [ 143 ] : bar ( ) locals : { ' k ' : 10 } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -NameError Traceback ... | How many local variables can a Python ( CPython implementation ) function possibly hold ? |
Python | For example : Say you have the following array : and you want to generate this array : | [ 1,2,3 ] [ 4,5,6 ] [ 7,8,9 ] [ 1,5,9 ] [ 1,6,8 ] [ 4,2,9 ] [ 4,8,3 ] [ 7,2,6 ] [ 7,5,3 ] | In Python , how do you generate permutations of an array where you only have one element from each column and row ? |
Python | I just started fooling around with python today ; I have absolutely no idea what I 'm doing . Below is a little program I wrote to display primes , which seems to be working fine and pretty quickly : The sqrt ( ) function did n't work unless I kept in both the math.sqrt ( ) part and the import math part . Also when I w... | import mathN = input ( 'List primes up to : ' ) N = int ( N ) for i in range ( 3 , N,2 ) : for d in range ( 2 , int ( math.sqrt ( i ) ) ) : if i % d==0 : breakelse : print ( str ( i ) ) | Is the expression math.sqrt ( ) necessary ? |
Python | Obviously this shell script is calling itself as a Python script : ( Whole script : https : //android.googlesource.com/tools/repo/+/v1.0/repo ) Can anyone explainthe purpose of calling it this way ? Why not having # ! /usr/bin/env python in the first line so it gets interpretedas Python script from the beginning ? the ... | # ! /bin/sh # # repo default configuration # # REPO_URL='git : //android.git.kernel.org/tools/repo.git'REPO_REV='stable'magic= ' -- calling-python-from-/bin/sh -- ' '' '' '' exec '' python -E `` $ 0 '' `` $ @ '' `` '' '' # $ magic '' if __name__ == '__main__ ' : import sys if sys.argv [ -1 ] == ' # % s ' % magic : del ... | Why is this shell script calling itself as python script ? |
Python | I have been asking related questions on this stack for the past week to try to isolate things I did n't understand about using the @ jit decorator with Numba in Python . However , I 'm hitting the wall , so I 'll just write the whole problem.The issue at hand is to calculate the minimal distance between pairs of a larg... | import numpy as npfrom numba import jit , autojit , double , float64 , float32 , void , int32def my_dot ( a , b ) : res = a [ 0 ] *b [ 0 ] +a [ 1 ] *b [ 1 ] +a [ 2 ] *b [ 2 ] return resdot_jit = jit ( double ( double [ : ] , double [ : ] ) ) ( my_dot ) # I know , it 's not of much use here . def compute_stuff ( array_t... | Inter segment distance using numba jit , Python |
Python | from the Python documentation , I see that you can set methods for handling properties transparently : Now assume that C._x is a list . In init it is simply set to [ ] . So if I do the following : c.x will be set to [ 1,2,3 ] . What I want to be able to do now isSo that c.x is now [ 1,2,3,4 ] . The example is trivial ,... | class C ( object ) : def __init__ ( self ) : self._x = None def getx ( self ) : return self._x def setx ( self , value ) : self._x = value def delx ( self ) : del self._x x = property ( getx , setx , delx , `` I 'm the ' x ' property . '' ) c = C ( ) c.x = [ 1,2,3 ] # ... c.x += 4 | make python @ property handle += , -= etc |
Python | I 've written a script in python to log in to a website and parse the username to make sure I 've really been able to log in . Using the way I 've tried below seems to get me there . However , I 've used hardcoded cookies taken from chrome dev tools within the script to get success.I 've tried with : I 've tried with t... | import requestsfrom bs4 import BeautifulSoupurl = 'https : //secure.imdb.com/ap/signin ? openid.pape.max_auth_age=0 & openid.return_to=https % 3A % 2F % 2Fwww.imdb.com % 2Fap-signin-handler & openid.identity=http % 3A % 2F % 2Fspecs.openid.net % 2Fauth % 2F2.0 % 2Fidentifier_select & openid.assoc_handle=imdb_pro_us & o... | Ca n't parse the username to make sure I 'm logged in to a website |
Python | I 'm trying to write Python expression evaluation visualizer , that will show how Python expressions are evaluated step by step ( for education purposes ) . Philip Guo 's Python Tutor is great , but it evaluates Python program line by line , and I found that students sometimes do not understand how one-line expressions... | sorted ( [ 4 , 2 , 3 , 1 ] + [ 5 , 6 ] ) [ 1 ] == 2sorted ( > > [ 4 , 2 , 3 , 1 ] + [ 5 , 6 ] < < ) [ 1 ] == 2 > > sorted ( [ 4 , 2 , 3 , 1 , 5 , 6 ] ) < < [ 1 ] == 2 > > [ 1 2 3 4 5 6 ] [ 1 ] < < == 2 > > 2 == 2 < < True | Tracing Python expression evaluation step by step |
Python | So I want to align fields containing non-ascii characters . The following does not seem to work : Is there a solution ? | for word1 , word2 in [ [ 'hello ' , 'world ' ] , [ 'こんにちは ' , '世界 ' ] ] : print `` { : < 20 } { : < 20 } '' .format ( word1 , word2 ) hello worldこんにちは 世界 | Formatting columns containing non-ascii characters |
Python | I have a map with a scale like this one : ( the numbers are just an example ) which describes a single variable on a map . However , I do n't have access to the original data and know pretty close to nothingabout image processing . What I have done is use PIL to get the pixel-coordinates and RGB values of each point on... | def rgb2hls ( colotup ) : `` 'converts 225 based RGB to 360 based HLS ` input ` : ( 222,98,32 ) tuple '' ' dec_rgb = [ x/255.0 for x in colotup ] # use decimal 0.0 - 1.0 notation for RGB hsl_col = colorsys.rgb_to_hls ( dec_rgb [ 0 ] , dec_rgb [ 1 ] , dec_rgb [ 2 ] ) # PIL uses hsl ( 360 , x % , y % ) notation and throw... | guessing the rgb gradient from a map ? |
Python | I am using Python 3.6.4 . I first encountered an issue where logger.setLevel ( logging.INFO ) was ignored , and came across this answer , which confused me and gave rise to this question.Given the code below,1 . Why does logging.info ( ' 2 ' ) get printed in Snippet 2 , but not in 1 ? ( Is n't logging.info ( ) is a mod... | > > > import logging > > > logger = logging.getLogger ( 'foo ' ) # named logger > > > logger.setLevel ( logging.INFO ) > > > logger.info ( ' 1 ' ) > > > logging.info ( ' 2 ' ) # prints nothing > > > logger.info ( ' 3 ' ) INFO : foo:3 > > > import logging > > > logger = logging.getLogger ( ) # no name > > > logger.setLe... | Why does logger.info ( ) only appear after calling logging.info ( ) ? |
Python | I currently have a keras model that looks like this : The Keras documentation tells me : The model needs to know what input shape it should expect . For this reason , the first layer in a Sequential model ( and only the first , because following layers can do automatic shape inference ) needs to receive information abo... | model = keras.Sequential ( ) model.add ( keras.layers.Dense ( 100 , activation=tf.nn.relu ) ) model.add ( keras.layers.Dense ( 100 , activation=tf.nn.relu ) ) model.add ( keras.layers.Dense ( len ( labels ) , activation=tf.nn.softmax ) ) | Keras Sequential without providing input shape |
Python | Storing the same value in a sqlite database as a Boolean or Integer using Python and Sqlalchemy produces the following results.Why is there such a performance issue when using the Boolean type ? I know SQLite does n't have the concept of boolean type and instead stores them as an integer 1 ( True ) or 0 ( False ) . I w... | Value stored as Boolean : SqlAlchemy ORM : Total time for 40000 records 62.5009999275 secsSqlAlchemy Core : Total time for 40000 records 56.0600001812 secsValue stored as Integer : SqlAlchemy ORM : Total time for 40000 records 5.72099995613 secsSqlAlchemy Core : Total time for 40000 records 0.770999908447 secs import t... | Why is there a large insert performance difference between python SqlAlchemy Boolean and Integer Type |
Python | I have the following list data.where the first argument is date & second argument is total.i want result using group by month & year from the above list.i.e result would like : | data = [ [ '2009-01-20 ' , 3000.0 ] , [ '2011-03-01 ' , 6000.0 ] , [ '2008-12-15',6000.0 ] , [ '2002-02-15 ' , 6000.0 ] , [ '2009-04-20 ' , 6000.0 ] , [ '2010-08-01',4170.0 ] , [ '2002-07-15 ' , 6000.0 ] , [ '2008-08-15 ' , 6000.0 ] , [ '2010-12-01',6000.0 ] , [ '2011-02-01 ' , 8107.0 ] , [ '2011-04-01 ' , 8400.0 ] , [... | Best pythonic way to populate the list containing the date type data ? |
Python | I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts . However , these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include ( most often multiple ) calls to sys.path.append on my top-level scri... | import syssys.path.append ( '..//shared1//reusable_foo ' ) import Foosys.path.append ( '..//shared2//reusable_bar ' ) import Bar import Fooimport Bar | In Python , how can I efficiently manage references between script files ? |
Python | I am fairly new to the internals of TensorFlow . Towards trying to understand TensorFlow 's implementation of AdamOptimizer , I checked the corresponding subgraph in TensorBoard . There seems to be a duplicate subgraph named name + '_1 ' , where name='Adam ' by default . The following MWE produces the graph below . ( N... | import tensorflow as tftf.reset_default_graph ( ) x = tf.Variable ( 1.0 , name= ' x ' ) train_step = tf.train.AdamOptimizer ( 1e-1 , name='MyAdam ' ) .minimize ( x ) init = tf.global_variables_initializer ( ) with tf.Session ( ) as sess : sess.run ( init ) with tf.summary.FileWriter ( './logs/mwe ' ) as writer : writer... | Why is AdamOptimizer duplicated in my graph ? |
Python | I have the same question as was asked here but erroneously closedas a duplicate of another related question : How can a Python library raise an exception in such a way that its owncode it not exposed in the traceback ? The motivation is to make itclear that the library function was called incorrectly : the offendinglin... | import sys # home-made six-esque Python { 2,3 } -compatible reraise ( ) definitiondef reraise ( cls , instance , tb=None ) : # Python 3 definition raise ( cls ( ) if instance is None else instance ) .with_traceback ( tb ) try : Exception ( ) .with_tracebackexcept : # fall back to Python 2 definition exec ( 'def reraise... | raising an exception that appears to come from the caller |
Python | I 'm trying to base64 encode some RSA encrypted data , but the RSA encryption returns a tuple and the base64 encoding requires a bytes-like object.File `` C : \PATH\AppData\Local\Continuum\anaconda3\lib\base64.py '' , line 58 , in b64encode encoded = binascii.b2a_base64 ( s , newline=False ) TypeError : a bytes-like ob... | from Crypto.Cipher import AESfrom Crypto.PublicKey import RSAdef rsa_encrypt ( data ) : return pub_keyObj.encrypt ( data , 32 ) def rsa_encrypt_base64 ( data ) : return base64.standard_b64encode ( rsa_encrypt ( data ) ) encrypted_data = aes_encode ( data , key , iv ) # AES encoding is working fineprint ( `` EncryptedSt... | Convert an element in tuple to a bytes-like object |
Python | I want to download and process a lot of files from website . The terms of service for the site restrict the number of files you 're permitted to download per second . The time that it takes to process the files is actually the bottle neck , so I 'd like to be able process multiple files in parallel . But I do n't want ... | import multiprocessingfrom multiprocessing.managers import BaseManagerimport timeclass DownloadLimiter ( object ) : def __init__ ( self , time ) : self.time = time self.lock = multiprocessing.Lock ( ) def get ( self , url ) : self.lock.acquire ( ) time.sleep ( self.time ) self.lock.release ( ) return urlclass DownloadM... | Rate Limit Downloads Amongst Multiple Processes |
Python | The problem is stated as : Given a string that contains only digits 0-9 and a target value , return all expressions that are created by adding some binary operators ( + , - , or * ) between the digits so they evaluate to the target value . In some cases there may not be any binary operators that will create valid expre... | [ [ ' 1 ' , ' 2 ' , ' 3 ' ] , [ ' 1 ' , '23 ' ] , [ '12 ' , ' 3 ' ] , [ '123 ' ] ] { 0 : [ ( ) ] , 1 : [ ( '+ ' , ) , ( '- ' , ) , ( '* ' , ) ] , 2 : [ ( '+ ' , '+ ' ) , ( '+ ' , '- ' ) , ( '+ ' , '* ' ) , ( '- ' , '+ ' ) , ( '- ' , '- ' ) , ( '- ' , '* ' ) , ( '* ' , '+ ' ) , ( '* ' , '- ' ) , ( '* ' , '* ' ) ] } if e... | Efficient Algorithm to compose valid expressions with specific target |
Python | I 've been reading the PyYAML source code to try to understand how to define a proper constructor function that I can add with add_constructor . I have a pretty good understanding of how that code works now , but I still do n't understand why the default YAML constructors in the SafeConstructor are generators . For exa... | def construct_yaml_map ( self , node ) : data = { } yield data value = self.construct_mapping ( node ) data.update ( value ) if isinstance ( data , types.GeneratorType ) : generator = data data = generator.next ( ) if self.deep_construct : for dummy in generator : pass else : self.state_generators.append ( generator ) ... | Why does PyYAML use generators to construct objects ? |
Python | I was just messing around with numpy arrays when I realized the lesser known behavior of the dtypes parameter.It seems to change as the input changes . For example , gives dtype ( 'int32 ' ) However , gives dtype ( 'int64 ' ) So , my first question is : How is this calculated ? Does it make the datatype suitable for th... | t = np.array ( [ 2 , 2 ] ) t.dtype t = np.array ( [ 2 , 22222222222 ] ) t.dtype t = np.array ( [ 2 , 2 ] ) t [ 0 ] = 222222222222222 | How the dtype of numpy array is calculated internally ? |
Python | I 'm trying to wrap a c library in a high-level python interface with Boost.Python . One of the client contracts of the c library is that one of the handles can only be allocated once per-process . I was hoping I could enforce this contract on the python side by using a module global . Here is my django component modul... | import my_c_modimport osprint `` imager__init__ ( ) '' print os.getpid ( ) ptl = my_c_mod.PyGenTL ( ) BOOST_PYTHON_MODULE ( my_c_mod ) { using namespace boost : :python ; // Create the Python type object for our extension class and define __init__ function . class_ < PyGenTL > ( `` PyGenTL '' ) .def ( `` sys_info '' , ... | why is __init__ module in django project loaded twice In the same process ? |
Python | I 'm using a remote workstation ( Ubunutu 18.04 ) with a GPU via Docker Machine . With PyCharm Professional 2018.1.4 I can connect remotely to the workstation and create/start containers , connect to them and attach a terminal . The problem occurs when I try to run a python script via docker compose with PyCharm . I ge... | version : ' 3'services : densepose : build : Dockerfile image : densepose volumes : - ./ : /opt/project # I have tried adding and removing this to no avail - ./included_files : /included_files - ./output : /output | Running/Debugging Pycharm Python Scripts with remote Docker Machine |
Python | I have a pandas DataFrame with a MultiIndex of columns : I want to group by the index , and use the 'min ' aggregation on the a columns , and the 'sum ' aggregation on the b columns.I know I can do this by creating a dict that specifies the agg function for each column : Is there a simpler way ? It seems like there sho... | columns=pd.MultiIndex.from_tuples ( [ ( c , i ) for c in [ ' a ' , ' b ' ] for i in range ( 3 ) ] ) df = pd.DataFrame ( np.random.randn ( 4 , 6 ) , index= [ 0 , 0 , 1 , 1 ] , columns=columns ) print ( df ) a b 0 1 2 0 1 20 0.582804 0.753118 -0.900950 -0.914657 -0.333091 -0.9659120 0.498002 -0.842624 0.155783 0.559730 -... | pandas groupby : can I select an agg function by one level of a column MultiIndex ? |
Python | Given a list like : how do I split it into a list of sublists : Effectively I need an equivalent of str.split ( ) for lists . I can hack together something , but I ca n't seem to be able to come up with anything neat and/or pythonic.I get the input from an iterator , so a generator working on that is acceptable as well... | [ a , SEP , b , c , SEP , SEP , d ] [ [ a ] , [ b , c ] , [ ] , [ d ] ] [ a , SEP , SEP , SEP ] - > [ [ a ] , [ ] , [ ] , [ ] ] [ a , b , c ] - > [ [ a , b , c ] ] [ SEP ] - > [ [ ] , [ ] ] | How to split a list into sublists based on a separator , similar to str.split ( ) ? |
Python | Please forgive me up front . When I 've tried to research this question I end up looking at code that I simply ca n't comprehend . I have about 3 hours of experience with Python and am probably attempting more than I can handle.The problem is simple . I can successfully call Python from R ( my analysis software ) to se... | import smtplibimport osfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email.MIMEText import MIMETextfrom email.Utils import COMMASPACE , formatdatefrom email import Encodersimport email.utilsfromaddr = 'someone @ gmail.com'toaddrs = 'recipient @ gmail.org'msg = MIMEMultipart ( MIME... | Attaching a single file to an e-mail |
Python | In Python , you can implement __call__ ( ) for a class such that calling an instance of the class itself executes the __call__ ( ) method.Do JavaScript classes have an equivalent method ? EditA summary answer incorporating the discussion here : Python and JavaScript objects are not similar enough for a true equivalent ... | class Example : def __call__ ( self ) : print ( `` the __call__ method '' ) e = Example ( ) e ( ) # `` the __call__ method '' | Do JavaScript classes have a method equivalent to Python classes ' __call__ ? |
Python | I have a numpy boolean array I would like to get the index of the first time there are at n_at_least false values.For instance here I have triedwhich does increase every time a False value is encountered.However , when True is encountered the counter is not starting from 0 again so I only get the total count of False e... | w=np.array ( [ True , False , True , True , False , False , False ] ) ` n_at_least ` =1 - > desired_index=1 ` n_at_least ` =3 - > desired_index=4 np.cumsum ( ~w ) | get index of the first block of at least n consecutive False values in boolean array |
Python | In Appengine , I am trying to have a property value computed automatically and stored with the object.I have a class , Rectangle , and it has a width , height and area . Obviously the area is a function of width and height , but I want it to be a property because I want to use it for sorting . So I try to modify the pu... | class Rectangle ( db.Model ) : width = db.IntegerProperty ( ) height = db.IntegerProperty ( ) area = db.IntegerProperty ( ) def put ( self , **kwargs ) : self.area = self.width * self.height super ( Rectangle , self ) .put ( **kwargs ) re1 = Rectangle ( width=10 , height=10 ) re1.put ( ) print re1.area # > > 10 re2 = R... | How to overwrite the put ( ) method on a python app engine model ? |
Python | I had an idea to transform all given functions that are tagged using a decorator similar to the below , In transform_ast , I get the source , extract the ast , transform it , and then create a code object and function type from it again . It looks something like the below , However , it does n't seem to work properly w... | @ transform_astdef foo ( x ) : return x import astimport inspectimport typesclass Rewrite ( ast.NodeTransformer ) : passdef transform_ast ( f ) : source = inspect.getsource ( f ) source = '\n'.join ( source.splitlines ( ) [ 1 : ] ) # remove the decorator first line . print ( source ) old_code_obj = f.__code__ old_ast =... | Python transforming ast through function decorators |
Python | First read this . It is about lambda x=x : foo ( x ) catching x even in for loop.This is a window with label and two buttons generated in for loop . When button is clicked , it name appears in label . If we use usual lambda : label.setText ( `` button -- `` + str ( i ) ) , then the result is last i in the loop , no mat... | import sysfrom PyQt4.QtGui import *class MainWindow ( QWidget ) : def __init__ ( self , parent=None ) : QWidget.__init__ ( self , parent ) vbox = QVBoxLayout ( self ) # label for action label = QLabel ( `` ) vbox.addWidget ( label ) # adding buttons for i in range ( 1 , 3 ) : btn = QPushButton ( str ( i ) ) btn.clicked... | lambda i=i : foo ( i ) in for loop not working |
Python | I 'm writing an app that pulls chunks of svg together and serves them as part of a page mixed with css and javascript . I 'm using Python and Google App Engine . What I 'm doing works fine on my local development server but fails to render once it 's deployed.So here 's some test python to build a response : Now if I r... | self.response.headers.add_header ( 'Content-Type ' , 'application/xhtml+xml ' ) self.response.out.write ( `` < html xmlns='http : //www.w3.org/1999/xhtml ' > '' ) self.response.out.write ( `` < body > '' ) self.response.out.write ( `` < svg version= ' 1.1 ' xmlns='http : //www.w3.org/2000/svg ' xmlns : xlink='http : //... | Inline SVG Served By Python Script in Google App Engine Not Appearing |
Python | I am trying to extract multiple submatrices if my sparse matrix has multiple regions of non-zero values.For example , Say I have the following matrix : Then I need to be able to extract the regions with non-zero values , ie and I have been using np.where ( ) to find the indices of non-zero values and returning the regi... | x = np.array ( [ 0,0,0,0,0,0 ] , [ 0,1,1,0,0,0 ] , [ 0,1,1,0,0,1 ] , [ 0,0,0,0,1,1 ] , [ 0,0,0,0,1,0 ] ) x_1 = [ [ 1,1 ] [ 1,1 ] ] x_2 = [ [ 0,1 ] , [ 1,1 ] , [ 1,0 ] ] | Extracting multiple submatrices in Python |
Python | Suppose I have three lists : I wish to generate all combinations where I take five elements from list1 , two elements from list2 and three elements from list3.eg . I tried to use itertools.combinations . But I am getting output with iterations happening only on list3 . In all the output , only first five elements from ... | list1 -- > [ a , b , c , d , e , f , g , h ] list2 -- > [ i , j , k ] list3 -- > [ l , m , n , o , p ] a , b , c , d , e , i , j , l , m , n a , b , c , d , e , i , j , l , m , oetc . l1_combinations = itertools.combinations ( list1 , 5 ) l2_combinations = itertools.combinations ( list2 , 2 ) l3_combinations = itertool... | Combinations of multiple lists |
Python | If I have a string , I can split it up around whitespace with the str.split method : returnsIf I have a list likeIs there a split method that will split around None and give meIf there is no built-in method , what would be the most Pythonic/elegant way to do it ? | `` hello world ! `` .split ( ) [ 'hello ' , 'world ! ' ] [ 'hey ' , 1 , None , 2.0 , 'string ' , 'another string ' , None , 3.0 ] [ [ 'hey ' , 1 ] , [ 2.0 , 'string ' , 'another string ' ] , [ 3.0 ] ] | Is there a str.split equivalent for lists in Python ? |
Python | I have a question about removing duplicates in Python . I 've read a bunch of posts but have not yet been able to solve it . I have the following csv file : EDITInput : Output should be : In words , if the ID is the same , take values from the row with source `` NY Times '' , if the row with `` NY Times '' has a blank ... | ID , Source , 1.A , 1.B , 1.C , 1.D1 , ESPN , 5,7 , , , M1 , NY Times , ,10,12 , W1 , ESPN , 10 , ,Q , ,M ID , Source , 1.A , 1.B , 1.C , 1.D , duplicate_flag1 , ESPN , 5,7 , , , M , duplicate1 , NY Times , ,10,12 , W , duplicate1 , ESPN , 10 , ,Q , ,M , duplicate 1 , NY Times , 5 ( or 10 does n't matter which one ) ,7... | Python Duplicate Removal |
Python | I have a pandas DataFrame : I have then converted this into a Bokeh DataTable but have only included columns I , A and B. I 'd like to add a tooltip for the cells in columns A and B and to show the corresponding value in A2 or B2 . So , for example if you were hovering over 'dog ' , the tooltip would be 10 and if you h... | I A A2 B B21 'dog ' 10 'cat ' 202 'elf ' 15 'egg ' 453 'hat ' 80 'bag ' 50 | Add tooltip to Bokeh DataTable |
Python | I have to write a function that takes a string , and will return the string with added `` asteriks '' or `` * '' symbols to signal multiplication.As we know 4 ( 3 ) is another way to show multiplication , as well as 4*3 or ( 4 ) ( 3 ) or 4* ( 3 ) etc . Anyway , my code needs to fix that problem by adding an asterik bet... | while index < len ( stringtobeconverted ) parenthesis = stringtobeconverted [ index ] if parenthesis == `` ( `` : stringtobeconverted [ index-1 ] = `` * '' | Write a functon to modify a certain string in a certain way by adding character |
Python | I am trying to clean my dataframe such that if my `` Base_2007 '' and `` Base_2011 '' column contains NA , then I should completely drop that county . In my case since both Counties contains NA both of them will be dropped . Thus empty dataset will be returned . Is it possible to do something like this ? Data : Tail se... | State Year Base_2007 Base_2011 County0 AL 2012 NaN 14.0 Alabama_Country1 AL 2013 12.0 20.0 Alabama_Country2 AL 2014 13.0 NaN Alabama_Country3 DC 2011 NaN 20.0 Trenton4 DC 2012 19.0 NaN Trenton5 DC 2013 20.0 21.0 Trenton6 DC 2014 25.0 30.0 Trenton { 'State ' : { 82550 : 'WY ' , 82551 : 'WY ' , 82552 : 'WY ' , 82553 : 'W... | Delete group if NaN is present anywhere in multiple columns |
Python | I have a package for python 3.5 and 3.6 that has optional dependencies for which I want tests ( pytest ) that run on either version . I made a reduced example below consisting of two files , a simple __init__.py where the optional package `` requests '' ( just an example ) is imported and a flag is set to indicate the ... | mypackage/├── mypackage│ └── __init__.py└── test_init.py # ! /usr/bin/env python # -*- coding : utf-8 -*-requests_available = Truetry : import requestsexcept ImportError : requests_available = False # ! /usr/bin/env python # -*- coding : utf-8 -*-import pytest , sysdef test_requests_missing ( monkeypatch ) : import myp... | Test for import of optional dependencies in __init__.py with pytest : Python 3.5 /3.6 differs in behaviour |
Python | Excuse the strange title , I could n't really think of a suitable wording.Say I have an array like : I 'm looking to `` etch '' away the 1s that touch 0s , which would result in : I 've tried a few things with the likes of np.roll but it seems inefficient ( and has edge effects ) . Is there a nice short way of doing th... | arr = [ [ 0 1 1 1 1 1 1 1 0 ] , [ 0 0 1 1 1 1 1 0 0 ] , [ 0 0 0 1 1 1 0 0 0 ] , [ 0 0 0 0 1 0 0 0 0 ] , [ 0 0 0 0 0 0 0 0 0 ] ] arr = [ [ 0 0 1 1 1 1 1 0 0 ] , [ 0 0 0 1 1 1 0 0 0 ] , [ 0 0 0 0 1 0 0 0 0 ] , [ 0 0 0 0 0 0 0 0 0 ] , [ 0 0 0 0 0 0 0 0 0 ] ] . | How do I dissolve a pattern in a numpy array ? |
Python | I know , this is wrong , but is it possible ? I thought an object is considered an iterable when its .__iter__ method returned an iterator ? So why does n't this work ? int does seem to have an __iter__ method now : | > > > from forbiddenfruit import curse > > > def __iter__ ( self ) : ... for i in range ( self ) : ... yield i > > > curse ( int , `` __iter__ '' , __iter__ ) > > > for x in 5 : ... print x ... Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : 'int ' object is not iterable ... | Make int iterable with forbiddenfruit |
Python | I have a sumranges ( ) function , which sums all the ranges of consecutive numbers found in a tuple of tuples . To illustrate : As you can see , it returns the number of ranges of consecutive digits within the tuple , that is : len ( ( 1 , 2 , 3 , 4 ) , ( 1 ) , ( 5 , 6 ) , ( 19 , 20 ) , ( 24 ) , ( 29 ) , ( 400 ) ) = 7 ... | def sumranges ( nums ) : return sum ( [ sum ( [ 1 for j in range ( len ( nums [ i ] ) ) if nums [ i ] [ j ] == 0 or nums [ i ] [ j - 1 ] + 1 ! = nums [ i ] [ j ] ] ) for i in range ( len ( nums ) ) ] ) > > > nums = ( ( 1 , 2 , 3 , 4 ) , ( 1 , 5 , 6 ) , ( 19 , 20 , 24 , 29 , 400 ) ) > > > print sumranges ( nums ) 7 from... | Summing Consecutive Ranges Pythonically |
Python | The following is taken from David Beazley 's slides on generators ( here for anybody interested ) . A Task class is defined which wraps a generator that yields futures , the Task class , in full ( w/o error handling ) , follows : In an example , the following recursive function is also defined : The following two cases... | class Task : def __init__ ( self , gen ) : self._gen = gen def step ( self , value=None ) : try : fut = self._gen.send ( value ) fut.add_done_callback ( self._wakeup ) except StopIteration as exc : pass def _wakeup ( self , fut ) : result = fut.result ( ) self.step ( result ) from concurrent.futures import ThreadPoolEx... | Seemingly infinite recursion with generator based coroutines |
Python | I 'm using Trumbowyg , a WYSIWYG JavaScript editor which has a feature of rendering images from URLs pasted in . It also has an upload plugin which enables uploading local images and custom server side handling . My python/django function upload_image ( ) can successfully detect the uploaded image - however when I use ... | $ ( ' # id_content ' ) .trumbowyg ( { btnsDef : { // Create a new dropdown image : { dropdown : [ 'insertImage ' , 'upload ' ] , ico : 'insertImage ' } } , // Redefine the button pane btns : [ [ 'strong ' , 'em ' , 'del ' ] , [ 'link ' ] , [ 'image ' ] , // Our fresh created dropdown ] , plugins : { // Add imagur param... | Trumbowyg : Django server can detect file upload but not image URL input |
Python | I 'm having an issue getting data out of a c # array serialized class with python . I have two files containing the classes . The first I am able to loop though the array and grab the public variables . However in the second file I see the class but am Unable to access any of the variables . It 's been 10+ years since ... | from System.Runtime.Serialization.Formatters.Binary import BinaryFormatterfrom System.IO import FileStream , FileMode , FileAccess , FileSharefrom System.Collections.Generic import *def read ( name ) : bformatter = BinaryFormatter ( ) file_stream = FileStream ( name , FileMode.Open , FileAccess.Read , FileShare.Read ) ... | python open a serialized C # file |
Python | What would be the best generalized approach to traverse/extract/parse an HDFS directory of following general file type into a spark dataframe , rdd , or a sparse array ? I find it somewhat unwieldy to try to convert this into a format that would be suitable for traditional analytic workloads . One of the approaches I t... | { `` resourceType '' : `` Bundle '' , `` id '' : `` bundle-example '' , `` meta '' : { `` fhir_comments '' : [ `` this example bundle is a search set `` , `` when the search was executed `` ] , `` lastUpdated '' : `` 2014-08-18T01:43:30Z '' } , `` type '' : `` searchset '' , `` total '' : 3 , `` _total '' : { `` fhir_c... | Parse FHIR Bundle JSON Apache Spark |
Python | I 'm trying to write a Python script for parallel crawling of a website . I made a prototype that would allow me to crawl to depth one.However , join ( ) does n't seem to be working and I ca n't figure out why.Here 's my code : | from threading import Threadimport Queueimport urllib2import refrom BeautifulSoup import *from urlparse import urljoindef doWork ( ) : while True : try : myUrl = q_start.get ( False ) except : continue try : c=urllib2.urlopen ( myUrl ) except : continue soup = BeautifulSoup ( c.read ( ) ) links = soup ( ' a ' ) for lin... | Queue.join ( ) does n't unblock |
Python | I am writing a simple platform game , and I 've found that when removing 'ghost ' instances , they persist and are not garbage collected . It seems that although I am removing all references , the ghost objects have some kind of internal references that are preventing them being garbage collected . Specifically they ha... | import weakrefweak_ghosts = weakref.WeakKeyDictionary ( ) class Ghost ( object ) : def __init__ ( self ) : # pass self.switch = { 'eat ' : self.eat , 'sleep ' : self.sleep } def eat ( self ) : pass def sleep ( self ) : passghost = Ghost ( ) weak_ghosts [ ghost ] = None # ghost.switch = { } # uncomment this line and gho... | internal reference prevents garbage collection |
Python | If have a list like so : And would like to create the following new lists ( I cross each element with every other and create a string where first part is alphanumerically before the second ) : I have something like this : However , this is pretty slow for large lists ( e.g . 1000 where I have 1000*999*0.5 outputs ) . I... | shops= [ ' A ' , ' B ' , ' C ' , 'D ' ] [ ' A-B ' , ' A-C ' , ' A-D ' ] [ ' A-B ' , ' B-C ' , ' B-D ' ] [ ' A-C ' , ' B-C ' , ' C-D ' ] [ ' A-D ' , ' B-D ' , ' C-D ' ] for a in shops : cons = [ ] for b in shops : if a ! =b : con = [ a , b ] con = sorted ( con , key=lambda x : float ( x ) ) cons.append ( con [ 0 ] +'-'+... | Fast way of crossing strings in a list |
Python | I 'm running an ordinal ( i.e . multinomial ) ridge regression using mord ( scikitlearn ) library.y is a single column containing integer values from 1 to 19.X is made of 7 numerical variables binned in 4 buckets , and dummied into a final of 28 binary variables.mul_lr.coef_ returns a [ 28 x 1 ] array but mul_lr.interc... | import pandas as pdimport numpy as np from sklearn import metricsfrom sklearn.model_selection import train_test_splitimport mordin_X , out_X , in_y , out_y = train_test_split ( X , y , stratify=y , test_size=0.3 , random_state=42 ) mul_lr = mord.OrdinalRidge ( alpha=1.0 , fit_intercept=True , normalize=False , copy_X=T... | Ordinal logistic regression : Intercept_ returns [ 1 ] instead of [ n ] |
Python | I 've created a scraper to grab some product names from a webpage . It is working smoothly . I 've used CSS selectors to do the job . However , the only thing I ca n't understand is the difference between the selectors a : :text and a : :text ( do n't overlook the space between a and : :text in the latter ) . When I ru... | import requestsfrom scrapy import Selectorres = requests.get ( `` https : //www.kipling.com/uk-en/sale/type/all-sale/ ? limit=all # '' ) sel = Selector ( res ) for item in sel.css ( `` .product-list-product-wrapper '' ) : title = item.css ( `` .product-name a : :text '' ) .extract_first ( ) .strip ( ) title_ano = item.... | Difference between Scrapy selectors `` a : :text '' and `` a : :text '' |
Python | Answering this question , I found out that window functions are not allowed to combine with filter ( technically , they are , but filter clause affects the window ) . There is a hint to wrap window function in an inner query , so that final SQL looks like this ( as I understand ) : The question is : how can I write thi... | SELECT * FROM ( SELECT * , *window_function* FROM TABLE ) WHERE *filtering_conditions* | Django ORM : window function with subsequent filtering |
Python | Here is the main problem . I have very large database ( 25,000 or so ) of 48 dimensional vectors , each populated with values ranging from 0-255 . The specifics are not so important but I figure it might help give context.I do n't need a nearest neighbor , so approximate neighbor searches that are within a degree of ac... | def lsh ( vector , mean , stdev , r = 1.0 , a = None , b = None ) : if not a : a = [ normalvariate ( mean , stdev ) for i in range ( 48 ) ] if not b : b = uniform ( 0 , r ) hashVal = ( sum ( [ a [ i ] *vectorA [ i ] for i in range ( 48 ) ] ) + b ) /r return hashVal | High Dimension Nearest Neighbor Search and Locality Sensitivity Hashing |
Python | The coding task is hereThe heap solution : The sort solution : According to the explanation here , Python 's heapq.nsmallest is O ( n log ( t ) ) , and Python List.sort ( ) is O ( n log ( n ) ) . However , my submission results show that sort is faster than heapq . How did this happen ? Theoretically , it 's the contra... | import heapqclass Solution : def kClosest ( self , points : List [ List [ int ] ] , K : int ) - > List [ List [ int ] ] : return heapq.nsmallest ( K , points , key = lambda P : P [ 0 ] **2 + P [ 1 ] **2 ) class Solution ( object ) : def kClosest ( self , points : List [ List [ int ] ] , K : int ) - > List [ List [ int ... | Why is heap slower than sort for K Closest Points to Origin ? |
Python | I 'm trying to make a function which concatenate multiple list if one element is the same in 2 or more different list.Example : [ [ 1,2 ] , [ 3,4,5 ] , [ 0,4 ] ] would become [ [ 1,2 ] , [ 0,3,4,5 ] [ [ 1 ] , [ 1,2 ] , [ 0,2 ] ] would become [ [ 0,1,2 ] ] [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] ] would become [ [ 1,2,3,4 ]... | def concat ( L ) : break_cond = False print ( L ) for L1 in L : for L2 in L : if ( bool ( set ( L1 ) & set ( L2 ) ) and L1 ! = L2 ) : break_cond = True if ( break_cond ) : i , j = 0 , 0 while i < len ( L ) : while j < len ( L ) : if ( bool ( set ( L [ i ] ) & set ( L [ j ] ) ) and i ! = j ) : L [ i ] = sorted ( L [ i ]... | Large amount of lists concatenation |
Python | I have a DataFrame that looks like : I want to create a moving average with a maximum period of 3 , where each observation is df [ ' a ' ] *df [ ' b ] . If df [ ' a ' ] .rolling ( window=3 ) .sum ( ) < = 3 , then the MA would be : df [ 'MA ' ] = ( df [ ' a ' ] *df [ ' b ' ] ) .rolling ( window=3 ) .mean ( ) . However ,... | a b 1 0.9 0.796522123 2 0.8 0.701075019 3 0.6 0.777130253 4 0.5 0.209912906 5 0.75 0.920537662 6 1 0.955212665 7 3.5 0.227221963 8 2 0.336632891 9 1.25 0.563511758 10 1 0.832624112 def MA ( a , b , period ) : total = 0 sum_a = 0 for i in ( b ) : if sum_a < period : sum_a += a total += ( a*b ) else : sum_a = sum_a - a d... | Variable Moving Average |
Python | For a project I 'm working on , I 'm implementing a linked-list data-structure , which is based on the idea of a pair , which I define as : where self.next_pair and self.prev_pair are pointers to the previous and next links , respectively . To set up the linked-list , I have an install function that looks like this.Ove... | class Pair : def __init__ ( self , name , prefs , score ) : self.name = name self.score = score self.preferences = prefs self.next_pair = 0 self.prev_pair = 0 def install ( i , pair ) : flag = 0 try : old_pair = pair_array [ i ] while old_pair.next_pair ! = 0 : if old_pair == pair : # if pair in remainders : remainders... | How Does Calling Work In Python ? |
Python | I am currently using python 2.7 requests library and there is no support for ordered headers . I can put ordered data for post and get ( like an ordered dictionary ) but there is simply no support for headers . Not even in python 3I know HTTP protocol RFC , indicates that order of headers is insignificant , but the pro... | data= ( ( `` param1 '' , '' something '' ) , ( `` param2 '' , '' something_else '' ) ) headers= { 'id ' : 'some_random_number ' , 'version ' : 'some_random_number ' , 'signature ' : 'some_random_number ' , 'Content-Type ' : 'application/x-www-form-urlencoded ' , 'charset ' : 'utf-8 ' , 'Content-Length ' : str ( len ( u... | Python - Ordered Headers HTTP Requests |
Python | I am writing simple tray for windows using python.I succeeded in creating a tray icon , menu , sub menu . I stucked at adding image for particular tray item.here is code I used . ( Link ) Even this code did not work . Windows documentation is not clear.Can someone help me.EditAttaching image . In small box beside `` Op... | def addMenuItem ( self , wID , title , menu ) : path = os.path.dirname ( os.path.abspath ( __file__ ) ) path += `` \print_pref.ico '' option_icon = self.prep_menu_icon ( path ) item , extras = win32gui_struct.PackMENUITEMINFO ( text=title , hbmpItem=option_icon , wID=wID ) win32gui.InsertMenuItem ( menu , 0 , 1 , item ... | Add image in window tray menu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.