lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I have a situation with some parallel lists that need to be filtered based on the values in one of the lists . Sometimes I write something like this to filter them : This gives filtered_a == ( 1 , 2 ) and filtered_b == ( 7 , 8 ) However , changing the final condition from a < 3 to a < 0 causes an exception to be raised... | lista = [ 1 , 2 , 3 ] listb = [ 7 , 8 , 9 ] filtered_a , filtered_b = zip ( * [ ( a , b ) for ( a , b ) in zip ( lista , listb ) if a < 3 ] ) Traceback ( most recent call last ) : ... ValueError : need more than 0 values to unpack | Handling empty case with tuple filtering and unpacking |
Python | I 've got linear system to solve which consists of large , sparse matrices.I 've been using the scipy.sparse library , and its linalg sub-library to do this , but I ca n't get some of the linear solvers to work.Here is a working example which reproduces the issue for me : Running this produces the following errorfor th... | from numpy.random import randomfrom scipy.sparse import csc_matrixfrom scipy.sparse.linalg import spsolve , minresN = 10A = csc_matrix ( random ( size = ( N , N ) ) ) A = ( A.T ) .dot ( A ) # force the matrix to be symmetric , as required by minresx = csc_matrix ( random ( size = ( N,1 ) ) ) # create a solution vectorb... | Issues using the scipy.sparse.linalg linear system solvers |
Python | I came across this interesting example todaySo it seems that comparisons inside containers works differently in Python . I would expect that the call to == would use each object 's implementation of __eq__ , otherwise what 's the point ? AdditionallyDoes this mean that Python uses is from within container 's implementa... | class TestableEq ( object ) : def __init__ ( self ) : self.eq_run = False def __eq__ ( self , other ) : self.eq_run = True if isinstance ( other , TestableEq ) : other.eq_run = True return self is other > > > eq = TestableEq ( ) > > > eq.eq_runFalse > > > eq == eqTrue > > > eq.eq_runTrue > > > eq = TestableEq ( ) > > >... | How does Python 2.7 compare items inside a list |
Python | I 'm trying to write a function that retrieves a file under a specified name using the magic command % store.For example , if I have stored a file as `` df '' but later want to retrieve it under the name `` frame '' then I want to call the function using retrieve ( 'df ' , 'frame ' ) after which the variable frame woul... | import IPythonimport gcimport osimport numpy as npimport pandas as pdpath = IPython.paths.get_ipython_dir ( ) +'\profile_default\db\\autorestore\\ ' def retrieve ( inputfile , outputfile='temp ' ) : os.rename ( r '' +path+inputfile , r '' +path+outputfile ) % store -r outputfile os.rename ( r '' +path+outputfile , r ''... | Ipython use % store magic to retrieve dynamic name |
Python | I seem to have to problems determining which tool I can trust ... The tools i 've been testing is Librosa and Kaldi in creating dataset for plots visualizations of 40 filterbank energies of an audio file.The filterbank energies are extracted using these configuration in kaldi.fbank.confThe data extracted are plotted us... | -- htk-compat=false -- window-type=hamming -- sample-frequency=16000 -- num-mel-bins=40 -- use-log-fbank=true print static.shapeprint type ( static ) print np.min ( static ) print np.max ( static ) fig = plt.figure ( ) librosa.display.specshow ( static.T , sr=16000 , x_axis='frames ' , y_axis='mel ' , hop_length=160 , ... | Which tool can I trust ? |
Python | I have a C library that is compiled to a shared object and want to build a ctypes interface around it to call the C functions from Python.In general it works fine but there is this definition of a double array in the C library : I found no way to access this type directly , so I defined in Python : While this works out... | typedef double __attribute__ ( ( aligned ( 32 ) ) ) double_array [ 512 ] ; DoubleArray = ctypes.c_double * 512 | Python ctypes align data structure |
Python | I would like to parse Python code that contains semicolons ; for separating commands and produce code that replaces those by newlines \n . E.g. , fromI 'd like to produceAny hints ? | def main ( ) : a = `` a ; b '' ; return a def main ( ) : a = `` a ; b '' return a | replace semicolon by newline in python code |
Python | I am trying to use AWS DynamoDB in a Flutter app , and given the lack of an official AWS SDK for Dart I am forced to use the low level HTTP REST API.The method for signing an AWS HTTP request is quite tedious , but using an AWS supplied sample as a guide , I was able to convert the Python to Dart pretty much line-for-l... | import requestsheaders = { 'Content-Type ' : 'application/json ' , ' X-Amz-Date ' : '20190307T214900Z ' , ' X-Amz-Target ' : 'DynamoDB_20120810.GetItem ' , 'Authorization ' : 'AWS4-HMAC-SHA256 Credential=AKIAJFZWA7QQAQT474EQ/20190307/ap-southeast-2/dynamodb/aws4_request , SignedHeaders=content-type ; host ; x-amz-date ... | AWS HTTP API - same request but different response in Python Requests vs Dart HTTP |
Python | I 'm having trouble in python with the scipy.signal method called welch ( https : //docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.welch.html ) , which estimates the frequency spectrum of a time signal , because it does not ( at all ) provide the same output as MATLAB 's method called pwelch , given t... | import numpy as npfrom scipy.signal import welch , get_windowinput = np.genfromtxt ( 'python_input.csv ' , delimiter= ' , ' ) fs = 128window = get_window ( 'hamming ' , fs*1 ) ff , yy = welch ( input , fs=fs , window = window , noverlap = fs/2 , nfft=fs*2 , axis=0 , scaling= '' density '' , detrend=False ) np.savetxt (... | Scipy welch and MATLAB pwelch does not provide same answer |
Python | For a large set of randomly distributed points in a 2D lattice , I want to efficiently extract a subarray , which contains only the elements that , approximated as indices , are assigned to non-zero values in a separate 2D binary matrix . Currently , my script is the following : However , I suspect there must be a bett... | lat_len = 100 # lattice lengthinput = np.random.random ( size= ( 1000,2 ) ) * lat_lenbinary_matrix = np.random.choice ( 2 , lat_len * lat_len ) .reshape ( lat_len , -1 ) def landed ( input ) : output = [ ] input_as_indices = np.floor ( input ) for i in range ( len ( input ) ) : if binary_matrix [ input_as_indices [ i,0... | Fast array manipulation based on element inclusion in binary matrix |
Python | I 'm using pytest . I have a test which involves checking that an import is not made when something happens . This is easy enough to make , but when the test is run in pytest it gets run in the same process as many other tests , which may import that thing beforehand.Is there some way to mark a test to be run in its ow... | @ pytest.mark.run_in_isolationdef test_import_not_made ( ) : ... . | Mark test to be run in independent process |
Python | I 'm trying to build Python 3.7.2 in a Ubuntu 18.04 Docker container with the build being optimized ( -- enable-optimizations and -- with-lto ) . During this build , the tests ( specifically it looks like test_sys_settrace ) fail withIt is n't very clear to me why this is happening , and searching on unhandled exceptio... | unhandled exception during asyncio.run ( ) shutdowntask : < Task finished coro= < < async_generator_athrow without __name__ > ( ) > exception=RuntimeError ( `` ca n't send non-None value to a just-started coroutine '' ) > RuntimeError : ca n't send non-None value to a just-started coroutineunhandled exception during as... | Python 3.7.2 tests failure during build from unhandled exception during asyncio.run ( ) shutdown |
Python | Even though sets are unhashable , membership check in other set works : I expected TypeError : unhashable type : 'set ' , consistent with other behaviours in Python : So , how is set membership in other set implemented ? | > > > set ( ) in { frozenset ( ) } True > > > set ( ) in { } # does n't work when checking in dictTypeError : unhashable type : 'set ' > > > { } in { frozenset ( ) } # looking up some other unhashable type does n't workTypeError : unhashable type : 'dict ' | How/why does set ( ) in { frozenset ( ) } work ? |
Python | The Problem : I have two lists which contain tuples ( each consisting of a time stamp and a queue-length ) which need to be merged : I need a function merge ( L1 , L2 ) that returns : [ note : I do n't need the 60+80 - it is merely to indicate which values are added the result of 60+80 = 140 is what I need ] What I ext... | L1 = [ [ 0 , 50 ] , [ 7.75 , 120 ] , [ 10.25 , 70 ] , [ 17 , 100 ] , [ 20 , 60 ] ] L2 = [ [ 0 , 80 ] , [ 8 , 120 ] , [ 10 , 85 ] , [ 10.25 , 80 ] ] [ [ 0.00 , 50+80 ] , [ 7.75 , 120+80 ] , [ 8.00 , 120+120 ] , [ 10.00 , 85+120 ] , [ 10.25 , 70+80 ] , [ 17.00 , 100+80 ] , [ 20.00 , 60+80 ] ] # note | Merge two lists of tuples with timestamps and queue lengths |
Python | I ' ve got a bunch of tasks in Celery all connected using a canvas chain . So far so good . The problem is that I 'm looking for the best practice when it comes to using a common utility function like this : What't the best way to do that without the tasks blocking ? For example can I just replace run common cleanup fu... | @ shared_task ( bind=True ) def my_task_A ( self ) : try : logger.debug ( 'running task A ' ) do something except Exception : run common cleanup function @ shared_task ( bind=True ) def my_task_B ( self ) : try : logger.debug ( 'running task B ' ) do something else except Exception : run common cleanup function ... def... | Share a common utility function between Celery tasks |
Python | I 'm writing an application that involves having users enter time 's in the following format : The data can have a single `` minute designation '' , a single `` second designation '' , or both . What is the proper way to parse these strings into a format similar to : | 1m30s # 1 Minute , 30 Seconds3m15s # 3 Minutes , 15 Seconds2m25s # 2 Minutes , 25 Seconds2m # 2 Minutes55s # 55 Seconds { `` minutes '' : 3 `` seconds '' : 25 } | Parsing 'time string ' with Python ? |
Python | Here is a contrived example of how a lot of our classes return binary representations ( to be read by C++ ) of themselves.What I dislike : Every line starts with data.append ( struct.pack ( , distracting from the unique part of the line.The byte order ( ' < ' ) is repeated over and over again.You have to remember to re... | def to_binary ( self ) : 'Return the binary representation as a string . ' data = [ ] # Binary version number . data.append ( struct.pack ( ' < I ' , [ 2 ] ) ) # Image size . data.append ( struct.pack ( ' < II ' , *self.image.size ) ) # Attribute count . data.append ( struct.pack ( ' < I ' , len ( self.attributes ) ) )... | More Pythonic conversion to binary ? |
Python | I 'm using fixture to test a Pylons app , but I stumbled upon a problem.Let 's say I have such data set : Now , the problem is , that when I use this data in a functional test ( like described at http : //farmdev.com/projects/fixture/using-fixture-with-pylons.html ) , I ca n't obtain the id ( primary key ) of the compa... | class CompanyData ( DataSet ) : class test_company : company_full_name = u'Firma Tęst ' company_short_name = u'TęstCo'class UserData ( DataSet ) : class test_user : user_login = 'testuser ' user_password = 'test ' company = CompanyData.test_company self.app.post ( url ( controller='main ' , action='login ' ) , params= ... | Getting the primary key ( id ) in fixture ( Python , SQLAlchemy ) |
Python | In python 2.x , super accepts the following casesas far as I see , super is a class , wrapping the type and ( eventually ) the instance to resolve the superclass of a class.I 'm rather puzzled by a couple of things : why there is also no super ( instance ) , with typical usage e.g . super ( self ) .__init__ ( ) . Techn... | class super ( object ) | super ( type ) - > unbound super object | super ( type , obj ) - > bound super object ; requires isinstance ( obj , type ) | super ( type , type2 ) - > bound super object ; requires issubclass ( type2 , type ) | Typical use to call a cooperative superclass method : | Why python super does not accept only instance ? |
Python | Given a range , how could I find all sets of size x that meet the specific criteria of being at least x distance apart , not exceeding the range maximum ? If I wanted to find sets of three numbers that are 5 apart in a range of 30 , I 'd expect to get these values back : I 've looked at itertools , thinking there would... | [ 0,5,10 ] [ 0,6,11 ] [ 0,7,12 ] ..etc [ 1,6,11 ] [ 1,7,12 ] [ 1,8,13 ] ..etc lst = [ ( x , x+5 , x+10 ) for x in range ( 20 ) ] | Python : find all sets of numbers inside a range where each set contains values that are x distance apart and do n't exceed the range |
Python | EDIT : Could you read my question more carefully ? This question is specific and not duplicated as has been said . Obviously I read this question before post . In this demo code from the docs , the fragment after the lang parameter will be static . So , in English /en/about , and for example , in Portuguese /pt/about .... | from flask import Flask , gapp = Flask ( __name__ ) @ app.url_defaultsdef add_language_code ( endpoint , values ) : if 'lang_code ' in values or not g.lang_code : return if app.url_map.is_endpoint_expecting ( endpoint , 'lang_code ' ) : values [ 'lang_code ' ] = g.lang_code @ app.url_value_preprocessordef pull_lang_cod... | Format canonical URL structure correctly with URL Processors |
Python | I have two 4 column numpy arrays ( 2D ) with several hundred ( float ) rows ( cap and usp ) in each . Considering a subset of 3 columns in each array ( e.g . capind=cap [ : ,:3 ] ) : There are many common rows between both arrays.Each row tuple/ '' triplet '' is unique in each array.I am looking for an an efficient mea... | cap=array ( [ [ 2.50000000e+01 , 1.27000000e+02 , 1.00000000e+00 , 9.81997200e-06 ] , [ 2.60000000e+01 , 1.27000000e+02 , 1.00000000e+00 , 9.14296800e+00 ] , [ 2.70000000e+01 , 1.27000000e+02 , 1.00000000e+00 , 2.30137100e-04 ] , ... , [ 6.10000000e+01 , 1.80000000e+02 , 1.06000000e+02 , 8.44939900e-03 ] , [ 6.20000000... | 2D numpy array search ( equivalent toMatlab 's intersect 'rows ' option ) |
Python | I 'm aware that django test cases are done with DEBUG=False and TEMPLATE_DEBUG=False , and that I can change it to True for a specific function , using But maybe there is a better , more generic solution that apply for eveything at once ? I have an error in my template : I included another template and the link is brok... | from django.test.utils import override_settings @ override_settings ( DEBUG=True ) def test_one_function ( self ) : # This test should be failing and is not . # If I did not test manually I would'nt know ! pass | How to make test case fail if a django template has a rendering error that would silently fail in production |
Python | I try and keep my code within 80 characters wide so it is easy to see side by side in a standard window I set up . In doing this , I have a Python v2.7 construct like this : So I broke it up like this : But that caused errors NameError : name 'subseq_id_to_intervals_dict ' is not definedUntil I added backslashes : Why ... | subseq_id_to_intervals_dict , subseq_id_to_ccid_formats_dict , subseq_id_to_min_max_count_dict = map_cases ( opts , format_to_ccid_funcs , sys.stdin ) subseq_id_to_intervals_dict , subseq_id_to_ccid_formats_dict , subseq_id_to_min_max_count_dict = map_cases ( opts , format_to_ccid_funcs , sys.stdin ) subseq_id_to_inter... | Avoiding long lines of code in Python |
Python | I 'm looking for a library ( preferably Python , but the language does n't matter much ) that is able to iterate recurring iCal events and handles specific instances automatically.The iCal file that I 'm working with contains recurring events ( for example : RRULE : FREQ=WEEKLY ; UNTIL=20150614 ; BYDAY=MO , TU , WE , T... | [ { start : '2015-06-15 09:00:00 ' , end : '2015-06-15 10:00:00 ' } , { start : '2015-06-16 09:00:00 ' , end : '2015-06-16 10:00:00 ' } , { start : '2015-06-18 09:00:00 ' , end : '2015-06-18 10:00:00 ' } , { start : '2015-06-19 10:00:00 ' , end : '2015-06-19 11:00:00 ' } , ] | iCal library to iterate recurring events with specific instances |
Python | I have a 3D matrix A of dimensions h x w x c. I want to extract patches of dimensions ph x pw from each `` channel '' c. ph divides h and pw divides w. In this example , I know how to do this in tensorflow using gather_nd but I was hoping for something more efficient in terms of setting it up , because the dimensions w... | h x w x c = 4 x 4 x 3ph x pw = 2 x 2 | Extract patches from 3D Matrix |
Python | In MATLAB I can issue the command : In order to compute the eigenvalues without the balance option.What is the equivalent command in NumPy ? When I run the NumPy version of eig , it does not produce the same result as the MATLAB result with nobalance turned on . | [ X , L ] = eig ( A , 'nobalance ' ) ; | How to use eig with the nobalance option as in MATLAB ? |
Python | I 've created a toy graph with the iris dataset . My layout is from PCA ordination which separates out the nodes nicely . I 've recently discovered edge bundling . Does anybody know of a way to do this with matplotlib and networkx ? Here is an example of edge bundling from datashader ( not for this graph ) . Aside from... | from sklearn.decomposition import PCAimport pandas as pdimport networkx as nximport matplotlib.pyplot as pltimport numpy as np # DataX_iris = pd.DataFrame ( { 'sepal_length ' : { 'iris_0 ' : 5.1 , 'iris_1 ' : 4.9 , 'iris_2 ' : 4.7 , 'iris_3 ' : 4.6 , 'iris_4 ' : 5.0 , 'iris_5 ' : 5.4 , 'iris_6 ' : 4.6 , 'iris_7 ' : 5.0... | How to use `` edge bundling '' with networkx and matplotlib in Python ? |
Python | Let 's say I have two python functions f and g : These two functions are clearly functionally equivalent ( both return x**2 + 1 ) .My definition of functionally equivalent is as follows : If two functions f and g always produce the same output given the same input , then f and g are functionally equivalent.Further , le... | def f ( x ) : y = x**2 + 1 return ydef g ( x ) : a = x**2 b = a + 1 return b | Is it possible to know if two python functions are functionally equivalent ? |
Python | You have an array A , and you want to turn every value in it as an absolute value . The problem iscreates a new matrix , and the values in A stay where they were . I find two ways to set put the absolute values back to AorBased on timeit test , their performance is almost the sameQuestion : Are there more efficient way... | numpy.abs ( A ) A *= numpy.sign ( A ) A [ : ] = numpy.abs ( A ) | Numpy set absolute value in place |
Python | I am making algorithm for checking the string ( e-mail ) - like `` E-mail addres is valid '' but their are rules . First part of e-mail has to be string that has 1-8 characters ( can contain alphabet , numbers , underscore [ _ ] ... all the parts that e-mail contains ) and after @ the second part of e-mail has to have ... | email = raw_input ( `` Enter the e-mail address : '' ) length = len ( email ) if length > 20 print `` Address is too long '' elif lenght < 7 : print `` Address is too short '' if not email.endswith ( `` .com '' ) : print `` Address does n't contain correct domain ending '' try : first_part = len ( splitting [ 0 ] ) sec... | Filtering string in Python |
Python | I have a task of creating a script which takes a huge text file as an input . It then needs to find all words and the number of occurrences and create a new file with each line displaying a unique word and its occurrence . As an example take a file with this content : I need to create a file which looks like this : For... | Lorem ipsum dolor sit amet , consectetur adipisicing elit , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua . Ut enim ad minim veniam , quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat . Duis aute iruredolor in reprehenderit in voluptate velit esse cillum dolore eu fug... | Is it possible to make this shell script faster ? |
Python | Python 3.3I 've constructed this slightly cryptic piece of python 3.3 : If I use a generator comprehension inside a list constructor , I get a different result : Why is n't the list comprehension returning a list ? Python 2.7I can get a similarly odd effect in python 2 ( using a set comprehension , because list compreh... | > > > [ ( yield from ( i , i + 1 , i ) ) for i in range ( 5 ) ] < generator object < listcomp > at 0x0000008666D96900 > > > > list ( _ ) [ 0 , 1 , 0 , 1 , 2 , 1 , 2 , 3 , 2 , 3 , 4 , 3 , 4 , 5 , 4 ] > > > list ( ( yield from ( i , i + 1 , i ) ) for i in range ( 5 ) ) [ 0 , 1 , 0 , None , 1 , 2 , 1 , None , 2 , 3 , 2 , ... | ( list|set|dict ) comprehension containing a yield expression does not return a ( list|set|dict ) |
Python | Have a 2-dimensional array , like -Need to select one element from each of the sub-array in a way that the resultant set of numbers are closest , that is the difference between the highest number and lowest number in the set is minimum.The answer to the above will be = [ 9 , 6 , 8 , 7 ] .Have made an algorithm , but do... | a [ 0 ] = [ 0 , 4 , 9 ] a [ 1 ] = [ 2 , 6 , 11 ] a [ 2 ] = [ 3 , 8 , 13 ] a [ 3 ] = [ 7 , 12 ] INPUT - Dictionary : table { } OUTPUT - Dictionary : low_table { } # N = len ( table ) for word_key in table : for init in table [ word_key ] : temp_table = copy.copy ( table ) del temp_table [ word_key ] per_init = copy.copy... | Finding N closest numbers |
Python | I am doing a Kaggle tutorial for Titanic using the Datacamp platform.I understand the use of .loc within Pandas - to select values by row using column labels ... My confusion comes from the fact that in the Datacamp tutorial , we want to locate all the `` Male '' inputs within the `` Sex '' column , and replace it with... | titanic.loc [ titanic [ `` Sex '' ] == `` male '' , `` Sex '' ] = 0 titanic.loc [ `` male '' , `` Sex '' ] = 0 | Python .loc confusion |
Python | does create the file , but it contains nothing.I had to useBut would n't the from ... import ... automatically make the name available ? Why do I still have to use sys.stdout instead of stdout ? | from sys import stdoutstdout = open ( 'file ' , ' w ' ) print 'test'stdout.close ( ) import syssys.stdout = open ( 'file ' , ' w ' ) print 'test'sys.stdout.close ( ) | Why the following python code does not print to file |
Python | We have a numpy-based algorithm that is supposed to handle data of different type.If we pass a=np.array [ 1.0 , 2.0 , 3.0 ] then b evaluates to [ 6.0 ] .If we pass a=6.0 then we get The desired behavior would be that we get same return value 6.0 not ( [ 6.0 ] ) for both inputs.What is the correct pythonic and safe way ... | def my_fancy_algo ( a ) : b = np.sum ( a , axis=1 ) # Do something b return b *** ValueError : 'axis ' entry is out of bounds | Sum up over np.array or np.float |
Python | I just found the pattern matching feature in Racket very powerful.Is there similar syntax sugar or library to do that in Python ? | > ( match ' ( 1 2 3 ) [ ( list a b c ) ( list c b a ) ] ) ' ( 3 2 1 ) > ( match ' ( 1 2 3 ) [ ( list 1 a ... ) a ] ) ' ( 2 3 ) > ( match ' ( 1 2 3 ) [ ( list 1 a ..3 ) a ] [ _ 'else ] ) 'else > ( match ' ( 1 2 3 4 ) [ ( list 1 a ..3 ) a ] [ _ 'else ] ) ' ( 2 3 4 ) > ( match ' ( 1 2 3 4 5 ) [ ( list 1 a ..3 5 ) a ] [ _ ... | Are there pattern matching functions in Python like this ? |
Python | This is pretty bad micro-optimizing , but I 'm just curious . It usually does n't make a difference in the `` real '' world.So I 'm compiling a function ( that does nothing ) using compile ( ) then calling exec on that code and getting a reference to the function I compiled . Then I 'm executing it a couple million tim... | import datetimedef getCompiledFunc ( ) : cc = compile ( `` def aa ( ) : pass '' , ' < string > ' , 'exec ' ) dd = { } exec cc in dd return dd.get ( 'aa ' ) compiledFunc = getCompiledFunc ( ) def localFunc ( ) : passdef testCall ( f ) : st = datetime.datetime.now ( ) for x in xrange ( 10000000 ) : f ( ) et = datetime.da... | Why is an empty function call in python around 15 % slower for dynamically compiled python code |
Python | Given a list of sets : What is a pythonic way to compute the corresponding list of sets of elements having no overlap with other sets ? Is there a way to do this with a list comprehension ? | allsets = [ set ( [ 1 , 2 , 4 ] ) , set ( [ 4 , 5 , 6 ] ) , set ( [ 4 , 5 , 7 ] ) ] only = [ set ( [ 1 , 2 ] ) , set ( [ 6 ] ) , set ( [ 7 ] ) ] | Subtraction over a list of sets |
Python | Python has the built-in function type : class type ( object ) With one argument , return the type of an object . The return value is a type object and generally the same object as returned by object.__class__.Python also has the special attribute __class__ : instance.__class__The class to which a class instance belongs... | def __instancecheck__ ( cls , instance ) : `` '' '' Override for isinstance ( instance , cls ) . '' '' '' # Inline the cache checking subclass = instance.__class__ # [ … ] subtype = type ( instance ) if subtype is subclass : # [ … ] | When is type ( instance ) different from instance.__class__ ? |
Python | I was surprised to discover recently that while dicts are guaranteed to preserve insertion order in Python 3.7+ , sets are not : What is the rationale for this difference ? Do the same efficiency improvements that led the Python team to change the dict implementation not apply to sets as well ? I 'm not looking for poi... | > > > d = { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 } > > > d { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 } > > > d [ 'd ' ] = 4 > > > d { ' a ' : 1 , ' b ' : 2 , ' c ' : 3 , 'd ' : 4 } > > > s = { ' a ' , ' b ' , ' c ' } > > > s { ' b ' , ' a ' , ' c ' } > > > s.add ( 'd ' ) > > > s { 'd ' , ' b ' , ' a ' , ' c ' } | Why do n't Python sets preserve insertion order ? |
Python | I have a C++ program , I want to import a Python module and list all function names in this module . How can I do it ? I used the following code to get the dict from a module : But how to list the functions names ? | PyDictObject* pDict = ( PyDictObject* ) PyModule_GetDict ( pModule ) ; | How to list all function names of a Python module in C++ ? |
Python | I have a code framework which involves dumping sessions with dill . This used to work just fine , until I started to use pandas . The following code raises a PicklingError on CentOS release 6.5 : The problem seems to stem from pandas.algos . In fact , it 's enough to run this to reproduce the error : The error is pickl... | import pandasimport dilldill.dump_session ( ' x.dat ' ) import pandas.algosimport dilldill.dump_session ( ' x.dat ' ) / dill.dumps ( pandas.algos ) > > > dill.detect.badobjects ( pandas.algos , depth = 1 ) { '__builtins__ ' : < module '__builtin__ ' ( built-in ) > , '_return_true ' : < cyfunction lambda2 at 0x1484d70 >... | pandas.algos._return_false causes PicklingError with dill.dump_session on CentOS |
Python | Twisted includes a reactor implemented on top of MsgWaitForMultipleObjects . Apparently the reactor has problems reliably noticing when a TCP connection ends , at least in the case where a peer sends some bytes and then quickly closes the connection . What seems to happen is : The reactor calls MsgWaitForMultipleObject... | Waits until one or all of the specified objects are in the signaled stateor the time-out interval elapses . | How can a disconnected TCP socket be reliably detected using MsgWaitForMultipleObjects ? |
Python | Basically I have an array that may vary between any two numbers , and I want to preserve the distribution while constraining it to the [ 0,1 ] space . The function to do this is very very simple . I usually write it as : Of course it can and should be more complex to account for tons of situations , such as all the val... | def to01 ( array ) : array -= array.min ( ) array /= array.max ( ) return array | NumPy array to bounded by 0 and 1 ? |
Python | I noticed that Stack Overflow 's number of users and their reputation follows an interesting distribution . I created a pandas DF to see if I could create a parametric fit : Which returns this : If I graph this , I obtain the following chart : The distribution seems to follow a Power Law . So to better visualize it , I... | import pandas as pdimport numpy as npsoDF = pd.read_excel ( 'scores.xls ' ) print soDF total_rep users0 1 43642261 200 2691102 500 1588243 1000 903684 2000 486095 3000 326046 5000 189217 10000 86188 25000 28029 50000 100010 100000 334 soDF [ 'log_total_rep ' ] = soDF [ 'total_rep ' ] .apply ( np.log10 ) soDF [ 'log_use... | using pandas and numpy to parametrize stack overflow 's number of users and reputation |
Python | I have data streaming into a number of TCP sockets continuously . For each , I have a different regular expression that I need to pull out matches for . For example , one might match numbers of the format # # . # followed by the letter f : Another might match numbers of the format # # # preceded by the letter Q : In re... | r = re.compile ( rb ' ( [ 0-9 ] [ 0-9 ] \ . [ 0-9 ] ) f ' ) r = re.compile ( rb ' Q ( [ 0-9 ] [ 0-9 ] [ 0-9 ] ) ' ) def advance ( self ) : m = self.r.search ( self.buffer ) # No match . Return . if m is None : return None # Match . Advance the buffer and return the matched groups . self.buffer = self.buffer [ m.end ( )... | Incrementally finding regular expression matches in streaming data in Python |
Python | I am working on a project where I have large input files which come from numerical solutions of pdes . The format of the data is as follows.For each value of y , we have several values of x , and the function value evaluated at each point . The size of the data I 'm dealing with is about [ -3 , 5 ] x [ -3 , 5 ] in step... | x \t y \t f ( x , y ) | Storing and reading large data files efficiently |
Python | With Python 3.8 Assignment Expressions have been introduced , allowing to assign values in conditionals and lambdas as such : However it appears this does not extends to attribute assignment , as trying to do something like thisWill result in the following error : Is it really only possible to update attribute in assig... | if x : = True : print ( x ) from typing import NamedTuple class Test ( NamedTuple ) : field : booltest = Test ( field=False ) if test.field : = True : print ( test.field ) SyntaxError : can not use named assignment with attribute | Can not set field value in assignment expression |
Python | I 'm new to Apache Beam , and I want to calculate the mean and std deviation over a large dataset.Given a .csv file of the form `` A , B '' where A , B are ints , this is basically what I have.I 'd like to do something like : or something , but I ca n't figure out how . | import apache_beam as beamfrom apache_beam.options.pipeline_options import PipelineOptionsfrom apache_beam.io.textio import ReadFromTextclass Split ( beam.DoFn ) : def process ( self , element ) : A , B = element.split ( ' , ' ) return [ ( ' A ' , A ) , ( ' B ' , B ) ] with beam.Pipeline ( options=PipelineOptions ( ) )... | How to compute standard deviation in Apache Beam |
Python | This is somehow related to my question Why is `` > 0 True in Python ? In Python 2.6.4 : From the answer to my original question I understand that when comparing objects of different types in Python 2.x the types are ordered by their name . But in this case : Why is Decimal ( ' 0 ' ) > 9999.0 == True then ? UPDATE : I u... | > > Decimal ( ' 0 ' ) > 9999.0True > > type ( Decimal ( ' 0 ' ) ) .__name__ > type ( 9999.0 ) .__name__False > > Decimal ( ' 0 ' ) > 9999.0False | Why is Decimal ( ' 0 ' ) > 9999.0 True in Python ? |
Python | For some reason , after pip is upgraded to version 19.0 , I 'm not able to install the most recent version of numpy ( it still perfectly works with pip version 18.1 ) .When I runI get this exceptionI 'm also using python version 3.6 , and virtualenvwrapper version 16.0.0.UPD 0gives this tremendous outputUPD 1I 've open... | pip install numpy -- no-cache Exception : Traceback ( most recent call last ) : File `` /home/me/.venvs/_/lib/python3.6/site-packages/pip/_internal/cli/base_command.py '' , line 176 , in main status = self.run ( options , args ) File `` /home/me/.venvs/_/lib/python3.6/site-packages/pip/_internal/commands/install.py '' ... | Ca n't install numpy after a pip upgrade |
Python | If I initialise a python listthen it returnsbut if I do the same with a numpy arraythen it only returnsHow can I make it return a nested empty list as it does for a normal python list ? | x = [ [ ] , [ ] , [ ] ] print ( x ) [ [ ] , [ ] , [ ] ] x = np.array ( [ np.array ( [ ] ) , np.array ( [ ] ) , np.array ( [ ] ) ] ) print ( x ) [ ] | why are empty numpy arrays not printed |
Python | I 'm just fiddling with a simulation of ( Mendel 's First Law of Inheritance ) .Before i can let the critters mate and analyze the outcome , the population has to be generated , i.e. , a list has to be filled with varying numbers of three different types of tuples without unpacking them.While trying to get familiar wit... | import itertoolsk = 2m = 3n = 4hd = ( ' A ' , ' A ' ) # homozygous dominanthet = ( ' A ' , ' a ' ) # heterozygous hr = ( ' a ' , ' a ' ) # homozygous recessivefhd = itertools.repeat ( hd , k ) fhet = itertools.repeat ( het , m ) fhr = itertools.repeat ( hr , n ) population = [ x for x in fhd ] + [ x for x in fhet ] + [... | Populate list with tuples |
Python | From what I ’ ve read , unit test should test only one function/method at a time . But I ’ m not clear on how to test methods that only set internal object data with no return value to test off of , like the setvalue ( ) method in the following Python class ( and this is a simple representation of something more compli... | class Alpha ( object ) : def __init__ ( self ) : self.__internal_dict = { } def setvalue ( self , key , val ) : self.__internal_dict [ key ] = val def getvalue ( self , key ) : return self.__internal_dict [ key ] import pytestdef test_alpha01 ( ) : alpha = Alpha ( ) alpha.setvalue ( 'abc ' , 33 ) expected_val = 33 resu... | How do I unit test a method that sets internal data , but does n't return ? |
Python | Why should we have this inconsistency : | import numpy as npa = np.array ( [ 0 ] ) b = np.array ( [ None ] ) c = np.array ( [ `` ] ) d = np.array ( [ ' ' ] ) > > > bool ( a ) False > > > bool ( b ) False > > > bool ( c ) True > > > bool ( d ) False | Truth value of numpy array with one falsey element seems to depend on dtype |
Python | Here 's a CPython program that tries to initialize the interpreter with an empty sys.path : Executing the program above raises the following error : So which of the packages and modules in the Python 3.5 standard library , besides the encodings package , are absolutely required to run the Python 3.5 interpreter ? This ... | # include < Python.h > int main ( int argc , char** argv ) { wchar_t* program = NULL ; wchar_t* sys_path = NULL ; Py_NoSiteFlag = 1 ; program = Py_DecodeLocale ( argv [ 0 ] , NULL ) ; Py_SetProgramName ( program ) ; sys_path = Py_DecodeLocale ( `` '' , NULL ) ; Py_SetPath ( sys_path ) ; Py_Initialize ( ) ; PyMem_RawFre... | Which standard library modules are required to run the Python 3.5 interpreter ? |
Python | How do I encode my hyphenated fasta format string to group all consecutive Nucleotide and hyphens and encode them as run length.Consider my sequence as `` ATGC -- -- CGCTA -- -- -G -- - '' . The string has sequence of Nucleotide followed by sequence of hyphens . I am trying to group all consecutive Nucleotide as the le... | ATGC -- -- CGCTA -- -- -G -- - | | | | | | V V V V V V4M 4D 5M 5D 1M 3D from collections import Counterseq= '' ATGC -- -- CGCTA -- -- -G -- - '' M=0D=0 cigar= [ ] for char in seq : if char.isalpha ( ) : M+=1 cigar.append ( `` M '' ) else : D+=1 cigar.append ( `` D '' ) print Counter ( cigar ) | Counting consecutive alphabets and hyphens and encode them as run length |
Python | I am using the kubernetes python client . In the event that kubernetes is n't available when my code starts up , I would like to retry the connection . When the client is unable to connect , it throws what appears to be a urllib3.exceptions.MaxRetryError exception , so I started with something like this : But that comp... | import timeimport urllib3import kuberneteskubernetes.config.load_kube_config ( ) api = kubernetes.client.CoreV1Api ( ) while True : try : w = kubernetes.watch.Watch ( ) for event in w.stream ( api.list_pod_for_all_namespaces ) : print event except urllib3.exceptions.HTTPError : print ( 'retrying in 1 second ' ) time.sl... | isinstance ( ) unexpectedly returning False |
Python | One way to manually persist a dictionary to a database is to flatten it into a sequence of sequences and pass the sequence as an argument to cursor.executemany ( ) .The opposite is also useful , i.e . reading rows from a database and turning them into dictionaries for later use.What 's the best way to go from myseq to ... | > > > myseq = ( ( 0,1,2,3 ) , ( 4,5,6,7 ) , ( 8,9,10,11 ) ) > > > mydict = { 0 : ( 1 , 2 , 3 ) , 8 : ( 9 , 10 , 11 ) , 4 : ( 5 , 6 , 7 ) } | Convert a sequence of sequences to a dictionary and vice-versa |
Python | For example : Only imagine this had several thousand / million such names , all unique by first name.If I wanted to see if the key `` Paul '' existed , what does it do under the hood ? | d = { `` John '' : `` Doe '' , `` Paul '' : `` Allen '' , `` Bill '' : `` Gates '' } | Does Python optimize dictionary lookups under the hood ? |
Python | Here is a simple matlab script to read a csv file , and generate a plot ( with which I can zoom in with the mouse as I desire ) . I would like to see an example of how this is done in python and mathplotlib.In general , the examples in mathplotlib tutorials I 've seen will create a static graph , but it 's not interact... | data = csvread ( 'foo.csv ' ) ; % read csv data into vector 'data'figure ; % create figureplot ( data , ' b ' ) ; % plot the data in blue | How can I duplicate this simple matlab plot functionality with mathplotlib ? |
Python | I 'm trying to do a doctest . The 'Expected ' and 'Got ' results are identical , but my doctest still fails . It 's failing because there are trailing spaces after x-axis y-axis in the printout which I have n't included in my docstring . How do I include it though ? When I insert the spaces manually , and do the test ,... | import pandas as pdimport doctestclass NewDataStructure ( pd.DataFrame ) : `` '' '' > > > arrays = [ [ 1 , 1 , 2 , 2 ] , [ 10 , 20 , 10 , 20 ] ] > > > index = pd.MultiIndex.from_arrays ( arrays , names= ( ' x-axis ' , ' y-axis ' ) ) > > > data_input = { `` Pressure ( Pa ) '' : [ 1+1j , 2+2j , 3+3j , 4+4j ] , ... `` Tem... | How to insert trailing spaces in a doctest , so that it does n't fail even when actual and expected result look the same ? |
Python | If I have an numpy array like the one below , how can I right justify or left justify the elements tat are greater than zero for example , If I wanted to right justify this array , it would look like : | [ [ 0 . 5 . 0 . 2 . ] [ 0 . 0 . 3 . 2 . ] [ 0 . 0 . 0 . 0 . ] [ 2 . 0 . 0 . 1 . ] ] [ [ 5 . 2 . 0 . 0 . ] [ 3 . 2 . 0 . 0 . ] [ 0 . 0 . 0 . 0 . ] [ 2 . 1 . 0 . 0 . ] ] | Python : moving all elements greater than 0 to left and right in numpy array |
Python | I have a list in Python that I generate as part of the program . I have a strong assumption that these are all different , and I check this with an assertion.This is the way I do it now : If there are two elements : If there are three : And if I ever have to do this with four elements I 'll go crazy.Is there a better w... | try : assert ( x [ 0 ] ! = x [ 1 ] ) except : print debug_info raise Exception ( `` throw to caller '' ) try : assert ( x [ 0 ] ! = x [ 1 ] ) assert ( x [ 0 ] ! = x [ 2 ] ) assert ( x [ 1 ] ! = x [ 2 ] ) except : print debug_info raise Exception ( `` throw to caller '' ) | What 's the most pythonic way to ensure that all elements of a list are different ? |
Python | When multiplying a numpy float with a list , the float is automatically cast to intA normal float gives a TypeErrorHowever , the numpy float can not be used for indexingWhat is the logic behind this behaviour ? | > > > import numpy as np > > > a = [ 1 , 2 , 3 ] > > > np.float64 ( 2.0 ) * a # # # This behaves as 2 * a [ 1 , 2 , 3 , 1 , 2 , 3 ] > > > 2.0 * a # # # This does notTraceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : ca n't multiply sequence by non-int of type 'float ' > > > ... | Why is float64 cast to int when multiplying with a list ? |
Python | I am using this Python ORM to manage my database in my application : ponyorm.comI just changed an attribute in my table , I would make a rowcount to me that he return 1 for TRUE and 0 for FALSE.Ex : Using sqlite3 only I would do so : | user = conn.execute ( 'SELECT * FROM users ' ) count = user.rowcountif count == 1 : print ( 'Return % d lines ' % count ) else : print ( 'Bad ... .return % d lines ' , % count ) | how to make a rowcount in ponyorm ? Python |
Python | Python 3I learn Python via a book . Right now I learned that Python has n't constants in that sense in which they are available in C ++ or C # ... For example , it is possible to write such danger code : Hm ... It is an unpleasant surprise for me ... I.e . potentially I am not protected from the fact that any module ( ... | > > > import math > > > math.pi3.141592653589793 > > > math.pi = 123.456 > > > math.pi123.456 > > > | Why Python has n't true constants ? Is it not dangerous ? |
Python | I want to create a FastAPI endpoint that just accepts an arbitrary post request body and returns it.If I send { `` foo '' : `` bar '' } , I want to get { `` foo '' : `` bar '' } back . But I also want to be able to send { `` foo1 '' : `` bar1 '' , `` foo2 '' : `` bar2 '' } and get that back.I tried : But that returns a... | from fastapi import FastAPIapp = FastAPI ( ) app.post ( `` / '' ) async def handle ( request : BaseModel ) : return request | FastAPI/Pydantic accept arbitrary post request body ? |
Python | I am stuck on a little issue in the project I am currently working on.Getting straight to the point , let 's assume I have a 2-dimensional numpy.array - I will call it arr . I need to slice arr , but this slice must contain some padding depending on the selected interval.Example : Actually , numpy 's response for arr [... | arr = numpy.array ( [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 10 ] , [ 11 , 12 , 13 , 14 , 15 ] , [ 16 , 17 , 18 , 19 , 20 ] , [ 21 , 22 , 23 , 24 , 25 ] ] ) array ( [ [ 19 , 20 ] , [ 24 , 25 ] ] ) array ( [ [ 19 , 20 , 0 , 0 ] , [ 24 , 25 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] ) array ( [ [ 0 , 0 , 0 , ... | How to get a padded slice of a multidimensional array ? |
Python | We upgraded our sklearn from the old 0.13-git to 0.14.1 , and find the performance of our logistic regression classifier changed quite a bit . The two classifiers trained with the same data have different coefficients , and thus often give different classification results.As an experiment I used 5 data points ( high di... | clf.fit ( data_test.data , y ) LogisticRegression ( C=10 , class_weight='auto ' , dual=False , fit_intercept=True , intercept_scaling=1 , penalty='l2 ' , tol=0.0001 ) np.sort ( clf.coef_ ) array ( [ [ -0.12442518 , -0.11137502 , -0.11137502 , ... , 0.05428562,0.07329358 , 0.08178794 ] ] ) clf1.fit ( data_test.data , y ... | Different versions of sklearn give quite different training results |
Python | Suppose we have this list : Separately , both ways to slice work as expected : But , when combined : I would expect it to be [ 7 , 6 , 5 ,4 , 3 ] or perhaps [ 6 , 5 , 4 , 3 , 2 ] ( if reversing happened first ) .It is also interesting to consider what happens when either start or stop parameters are not passed : This i... | > > > a = [ x for x in range ( 10 ) ] > > > print ( a ) [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] > > > a [ 3:8 ] [ 3 , 4 , 5 , 6 , 7 ] > > > a [ : :-1 ] [ 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ] > > > a [ 3:8 : -1 ] [ ] > > > a [ :5 : -1 ] [ 9 , 8 , 7 , 6 ] | Strange behavior with python slicing |
Python | I have a property that only gets computed once per instance and that uses None as a guard value . This is a pretty common pattern with properties.What 's the best way to annotate it ? edit/clarification : This question is about how to use mypy to validate my property 's code . Not about how to refactor the code . The p... | class Book : def __init__ ( self , title ) : self.title = title _the_answer = None # line 6 # _the_answer : int = None # line 7 def __str__ ( self ) : return `` % s = > % s '' % ( self.title , self.the_answer ) @ property def the_answer ( self ) - > int : `` '' '' always should be an int . Not an Optional int '' '' '' ... | Property annotation that checks assignment to a guard value initially set to None |
Python | If I had the table : And wanted to do two things 1 ) Pick out the column with the highest value across the axis and assign it to a column 2 ) Take the value and assign it to another column , such as : Is this possible ? | a b c15 15 520 10 725 30 9 a b c 1st 1st_value 2nd 2nd_value 3rd 3rd_value15 15 5 a/b 15 c 5 NaN NaN20 10 7 a 20 b 10 c 725 30 9 b 30 a 25 c 9 | Ranking columns and selecting column names |
Python | Does python support chaining is operators , such as the following ? This outputs True , some doc references would be nice . | a = Noneb = Nonea is b is None | Chaining `` is '' operators |
Python | I do have several screens . One of them ( DataScreen ) contains 8 labels which should show the current sensor values . Sensors are read by a separate process ( which is started from the MainScreen ) . The process itself is an instance of multiprocessing.Process.I can get a reference to the labels by sensor_labels = sel... | for item in sensor_labels : item.text = 'Update ' # ! /usr/bin/env python '' '' '' Reading sensor data '' '' '' from kivy.config import ConfigConfig.set ( 'kivy ' , 'keyboard_mode ' , 'multi ' ) from kivy.app import Appfrom kivy.lang import Builderfrom kivy.properties import StringProperty , ObjectProperty , NumericPro... | Update labels in a separate worker ( Process instance ) |
Python | While reading some CTF write-ups I came across this scriptAnd when I run it on my usb.pcap I get this error : Why it is happening ? | # ! /usr/bin/env pythonimport structimport Imageimport dpktINIT_X , INIT_Y = 100 , 400def print_map ( pcap , device ) : picture = Image.new ( `` RGB '' , ( 1200 , 500 ) , `` white '' ) pixels = picture.load ( ) x , y = INIT_X , INIT_Y for ts , buf in pcap : device_id , = struct.unpack ( `` b '' , buf [ 0x0B ] ) if devi... | USB mapping with python |
Python | This is most likely something very basic , but I ca n't figure it out . Suppose that I have a Series like this : How can I do operations on sub-series of this Series without having to revert to using a for-loop ? Suppose , for example , that I want to turn it into a new Series that contains four elements . The first el... | s1 = pd.Series ( [ 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 ] ) s2 = pd.Series ( [ 3 , 6 , 9 , 12 ] ) | More Pythonic/Pandaic approach to looping over a pandas Series |
Python | I was just bitten by the following scenario : Now , digging through the Python docs , it 's clear that this is intended behavior , but why ? I do n't work with any other languages with power as a builtin operator , but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.Is th... | > > > -1 ** 2-1 | Why does `` ** '' bind more tightly than negation ? |
Python | I have a little helper class : This lets me do sweet magic like : without having to use a list comprehension ( as in np.array ( x in ( 2,3 ) for x in arr ) . ( I maintain a UI that lets ( trusted ) users type in arbitrary code , and a == AnyOf ( 1,2,3 ) is a lot more palatable than a list comprehension to the non-techn... | class AnyOf ( object ) : def __init__ ( self , *args ) : self.elements = args def __eq__ ( self , other ) : return other in self.elements > > > arr = np.array ( [ 1,2,3,4,5 ] ) > > > arr == AnyOf ( 2,3 ) np.array ( [ False , True , True , False , False ] ) | Why does n't Python have a `` __req__ '' ( reflected equality ) method ? |
Python | Below I define type variable , generic type alias , and a dot product function . mypy does n't raise an error . Why not ? I would expect it to raise an error for v3 because it 's a vector of strings and I 've specified that T must be an int , float , or complex . | from typing import Any , Iterable , Tuple , TypeVarT = TypeVar ( 'T ' , int , float , complex ) Vector = Iterable [ T ] def dot_product ( a : Vector [ T ] , b : Vector [ T ] ) - > T : return sum ( x * y for x , y in zip ( a , b ) ) v1 : Vector [ int ] = [ ] # same as Iterable [ int ] , OKv2 : Vector [ float ] = [ ] # s... | Why does mypy ignore a generic-typed variable that contains a type incompatible with the TypeVar ? |
Python | I 'm trying to scrape a page using BeatifulSoupThe problem is the text I would like to return is not enclosed in it 's own html tagWhat I want to returnChuck Ragan - Rotterdam - Folkadelphia SessionBonus Points : The data returned is of the format Artist/Song/Album . What would be the proper data structure to use to st... | import urllib2from bs4 import BeautifulSoupurl='http : //www.xpn.org/playlists/xpn-playlist'page = urllib2.urlopen ( url ) soup = BeautifulSoup ( page.read ( ) ) for link in soup.find_all ( `` li '' , class_= '' song '' ) : print link < li class= '' song '' > < a href= '' /default.htm '' onclick= '' return clickreturnv... | Scrape just the text , within an html element that has a class , using beautiful soup |
Python | So I am running Chromedriver on my computer ( win , administrator mode ) likeOn my server I have tests that I want to run on my own computer.So I set up the Remote Webdriver , and the tests seems to start up without problems but I do n't see any Chrome window spawned by Chromedriver on my computer , nor do I see any lo... | chromedriver.exe -- verbose -- whitelisted-ips= File `` /server/tests/test.py '' , line 173 , in test browser = Browser ( driver_name= '' remote '' , url= '' http : //23.23.23.23:9515/wd/hub '' , browser='chrome ' , user_agent='test ' , desired_capabilities=options.to_capabilities ( ) ) File `` /usr/local/lib/python2.7... | Selenium : Run test on my machine remotely ? |
Python | I am reading the Multiprocessing topic for Python 3 and trying to incorporate the method into my script , however I receive the following error : AttributeError : __ exit __I use Windows 7 with an i-7 8-core processor , I have a large shapefile which I want processed ( with the mapping software , QGIS ) using all 8 cor... | from multiprocessing import Process , Pooldef f ( ) : general.runalg ( `` qgis : dissolve '' , Input , False , 'LAYER_ID ' , Output ) if __name__ == '__main__ ' : with Pool ( processes=8 ) as pool : result = pool.apply_async ( f ) | How to perform multiprocessing for a single function in Python ? |
Python | I am trying to plot unfilled symbols but the matplotlib facecolors='none ' argument just seems to change the fill colour . Note , i am using matplotlib style 'ggplot'.Original code snippet with filled symbols : Now attempting to use facecolors='none ' ( and setting edgecolors to the colour i want them ) It turns out th... | ax=df.plot ( kind='scatter ' , x='clay ' , y='vf1 ' , xlim= [ 0,0.6 ] , ylim= [ 0,6.0e-06 ] , color='DarkBlue ' , s=40 , label= ' u*=1 , w=0 ' ) ax=df.plot ( kind='scatter ' , x='clay ' , y='vf1 ' , xlim= [ 0,0.6 ] , ylim= [ 0,6.0e-06 ] , facecolors='none ' , edgecolors='DarkBlue ' , s=40 , label= ' u*=1 , w=0 ' ) ax=d... | pandas scatterplots : how to make unfilled symbols |
Python | My main.py file in the root folder looks like below.My app.yaml file looks like below.Below is the requirements.txt file.I am running GAE in a flex environment . I followed the steps in https : //cloud.google.com/appengine/docs/flexible/python/quickstart and was able to succesfully deploy the app to app engine.When I g... | app = Flask ( __name__ ) def configure_app ( app ) : app.config [ 'SERVER_NAME ' ] = settings.FLASK_SERVER_NAME app.config [ 'SWAGGER_UI_DOC_EXPANSION ' ] = settings.RESTPLUS_SWAGGER_UI_DOC_EXPANSION app.config [ 'RESTPLUS_VALIDATE ' ] = settings.RESTPLUS_VALIDATE app.config [ 'RESTPLUS_MASK_SWAGGER ' ] = settings.REST... | 404 error when using Google App Engine with flask and flask-restplus |
Python | In order to expose a C++ exception to Python in a way that actually works , you have to write something like : But this does n't seem to interract with anything else in Boost.Python . If I want to expose : I could write : How can I combine the class binding for Error with the exception creation on PyErr_NewException ? ... | std : :string scope = py : :extract < std : :string > ( py : :scope ( ) .attr ( `` __name__ '' ) ) ; std : :string full_name = scope + `` . '' + name ; PyObject* exc_type = PyErr_NewException ( & full_name [ 0 ] , PyExc_RuntimeError , 0 ) ; // ... struct Error { int code ; } ; py : :class_ < Error > ( `` Error '' , py ... | Boost.Python add bindings to existing PyObject ( for exception handling ) |
Python | I have the following code to analyze a huge dataframe file ( 22G , over 2million rows and 3K columns ) . I tested the code in a smaller dataframe and it ran OK ( head -1000 hugefile.txt ) . However , when I ran the code on the huge dataframe , it gave me `` segmentation fault '' core dump . It output a core.number bina... | # ! /usr/bin/pythonimport pandas as pdimport numpy as nppath = `` /path/hugefile.txt '' data1 = pd.read_csv ( path , sep='\t ' , low_memory=False , chunksize=1000 , iterator=True ) data = pd.concat ( data1 , ignore_index=True ) # # # # # # # i=0marker_keep = 0marker_remove = 0while ( i < ( data.shape [ 0 ] ) ) : j=5 # ... | Using pandas to analyzing a over 20G data frame , out of memory , when specifying chunksize still would n't work |
Python | On the background of this image you can find some code , that looks like written in extended python dialect , which have to be processed with “ python -m dg ” to get “ normal ” python code.Google has no results for “ python -m dg ” query , and yandex.ru has only one page in cache , which briefly mention one examplewhic... | python -m dg < < < 'sum $ map int $ str 2 ** 1000 ' sum ( map ( int , str ( 2**1000 ) ) ) | Help to identify python module ( preprocessor ? ) `` python -m dg '' |
Python | Hi I 've been digging through the concat , join , and merge methods for pandas and ca n't seem to find what I want . Lets assume I have two dataframes Now I want to make a new dataframe with the columns merged , I think its easiest to explain if I make a multi index for how I want the columnsNow if I make an empty data... | A = pd.DataFrame ( `` A '' , index= [ 0,1,2,3,4 ] , columns= [ 'Col 1 ' , 'Col 2 ' , 'Col 3 ' ] ) B = pd.DataFrame ( `` B '' , index= [ 0,1,2,3,4 ] , columns= [ 'Col 1 ' , 'Col 2 ' , 'Col 3 ' ] ) > > > A Col 1 Col 2 Col 30 A A A1 A A A2 A A A3 A A A4 A A A > > > B Col 1 Col 2 Col 30 B B B1 B B B2 B B B3 B B B4 B B B in... | merge two dataframes and add column level with names |
Python | My current situation is involved in making a game in python using a library called pygame . I have a method called getTile ( ) that returns the tile every time the player moves . The lvlDict makes up the world.and i 'm thinking about changing it to thiswhere there would be some interpretation for what to do if it were ... | def getTile ( self , pos ) : x = pos [ 0 ] y = pos [ 1 ] return self.lvlDict [ x , y ] .kind def getTile ( self , pos ) : try : x = pos [ 0 ] y = pos [ 1 ] return self.lvlDict [ x , y ] .kind except KeyError : return None | Is it bad form to count on exceptions ? |
Python | I 've encountered several situations when using MongoDB that require the use of DBRefs . However , I 'd also like to cache some fields from the referenced document in the DBRef itself.For example , I may want to have the username available even though the user document is referenced . This would provide me all the bene... | { $ ref : 'user ' , $ id : '10285102912A ' , username : 'Soviut ' } | Can DBRefs contain additional fields ? |
Python | So I am trying to plot curved lines to join points , here is the code I am using : -The code is producing the following output : -But I want the curved lines to look somewhat like this : What changes should I have to do in my code to get the required result ? | def hanging_line ( point1 , point2 ) : a = ( point2 [ 1 ] - point1 [ 1 ] ) / ( np.cosh ( point2 [ 0 ] ) - np.cosh ( point1 [ 0 ] ) ) b = point1 [ 1 ] - a*np.cosh ( point1 [ 0 ] ) x = np.linspace ( point1 [ 0 ] , point2 [ 0 ] , 100 ) y = a*np.cosh ( x ) + b return ( x , y ) n_teams = 4n_weeks = 4fig , ax = plt.subplots ... | Draw curved lines to connect points in matplotlib |
Python | I 'm wrapping a library that makes massive use of enumerations and therefore contains many constant identifiers . Is there a way to make them available to Cython ( declare them as extern ) and at the same time make them available to Python ? I search for something like thiswhich should replaceNote : I know about the op... | cdef extern from * : public enum : spam foo ham cdef extern from * : enum : cspam `` spam '' cfoo `` foo '' cham `` ham '' spam = cspamfoo = cfooham = cham | Make externed enum `` public '' for Python ? |
Python | Is it possible to make Python use less than 12 bytes for an int ? I am not a computer specialist but is n't 12 bytes excessive ? The smallest int I want to store is 0 , the largest int 147097614 , so I should n't really need more than 4 bytes . ( There is probably something I misunderstand here as I could n't find an a... | > > > x=int ( ) > > > x0 > > > sys.getsizeof ( x ) 12 | Possible to store Python ints in less than 12 bytes ? |
Python | Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation.On a macbook : On a Windows box : On a Linux box : For hashing short messages , it 's way faster . For long messages , similar performance.Why is it hidden away in an underscore extension module , and why is n't this fa... | > > > timeit hashlib.md5 ( b '' hello world '' ) 597 ns ± 17.2 ns per loop ( mean ± std . dev . of 7 runs , 1000000 loops each ) > > > timeit _md5.md5 ( b '' hello world '' ) 224 ns ± 3.18 ns per loop ( mean ± std . dev . of 7 runs , 1000000 loops each ) > > > _md5 < module '_md5 ' from '/usr/local/Cellar/python/3.7.6_... | What is _md5.md5 and why is hashlib.md5 so much slower ? |
Python | I 've built an app written on python , based on ZeroMQ , but now I 'm facing perfomance issues . So I decided to rewrite some modules of my app using , let 's say , Golang . But when I try to establish messaging between sockets , implemented by different languages , anything does not work.I 've searched so far , but I ... | import zmqctx = zmq.Context ( ) sock = ctx.socket ( zmq.REP ) sock.bind ( `` tcp : //*:57000 '' ) msg = sock.recv ( ) package mainimport ( zmq `` github.com/pebbe/zmq4 '' ) func main ( ) { ctx , _ : = zmq.NewContext ( ) sock , _ : = ctx.NewSocket ( zmq.REQ ) sock.Connect ( `` tcp : //localhost:57000 '' ) sock.Send ( ``... | Compatibility of ZeroMQ sockets written on different languages |
Python | I am trying to sort values that are inside a dictionary of lists and create a new list out of them . Here is the data : What I am trying is to find the 20 smallest values in these and get a list of their corresponding keys . For example , the first three least values are 14 ( hillary ) , 181 ( hillary ) and 229 ( fbi )... | { 'fbi ' : [ 229 , 421 , 586 , 654 , 947 , 955 , 1095 , 1294 , 1467 , 2423 , 3063 , 3478 , 3617 , 3730 , 3848 , 3959 , 4018 , 4136 , 4297 , 4435 , 4635 , 4679 , 4738 , 5116 , 5211 , 5330 , 5698 , 6107 , 6792 , 6906 , 7036 ] , 'comey ' : [ 605 , 756 , 1388 , 1439 , 1593 , 1810 , 1959 , 2123 , 2506 , 3037 , 6848 ] , 'hil... | Sort dictionary of lists by key value pairs |
Python | I 'm very new to Apache Spark and big data in general . I 'm using the ALS method to create rating predictions based on a matrix of users , items , and ratings . The confusing part is that when I run the script to calculate the predictions , the results are different every time , without the input or the requested pred... | from pyspark import SparkContextfrom pyspark.mllib.recommendation import ALSsc = SparkContext ( `` local '' , `` CF '' ) # get ratings from textdef parseRating ( line ) : fields = line.split ( ' , ' ) return ( int ( fields [ 0 ] ) , int ( fields [ 1 ] ) , float ( fields [ 2 ] ) ) # define input and output filesratingsF... | Inconsistent results using ALS in Apache Spark |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.