lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | Consider this snippet : I 'd like to figure out whether it 's possible to change the folding icon to a custom icon different than the ones offered by QScintilla , specifically I 'd like to have a down arrow similar to Sublime 's : By looking at the QSciScintilla foldstyle you can see there is n't anything that remains ... | import sysfrom PyQt5.Qsci import QsciScintillafrom PyQt5.Qt import *if __name__ == '__main__ ' : app = QApplication ( sys.argv ) view = QsciScintilla ( ) # http : //www.scintilla.org/ScintillaDoc.html # Folding view.setFolding ( QsciScintilla.BoxedTreeFoldStyle ) # view.setFolding ( QsciScintilla.BoxedFoldStyle ) # vie... | How to use custom folding icons in QScintilla ? |
Python | I use python 's function zip a lot in my code ( mostly to create dicts like below ) I find it really useful , but sometimes it frustrates me because I end up with a situation where list_a is a different length to list_b . zip just goes ahead and zips together the two lists until it achieves a zipped list that is the sa... | dict ( zip ( list_a , list_b ) ) | Zen of Python : Errors should never pass silently . Why does zip work the way it does ? |
Python | If I have a list in python such as : with length n ( in this case 9 ) and I am interested in creating lists of length n/2 ( in this case 4 ) . I want all possible sets of n/2 values in the original list , for example : is there some list comprehension code I could use to iterate through the list and retrieve all of tho... | stuff = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] [ 1 , 2 , 3 , 4 ] , [ 2 , 3 , 4 , 5 ] , ... , [ 9 , 1 , 2 , 3 ] | Python list comprehension to return edge values of a list |
Python | I ca n't figure out for the life of me why this if statement is n't working in Python 3 . I have always worked with python 2.7 but I need to get familiar with 3 . Here is my codeI start this code , get presented with the question , ok , that 's normal . For input I give it a single lowercase y. I see that ' y ' printed... | print ( `` Answer the question ! [ ( Y ) es or ( N ) o ] : `` ) answer = input ( ) print ( answer ) if answer == `` y '' : print ( `` OK '' ) print ( `` done '' ) | Why wo n't this if statement work ? New to python 3 |
Python | I have a model like the following : It is populated with some data : I need to merge/join this with a collection ( not a queryset ) : So basically rows 0 and 2 should return when I search this model with this list of tuples.Currently my workaround is to read Foo.objects.all ( ) into a DataFrame and do a merge with the ... | class Foo ( models.Model ) : fruit = models.CharField ( max_length=10 ) stuff = models.CharField ( max_length=10 ) color = models.CharField ( max_length=10 ) owner = models.CharField ( max_length=20 ) exists = models.BooleanField ( ) class Meta : unique_together = ( ( 'fruit ' , 'stuff ' , 'color ' ) , ) fruit stuff co... | Searching in multiple fields respecting the row order |
Python | My code looks something like this : Why did Python convert the object s to the string `` s '' while updating the dictionary some_dict ? | class SomeClass ( str ) : passsome_dict = { 's':42 } > > > type ( some_dict.keys ( ) [ 0 ] ) str > > > s = SomeClass ( 's ' ) > > > some_dict [ s ] = 40 > > > some_dict # expected : Two different keys-value pairs { 's ' : 40 } > > > type ( some_dict.keys ( ) [ 0 ] ) str | Why is the dictionary key being converted to an inherited class type ? |
Python | I often include this , or something close to it , in Python scripts and IPython notebooks.This seems like a common enough use case that the standard library should provide a function that does the same thing . Is there such a function ? If there is n't , how come ? | import cPickledef unpickle ( filename ) : with open ( filename ) as f : obj = cPickle.load ( f ) return obj | How come Python does not include a function to load a pickle from a file name ? |
Python | I would like to use py.test combined with hunter : Unfortunately the output ( trace ) of hunter is not visible.Version : In a simpler ( smaller ) virtualenv it works ( same pytest version , but no plugins ) .What could be the reason ? How to debug this ? | PYTHONHUNTER= '' module_startswith='foo ' '' py.test -s -k test_bar foo_cok_d @ aptguettler : ~ $ py.test -- versionThis is pytest version 3.4.2 , imported from /home/foo_cok_d/local/lib/python2.7/site-packages/pytest.pycsetuptools registered plugins : pytest-xdist-1.22.2 at /home/foo_cok_d/local/lib/python2.7/site-pac... | No output , even with ` py.test -s ` |
Python | If our Django web application returns a 404 , we see this in the logs : I would like to change this particular line created by get_response ( ) from WARN to INFO.How to configure this with Django and Python ? An alternative solution would be to ignore this line , but WARN to INFO would be preferred . | 2017-11-21 12:48:26 django.request.get_response : WARNING Not Found : /foooooo | Python Logging : Change `` WARN '' to `` INFO '' |
Python | I 'd like to extract the bins for 'S ' individually , where each column ( X & Y ) > 0.5 , or multiple bins > 0.5 * 'number of rows'.In the example ; for 'AR1 ' should only bin 4 be selected , because ' X ' and ' Y ' are > 0.5 ( blue indicated ) for 'PO1 ' should bins 1 , 2 , 3 and 4 be selected , because ' X ' and ' Y ... | np.random.seed ( 0 ) N = 20S = [ 'AR1 ' , 'PO1 ' ] df = pd.DataFrame ( { ' X ' : np.random.uniform ( -1,1 , N ) , ' Y ' : np.random.uniform ( -1,1 , N ) , 'S ' : np.random.choice ( S , N ) , } ) df [ 'bins_X ' ] = df.groupby ( 'S ' ) [ ' X ' ] .apply ( pd.qcut , q=5 , labels=np.arange ( 5 ) ) # create bins per column '... | Selecting rows in a MultiIndexed dataframe |
Python | Assuming we have a certain number of possible strings : and receive new strings that are known to be one of them . We want to assign an integer to every new string , for example What is the fastest way to do that in Python 3.6 ? I tried several ways and using a dictionary is the fastest so far : However I am more or le... | possible_strings_list = [ 'foo ' , 'bar ' , 'baz ' , 'qux ' , 'spam ' , 'ham ' , 'eggs ' ] if new_string == 'foo ' : return 0elif new_string == 'bar ' : return 1 ... list_index 2.7494255019701086dictionary 0.9412809460191056if_elif_else 2.10705983400112lambda_function 2.6321219780365936tupple_index 2.751029207953252ter... | Fastest way to perform string lookups ? |
Python | I 'm serving a Python app through Django . Within the app I 'm storing the classic `` created '' field within a few tables.This is how the field looks like within the Django form : Unfortunately , datetime.now ( ) is not accurate . In fact in the database I have sets of rows with the exact same timestamp.The datetime.n... | created = models.DateTimeField ( blank=True , default=datetime.now ( ) ) | Datetime.now ( ) abnormality - Python |
Python | I am using RFECV for feature selection in scikit-learn . I would like to compare the result of a simple linear model ( X , y ) with that of a log transformed model ( using X , log ( y ) ) Simple Model : RFECV and cross_val_score provide the same result ( we need to compare the average score of cross-validation across a... | from sklearn.datasets import make_friedman1from sklearn.feature_selection import RFECVfrom sklearn import linear_modelfrom sklearn.model_selection import cross_val_scorefrom sklearn.compose import TransformedTargetRegressorimport numpy as npX , y = make_friedman1 ( n_samples=50 , n_features=10 , random_state=0 ) estima... | Target transformation and feature selection in scikit-learn |
Python | I 've written a script in python in combination with selenium to download few document files ( ending with .doc ) from a webpage . The reason I do not wish to use requests or urllib module to download the files is because the website I 'm currently palying with do not have any true url connected to each file . They are... | import osimport timefrom selenium import webdriverlink ='https : //www.online-convert.com/file-format/doc ' dirf = os.path.expanduser ( '~ ' ) desk_location = dirf + r'\Desktop\file_folder'if not os.path.exists ( desk_location ) : os.mkdir ( desk_location ) def download_files ( ) : driver.get ( link ) for item in drive... | Ca n't store downloaded files in their concerning folders |
Python | I have made a Secret language that I would to be able to put full words into the input and get the output as the list says the letters should be . Let 's say for example I input `` AB '' I would like the output to be `` QW '' . | while True : print ( `` type sentence you want translated '' ) Befor=input ( ) After=list ( Befor ) if Befor== '' A '' : print ( `` Q '' ) elif Befor== '' B '' : print ( `` W '' ) elif Befor== '' C '' : print ( `` E '' ) elif Befor== '' D '' : print ( `` R '' ) else : print ( `` -- '' ) print ( After ) pass | Taking characters out of list and turning them into other characters |
Python | I want to normalize the elements of columns in array ‘ x ’ , which contains both positive and negative numbers , to -1 , or 1.Negative elements of x should be normalized to x.min of each column where x.min becomes - 1 , and positive elements of x should be normalized to x.max of each column where x.max becomes 1 . Zero... | x = np.array ( [ [ 1 , 3 , 1 ] , [ -2 , -5 , -0.5 ] , [ -3 , -1 , 1.5 ] , [ 2 , 7 , 2 ] ] ) x_norm = x / x.max ( axis=0 ) print ( x_norm ) [ [ 0.5 0.42857143 0.5 ] [ -1 . -0.71428571 -0.25 ] [ -1.5 -0.14285714 0.75 ] [ 1 . 1 . 1 . ] ] print ( x_norm ) [ [ 0.5 0.42857143 0.5 ] [ -0.66 -1 . -1 . ] [ -1 . -0.2 0.75 ] [ 1 ... | Normalize the elements of columns in an array to 1 or -1 depending on their sign |
Python | I just randomly observed the following in Python and am curious to know the reason why this evaluates to False : Interestingly if you rearrange the syntax in the following ways , the first way evaluates as False , but the second as True : What is going on under the hood here ? | list ( list ( ) ) == [ [ ] ] list ( [ ] ) == [ [ ] ] [ list ( ) ] == [ [ ] ] | Why does n't [ [ ] ] == list ( list ( ) ) |
Python | I am filtering ancestry from the ABS in Australia.I am taking ancestry data as below.I am then having issues showing the changes in ancestry over time by using the newer 2016 dataset , as the api is extremely confusing ... here http : //stat.data.abs.gov.au/ # . ( I want to try and show how demographics are changing in... | allvic_url='ABS_CENSUS2011_T09/TOT+1+2+3+4+Z.TOT+TOTP+1101+1102+6101+3204+2303+2101+5201+2305+2306+3205+3304+7106+2201+3103+6902+4106+3206+3104+1201+1202+3307+3308+2102+3213+7115+9215+3106+4907+5107+2103+OTH+Z.2.SA2..A/all ? detail=Full & dimensionAtObservation=AllDimensions ' Suburb Ancestry Main Ancestry Secondary An... | Pandas - filtering data sets and combining them |
Python | Could you explain me this `` magic ? '' How is a converted from list to string ? response is an instance of rest_framework.response.Response . | > > > print type ( a ) < type 'list ' > > > > response.content = a > > > print type ( response.content ) < type 'str ' > | How is a REST response content `` magically '' converted from 'list ' to 'string ' |
Python | This is a generalization to this question : Way to extract pickles coming in and out of ipython / jupyter notebookAt the highest level , I 'm looking for a way to automatically summarize what goes on in an ipython notebook . One way I see of simplifying the problem is treat all the data manipulations that on inside the... | summary_dict = summerize_file_io ( ipynb_filepath ) print summary_dict [ `` inputs '' ] > [ `` ../Resources/Data/company_orders.csv '' , `` http : //special_company.com/company_financials.csv '' ] print summary_dict [ `` outputs '' ] > [ `` orders_histogram.jpg '' , '' data_consolidated.pickle '' ] | Determine all files read into and written from an ipython notebook |
Python | I 'm using the Windows Launcher development environment for Google App Engine.I have downloaded Django 1.1.2 source , and un-tarrred the `` django '' subdirectory to live within my application directory ( a peer of app.yaml ) At the top of each .py source file , I do this : In my file settings.py ( which lives at the r... | import settingsimport osos.environ [ `` DJANGO_SETTINGS_MODULE '' ] = 'settings ' DEBUG = TrueTEMPLATE_DIRS = ( 'html ' ) INSTALLED_APPS = ( 'filters ' ) import osos.environ [ `` DJANGO_SETTINGS_MODULE '' ] = 'settings'from google.appengine.dist import use_libraryuse_library ( 'django ' , ' 1.1 ' ) from django.template... | Google App Engine with local Django 1.1 gets Intermittent Failures |
Python | I 'm trying to add a decorator that adds callable attributes to functions that return slightly different objects than the return value of the function , but will execute the function at some point.The problem I 'm running into is that when the function object is passed into the decorator , it is unbound and does n't co... | def deco ( func ) : `` '' '' Add an attribute to the function takes the same arguments as the function but modifies the output. `` '' '' def string ( *args , **kwargs ) : return str ( func ( *args , **kwargs ) ) func.string = string return funcclass Test ( object ) : def __init__ ( self , value ) : self._value = 1 @ de... | Accessing self in a function attribute |
Python | Option 1 : Option 2 : So that I can then call : The options are to either determine whether the key is in directory before hand ( f1 ) , or just fallback to the exception ( f2 ) . Which one is preferred ? Why ? | def f1 ( c ) : d = { `` USA '' : `` N.Y. '' , `` China '' : `` Shanghai '' } if c in d : return d [ c ] return `` N/A '' def f2 ( c ) : d = { `` USA '' : `` N.Y. '' , `` China '' : `` Shanghai '' } try : return d [ c ] except : return `` N/A '' for c in ( `` China '' , `` Japan '' ) : for f in ( f1 , f2 ) : print `` % ... | which style is preferred ? |
Python | The native python codes are like this : However , I have to use numpy to do this job as the array is very large.Does anyone have ideas about how to do the same work in numpy ? | > > > a= [ 1,2,3,4,5,6 ] > > > [ [ i+j for i in a ] for j in a ] [ [ 2 , 3 , 4 , 5 , 6 , 7 ] , [ 3 , 4 , 5 , 6 , 7 , 8 ] , [ 4 , 5 , 6 , 7 , 8 , 9 ] , [ 5 , 6 , 7 , 8 , 9 , 10 ] , [ 6 , 7 , 8 , 9 , 10 , 11 ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] ] | How to use numpy to add any two elements in an array and produce a matrix ? |
Python | I am using the YouTube API and I 'm using Python urllib2.urlopen ( ) to send a GET request . Then I pass the result to Javascript . ( I 'm using Django ) So , something like this : I 'm using jQuery to parse the JSON formatted response , however some YouTube videos/descriptions have double quotes and this breaks the pa... | result = urllib2.urlopen ( 'https : //gdata.youtube.com/feeds/api/videos ? '+query+ ' & max-results=1 & alt=json ' ) | Ca n't figure out a way to escape quotes in json in YouTube API |
Python | Trying to run docker command : taken from https : //github.com/nouiz/Theano-Dockerreturns error : Appears the theano_secure image is not currently available ? Searching for theano_secure : The return of this command is empty so image is not available ? If so is there an alternative Theano docker image from nvidia ? Upd... | nvidia-docker run -d -p 8888:8888 -e PASSWORD= '' 123abcChangeThis '' theano_secure start-notebook.sh # Then open your browser at http : //HOST:8888 Error : image library/theano_secure : latest not found $ nvidia-docker search theano_secure : latestNAME DESCRIPTION STARS OFFICIAL AUTOMATED docker build -t theano_secure... | Nvidia Theano docker image not available |
Python | I am trying to insert records into postgres DB , and its taking about 3 hours while it takes 40seconds using python psycopg2 and cursor.copy_from methodWhat is wrong with my code , using clojure.java.jdbc/db-do-prepared also takes about 3 hours too.Please help ! File size is 175M and it has 409,854 records | ( defn- str < - > int [ str ] ( let [ n ( read-string str ) ] ( if ( integer ? n ) n ) ) ) ( with-open [ file ( reader `` /path/to/foo.txt '' ) ] ( try ( doseq [ v ( clojure-csv.core/parse-csv file ) ] ( clojure.java.jdbc/insert ! db : records nil [ ( v 0 ) ( v 1 ) ( v 2 ) ( str < - > int ( v 3 ) ) ] ) ) ( println `` R... | Insert file records into postgres db using clojure jdbc is taking long time compared to python psycopg2 |
Python | I 'm an old guy trying to learn programming . I 've tried searching for an answer to this question but most of the replies are way over my head . So here goes , I 've written code to get data from the web , convert it to json , and the print the results in the desired format . I 'm now using Tkinter to make a display o... | import requestsimport timefrom tkinter import * # Input Valuesapi = 'Enter API Key from Openweather.com'lat = '33.608'lon = '-111.863'unit = 'imperial ' # unit must be 'imperial ' or 'metric'fcast_time = [ 0 , 4 , 8 , 12 , 16 , 20 , 24 , 28 ] # each element is a 3 hour period ( i.e . 4 would be 12 hours out ) , max is ... | How to update a URL every 3 hours in Python |
Python | If I 've got a Python Decimal , how can I reliably get the precise decimal string ( ie , not scientific notation ) representation of the number without trailing zeros ? For example , if I have : I would like : However : The Decimal class does n't have any to_decimal_string method , or even any to_radix_string ( radix )... | > > > d = Decimal ( '1e-14 ' ) > > > get_decimal_string ( d ) ' 0.00000000000001 ' | Get precise decimal string representation of Python Decimal ? |
Python | I came across this code snippet for round robin in https : //more-itertools.readthedocs.io/en/latest/api.html , but I could n't understand how the last line nexts = cycle ( islice ( nexts , pending ) ) removes the exhausted generator from nexts iterator . To my understanding , this removes the last one from input but s... | def roundrobin ( *iterables ) : `` '' '' Yields an item from each iterable , alternating between them . > > > list ( roundrobin ( 'ABC ' , 'D ' , 'EF ' ) ) [ ' A ' , 'D ' , ' E ' , ' B ' , ' F ' , ' C ' ] This function produces the same output as : func : ` interleave_longest ` , but may perform better for some inputs ... | python itertools round robin explaintation |
Python | I am using the Python library , Fabric , to do some remote server maintenance . Fabric automatically outputs all of the responses to remote and local commands unless you wrap the command in a couple with statements . Like so , on a local machine , or like this on a remote machine : I am writing a long and complex task ... | with settings ( warn_only='true ' ) : with hide ( 'running ' , 'stdout ' , 'stderr ' , 'warnings ' ) : output = local ( `` uname -a '' , True ) with settings ( warn_only='true ' ) : with hide ( 'running ' , 'stdout ' , 'stderr ' , 'warnings ' ) : output = run ( `` uname -a '' ) def _mute ( fabric_cmd , args ) : with se... | What 's the pythonic way to wrap several functions in the same with statements |
Python | I 'm a lab practises tutor at the university , based on last year student comments , we wanted , my boss and I , to address them . My boss chose to go with writing a C script and I pick python ( python-constraint ) to try to resolve our problem . InformationsThere are 6 sessionsThere are 4 rolesThere are 6 practicesThe... | [ # Semester [ # Session [ # Practice/Team1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] , [ 17 , 18 , 19 , 20 ] , [ 21 , 22 , 23 , 24 ] ] , [ [ 25 , 26 , 27 , 28 ] , [ 29 , 30 , 31 , 32 ] , [ 33 , 34 , 35 , 36 ] , [ 37 , 38 , 39 , 40 ] , [ 41 , 42 , 43 , 44 ] , [ 45 , 46 , 47 , 48 ]... | constraint satisfaction problem missing one constraint |
Python | Lets say I have the following set : This gives each number the following frequency : Can you propose a way of reducing the set such that each number exists in it at least 2 times but where the number of tuples in the set is reduced to a minimum ? For example , the tuple ( 3 , 4 ) could be removed from the set , giving ... | { ( 2 , ) , ( 3 , ) , ( 1 , 4 ) , ( 1 , 2 , 3 ) , ( 2 , 3 ) , ( 3 , 4 ) , ( 2 , 4 ) } 2 : 4 , 3 : 4 , 4 : 3 , 1 : 2 2 : 4 , 3 : 3 , 4 : 2 , 1 : 2 def reduce ( a , limit ) : while True : remove = None for i in a : c = Counter ( [ i for s in a for i in s ] ) if c.most_common ( 1 ) [ 0 ] [ 0 ] in i : if min ( [ c [ j ] fo... | Reduce set size while preserving minimum frequency |
Python | Sometimes it can be useful to run only the first part of a large doctests file . There are many situations when the first part breaks after a code change , I would like to run only the first part , until it passes , and then run the whole file again.I could not yet find an easy way to do this.Let 's say I start my doct... | # ! /usr/bin/env pythonimport doctestdoctest.testfile ( `` scenario.rst '' ) > > > 'hello world '' hello world ' > > > exit ( ) > > > 'this should not be processed anymore ' ... lots of lines > > > 'this should also not be processed ' **********************************************************************File `` _scenar... | How to terminate a python 2 doctest file in the middle ? |
Python | I am using Python Selenium to crawl several web pages , and I previously know that some of the pages do n't have all elements.I am already waiting for the page to load and using try/except to find the element ( class xyz , for example ) , and it takes 30 seconds to get into the exception.How can I set a smaller timeout... | try : xyz = driver.find_element_by_css_selector ( 'div.xyz ' ) .textexcept NoSuchElementException : print ( `` \tError finding xyz ... '' ) | How to set Try/Except timeout to find element in Python Selenium ? |
Python | If a have a list within a another list that looks like this ... How can I add the middle element together so so for 'Harry ' for example , it shows up as [ 'Harry ' , 26 ] and also for Python to look at the group number ( 3rd element ) and output the winner only ( the one with the highest score which is the middle elem... | [ [ 'Harry',9,1 ] , [ 'Harry',17,1 ] , [ 'Jake',4,1 ] , [ 'Dave',9,2 ] , [ 'Sam',17,2 ] , [ 'Sam',4,2 ] ] [ [ 'Harry ' , 26 ] , [ 'Sam',21 ] ] grouped_scores = { } for name , score , group_number in players_info : if name not in grouped_scores : grouped_scores [ name ] = score grouped_scores [ group_number ] = group_nu... | Make a new list depending on group number and add scores up as well |
Python | I have a np.ndarray as follows : Is there a way to get the indices and values of the m smallest items in that nd array ? So , if I wanted the 4 smallest it would bewhere ( row , col , val ) is the notation above . If there are multiple values then one of them is just randomly chosen . For instance , there were 3 ones a... | [ [ inf 1 . 3 . 2 . 1 . ] [ inf inf 2 . 3 . 2 . ] [ inf inf inf 5 . 4 . ] [ inf inf inf inf 1 . ] [ inf inf inf inf inf ] ] [ ( 0,1,1 ) , ( 0,4,1 ) , ( 3,4,1 ) , ( 0,3,2 ) ] | m Smallest values from upper triangular matrix with their indices as a list of tuples |
Python | I have defined some classes thusly : I would expect that test.PartMaster.PIN would be an instance of CustomParameter , but instead it is a tuple tuple : ( < __main__.CustomParameter instance at 0x0000000002D724C8 > , ) Why is this , and how can I make it not be so ? I 'd like to construct my classes such that test.Part... | class CustomParameter ( ) : def __init__ ( self , strFriendlyAttribName , strSystemAttribName ) : self.FriendlyAttribName = strFriendlyAttribName self.SystemAttribName = strSystemAttribNameclass PartMaster ( ) : AttribNameList = [ `` Part Number '' , `` Name '' , `` Standard Part '' , `` Part Type '' , `` ControlledBy ... | Why do my nested python class instances become tuples ? |
Python | I have a model which stores a users location : I am trying to achieve a system that allows users to query and see who else is nearby but for security reasons I would like to limit the results to users with say 1KM . What is the best way to achieve this ? P.S - The `` status '' is tied to the normal user model in the dj... | [ { `` url '' : `` http : //192.168.0.22:8000/status/1/ '' , `` id '' : 1 , `` owner '' : 1 , `` test_info '' : `` '' , `` created_at '' : `` 2015-05-02T07:09:16.535689Z '' , `` updated_at '' : `` 2015-05-02T07:09:16.535746Z '' , `` geolocation '' : null , `` jukebox_mode_enabled '' : false } , { `` url '' : `` http : ... | Django Rest Framework - How do I limit results returned with Geolocation ? |
Python | I was just messing around when I came across this quirk . And I wanted to make sure I am not crazy.The following code ( works in 2.x and 3.x ) : Doing 3 runs on each version , same machine.note : I grouped the timings on the same line to save space here.On my Python 2.7.5 : On my Python 3.3.2 : I wonder why this is ...... | from timeit import timeitprint ( 'gen : % s ' % timeit ( ' '' - '' .join ( str ( n ) for n in range ( 1000 ) ) ' , number=10000 ) ) print ( 'list : % s ' % timeit ( ' '' - '' .join ( [ str ( n ) for n in range ( 1000 ) ] ) ' , number=10000 ) ) gen : 2.37875941643 , 2.44095773486 , 2.41718937347list : 2.1132466183 , 2.1... | Is `` join '' slower in 3.x ? |
Python | Given a string , find the first non-repeating character in it and return its index . If it does n't exist , return -1 . You may assume the string contain only lowercase letters.I 'm going to define a hash that tracks the occurrence of characters . Traverse the string from left to right , check if the current character ... | def firstUniqChar ( s ) : track = { } for index , i in enumerate ( s ) : if i in track : continue elif i in s [ index+1 : ] : # For the last element , i in [ ] holds False track [ i ] = 1 continue else : return index return -1firstUniqChar ( 'timecomplexity ' ) | Time complexity calculation for my algorithm |
Python | It 's my hope that the bounty will draw an individual who knows a thing or two about the inner workings of PyGame ( I tried looking at the source code.. there 's a bunch of it ) and can tell me if this is truly related to the presence of threading.py , or if there is some practice I can avoid in general to prevent this... | def make_explosion ( obj , func ) : def inner ( *args , **kwargs ) : newX , newY = obj.x , obj.y newBoom = Explosion ( newX , newY ) allqueue.add ( newBoom ) # an instance of pygame.sprite.Group return func ( *args , **kwargs ) return inner newEnemy = Enemy ( ) # # other code to add new AI , point values…eventually , t... | python and pygame - what happened during this wrapper 's execution ? |
Python | I 'm currently having a problem where I 'm able to use and import numpy in an interpreter environment , but I 'm unable to import or use numpy from python embedded in C/C++ . So I 'm curious to how numpy extension libraries , specifically is linked to the standard python package symbols ( PyExc_UserWarning symbol speci... | numpy/core/multiarray.cpython-35m-x86_64-linux-gnu.so ldd multiarray.cpython-35m-x86_64-linux-gnu.so | How are symbols contained in the libpythonX.X linked to numpy extension dynamic libraries ? |
Python | I 'm looking to maximize the number of stars given a certain budget and max limit on the combination.Example question : With a budget of 500 euro , visiting only the maximum allowed restaurants or less , dine and collect the most stars possible.I 'm looking to write an efficient algorithm , that could potentially proce... | import itertoolsclass Restaurant ( ) : def __init__ ( self , cost , stars ) : self.cost = cost self.stars = stars self.ratio = cost / stars def display ( self ) : print ( `` Cost : $ '' + str ( self.cost ) ) print ( `` Stars : `` + str ( self.stars ) ) print ( ) r1 = Restaurant ( 100 , 5 ) r2 = Restaurant ( 140 , 3 ) r... | Get the most efficient combination of a large List of objects based on a field |
Python | I have a spark dataframe ( prof_student_df ) that lists student/professor pair for a timestamp . There are 4 professors and 4 students for each timestamp and each professor-student pair has a “ score ” ( so there are 16 rows per time frame ) . For each time frame , I need to find the one to one pairing between professo... | + -- -- -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -+ -- -- -- -- -- +| time | professor_id | student_id | score | is_match |+ -- -- -- -- -- -- + -- -- -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -+ -- -- -- -- -- +| 1596048041 | p1 | s1 | 0.7 | FALSE || 1596048041 | p1 | s2 | 0.5 | TRUE || 15... | Implementing a recursive algorithm in pyspark to find pairings within a dataframe |
Python | I am trying to come up with a method to regression test number sequences.My system under tests produces a large amount of numbers for each system version ( e. g. height , width , depth , etc. ) . These numbers vary from version to version in an unknown fashion . Given a sequence of `` good '' versions and one `` new ''... | version width height depth 1 123 43 302 2 122 44 304 3 120 46 300 4 124 45 301 5 121 60 305 | Regression Tests on Arbitrary Number Sequences |
Python | I 'm trying to flatten hundreds of thousands of lists that contains primitive data types , lists and generators . Both the lists and the generators have primitive data types , so after flatten I will have only primitive data types ( floats , integers , strings and bools ) Example : My code : Since performance matter , ... | list_1 = [ 1 , 2 , 3 , 'ID45785 ' , False , `` , 2.85 , [ 1 , 2 , 'ID85639 ' , True , 1.8 ] , ( e for e in range ( 589 , 591 ) ) ] flatten = [ ] for item in list_1 : if isinstance ( item , ( str , bool , int , float ) ) : flatten.append ( item ) else : flatten.extend ( list ( item ) ) | How to flatten a list that has : primitives data types , lists and generators ? |
Python | I would like to use python-saml for sso integration with flask web app . while I am trying to install python-saml package using pip install python-saml , I am getting the below error message.I tried with conda install python-saml , same error also they stopped this package 2 years before . even I tried python3-samlthe ... | ( myvenv ) C : \Users\sekar > pip install python3-saml==1.9.0Collecting python3-saml==1.9.0 Using cached python3_saml-1.9.0-py3-none-any.whl ( 72 kB ) Collecting xmlsec > =0.6.0 Using cached xmlsec-1.3.3.tar.gz ( 29 kB ) Building wheels for collected packages : xmlsec Building wheel for xmlsec ( setup.py ) ... error ER... | Error while installing Python-saml package in windows |
Python | A game engine provides me with a Player class that has an uniqueid read-only property to identify players . I would like to `` convert '' this into an SQLAlchemy 's Column so that I can query players with it like this : Here 's what my class currently looks like : Next I would like to create a read-only interface for t... | query = session.query ( Player ) .filter ( Player.uniqueid=='STEAM_0:0:1234567 ' ) player = query.one_or_none ( ) if player is None : player = Player ( uniqueid='STEAM_0:0:1234567 ' ) class Player ( game.Player , db.Model ) : _uniqueid = Column ( 'uniqueid ' , String ( 21 ) , unique=True , nullable=False ) def __init__... | Override a read-only property with a read-only Column that gets the same value |
Python | The output : since the `` 1 or func ( ) '' terminates early without calling the func ( ) because `` 1 or something '' is always true.However , when switching to bitwise operator : I get the output : Why is that ? this does n't seem very efficient | def func ( ) : print 'no early termination ' return 0if __name__ == `` __main__ '' : if 1 or func ( ) : print 'finished ' finished def func ( ) : print 'no early termination ' return 0if __name__ == `` __main__ '' : if 1 | func ( ) : print 'finished ' no early terminationfinished | Why there is no early termination in bitwise operations ? |
Python | For background , I am referring to the Hierarchical Attention Network used for sentiment classification . For code : my full code is posted below , but it is just simple revision of the original code posted by the author on the link above . And I explain my changes below.For training data : hereFor word embeddings : th... | import numpy as npimport pandas as pdimport refrom bs4 import BeautifulSoupimport osfrom keras.preprocessing.text import Tokenizer , text_to_word_sequencefrom keras.utils import plot_modelfrom keras.utils.np_utils import to_categoricalfrom keras.layers import Dense , Inputfrom keras.layers import Embedding , GRU , Bidi... | Hierarchical Attention Network - model.fit generates error 'ValueError : Input dimension mis-match ' |
Python | After some reading , I found myself struggling with two different approaches to pass a list of arguments to a function . I read some indications . That 's what I figured out so far : Actual code : file caller.py : File : worker.py : And now I have : file caller.py : File : worker.py : Using the old approach ( actual co... | import workerworker.version_check ( iserver , login , password , proxyUser , proxyPass , proxyServer , packageInfo ) worker.version_get ( iserver , login , password , proxyUser , proxyPass , proxyServer , packageInfo ) worker.version_send ( iserver , login , password , proxyUser , proxyPass , proxyServer , packageInfo ... | Best approach to pass and handle arguments to function |
Python | We have a Single Page App which calls our back-end services ( C # and Python ) , authorizing these requests using the Auth0 SPA flow.Our back end services only make requests to each other as part of processing a request from an SPA user , so currently we just forward the Authorization header from the SPA request , usin... | sub : SPA-USER-IDaud : SPA-CLIENT-ID sub : SERVICE-ID @ clientsaud : API-IDscope : `` '' | Using Auth0 to Authorize API requests from both our SPA and our other back-end services |
Python | I wrote a python program using the quantopian zipline package http : //www.zipline.io/beginner-tutorial.html . I recently updated the package and have encountered that the zipline.transforms package is deprecated . I was using two functions from the zipline.transforms package , batch_transform ( ) and MovingAverage . I... | from zipline.algorithm import TradingAlgorithmfrom zipline.transforms import batch_transformfrom zipline.transforms import MovingAverageclass TradingStrategy ( TradingAlgorithm ) : def initialize ( self , window_length=6 ) : self.add_transform ( MovingAverage , 'kernel ' , [ 'price ' ] , window_length=self.window_lengt... | How to update the deprecated python zipline.transforms module ? |
Python | I have a function where I need to generate different output strings for another program I invoke , depending on which type it wants.Basically , the called program needs a command line argument telling it which type it was called with.Happily I found this answer on SO on how to check a variable for type . But I noticed ... | def myfunc ( val ) : cmd_type = ' i ' if instance ( val , str ) : cmd_type = 's ' cmdline = 'magicprogram ' + cmd_type + ' ' + val Popen ( cmdline , ... blah blah ) ... | What is the canonical way of handling different types in Python ? |
Python | Since python 3.6 ( or 3.4 ? I do n't remember ) we can annotate a function . Ex : Now what happens when a function returns a tuple ? We can do that : But if we know the tuple is a tuple of two integers ? I read here : How to annotate types of multiple return values ? that we can do that : But it requires to import the ... | def getVersion ( ) - > str : def func ( ) - > tuple : def func ( ) - > Tuple [ int , int ] def func ( ) - > ( int , int ) : | Python annotations : difference between Tuple and ( ) |
Python | I 'm looking for an efficient way to generate many M-sized subsets from a set S , of size N. Ideally I would like to generate all of these , but because I 'm using them for other computations , this becomes infeasible . Instead , I would like to generate K disparate subsets of S , such that the K chosen subsets minimiz... | def subset_split ( full_set , M , K ) : np.random.seed ( 0 ) # repeatibility seen = set ( [ ] ) subset_list = [ ] for kx in xrange ( K ) : np.random.shuffle ( full_set ) failsafe = 0 while True : np.random.shuffle ( full_set ) subset = tuple ( full_set [ 0 : M ] ) if not subset in seen : seen.add ( subset ) subset_list... | Deterministic python generator for K disparate M-sized subsets of a set |
Python | My task was to 'Write a function selectCoins that asks the user to enter an amount of money ( in pence ) and then outputs the number of coins of each denomination ( from £2 downto 1p ) that should be used to make up that amount exactly ( using the least possiblenumber of coins ) . For example , if the input is 292 , th... | def selectCoins ( ) : twopound = 200 onepound = 100 fiftyp = 50 twentyp = 20 tenp = 10 fivep = 5 twop = 2 onep = 1 a = 0 b = 0 c = 0 d = 0 e = 0 f = 0 g = 0 h = 0 money = int ( input ( 'Enter how much money you have in pence ' ) ) while True : if money > = twopound : money = money - twopound a = a + 1 elif money > = on... | How to turn money ( in pence ) to its individual coins ? |
Python | Appending to list can be possibly done in two ways:1 ) or 2 ) From the official Python documentation : The method append ( ) shown in the example is defined for list objects ; it adds a new element at the end of the list . In this example it is equivalent to result = result + [ a ] , but more efficient.The documentatio... | mat = [ ] for i in range ( 10 ) : mat.append ( i ) mat = [ ] for i in range ( 10 ) : mat += [ i ] | Why is list.append ( x ) more efficient than list += l [ x ] ? |
Python | Howdy , codeboys and codegirls ! I have came across a simple problem with seemingly easy solution . But being a Python neophyte I feel that there is a better approach somewhere.Say you have a list of mixed strings . There are two basic types of strings in the sack - ones with `` = '' in them ( a=potato ) and ones witho... | for arg in arguments : if '= ' in arg : equal.append ( arg ) else : plain.append ( arg ) equal = [ arg for arg in arguments if '= ' in arg ] | Evaluating into two or more lists |
Python | My aim : I am trying to make a python bot to win chrome 's dino game.The game allows 2 types of jumps : short jumpslong jumpsUsing main_body.send_keys ( Keys.SPACE ) ( as shown in the code below ) gives short jumps.My problem : I am having difficulty executing long jumps.My approach : Currently , for long jumps , I am ... | ActionChains ( driver ) \.key_down ( Keys.SPACE ) \.pause ( 0.2 ) \.key_up ( Keys.SPACE ) \.perform ( ) main_body.key_down ( Keys.SPACE ) time.sleep ( 0.2 ) main_body.key_up ( Keys.SPACE ) import keyboardfrom selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.action_c... | How to `` send keys '' to a canvas element for longer duration ? |
Python | I 'm writing the code to attend a service . I receive POST requests to a particular service and start processing . The whole process is rather simple ; I loop trough items in the request and add each item to the database . The problem arise when I have to process a lot of items and the loop takes like three minutes to ... | status = '200 OK'headers = [ ( 'Content-type ' , 'application/json ' ) , ( 'Access-Control-Allow-Origin ' , '* ' ) ] start_response ( status , headers ) return json.dumps ( response ) Exception happened during processing of request from ( 'XXX.XXX.XXX.XXX ' , 49172 ) Traceback ( most recent call last ) : File `` /usr/l... | Error with time-consuming REST service in Python |
Python | I have 2 pandas DataFrame that I want to multiply : I tried : returns : The rows 1 to 4 are NaN . How can I avoid that ? For example , row 1 should be -90 8 ( -90=-150*0.6 ; 8=20*0.4 ) .For example , Numpy may broadcast to match dimensions . | frame_score : Score1 Score20 100 801 -150 202 -110 703 180 994 125 20frame_weights : Score1 Score20 0.6 0.4 import pandas as pdimport numpy as npframe_score = pd.DataFrame ( { 'Score1 ' : [ 100 , -150 , -110 , 180 , 125 ] , 'Score2 ' : [ 80 , 20 , 70 , 99 , 20 ] } ) frame_weights = pd.DataFrame ( { 'Score1 ' : [ 0.6 ] ... | How can I multiply a n*m DataFrame with a 1*m DataFrame in pandas ? |
Python | Suppose I have several lists of integers like so : What 's the most efficient / most pythonic way to build a single list of all elements that occur in at least one list but do not occur in all lists ? In this case it would be | [ 0,3,4 ] [ 2,3,4,7 ] [ 2,3,4,6 ] [ 0,2,7,6 ] | Find elements that occur in some but not all lists |
Python | I tried to find an explanation of this , the Gotcha part : returns : I understand what happens with multiple equals : but using it together with a comma , I can not understand the behaviour , ideas in why it works that way ? | b = `` 1984 '' a = b , c = `` AB '' print ( a , b , c ) ( 'AB ' , ' A ' , ' B ' ) a = b = 1 | multiple assignments with a comma in python |
Python | Here is what I did , I created 2 procedures , one in a function and one in the python file itself . The one on the python file itself run almost 2 times slower even if it 's exactly the same . WHY ? Bellow is an example with 2 procedures that are just loops on P elementI have the following python file : Here is what I ... | from time import *P=1000000 # range of the 2 loopsdef loop ( N ) : for k in range ( N ) : continuestart=time ( ) loop ( P ) stop1=time ( ) for k in range ( P ) : continuestop2=time ( ) print `` time with function `` , stop1-startprint `` time without function `` , stop2-stop1 time with function 0.0950000286102time with... | Why a procedure is so much faster when put into a function ? |
Python | While experimenting with Euler 99 , I noticed that these operations take different time : I wonder what 's the reason for this ? | > > > 632382**518061 # never finishes.. > > > 632382**518061 > 519432**525806 # finishes in few secondsTrue | Exponential calculation in Python |
Python | I have a pandas dataframe : Output : Now , I want to regroup the Text column into a 2D array based on the Selection Valuecolumn . All words that appear between a 0 ( first integer , or after a 1 ) and a 1 ( including ) should be put into a 2D array . The last sentence of the dataset might have no closing 1 . This can b... | import pandas as pdimport numpy as npdf = pd.DataFrame ( columns= [ 'Text ' , 'Selection_Values ' ] ) df [ `` Text '' ] = [ `` Hi '' , `` this is '' , `` just '' , `` a '' , `` single '' , `` sentence . `` , `` This '' , np.nan , `` is another one . `` , '' This is '' , `` a '' , `` third '' , `` sentence '' , '' . `` ... | Structuring a 2D array from a pandas dataframe |
Python | I have this : My question is , in this case am I passing a list comprehension or a generator object to sum ? How do I tell that ? Is there a general rule around this ? Also remember sum by itself needs a pair of parentheses to surround its arguments . I 'd think that the parentheses above are for sum and not for creati... | > > > sum ( i*i for i in xrange ( 5 ) ) | How to identify a generator vs list comprehension |
Python | I am designing a library that has adapters that supports a wide-range of libraries . I want the library to dynamically choose which ever adapter that has the library it uses installed on the machine when importing specific classes.The goal is to be able to change the library that the program depends on without having t... | try : # import pika # Is pika installed ? from servicelibrary.simple.synchronous import Publisher from servicelibrary.simple.synchronous import Consumerexcept ImportError : # import ampq # Is ampq installed ? from servicelibrary.simple.alternative import Publisher from servicelibrary.simple.alternative import Consumer ... | Choose adapter dynamically depending on librarie ( s ) installed |
Python | Is it possible in python to change what is printed for classes . I know that if we provide __str__ __unicode__ methods , we can change the way instances of a class are printed . But i want to do this for a classEg : will print hello . Is it possible to change the behaviour of print A which by default prints something l... | class A ( object ) : def __str__ ( self ) : return 'hello ' a = A ( ) print a | python : change printing of class |
Python | I have an object that is a list of lists of dictionaries : I want to sort the list by the sum of play values in the dictionaries of each nested list . The object would then be sorted like this : If it were just a list of dicts then : sorted ( myObject , key=sum ( map ( itemgetter ( play ) ) ) , reverse=True ) would wor... | myObject = [ [ { `` play '' : 5.00 , `` id '' : 1 , `` uid '' : `` abc '' } , \ { `` play '' : 1.00 , `` id '' : 2 , `` uid '' : `` def '' } ] , \ [ { `` play '' : 6.00 , `` id '' : 3 , `` uid '' : `` ghi '' } , \ { `` play '' : 7.00 , `` id '' : 4 , `` uid '' : `` jkl '' } ] , \ [ { `` play '' : 3.00 , `` id '' : 5 , ... | Sorting a list of lists of dictionaries in python |
Python | I am leaning n-gram , and building a dictionary to save n-gram values . I have something like this : My dictionary has about 3million keys and it takes 0.0002 ( s ) to get a bigramvalue . Is there anything faster than dict that I could use ? | { `` it is '' : 0.01 , `` this is '' : 0.005 , `` hello i '' : 0.2 `` hello you '' : 0.3 ... } | Is there anything faster than a dictionary ? |
Python | For starters , I would like to say if anyone can help here , you are incredible.General QuestionMy Python program needs to interact with MSMQ . Basically , I want to peek at a queue , specifying a timeout if there 's nothing in the queue.However , despite my best efforts , I can not get Peek ( ) to wait out the timeout... | from socket import gethostnameimport win32com.clientimport pythoncomimport clrclr.AddReference ( `` System '' ) clr.AddReference ( `` System.Messaging '' ) from System import TimeSpanfrom System.Messaging import MessageQueue # Source : [ 1 ] # [ 1 ] https : //docs.microsoft.com/en-us/previous-versions/windows/desktop/m... | Python running MessageQueue.Peek via win32com , how to get timeout right ? |
Python | I have some raw data like this : The rule of the data is : Not everyone will start with `` Dear '' , while if there is any , it must end with costsThe item may not always normal words , it could be written without limits ( including str , num , etc . ) I want to group the information , and I tried to use regex . That '... | Dear John Buy 1 of Coke , cost 10 dollars Ivan Buy 20 of MilkDear Tina Buy 10 of Coke , cost 100 dollars Mary Buy 5 of Milk for line in file.readlines ( ) : match = re.search ( r'\s+ ( ? P < name > \w+ ) \D* ( ? P < num > \d+ ) \sof\s ( ? P < item > \w+ ) ( ? : \D+ ) ( ? P < costs > \d* ) ' , line ) if match is not Non... | Grouping data with a regex in Python |
Python | Given that I have a pandas Series , I want to fill the NaNs with zero if either all the values are NaN or if all the values are either zero or NaN.For example , I would want to fill the NaNs in the following Series with zeroes . But , I would not want to fillna ( 0 ) the following Series : I was looking at the document... | 0 01 02 NaN3 NaN4 NaN5 NaN6 NaN7 NaN8 NaN 0 01 02 23 04 NaN5 NaN6 NaN7 NaN8 NaN if s.dropna ( ) .eq ( 0 ) .all ( ) : s = s.fillna ( 0 ) | How to efficiently fillna ( 0 ) if series is all-nan , or else remaining non-nan entries are zero ? |
Python | I 'm trying to get x and y coordinates of all cumulative maximums in a vector . I wrote a naive for-loop but I have a feeling there is some way to do it with numpy that 's more elegant.Does anyone know of any functions , masking-technique , or one-liners in numpy that can do this ? The details should be described by th... | # Generate datax = np.abs ( np.random.RandomState ( 0 ) .normal ( size= ( 100 ) ) ) y = np.linspace ( 0,1 , x.size ) z = x*y # Get maximiumsidx_max = list ( ) val_max = list ( ) current = 0for i , v in enumerate ( z ) : if v > current : idx_max.append ( i ) val_max.append ( v ) current = v # Plot themwith plt.style.con... | How to get accumulative maximum indices with numpy in Python ? |
Python | I 'm using Django 2.0 , Python 3.7 , and MySql 5 . I recently installed the django_address module . I noticed when I ran my initial migration based on my models.py file ... It created some address tables , including ... However , this table has no data in it . Is there a way to obtain seed data for the table generated ... | from django.db import modelsfrom address.models import AddressFieldfrom phonenumber_field.modelfields import PhoneNumberFieldclass CoopType ( models.Model ) : name = models.CharField ( max_length=200 , null=False ) class Meta : unique_together = ( `` name '' , ) class Coop ( models.Model ) : type = models.ForeignKey ( ... | Does the django_address module provide a way to seed the initial country data ? |
Python | I 'm designing an Application where username will be an AutoIntegerField and unique.Here 's my model.Initially , I wanted user_id to be a primary_key , but I ca n't create an AutoField which is not primary_key . As a result , I 'd to let go off user_id as primary_key and assigned username as the primary key.Now , when ... | class ModelA ( models.Model ) : username = models.BigAutoField ( primary_key=True , db_index=False ) user_id = models.UUIDField ( default=uuid.uuid4 , unique=True , editable=False ) django.db.utils.ProgrammingError : operator class `` varchar_pattern_ops '' does not accept data type bigint Applying users.0005_auto_2018... | Django- Change Username field to BigAutoField ? |
Python | When shifting column of integers , I know how to fix my column when Pandas automatically converts the integers to floats because of the presence of a NaN.I basically use the method described here.However , if the shift introduces a NaN thereby converting all integers to floats , there 's some rounding that happens ( e.... | pd.DataFrame ( { 'epochee ' : [ 1495571400259317500,1495571400260585120,1495571400260757200 , 1495571400260866800 ] } ) Out [ 19 ] : epoch0 14955717909193175031 14959999999999999992 14955714002655555553 1495571400267777777 df [ 'prior_epochee ' ] = df [ 'epochee ' ] .shift ( 1 ) df.dropna ( axis=0 , how='any ' , inplac... | Pandas Shift Converts Ints to Float AND Rounds |
Python | Is there a way to code : as a lambda , in Python ? | def fn ( ) : return None | Argumentless lambdas in Python ? |
Python | I want to change the log-level temporarily.My current strategy is to use mocking.All logging.info ( ) calls inside the method should get ignored and not logged to the console.How to implement the ... to make logs of level INFO get ignored ? The code is single-process and single-thread and executed during testing only . | with mock.patch ( ... ) : my_method_which_does_log ( ) | Change log-level via mocking |
Python | I recently discovered the feature `` Go To -- > Test '' in PyCharm.If I choose `` Create New Test '' , then the target directory of the new python file is wrong.PyCharm wants to create the new python file in the same directory.Up to now I use this structure : How can I tell PyCharm to create test_real_code.py in above ... | src/myapp/setup.pysrc/myapp/myapp/real_code.pysrc/myapp/myapp/tests/test_real_code.py | PyCharm : Create Test -- > Target directory ? |
Python | I 'm developing a little test program to see if it is feasible to add noise to an ADC to gain oversampled bits . A little theory , before we begin . Nyquist 's sampling theorem suggests that an increase in one bit of resolution requires four additional samples , and in general , n more bits requires 2^ ( n+1 ) more sam... | 10 bits : 512 volts : 1.011 bits : 1024 volts : 1.012 bits : 2046 volts : 0.999023437513 bits : 4093 volts : 0.99926757812514 bits : 8189 volts : 0.99963378906215 bits : 16375 volts : 0.99945068359416 bits : 32753 volts : 0.99954223632817 bits : 65509 volts : 0.99958801269518 bits : 131013 volts : 0.99954986572324 bits... | What is causing a negative bias in my super-sampling simulation ? |
Python | am trying to scroll over all buckets in s3 and see if there is a prefix that matches and get into those folders and read the json files.I have tried to get the folders that contain a prefix , but failing to enter them.Code : Using this am getting the ones with prefix and fails when bucket doesnt have that prefix . stru... | import boto3bucket = [ 'test-eob ' , 'test-eob-images ' ] client = boto3.client ( 's3 ' ) for i in bucket : result = client.list_objects ( Bucket=i , Prefix = 'PROCESSED_BY/FILE_JSON ' , Delimiter='/ ' ) print ( result ) | read only particular json files from s3 buckets from multiple folders |
Python | I am trying to submit a form on this page using Mechanize.This however gives the following errorI figure this is because of some misplaced character encoding ( ref ) . I would want to know how to fix this . | br.open ( `` http : //mspc.bii.a-star.edu.sg/tankp/run_depth.html '' ) # selecting form to fillbr.select_form ( nr = 0 ) # input for the formbr [ 'pdb_id ' ] = '1atp'req = br.submit ( ) mechanize._form.ParseError : expected name token at ' < ! INPUT PDB FILE > \n\t ' | Fix Character encoding of webpage using python Mechanize |
Python | I just stumbled upon the following line in Python 3.I was expecting this to be True since 1 in range ( 2 ) is True and True == True is True.But this outputs False . So it does not mean the same as ( 1 in range ( 2 ) ) == True . Furthermore it does not mean the same as 1 in ( range ( 2 ) == True ) which raises an error.... | 1 in range ( 2 ) == True | What does x in range ( ... ) == y mean in Python 3 ? |
Python | So , I have a simple event library , written in C++ and using the Boost libraries . I wanted to expose said library to Python , so naturally I turned to Boost : :Python . I got the code to compile , eventually , but now I 'm faced with quite the problem : my library uses higher-order programming techniques . For exampl... | class listener { public : listener ( ) { } void alert ( cham : :event : :event e ) { if ( responses [ e.getName ( ) ] ) responses [ e.getName ( ) ] ( e.getData ( ) ) ; } void setResponse ( std : :string n , boost : :function < void ( std : :string d ) > c ) { responses.insert ( make_pair ( n , c ) ) ; } void setManager... | Higher-Order Programming Using Boost : :Python |
Python | There is a list : nodes = [ 20 , 21 , 22 , 23 , 24 , 25 ] .I used two ways to generate new 2-dimentional objects : The type of tour1 is a generator while tour2 is a list : I want to know why tour1 is not a tuple ? Thanks . | tour1 = ( ( ( a , b ) for a in nodes ) for b in nodes ) tour2 = [ [ ( a , b ) for a in nodes ] for b in nodes ] In [ 34 ] : type ( tour1 ) Out [ 34 ] : < type 'generator ' > In [ 35 ] : type ( tour2 ) Out [ 35 ] : < type 'list ' > | What 's the difference between `` ( ) '' and `` [ ] '' when generating in Python ? |
Python | Say I have two numpy arrays , A of shape ( d , f ) and I of shape ( d , ) containing indices in 0..n , e.g.I am looking for a fast way to make reductions , in particular sum , mean and max , over all the slices A [ I == i , : ] ; a slow version would bewhich gives in this caseEDIT : I did some timings based on Divakar ... | I = np.array ( [ 0 , 0 , 1 , 0 , 2 , 1 ] ) A = np.arange ( 12 ) .reshape ( 6 , 2 ) results = np.zeros ( ( I.max ( ) + 1 , A.shape [ 1 ] ) ) for i in np.unique ( I ) : results [ i , : ] = np.mean ( A [ I == i , : ] , axis=0 ) results = [ [ 2.66666667 , 3.66666667 ] , [ 7. , 8 . ] , [ 8. , 9 . ] ] ) from __future__ impor... | Numpy reductions over successive non-contiguous slices |
Python | I want to define a decorator within a class . I do n't want to define it as a separated , independent function , for this decorator is specifically for this class and I want to keep the correlated methods together.The purpose of this decorator is to check some prerequisites , especially the database connection , SSH co... | class TestClass : def __init__ ( self ) : self.flag = True def dec ( func ) : def wrapper ( self , *args , **kwargs ) : if not self.flag : print ( `` Wo n't run ! '' ) return empty_fun ( self , *args , **kwargs ) return func ( self , *args , **kwargs ) def empty_fun ( *args , **kwargs ) : return None return wrapper @ d... | Is my in-class decorator not Pythonic enough or PyCharm not smart enough in lint warning ? |
Python | I 've got a background in Python ( though entirely self-taught , so I might have some bad habits or misconceptions ) , and I 'm trying to learn Ruby to broaden my scope.I was reading through some comparisons , and saw a lot of assertions that `` Python ca n't do metaprogramming '' ( or , less inflammatorily , `` Python... | > > > class foo : ... def make_hello_method ( self ) : ... def hello ( obj ) : ... print 'hello ' ... self.hello = hello ... > > > f = foo ( ) > > > f.hello ( ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > AttributeError : foo instance has no attribute 'hello ' > > > f.make_hello_... | Metaprogramming in Python - adding an object method |
Python | I would like to construct an extension of pandas.DataFrame — let 's call it SPDF — which could do stuff above and beyond what a simple DataFrame can : Right now , methods of DataFrame that return another DataFrame , such as .diff ( ) in the MWE above , return me another SPDF , which is great . However , I would also li... | import pandas as pdimport numpy as npdef to_spdf ( func ) : `` '' '' Transform generic output of ` func ` to SPDF . Returns -- -- -- - wrapper : callable `` '' '' def wrapper ( *args , **kwargs ) : res = func ( *args , **kwargs ) return SPDF ( res ) return wrapperclass SPDF : `` '' '' Special-purpose dataframe . Parame... | pandas : Composition for chained methods like .resample ( ) , .rolling ( ) etc |
Python | Is there a built-in Pythonic way to determine if one list completely contains the contents of another , including duplicated entries but disregarding the order of items ? | > > > l1 = [ 2 , 2 , 3 ] > > > l2 = [ 2 , 2 ] > > > l3 = [ 3 , 2 ] > > > l4 = [ 2 , 2 , 2 ] > > > l5 = [ 2 , 5 , 2 ] > > > is_superset ( l1 , l2 ) True > > > is_superset ( l1 , l3 ) True > > > is_superset ( l1 , l4 ) False > > > is_superset ( l1 , l5 ) False | How to determine if one list contains another ? |
Python | I updated Spyder to version 4.1.0 ( together with all other packages in anaconda ) . Spyder itself works fine however the kernel is not working . I get the following error and ca n't figure out how to solve it : | An error ocurred while starting the kernelThe error is : Traceback ( most recent call last ) : File `` C : \Users\20172010\AppData\Local\Continuum\anaconda3\lib\site‑packages\spyder\plugins\ipythonconsole\plugin.py '' , line 1209 , in create_kernel_manager_and_kernel_clientkernel_manager.start_kernel ( stderr=stderr_ha... | Kernel error after updating Spyder in anaconda |
Python | I know I must be missing something simple , but I am not seeing it.If I have a generator expression like this : I can generate , easily , individual integers like this : If I write a generator like this : It is no bueno : ? ? ? What am I missing ? ? ? | > > > serializer= ( sn for sn in xrange ( 0 , sys.maxint ) ) > > > serializer.next ( ) 0 > > > serializer.next ( ) 1 > > > serializer.next ( ) 2 > > > def ser ( ) : ... for sn in xrange ( 0,100000 ) : ... yield sn > > > ser ( ) .next ( ) 0 > > > ser ( ) .next ( ) 0 > > > ser ( ) .next ( ) 0 | Generator Expression vs yield : Why is n't 'next ( ) ' working ? |
Python | I was bored and playing around with the ipython console and came upon the following behaviour I do n't really understandThe answer to [ 4 ] is not 4294967296L , it 's a very long number , but I ca n't really figure out why.The number can be found here : http : //pastie.org/475714 ( Ubuntu 8.10 , python 2.5.2 , ipython ... | In [ 1 ] : 2**2Out [ 1 ] : 4In [ 2 ] : 2**2**2Out [ 2 ] : 16In [ 3 ] : 2**2**2**2Out [ 3 ] : 65536In [ 4 ] : 2**2**2**2**2 | Strange python behaviour |
Python | I am trying to implement QM coding for educational purposes . My main resource is chapter 5.11 from Handbook of Data Compression , 5th edition . This is my rough implementation of encoder for now : I am mapping the interval to integers , since it should be more efficient as I understand . In the book , there is mention... | def _encode_bit ( self , bit ) : if bit == self._lps : self._code_lps ( ) else : self._code_mps ( ) def _code_mps ( self ) : self._a = self._a - self._q_e ( ) if self._a < 0x8000 : self._switch_intervals_if_needed ( ) self._renormalize ( ) self._p_table.next_mps ( ) def _code_lps ( self ) : self._c = self._c + self._a ... | QM coding implementation in Python - is 16 bit word obligatory ? |
Python | ContextSuppose I have the following Python code : example_function here is simply going through each of the elements in the ns list and halving them 3 times , while accumulating the results . The output of running this script is simply : Since 1/ ( 2^3 ) * ( 1+3+12 ) = 2.Now , let 's say that ( for any reason , perhaps... | def example_function ( numbers , n_iters ) : sum_all = 0 for number in numbers : for _ in range ( n_iters ) : number = halve ( number ) sum_all += number return sum_allns = [ 1 , 3 , 12 ] print ( example_function ( ns , 3 ) ) 2.0 def example_function ( numbers , n_iters ) : sum_all = 0 for number in numbers : print ( '... | Is there a pythonic way to decouple optional functionality from a function 's main purpose ? |
Python | Is there any explanation about the following Python condition syntax ? It seems to work like an if statement . Why does this work ? | > > > a = 10 > > > s = ( 0 , 1 ) [ a < 10 ] > > > print s0 > > > a = -10 > > > s = ( 0 , 1 ) [ a < 10 ] > > > print s1 | Special condition syntax with parentheses and brackets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.