lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I ca n't seem to figure out how to ask this question in a searchable way , but I feel like this is a simple question.Given a pandas Dataframe object , I would like to use one column as the index , one column as the columns , and a third column as the values.For example : I would like to user column ' a ' as my index va... | a b c0 1 dog 2 1 1 cat 12 1 rat 63 2 cat 24 3 dog 15 3 cat 4 dog cat rat1 2 1 62 0 2 03 1 4 0 | How do you use pandas.DataFrame columns as index , columns , and values ? |
Python | I am studying python . I am trying to understand how to design a library that exposes a public api . I want avoid to expose internal methods that could change in future . I am looking for a simple and pythonic way to do it.I have a library that contains a bunch of classes . Some methods of those classes are used intern... | class C : def public ( self ) : pass def internal ( self ) : pass class F : def build ( ) : c = C ( ) c.internal ( ) return c from mylib.c import Cfrom mylib.f import F import mylibf = mylib.F ( ) c = f.build ( ) c.public ( ) c.internal ( ) # I wish to hide this from client code class PC : def __init__ ( self , c ) : s... | How to design a library public api avoiding to expose internals ? |
Python | I have a long-running program on a remote machine and want to be sure that ( 1 ) I have a record of any exception that causes it to terminate and ( 2 ) someone is notified if it terminates . Does anyone see drawbacks to the method I am using ? ( or have recommendations for a better one ? ) I 've read the Python docs an... | import tracebacktry : # main program code hereexcept BaseException : tb = traceback.format_exc ( ) msg = `` Exiting program due to exception : '' + tb LogToFile ( msg ) # custom logging function SendAlertEmail ( msg ) # warn admin that program terminated raise # program exits with the existing exception except Exceptio... | Drawback to catch-all exception ( at highest program level , followed by re-raising , just to log before exiting ? ) |
Python | I 'm stuck trying to convert a Mac Path to a POSIX path in Python . I want to convert something like this : to this : I know I could simply split the string into a list and then rejoin it with the correct separator . But I believe there must be a much more elegant solution I 'm missing , possibly involving the `` macpa... | 'Main HD : Users : sasha : Documents : SomeText.txt ' '/Users/sasha/Documents/SomeText.txt ' 'Extra HD : SomeFolder : SomeOtherText.txt ' '/Volumes/Extra HD/SomeFolder/SomeOtherText.txt ' '/SomeFolder/SomeOtherText.txt ' | Convert mac path to posix in python |
Python | I 'm writing python code inside source blocks within an org-mode file ; I 'm editingthe code-block in a sub-buffer , in python mode using the emacs command C-c 'Example : and I 'm getting 5 space tabs everywhere , instead of the 4 space tabs that I want.Note : I have viper ( vim emulation ) on.Where in the configuratio... | # +begin_src pythondef function ( x ) : hitting_tab_inserts_5_spaces=x*2 if x < 0 : hitting_tab_inserts_5_spaces=-x return x | Emacs org-mode python blocks have 5 space tabs , but I want 4 space tabs |
Python | I have a script that is designed to accept input piped in from stdin and then prompt the user for more input . Here is a contrived example illustrating what I mean : When I pipe data in from stdin , python interprets stdin as closed before it gets to raw_input and it gives an EOFError : EOF when reading a line : ( Plea... | import sys # Get input from stdininput_nums = [ int ( n.strip ( ) ) for n in sys.stdin ] # Prompt usermult = int ( raw_input ( `` Enter a number by which to multiply your input : `` ) ) for num in input_nums : print num*mult [ user ] $ cat nums.txt2345 [ user ] $ cat nums.txt | python sample.pyEnter a number by which t... | How do I accept piped input and then user-prompted input in a Python script ? |
Python | I 'm trying to monkeypatch a method on SomeClass from an imported package : Where obj and node are in the default call signature of SomeClass.oldmethod : I 'm aware that monkeypatching is not good practice , but we need a workaround while we fix some issues that otherwise ca n't be tackled . The above approach works FI... | from somepackage import SomeClassdef newmethod ( obj , node , **kwargs ) : `` '' '' `` '' '' SomeClass.oldmethod = newmethod class SomeClass ( object ) : def oldmethod ( obj , node ) : `` '' '' `` '' '' from functools import partialnewmethod_a = partial ( newmethod , foo= ' a ' ) newmethod_b = partial ( newmethod , foo... | Monkey patching with a partial function |
Python | Does anybody knows why the os.path.join function does n't work with subclasses of str ? ( I 'm using Python3.2 x64 and Python2.7 x86 on Windows and the result is the same ) That 's the code I haveand the result I want : but the output is \\some_file.txt no matter the value of self.I know I can do either str ( self ) or... | class Path ( str ) : def __add__ ( self , other ) : return Path ( os.path.join ( self , other ) ) p = Path ( r ' C : \the\path ' ) d = p + 'some_file.txt ' ' C : \\the\\path\\some_file.txt ' | os.path.join with str subclass |
Python | What I want : I want to apply a 1D function to an arbitrarily shaped ndarray , such that it modifies a certain axis . Similar to the axis argument in numpy.fft.fft.Take the following example : The function transf1d takes a 1D ndarray f , and two more 1D arrays x , and y . It performs a fourier transform of f ( x ) from... | import numpy as npdef transf1d ( f , x , y , out ) : `` '' '' Transform ` f ( x ) ` to ` g ( y ) ` . This function is actually a C-function that is far more complicated and should not be modified . It only takes 1D arrays as parameters. `` '' '' out [ ... ] = ( f [ None , : ] *np.exp ( -1j*x [ None , : ] *y [ : ,None ]... | Apply 1D function on one axis of nd-array |
Python | While I 'm aware that you ca n't reference self directly in a decorator , I was wondering if it 's bad practice to work around that by pulling it from args [ 0 ] . My hunch is that it is , but I want to be sure.To be more specific , I 'm working on an API to a web service . About half the commands require a token to be... | def some_command ( self , ... , undo_token = None ) : if undo_token = None : undo_token = self.get_undo_token ( ) ... return fnord @ decoratordef undoable ( fn , *args , **kwargs ) : if 'undo_token ' not in kwargs : kwargs [ 'undo_token ' ] = args [ 0 ] .get_undo_token ( ) return ( fn ( *args , **kwargs ) , kwargs [ 'u... | Is it bad practice to use self in decorators ? |
Python | I am learning Python and right now I am on the topic of scopes and nonlocal statement.At some point I thought I figured it all out , but then nonlocal came and broke everything down.Example number 1 : Running it naturally fails.What is more interesting is that print ( ) does not get executed . Why ? .My understanding w... | print ( `` let 's begin '' ) def a ( ) : def b ( ) : nonlocal x x = 20 b ( ) a ( ) print ( `` let 's begin '' ) def a ( ) : if False : x = 10 def b ( ) : nonlocal x x = 20 b ( ) a ( ) | When is the existence of nonlocal variables checked ? |
Python | Currently , I ’ m filling out the form on a site with the following : But the form gets filled out the form sequentially , one after the other . Is there a way to fill out the form all at once ? Thank you and will be sure to vote up and accept the answer ! | browser.fill ( ‘ form [ firstname ] ’ , ‘ Mabel ’ ) browser.fill ( ‘ form [ email ] ’ , ‘ hi @ hi.com ’ ) browser.select ( ‘ form [ color ] ’ , ‘ yellow ’ ) | Python : How to fill out form all at once with splinter/Browser ? |
Python | The Python re module 's documentation says that when the re.UNICODE flag is set , '\s ' will match : whatever is classified as space in the Unicode character properties database.As far I can tell , the BOM ( U+FEFF ) is classified as a space.However : evaluates to None.Is this a bug in Python or am I missing something ... | re.match ( u'\s ' , u'\ufeff ' , re.UNICODE ) | Python regex '\s ' does not match unicode BOM ( U+FEFF ) |
Python | Here is an example , I have this data ; and I 'd like to transform it to this dataI can transform data with dirty codes but I 'd like to do it the elegant way . | datetime keyword COUNT0 2016-01-05 a_click 1001 2016-01-05 a_pv 2002 2016-01-05 b_pv 1503 2016-01-05 b_click 904 2016-01-05 c_pv 1205 2016-01-05 c_click 90 datetime keyword ctr0 2016-01-05 a 0.51 2016-01-05 b 0.62 2016-01-05 c 0.75 | How to calculate the click-through rate |
Python | I am on windows 7 . I installed mrjob and when I run the example word_count file from the website , it works fine on the local machine . However , I get the error when attempting to run it on Amazon EMR . I even tested connecting to amazon s3 with just boto and it works.mrjob.conf filerunning the following in my cmdit ... | runners : emr : aws_access_key_id : xxxxxxxxxxxxx aws_region : us-east-1 aws_secret_access_key : xxxxxxxx ec2_key_pair : bzy ec2_key_pair_file : C : \aa.pem ec2_instance_type : m1.small num_ec2_instances : 3 s3_log_uri : s3 : //myunique/ s3_scratch_uri : s3 : //myunique/ python word_count.py -c mrjob.conf -r emr mytext... | mrjob : Invalid bootstrap action path , must be a location in Amazon S3 |
Python | When calling a program from the command line , I can pipe the output to grep to select the lines I want to see , e.g.I am in search for the same kind of line selection , but for a C library called from Python . Consider the following example : When running this Python code , I want the output of the C part to be grep'e... | printf `` hello\ngood day\nfarewell\n '' | grep day import os # Function which emulate a C library calldef call_library ( ) : os.system ( 'printf `` hello\ngood day\nfarewell\n '' ' ) # Pure Python stuffprint ( 'hello from Python ' ) # C library stuffcall_library ( ) | grep library output from within Python |
Python | Someone posted this question here a few weeks ago , but it looked awfully like homework without prior research , and the OP promptly removed it after getting a few downvotes.The question itself was rather interesting though , and I 've been thinking about it for a week without finding a satisfying solution . Hopefully ... | def merge ( first , second ) : ( a , b ) , ( c , d ) = first , second if c < = b + 1 : return ( a , max ( b , d ) ) else : return Falsedef smallest_available_integer ( intervals ) : # Sort in reverse order so that push/pop operations are fast intervals.sort ( reverse = True ) if ( intervals == [ ] or intervals [ -1 ] [... | Computing the smallest positive integer not covered by any of a set of intervals |
Python | I have the following structure in Python : I would like to find all the possible combinations of letters in the order that they currently exist . For the example above this would be : This seems like it should be a very simple thing to do but I can not figure it out . | letters = [ [ ' a ' , ' b ' , ' c ' ] , [ ' p ' , ' q ' , ' r ' , 's ' ] , [ ' j ' , ' k ' , ' l ' ] ] apjapkaplaqjaqkaql ... cskcsl | How can I find all the possible combinations of a list of lists ( in Python ) ? |
Python | I have the following DataFrame df , which can be created as follows : And which looks like this : I want to flag the rows where the is_hit condition is True for the first time , such that the expected new column hit_first would be : How to create this hit_first column ? | date_today = datetime.now ( ) .date ( ) days = pd.date_range ( date_today , date_today + timedelta ( 19 ) , freq='D ' ) x = np.arange ( 0,2*np.pi,0.1*np.pi ) # start , stop , stepy = np.sin ( x ) df = pd.DataFrame ( { 'dates ' : days , 'vals ' : y , 'is_hit ' : abs ( y ) > 0.9 } ) df = df.set_index ( 'dates ' ) is_hit ... | Flag only first row where condition is met in a DataFrame |
Python | I 'm trying to map a function that takes 2 arguments to a list : This gives me a TypeError : < lambda > ( ) missing 1 required positional argument : 'value'.What is the correct way to map my lambda onto this input ? | my_func = lambda index , value : value.upper ( ) if index % 2 else value.lower ( ) import stringalphabet = string.ascii_lowercasen = map ( my_func , enumerate ( alphabet ) ) for element in n : print ( element ) | Using a function with multiple parameters with ` map ` |
Python | Here is what I am working with so farI am not interested in another way to achieve the desired output . Rather , for educational purposes , I would like to know why overriding the __call__ as I have done , does n't work as I expect . | def f ( n ) : return nf.__call__ = lambda n : n + 1print f ( 2 ) # I expect an output of 3 but get an output of 2 | How do I override a method object 's __call__ method in Python ? |
Python | I read this blog about new things in scikit . The OneHotEncoder taking strings seems like a useful feature . Below my attempt to use thisI encounter the below python error with this code and also I have some additional concerns . ValueError : X has 10 features per sample ; expecting 11To start from the beginning .. thi... | import pandas as pdfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import OneHotEncoderfrom sklearn.compose import ColumnTransformercols = [ 'Survived ' , 'Pclass ' , 'Sex ' , 'Age ' , 'SibSp ' , 'Parch ' , 'Fare ' , 'Embarked ' ] train_df = pd.read_csv ( '../../data/train.csv ' , usecols=... | Dummify categorical variables for logistic regression with pandas and scikit ( OneHotEncoder ) |
Python | How can I implement `` positional-only parameter '' for a function that is user defined in python ? | def fun ( a , b , / ) : print ( a**b ) fun ( 5,2 ) # 25fun ( a=5 , b=2 ) # should show error | How to implement `` positional-only parameter '' in a user defined function in python ? |
Python | I want a button to create a PDF file ( with Python 2.7 , Django 1.8 ) , but I have no clue how to express that to the machine.I started by reading some articles , trying to learn from the others how could that be done.Found this handy link , which redirected me to the following links : ReportLab on BitBucketSo , in ord... | pip install reportlab pip install Pillow Requirement already satisfied : Pillow in c : \pythonprojects\virtualenvs\apis\lib\site-packagesRequirement already satisfied : olefile in c : \pythonprojects\virtualenvs\apis\lib\site-packages ( from Pillow ) # views.pyfrom django.http import responsefrom django.core.files.stor... | TypeError at /app/profile/ , 'list ' object is not callable handle_pageBegin args= ( ) |
Python | I have a pygtk program designed to run on both Windows and Ubuntu . It 's Python 2.7 and gtk2 with the static bindings ( ie no gobject introspection ) . The problem I 'm experiencing exists on Ubuntu but not on Windows.My program is supposed to be able process large numbers of files ( here I test with about 200 ) , but... | import gtk , gobject , timedef print_how_long_it_was_frozen ( ) : print time.time ( ) - start_timedef button_clicked ( button ) : dialog = gtk.FileChooserDialog ( 'Select files to add ' , w , gtk.FILE_CHOOSER_ACTION_OPEN , buttons= ( gtk.STOCK_CANCEL , gtk.RESPONSE_CANCEL , gtk.STOCK_OPEN , gtk.RESPONSE_OK ) ) dialog.s... | Platform-dependent performance issues when selecting a large number of files with gtk.FileChooserDialog |
Python | The simplest way to manipulate the GIL in Python C extensions is to use the macros provided : This works great , letting me release the GIL for the bulk of my code , but re-grabbing it for small bits of code that need it.The problem is when I compile this with gcc , I get : because Py_BEGIN_ALLOW_THREADS is defined lik... | my_awesome_C_function ( ) { blah ; Py_BEGIN_ALLOW_THREADS // do stuff that does n't need the GIL if ( should_i_call_back ) { Py_BLOCK_THREADS // do stuff that needs the GIL Py_UNBLOCK_THREADS } Py_END_ALLOW_THREADS return blah blah ; } ext/engine.c:548 : warning : '_save ' might be used uninitialized in this function #... | How to avoid gcc warning in Python C extension when using Py_BEGIN_ALLOW_THREADS |
Python | Given the following program in Python : and the equivalent in C : When I pipe the program with cat , the output is by default buffered ( instead of line-buffered ) . As a consequence , I have no output : I can use stdbuf to switch back to line-buffering : But that does n't work with Python : Any idea why ? I 'm aware o... | import sysprint ( `` input '' ) while True : pass # include < stdio.h > int main ( ) { printf ( `` input\n '' ) ; while ( 1 ) ; return 0 ; } % python3 ./a.py | cat ( empty ) % ./a.out | cat ( empty ) % stdbuf -oL ./a.out | catinput % stdbuf -oL python3 a.py | cat ( empty ) | Why stdbuf has no effect on Python ? |
Python | I have a little bit of experience with promises in Javascript . I am quite experienced with Python , but new to its coroutines , and there is a bit that I just fail to understand : where does the asynchronicity kick in ? Let 's consider the following minimal example : As I understand it , await something puts execution... | async def gen ( ) : await something return 42 | Python coroutines |
Python | I am presently writing a Python script to process some 10,000 or so input documents . Based on the script 's progress output I notice that the first 400+ documents get processed really fast and then the script slows down although the input documents all are approximately the same size.I am assuming this may have to do ... | pattern = re.compile ( ) | Pythonic and efficient way of defining multiple regexes for use over many iterations |
Python | I 'm trying to parse some Traffic Violation sentences using pyparsing , when I use grammar.searchString ( sentence ) it is ok , but when I use parseString a ParseException is thrown . Can anybody help me please saying what is wrong with my code ? Error traceback Traceback ( most recent call last ) : File `` script3.py ... | from pyparsing import Or , Literal , oneOf , OneOrMore , nums , alphas , Regex , Word , \ SkipTo , LineEnd , originalTextFor , Optional , ZeroOrMore , Keyword , Groupimport pyparsing as ppfrom nltk.tag import pos_tagsentences = [ 'Failure to control vehicle speed on highway to avoid collision ' , 'Failure to stop at st... | pyparsing.ParseException when using parseString ( searchString works ) |
Python | Simple question to which I ca n't find any `` nice '' answer by myself : Let 's say I have the following condition : Where the number of or statement can be quite longer depending on the situation.Is there a `` nicer '' ( more Pythonic ) way of writing this , without sacrificing performance ? If thought of using any ( ... | if 'foo ' in mystring or 'bar ' in mystring or 'hello ' in mystring : # Do something pass | Is there any nicer way to write successive `` or '' statements in Python ? |
Python | So I have a client in python and a backend in PHP . The python client is using pyjwt and the php server is using Firebase JWT.When encoding and decoding tokens within php everything works fine . But when I encode tokens from python and decode them with php the Firebase library returns an error : The encoding python cod... | Firebase\JWT\SignatureInvalidException Object ( [ message : protected ] = > Signature verification failed [ string : Exception : private ] = > [ code : protected ] = > 0 [ file : protected ] = > /var/www/vendor/firebase/php-jwt/src/JWT.php [ line : protected ] = > 110 ... import jwt ... payload = { 'sub ' : self.client... | Firebase JWT library ca n't verify Python JWT token |
Python | The default CherryPy routing style is based on instances of classes with methods decorated by @ cherrypy.expose . In the example below , these urls are provided by simple tweaking on otherwise ordinary classes.I wonder if there is a way to achieve this using Flask 's @ route or some other decorator . | //hello/hello/again/bye/bye/again import cherrypyclass Root ( object ) : @ cherrypy.expose def index ( self ) : return 'my app'class Greeting ( object ) : def __init__ ( self , name , greeting ) : self.name = name self.greeting = greeting @ cherrypy.expose def index ( self ) : return ' % s % s ! ' % ( self.greeting , s... | Can Flask provide CherryPy style routing ? |
Python | I currently have two sets of data files that look like this : File 1 : and in file 2 : I would like to combine the files based on mathching rows in the first column ( so that `` tests '' match up ) like so : I have this CodeHowever the output ends up looking like this : Can anyone help me with how to make the output so... | test1 ba ab cd dh gftest2 fa ab cd dh gftest3 rt ty er wq eetest4 er rt sf sd sa test1 123 344 123test1 234 567 787test1 221 344 566test3 456 121 677 test1 ba ab cd dh gf 123 344 123test1 ba ab cd dh gf 234 567 787test1 ba ab cd dh gf 221 344 566test3 rt ty er wq ee 456 121 677 def combineFiles ( file1 , file2 , outfil... | Merging data based on matching first column in Python |
Python | I was running into some problems using with statement ( PEP 343 ) in python to automatically manage resource clean up after the context . In particular , with statement always assumes the resource clean up method is .close ( ) . I.E . in the following block of code , browser.close ( ) is automatically getting called wh... | with contextlib.closing ( webdriver.Firefox ( ) ) as browser : # do something with browser # at this point browser.close ( ) has been called . def __exit__ ( self , *exc_info ) : self.thing.close ( ) | Is it possible to have contextlib.closing ( ) to call an arbitrary cleanup method instead of .close ( ) |
Python | I 'm a C # programmer trying to understand some Python code . The code in question is a generator function , and looks like this : If I understand this correctly , this will generate a iterable sequence with one member . However , there is no expression after the yield statement . What is such an expression-less statem... | def func ( ) : oldValue = curValue yield curValue = oldValue | What happens when a Python yield statement has no expression ? |
Python | Following tutorial on https : //testdriven.io/ , I have created a websocket test for testing my websocket connection : I have created pytest.ini : but whenever I run pytest , I just got this error : I 'm complete new to testing and all ; I 'm not even sure how it works , I have tried researching a bit but did n't under... | # tests/test_websockets.pyfrom django.contrib.auth import get_user_modelfrom django.contrib.auth.models import Groupfrom django.test import Clientfrom channels.db import database_sync_to_asyncfrom channels.layers import get_channel_layerfrom channels.testing import WebsocketCommunicatorfrom nose.tools import assert_equ... | PytestDeprecationWarning at test setup : the funcargnames attribute was an alias for fixturenames |
Python | The below code summarises all the numbers in the list held in all_numbers . This makes sense as all the numbers to be summarised are held in the list.When converting the above function to a generator function , I find I get the same result with less memory used ( below code ) . What I do n't understand is how can all_n... | def firstn ( n ) : `` 'Returns list number range from 0 to n `` ' num , nums = 0 , [ ] while num < n : nums.append ( num ) num += 1 return nums # all numbers are held in a list which is memory intensiveall_numbers = firstn ( 100000000 ) sum_of_first_n = sum ( all_numbers ) # Uses 3.8Gb during processing and 1.9Gb to st... | Where are the 'elements ' being stored in a generator ? |
Python | Are file.write operations atomic in Python or C ? ExampleConsider the following two threadsThread 1Thread 2Are we guaranteed not to get intermingled text like the following ? but instead get one of the two possible correct resultsNote that there is a single call to write in each thread , obviously atomic multiple write... | with open ( 'foo ' , ' a ' ) as f : f.write ( '123456 ' ) with open ( 'foo ' , ' a ' ) as f : f.write ( 'abcdef ' ) 1a2b3c4d5e6for 123abc456def 123456abcdefabcdef123456 | Is Python 's file.write atomic ? |
Python | When I do a query with isql I get the following message and the query blocks . The transaction log in database foo is almost full . Your transaction is being suspended until space is made available in the log.When I do the same from Python : The query blocks , but I would like see this message.I tried : I 'm using : py... | cursor.execute ( sql ) Sybase.set_debug ( sys.stderr ) connection.debug = 1 | How do I capture this warning message when the query is blocking ? |
Python | I have a directory full of data files to feed into tests , and I load them using something along the lines ofAs the test suite grows , this is becoming unmaintainable . Is there a way to programatically create fixtures ? Ideally it would be something like : Is there a way to accomplish this ? | @ pytest.fixture ( scope= '' function '' ) def test_image_one ( ) : return load_image ( `` test_image_one.png '' ) for fname in [ `` test_image_one '' , `` test_image_two '' , ... ] : def pytest_fixutre_function ( ) : return load_image ( `` { } .png '' .format ( fname ) ) pytest.magic_create_fixture_function ( fname , ... | Programmatically create pytest fixtures |
Python | I currently have this piece of code ( feel free to comment on it too : ) ) On an Intel i7 it spawns eight workers when running on Linux ; however , when running Windows 8.1 Pro it only spawns one worker . I checked and cpu_count ( ) returns 8 on both Linux and Windows . Is there something I am missing here , or doing w... | def threaded_convert_to_png ( self ) : paths = self.get_pages ( ) pool = Pool ( ) result = pool.map ( convert_to_png , paths ) self.image_path = result | Python multiprocessing Pool on Windows 8.1 spawns only one worker |
Python | I 'd like to know why one is able to create a new attribute ( `` new '' means `` not previously defined in the class body '' ) for an instance of a custom type , but is not able to do the same for a built-in type , like object itself . A code example : | > > > class SomeClass ( object ) : ... pass ... > > > sc = SomeClass ( ) > > > sc.name = `` AAA '' > > > sc.name'AAA ' > > > obj = object ( ) > > > obj.name = `` BBB '' Traceback ( most recent call last ) : File `` < console > '' , line 1 , in < module > AttributeError : 'object ' object has no attribute 'name ' | Why custom types accept ad-hoc attributes in Python ( and built-ins do n't ) ? |
Python | A lot of inbuilt functions in python do n't take keyword arguments . For example , the chr function.Trying to pass values to chr using keyword arguments do n't work.I know that the / character in the help text of the chr function means that it wo n't take keyword arguments.How can I define a function that does not take... | > > > help ( chr ) Help on built-in function chr in module builtins : chr ( i , / ) Return a Unicode string of one character with ordinal i ; 0 < = i < = 0x10ffff . > > > chr ( i=65 ) Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > TypeError : chr ( ) takes no keyword arguments > > >... | How to create a python function which take only positional arguments and no keyword arguments ? |
Python | Can someone explain me why I do not get the same result in those ? The output of this code is : 2017-10-25 20:10:50+01:35The output of this code is : 2017-10-25 20:10:50+03:00My question is why they have different timezones ( 1:35 and 3:00 ) . I know that the second code is true because my UTC is 3:00 . But can you tel... | import datetime , pytzvar1 = datetime.datetime ( 2017,10,25,20,10,50 , tzinfo=pytz.timezone ( `` Europe/Athens '' ) ) ) print ( var1 ) import datetime , pytzvar1 = datetime.datetime ( 2017,10,25,20,10,50 ) var1 = pytz.timezone ( `` Europe/Athens '' ) .localize ( var1 ) print ( var1 ) | Why does creating a datetime with a tzinfo from pytz show a weird time offset ? |
Python | I was trying to do a challenge on codeeval in python3 and got stuck trying to improve my solution . Every time i tried to iterate ( or print , or some other action ) two times consecutively over the same iterator , the second loop came up empty . Here is a minimal example that produces this behavior , although I tried ... | numbers = ( ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' ) numbers = map ( int , numbers ) print ( list ( numbers ) ) print ( list ( numbers ) ) [ 1 , 2 , 3 , 4 , 5 ] [ ] | Python iterator is empty after performing some action on it |
Python | I have a special use case that I have to separate inference and back-propagation : I have to inference all images and slice outputs into batches followed by back-propagating batches by batches . I do n't need to update my networks ' wegiths.I modified snippets of cifar10_tutorial into the following to simulate my probl... | for epoch in range ( 2 ) : # loop over the dataset multiple times for i , data in enumerate ( trainloader , 0 ) : # get the inputs inputs , labels = data inputs.requires_grad = True # zero the parameter gradients optimizer.zero_grad ( ) # forward + backward + optimize outputs = net ( inputs ) for j in range ( 4 ) : # j... | Pytorch - inference all images and back-propagate batch by batch |
Python | I need to pass huge list/tuple to function through *args.And I wonder what happens at function call.Does it handle arguments similar to any positional variable : save it and access on-demand during body execution ? Or does it iterate through arguments even before body execution , extending positional arguments ? Or is ... | def f ( *args ) : # defined in foreign module passarguments = tuple ( range ( 10000 ) ) f ( *arguments ) | What is execution model for *args in function call ? |
Python | I want to implement my own matrix-class that inherits from numpy 's matrix class.numpy 's matrix constructor requires an attribute , something like ( `` 1 2 ; 3 4 ' '' ) . In contrast , my constructor should require no attributes and should set a default attribute to the super-constructor.That 's what I did : There mus... | import numpy as npclass MyMatrix ( np.matrix ) : def __init__ ( self ) : super ( MyMatrix , self ) .__init__ ( `` 1 2 ; 3 4 '' ) if __name__ == `` __main__ '' : matrix = MyMatrix ( ) this_matrix = np.matrix ( ) TypeError : __new__ ( ) takes at least 2 arguments ( 1 given ) | Numpy Matrix class : Default constructor attributes for inherited class |
Python | I found out that Python is intending to support static typing , but it still in beta phase.I tried the following code with python 3.4.3 : the syntax is supported but I did not get the expected result . if I type somme ( ' 1 ' , ' 3 ' ) I get 13 , while I should get TypeError exception saying int variable expected.Has a... | def somme ( a : int , b : int ) - > int : return a + b | Python static typing does not work |
Python | I have a python web app that uses the pylibmc module to connect to a memcached server . If I test my app with requests once per second or slower , everything works fine . If I send more than one request per second , however , my app crashes and I see the following in my logs : Assertion `` ptr- > query_id == query_id +... | self.mc = pylibmc.Client ( servers= [ os.environ.get ( MEMCACHE_SERVER_VAR ) ] , username=os.environ.get ( MEMCACHE_USER_VAR ) , password=os.environ.get ( MEMCACHE_PASS_VAR ) , binary=True ) # ... if ( self.mc ! = None ) : self.mc.set ( key , stored_data ) # ... page = self.mc.get ( key ) | pylibmc : 'Assertion `` ptr- > query_id == query_id +1 '' failed for function `` memcached_get_by_key '' ' |
Python | I am using Komodo 7 for writing my django/python code.There is one thing that I really liked when I used Eclipse for my python stuff and it was that I could do : and by that help eclipse determine the coding completion for the specific variable.Is there any way to do it using Komodo ? the IsInstance trick does n't work... | assert isinstance ( [ variable ] , [ type ] ) | Komodo 7 or 8 code completion for django |
Python | I have a python list of integers , and I 'd like to know how much space it will take up when encoded as a sequence of Protocol Buffers variable-length integers , or varints . What 's the best way to figure this out without actually encoding the integers ? | my_numbers = [ 20 , 69 , 500 , 38987982344444 , 420 , 99 , 1 , 999 ] e = MyCoolVarintArrayEncoder ( my_numbers ) print ( len ( e ) ) # ? ? ? | Given an integer , how big is its varint encoding ? |
Python | I have the following class : I want to change number to being a property . This means I also want to change all of it usages . Does PyCharm have this built into it 's refactoring tools ? It seems to be according to this issue.At this point , I 'm doing `` find all usages '' and then manually fixing each instance . If t... | class Dogs ( object ) : def __init__ ( self ) : self.names = [ ] self.breeds = set ( ) def number ( self ) : return len ( self.names ) | Refactor class method to property using Pycharm |
Python | Consider the following loop : “ command 2 ” command takes systematically longer to run when “ command 1 ” is run before it . The following plot shows the execution time of 1+1 as a function of the loop index i , averaged over 100 runs . Execution of 1+1 is 30 times slower when preceded by subprocess.Popen.It gets even ... | for i in range ( 20 ) : if i == 10 : subprocess.Popen ( [ `` echo '' ] ) # command 1 t_start = time.time ( ) 1+1 # command 2 t_stop = time.time ( ) print ( t_stop - t_start ) var = 0for i in range ( 20 ) : if i == 10 : # command 1 subprocess.Popen ( [ 'echo ' ] ) # command 2a t_start = time.time ( ) 1 + 1 t_stop = time... | Why are Python operations 30× slower after calling time.sleep or subprocess.Popen ? |
Python | I 'd like to delete the back line-separators ( dividers ? ) in the drawn colormap , using ColorbarBase : It always gives me too many black lines in between.. is there a way to eliminate them ? I already tried stuff like : oras seen in the ColorbarBase methods in http : //fossies.org/dox/matplotlib-1.2.0/matplotlib_2col... | cm = get_cmap ( 'RdBu ' ) Ncol = 501cccol = cm ( 1 . *arange ( Ncol ) /Ncol ) cax = fig.add_axes ( [ 0.15,0.15,0.05,0.4 ] ) fig.add_axes ( [ 0.5,0.15,0.3,0.03 ] ) norm = mpl.colors.Normalize ( vmin=valmin , vmax=valmax ) cb1 = mpl.colorbar.ColorbarBase ( cax , cmap=cm , norm=norm , orientation='vertical ' ) del cb1.lin... | Matplotlib ColorbarBase : delete color separators |
Python | Here is a very simple program : Here is the output I was expecting : But instead I get this : There is really something I do not get here ! | a = [ [ ] ] *3 print str ( a ) a [ 0 ] .append ( 1 ) a [ 1 ] .append ( 2 ) a [ 2 ] .append ( 3 ) print str ( a [ 0 ] ) print str ( a [ 1 ] ) print str ( a [ 2 ] ) [ [ ] , [ ] , [ ] ] [ 1 ] [ 2 ] [ 3 ] [ [ ] , [ ] , [ ] ] [ 1 , 2 , 3 ] [ 1 , 2 , 3 ] [ 1 , 2 , 3 ] | Python : how to append new elements in a list of list ? |
Python | isinstance can be used to check if the object which is the first argument is an instance or subclass of classinfo class which is the second argument.Is there a similar way to check if an operator validate in Python ? Something likeI am trying to build an online executor for Python very beginner.When they input like thi... | a = 1b = [ 1 ] isinstance ( a , list ) isinstance ( b , list ) isoperator ( '= ' ) isoperator ( ' : = ' ) isoperator ( ' < - ' ) | Is there a way to check if a symbol is a valid operator in Python ? |
Python | I am writing some code in Python something like this : When I try to interrupt the loop , I basically need to hold down Control+C long enough to cancel every invocation of the function for all the elements of large-list , and only then does my program exit.Is there any way I can prevent the function from catching Keybo... | import systry : for x in large_list : function_that_catches_KeyboardInterrupt ( x ) except KeyboardInterrupt : print `` Canceled ! '' sys.exit ( 1 ) | In Python , can I prevent a function from catching KeyboardInterrupt and SystemExit ? |
Python | I 'm trying to subclass numpy.complex64 in order to make use of the way numpy stores the data , ( contiguous , alternating real and imaginary part ) but use my own __add__ , __sub__ , ... routines.My problem is that when I make a numpy.ndarray , setting dtype=mysubclass , I get a numpy.ndarray with dtype='numpy.complex... | import numpy as npclass mysubclass ( np.complex64 ) : passa = mysubclass ( 1+1j ) A = np.empty ( 2 , dtype=mysubclass ) print type ( a ) print repr ( A ) < class '__main__.mysubclass ' > array ( [ -2.07782988e-20 +4.58546896e-41j , -2.07782988e-20 +4.58546896e-41j ] , dtype=complex64 ) ' | Subclassing numpy scalar types |
Python | How can I make my ( Python 2.7 ) code aware whether it is running in a doctest ? The scenario is as follows : I have a function that print ( ) s some output to a file descriptor passed in as an argument , something like this : But when I try to use printing_func ( ) in a doctest , the test fails ; because of my specifi... | from __future__ import print_functiondef printing_func ( inarg , file=sys.stdout ) : # ( do some stuff ... ) print ( result , file=file ) | How to determine whether code is running in a doctest ? |
Python | In JavaScript , a module 's default object can be set using `` module.exports '' : Similar behavior can be achieved in Python with : ... but is it possible to set a default object in Python ? | MyCache = require ( `` ./MyCache '' ) ; cache = new MyCache ( ) ; from MyCache import Create as MyCachecache = MyCache ( ) import MyCachecache = MyCache ( ) | Is there a Python analogue for JavaScript 's module.exports ? |
Python | I need to use TensorFlow Probability to implement Markov Chain Monte Carlo with sampling from a Bernoulli distribution . However , my attempts are showing results not consistent with what I would expect from a Bernoulli distribution.I modified the example given in the documentation of tfp.mcmc.sample_chain ( sampling f... | import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport tensorflow as tfimport tensorflow_probability as tfptfd = tfp.distributionsdef make_likelihood ( event_prob ) : return tfd.Bernoulli ( probs=event_prob , dtype=tf.float32 ) dims=1event_prob = 0.3num_results = 30000likelihood = make_likelihood ... | TensorFlow Probability MCMC with Bernoulli distribution |
Python | I was playing around with Python classes and arrived at the following example in which two variables which appear to be static class variables have different behavior when modified.What 's going on here ? My first instinct is that something tricky is going on with references . | class Foo : a = [ ] n = 0 def bar ( self ) : self.a.append ( 'foo ' ) self.n += 1x = Foo ( ) print x.a , x.n ( [ ] 0 ) x.bar ( ) print x.a , x.n ( [ 'foo ' , 1 ] ) y = Foo ( ) print y.a , y.n ( [ 'foo ' , 0 ] ) y.bar ( ) print y.a , y.n ( [ 'foo ' , 'foo ' ] , 1 ) | Python class variable int vs array |
Python | Edit : found out this happens on a very basic project generated by djangocms-installer , I 've reported an issue about this.I 've setup a simple project with django-cms and my client 's native language is french . Thanks to Transifex , French translation is always up to date . Not quite sure why , everything related to... | import osgettext = lambda s : sDATA_DIR = os.path.dirname ( os.path.dirname ( __file__ ) ) '' '' '' Django settings for omg project.For more information on this file , seehttps : //docs.djangoproject.com/en/1.6/topics/settings/For the full list of settings and their values , seehttps : //docs.djangoproject.com/en/1.6/r... | django-cms not using user 's language for its core translations |
Python | When using the hypothesis library and performing unit testing , how can I see what instances the library is trying on my code ? ExampleThe question is : how do I print / see the some_number variable , generated by the library ? | from hypothesis import givenimport hypothesis.strategies as st @ given ( st.integers ( ) ) def silly_example ( some_number ) : assert some_number > 0 | How to see the output of Python 's hypothesis library |
Python | EnvironmentGNU/Linux ( Fedora 25 ) .Conda environment.Python 3.6.1.Numba 0.33.0 ( np112py36_0 ) .Initial setup ( works fine ) Two files main.py and numbamodule.py : main.pyWhich spawns 2 processes to run the execute_numba function.numbamodule.pyWhich defines a simple function numba_function : I can run the main.py scri... | import timefrom importlib import import_modulefrom multiprocessing import Processdef execute_numba ( name ) : # Import the function importfunction = 'numbamodule.numba_function ' module = import_module ( importfunction.split ( ' . ' ) [ 0 ] ) function = getattr ( module , importfunction.split ( ' . ' ) [ -1 ] ) while T... | Weird multiprocessing block importing Numba function |
Python | I wish to dynamically import a module in Python ( 3.7 ) , whereby the module 's code is defined within a string.Below is a working example that uses the imp module , which is deprecated in favour of importlib ( as of version 3.4 ) : Python 's documentation states that importlib.util.module_from_spec ( ) should be used ... | import impdef import_code ( code , name ) : # create blank module module = imp.new_module ( name ) # populate the module with code exec ( code , module.__dict__ ) return modulecode = `` '' '' def testFunc ( ) : print ( 'spam ! ' ) '' '' '' m = import_code ( code , 'test ' ) m.testFunc ( ) | Python : Dynamically import module 's code from string with importlib |
Python | Is it possible to combine async context managers in python ? Something similar to asyncio.gather , but able to be used with context managers . Something like this : Is this currently possible ? | async def foo ( ) : async with asyncio.gather_cm ( start_vm ( ) , start_vm ( ) ) as vm1 , vm2 : await vm1.do_something ( ) await vm2.do_something ( ) | Multiple Async Context Managers |
Python | I have two lists made of numbers ( integers ) ; both have 2 million unique elements.I want to find number a from list 1 and b from list 2 , that -here 's what I came up with : any suggestions ? edit : my method is too slow . It would take more than one day . | 1 ) a*b should be maximized.2 ) a*b has to be smaller than certain limit . maxpq = 0nums = sorted ( nums , reverse=True ) nums2 = sorted ( nums2 , reverse=True ) for p in nums : n = p*dropwhile ( lambda q : p*q > sqr , nums2 ) .next ( ) if n > maxpq : maxpq=nprint maxpq | python - 2 lists , and finding maximum product from 2 lists |
Python | I 'm working on a personal project using opencv in python . Want to detect a sudoku grid . The original image is : So far I have created this : Then tried to select a big blob . Result may be similar to this : I got a black image as result : The code is : The code in repl is : https : //repl.it/ @ gmunumel/SudokuSolver... | import cv2import numpy as npdef find_biggest_blob ( outerBox ) : max = -1 maxPt = ( 0 , 0 ) h , w = outerBox.shape [ :2 ] mask = np.zeros ( ( h + 2 , w + 2 ) , np.uint8 ) for y in range ( 0 , h ) : for x in range ( 0 , w ) : if outerBox [ y , x ] > = 128 : area = cv2.floodFill ( outerBox , mask , ( x , y ) , ( 0 , 0 , ... | How to detect Sudoku grid board in OpenCV |
Python | In Python ( 2 and 3 ) . Whenever we use list slicing it returns a new object , e.g . : OutputIf the same thing is repeated with tuple , the same object is returned , e.g . : OutputIt would be great if someone can shed some light on why this is happening , throughout my Python experience I was under the impression empty... | l1 = [ 1,2,3,4 ] print ( id ( l1 ) ) l2 = l1 [ : ] print ( id ( l2 ) ) > > > 140344378384464 > > > 140344378387272 t1 = ( 1,2,3,4 ) t2 = t1 [ : ] print ( id ( t1 ) ) print ( id ( t2 ) ) > > > 140344379214896 > > > 140344379214896 | Tuple slicing not returning a new object as opposed to list slicing |
Python | I posted this on programmers.stackexchange.com , but I figured it may be more appropriate on SO . I use emacs for all my code edit needs . Typically , I will use M-x compile to run my test runner which I would say gets me about 70 % of what I need to do to keep the code on track however lately I 've been wondering how ... | M-x pdbRun pdb ( like this ) : /Users/twillis/projects/hydrant/bin/python /Users/twillis/bin/pdb /Users/twillis/projects/hydrant/bin/devappserver /Users/twillis/projects/hydrant/parts/hydrant-app/ HellooKitty : hydrant twillis $ cat ~/bin/pdb # ! /usr/bin/env pythonif __name__ == `` __main__ '' : import sys sys.version... | Emacs : methods for debugging python |
Python | I have a parent widget that in some cases calls a custom QDialog to get user input . How do I write a unit test to ensure the dialog is called , and that it will handle correct input correctly ? Here 's a mini example : So in this case , I 'd want to write a unit test that inserts different values into self.field and t... | from PyQt5.QtWidgets import QDialog , QVBoxLayout , QWidget , QLabel , QApplicationfrom PyQt5.Qt import pyqtSignal , QPushButton , pyqtSlot , QLineEditimport sysclass PopupDialog ( QDialog ) : result = pyqtSignal ( str ) def __init__ ( self ) : super ( ) .__init__ ( ) layout = QVBoxLayout ( self ) self.setLayout ( layo... | PyQt unit test that QDialog is created |
Python | I 'm trying to add a data summary table to a plot I 'm creating like so : But where the grid and the table overlap the grid is still visible which makes the table hard to read.So I tried adding this code to set the background of the table cells to white and opaque like so : But it does n't change . If I use a color oth... | import matplotlib.pyplot as pltplt.figure ( ) plt.plot ( [ 0,2 ] , [ 0,2 ] ) plt.grid ( 'on ' ) values = [ [ 0,1 ] , [ 2,3 ] ] rowLabels = [ 'row1 ' , 'row2 ' ] colLabels = [ 'col1 ' , 'col2 ' ] table = plt.table ( cellText=values , colWidths= [ 0.1 ] *3 , rowLabels = rowLabels , colLabels=colLabels , loc = 'center rig... | Grid appearing inside table in matplotlib/pyplot graph |
Python | What would be the Pythonic way of performing a reduce with accumulation ? For example , take R 's Reduce ( ) . Given a list and an arbitrary lambda function it allows for yielding a vector of accumulated results instead of only the final result by setting accumulate=T . An example for this with a simple multiplication ... | Reduce ( ` * ` , x=list ( 5,4,3,2 ) , accumulate=TRUE ) # [ 1 ] 5 20 60 120 # the source listl = [ 0.5 , 0.9 , 0.8 , 0.1 , 0.1 , 0.9 ] # the lambda function for aggregation can be arbitrary # this one is just made up for the examplefunc = lambda x , y : x * 0.65 + y * 0.35 # the accumulated reduce : # a ) the target li... | Pythonic reduce with accumlation and arbitrary lambda function ? |
Python | How to get ids from bulk inserting in Peewee ? I need to return inserted ids for create a new array of dict like this : Then I need to insert this using bulk like : In its turn the last query should return me new ids for further similar insertion . | a = [ { `` product_id '' : `` inserted_id_1 '' , `` name '' : `` name1 '' } , { `` product_id '' : `` inserted_id_2 '' , `` name '' : `` name1 '' } ] ids = query.insertBulk ( a ) | How to get ids from bulk inserting in Peewee ? |
Python | If I create an Axes object in matplotlib and mutate it ( i.e . by plotting some data ) and then I call a function without passing my Axes object to that function then that function can still mutate my Axes . For example : My question is : can I prevent this global-variable behaviour in general ? I know I can call plt.c... | import matplotlib.pyplot as pltimport numpy as npdef innocent_looking_function ( ) : # let 's draw a red line on some unsuspecting Axes ! plt.plot ( 100*np.random.rand ( 20 ) , color= ' r ' ) fig , ax = plt.subplots ( ) ax.plot ( 100*np.random.rand ( 20 ) , color= ' b ' ) # draw blue line on ax # ax now has a blue line... | Prevent matplotlib statefulness |
Python | Previously , I had been cleaning out data using the code snippet belowThere are newline characters in the file that i want to keep.The following records the time taken for cc_re.sub ( `` , s ) to substitute the first few lines ( 1st column is the time taken and 2nd column is len ( s ) ) : As @ ashwinichaudhary suggeste... | import unicodedata , re , ioall_chars = ( unichr ( i ) for i in xrange ( 0x110000 ) ) control_chars = `` .join ( c for c in all_chars if unicodedata.category ( c ) [ 0 ] == ' C ' ) cc_re = re.compile ( ' [ % s ] ' % re.escape ( control_chars ) ) def rm_control_chars ( s ) : # see http : //www.unicode.org/reports/tr44/ ... | Is there a faster way to clean out control characters in a file ? |
Python | I am writing tests for a large Django application , as part of this process I am gradually creating factories for all models of the different apps within the Django project.However , I 've run into some confusing behavior with FactoryBoy where it almost seems like SubFactories have an max depth beyond which no instance... | def test_subfactories ( self ) : `` '' '' Verify that the factory is able to initialize `` '' '' user = UserFactory ( ) self.assertTrue ( user ) self.assertTrue ( user.profile ) self.assertTrue ( user.profile.tenant ) order = OrderFactory ( ) self.assertTrue ( order ) self.assertTrue ( order.user.profile.tenant ) @ fac... | FactoryBoy - nested factories / max depth ? |
Python | I 'm trying to create a new CodeType , the following code runs just fine in Python 2.7 , but in Python 3.2 I get an error : Usage : The debug line proves that I 'm sending in an int as co_stacksize ... what changed in Python 3 to make this not work ? Edit : Here 's the error ( do n't know why I forgot that before ) : T... | def newCode ( co_argcount = 0 , co_nlocals = 0 , co_stacksize = 0 , co_flags = 0x0000 , co_code = bytes ( ) , co_consts = ( ) , co_names = ( ) , co_varnames = ( ) , filename = `` < string > '' , name = `` '' , firstlineno = 0 , co_lnotab = bytes ( ) , co_freevars = ( ) , co_cellvars = ( ) ) : `` '' '' wrapper for CodeT... | TypeError on CodeType creation in Python 3 |
Python | I was reviewing some code earlier and the developer wrote an inline if/else rather than a get ( ) to retrieve an element from a list if it exists ( otherwise give it a default value ) . I decided to spring some timeit code on repl and was pretty confused by the result . The if/else takes 1/3 the time of the get ( ) . H... | import timeitD = { `` a '' : 1 , `` b '' : 2 , `` c '' : 3 } def ef ( ) : return D [ ' a ' ] if ' a ' in D else 1def gt ( ) : return D.get ( ' a ' , 1 ) print `` gt1 '' , timeit.timeit ( gt , number=10000 ) print `` ef1 '' , timeit.timeit ( ef , number=10000 ) print `` ef2 '' , timeit.timeit ( ef , number=10000 ) print... | Why is an inline if/else faster than a .get ( ) in Python ? |
Python | I 'm trying to get Kaitai Struct to reverse engineer a binary structure . seq fields work as intended , but instances do n't seem to work as I want them to.My binary format includes a header with a list of constants that I parse as header field with consts array subfield : However , when I try to use the following decl... | types : header : seq : # ... - id : consts type : u8 repeat : expr repeat-expr : 0x10 instances : index_const : value : '_root.header.consts [ idx - 0x40 ] ' if : idx > = 0x40 and idx < = 0x4f @ property def index_const ( self ) : if hasattr ( self , '_m_index_const ' ) : return self._m_index_const if self.idx > = 64 a... | Kaitai Struct : calculated instances with a condition |
Python | In digging through the python Counter class in collections , I found something I thought was peculiar : They do n't explicitly use the self argument in the __init__ function 's arguments.See code below ( copied directly without the docstring ) : Later in this same class , the update and subtract methods are also define... | class Counter ( dict ) : def __init__ ( *args , **kwds ) : if not args : raise TypeError ( `` descriptor '__init__ ' of 'Counter ' object `` `` needs an argument '' ) self , *args = args if len ( args ) > 1 : raise TypeError ( 'expected at most 1 argments , got % d ' % len ( args ) ) super ( Counter , self ) .__init__ ... | __init__ function definition without self argument |
Python | I `` accidentally '' came across this weird but valid syntax ( for every even no : of minus symbol , it outputs 6 else 0 , why ? ) Does this do anything useful ? Update ( Do n't take it the wrong way..I love python ) : One of Python 's principle says There should be one -- and preferably only one -- obvious way to do i... | i=3print i+++i # outputs 6print i+++++i # outputs 6print i+-+i # outputs 0print i+ -- +i # outputs 6 | Why is i++++++++i valid in python ? |
Python | I 'm using a logistic sigmoid for an application . I compared the times using the scipy.special function , expit , versus using the hyperbolic tangent definition of the sigmoidal.I found that the hyperbolic tangent was 3 times as fast . What is going on here ? I also tested times on a sorted array to see if the result ... | In [ 1 ] : from scipy.special import expitIn [ 2 ] : myexpit = lambda x : 0.5*tanh ( 0.5*x ) + 0.5In [ 3 ] : x = randn ( 100000 ) In [ 4 ] : allclose ( expit ( x ) , myexpit ( x ) ) Out [ 4 ] : TrueIn [ 5 ] : timeit expit ( x ) 100 loops , best of 3 : 15.2 ms per loopIn [ 6 ] : timeit myexpit ( x ) 100 loops , best of ... | Why is using tanh definition of logistic sigmoid faster than scipy 's expit ? |
Python | Look at the following exampleIt would be very tempting to call : Possible workarounds would be : But why is Rect ( *point , *size , color ) not allowed , is there any semantic ambiguity or general disadvantage you could think of ? EDIT : Specific QuestionsWhy are multiple *arg expansions not allowed in function calls ?... | point = ( 1 , 2 ) size = ( 2 , 3 ) color = 'red'class Rect ( object ) : def __init__ ( self , x , y , width , height , color ) : pass Rect ( *point , *size , color ) Rect ( point [ 0 ] , point [ 1 ] , size [ 0 ] , size [ 1 ] , color ) Rect ( * ( point + size ) , color=color ) Rect ( * ( point + size + ( color , ) ) ) | Why is foo ( *arg , x ) not allowed in Python ? |
Python | I have a problem with the Python MROFor this code : I get this output : ( < class '__main__.A ' > , < class '__main__.D ' > , < class '__main__.B ' > , < class '__main__.C ' > , < class '__main__.E ' > , < class '__main__.G ' > , < class '__main__.H ' > , < class '__main__.F ' > , < class 'object ' > ) Why do I get < c... | class F : pass class G : pass class H : passclass E ( G , H ) : passclass D ( E , F ) : pass class C ( E , G ) : passclass B ( C , H ) : passclass A ( D , B , E ) : passprint ( A.__mro__ ) | Why are classes being ordered this way in the MRO ? |
Python | There is a famous trick in u-net architecture to use custom weight maps to increase accuracy.Below are the details of it-Now , by asking here and at multiple other place , I get to know about 2 approaches.I want to know which one is correct or is there any other right approach which is more correct ? 1 ) First is to us... | gt # Ground truth , format torch.longpd # Network outputW # per-element weighting based on the distance map from UNetloss = criterion ( pd , gt ) loss = W*loss # Ensure that weights are scaled appropriatelyloss = torch.sum ( loss.flatten ( start_dim=1 ) , axis=0 ) # Sums the loss per imageloss = torch.mean ( loss ) # A... | Pytorch : Correct way to use custom weight maps in unet architecture |
Python | I had this problem in one of my interview practices and had a problem getting this with a better time complexity other than O ( N^2 ) . At some level you 'll have to visit each element in the list . I thought about using hash table but it would still have to conduct the hash table and populate it then do the calculatio... | def concatenationsSum ( a ) : sum = 0 current_index_looking_at = 0 for i in a : for x in a : temp = str ( i ) +str ( x ) sum += int ( temp ) return sum Given an array of positive integers a , your task is to calculate the sumof every possible a [ i ] ∘ a [ j ] , where a [ i ] ∘ a [ j ] is the concatenationof the string... | Efficient algorithm to find the sum of all concatenated pairs of integers in a list |
Python | I recently learned about a powerful way to use decorators to memoize recursive functions . `` Hey that 's neat , let 's play with it ! `` Which timeit shows this indeed speeds up the algorithm : '' Wow , that could be really useful ! I wonder how far I can push it ? `` I found when I start using inputs higher than 140 ... | class memoize : `` '' '' Speeds up a recursive function '' '' '' def __init__ ( self , function ) : self.function = function self.memoized = { } def __call__ ( self , *args ) : try : return self.memoized [ args ] except KeyError : self.memoized [ args ] = self.function ( *args ) return self.memoized [ args ] # fibmemo ... | Combining memoization and tail call optimization |
Python | I 'm writing a Python program to generate the Luna Free State flag from the famous Heinlein novel The Moon is a Harsh Mistress , as a personal project . I 've been cribbing heraldry rules and matching mathematical formulas off the web , but something is clearly wrong in my bendsinister routine , since the assertion fai... | # ! /usr/bin/python'generate bend sinister according to rules of heraldry'import sys , os , random , math , Image , ImageDrawFLAG = Image.new ( 'RGB ' , ( 900 , 600 ) , 'black ' ) CANVAS = ImageDraw.Draw ( FLAG ) DEBUGGING = Truedef bendsinister ( image = FLAG , draw = CANVAS ) : `` ' a bend sinister covers 1/3 of the ... | bad math or bad programming , maybe both ? |
Python | The R ppoints function is described as : I 've been trying to replicate this function in python and I have a couple of doubts.1- The first m in ( 1 : m - a ) / ( m + ( 1-a ) -a ) is always an integer : int ( n ) ( ie : the integer of n ) if length ( n ) ==1 and length ( n ) otherwise.2- The second m in the same equatio... | Ordinates for Probability PlottingDescription : Generates the sequence of probability points ‘ ( 1 : m - a ) / ( m + ( 1-a ) -a ) ’ where ‘ m ’ is either ‘ n ’ , if ‘ length ( n ) ==1 ’ , or ‘ length ( n ) ’ .Usage : ppoints ( n , a = ifelse ( n < = 10 , 3/8 , 1/2 ) ) ... def ppoints ( vector ) : `` ' Mimics R 's funct... | Imitating 'ppoints ' R function in python |
Python | How can I create new rows from an existing DataFrame by grouping by certain fields ( in the example `` Country '' and `` Industry '' ) and applying some math to another field ( in the example `` Field '' and `` Value '' ) ? Source DataFrameTarget DataFrameNet = Import - Export | df = pd.DataFrame ( { 'Country ' : [ 'USA ' , 'USA ' , 'USA ' , 'USA ' , 'USA ' , 'USA ' , 'Canada ' , 'Canada ' ] , 'Industry ' : [ 'Finance ' , 'Finance ' , 'Retail ' , 'Retail ' , 'Energy ' , 'Energy ' , 'Retail ' , 'Retail ' ] , 'Field ' : [ 'Import ' , 'Export ' , 'Import ' , 'Export ' , 'Import ' , 'Export ' , 'I... | Pandas DataFrames : Create new rows with calculations across existing rows |
Python | I want to create a symmetric relationship on my model and also add a field in the relationship . I came across this blog ( and also this another blog ) and followed the steps in creating my own models.But when I create the relationship from admin , only one is created . Can you please help me figure out the problem ? | class CreditCardIssuer ( models.Model ) : name = models.CharField ( _ ( 'name ' ) , max_length=256 ) transfer_limits = models.ManyToManyField ( 'self ' , through='Balancetransfer ' , related_name='no_transfer_allowed+ ' , symmetrical=False , help_text=_ ( 'List of issuers to which balance transfer is not allowed . ' ) ... | How to automatically create symmetric object on Django 's ManyToManyField ? |
Python | Is there any built-in method to get back numpy array after applying str ( ) method , for example , Following two methods do n't work : Update 1 : Unfortunatelly i have very big data already converted with str ( ) method so I connot reconvert it with some other method . | import numpy as npa = np.array ( [ [ 1.1 , 2.2 , 3.3 ] , [ 4.4 , 5.5 , 6.6 ] ] ) a_str = str ( a ) # to get back a ? a = some_method ( a_str ) . from ast import literal_evala = literal_eval ( a_str ) # Errorimport numpy as npa = np.fromstring ( a_str ) # Error | str ( ) method on numpy array and back |
Python | Is there a way to choose a function randomly ? Example : The code above seems to execute all 3 functions , not just the randomly chosen one . What 's the correct way to do this ? | from random import choicedef foo ( ) : ... def foobar ( ) : ... def fudge ( ) : ... random_function_selector = [ foo ( ) , foobar ( ) , fudge ( ) ] print ( choice ( random_function_selector ) ) | Choosing a function randomly |
Python | When using PyAudio ( Portaudio binding ) with ASIO+DirectSound support , this code : ... produces this error : How can we solve this problem ? The problem may come from `` pyaudio.py '' , line 990 , because of an unsucessful utf8 decoding : This answer here Special characters in audio devices name : Pyaudio ( `` do n't... | import pyaudiop = pyaudio.PyAudio ( ) for i in range ( p.get_device_count ( ) ) : print p.get_device_info_by_index ( i ) UnicodeDecodeError : 'utf8 ' codec ca n't decode byte 0xe9 in position 1 : invalid continuation byte return { 'index ' : index , 'structVersion ' : device_info.structVersion , 'name ' : device_info.n... | PyAudio 'utf8 ' error when listing devices |
Python | So far every other answer on SO answers in the exact same way : construct your metaclasses and then inherit the 'joined ' version of those metaclasses , i.e.But I do n't know what world these people are living in , where they 're constructing your own metaclasses ! Obviously , one would be using classes from other libr... | class M_A ( type ) : passclass M_B ( type ) : passclass A ( metaclass=M_A ) : passclass B ( metaclass=M_B ) : passclass M_C ( M_A , M_B ) : passclass C : ( A , B , metaclass=M_C ) : pass class InterfaceToTransactions ( ABC ) : def account ( self ) : return None ... class Category ( PolymorphicModel , InterfaceToTransac... | Using ABC , PolymorphicModel , django-models gives metaclass conflict |
Python | I want to perform polynomial calculus in Python . The polynomial package in numpy is not fast enough for me . Therefore I decided to rewrite several functions in Fortran and use f2py to create shared libraries which are easily imported into Python . Currently I am benchmarking my routines for univariate and bivariate p... | subroutine polyval ( p , x , pval , nx ) implicit none real ( 8 ) , dimension ( nx ) , intent ( in ) : : p real ( 8 ) , intent ( in ) : : x real ( 8 ) , intent ( out ) : : pval integer , intent ( in ) : : nx integer : : i pval = 0.0d0 do i = nx , 1 , -1 pval = pval*x + p ( i ) end doend subroutine polyvalsubroutine pol... | Why is univariate Horner in Fortran faster than NumPy counterpart while bivariate Horner is not |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.