text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : Consider the following example : When I now try to parse that string back into a datetime with the exact format I used to serialize it in the first place , a ValueError is thrown at me : ValueError : time data ' 1-01-01T00:00:00 ' does not match format ' % Y- % m- % dT % H : % M : % S'Howeverworks as expected.... | Parse dates from before the year 1000 |
Python : The way it is I get a 'NameError : name 'Interval ' is not defined ' . Can someone tell me which type would be correct here ? <code> class Interval ( object ) : def __sub__ ( self , other : Interval ) : pass | Type hint for 'other ' in magic methods ? |
Python : Is there a way to get the output from a test that you run via pytest , using the call to main ? If this was a process I could get the output using communicate ( ) but I ca n't find the equivalent for pytest when running it as function from Python3 , instead than run it as standalone from terminal.EDIT : I did ... | Output stdio and stderr from pytest.main ( ) |
Python : When I edit a file with vi like : I have colors.When in python 's script I have : I don't.Why ( I 'm guessing that I open a different shell but I ca n't figure why the settings are different ) ? And how to solve this ? I am running fedora and my shell is bash.gives : <code> vi .bashrc os.system ( `` vi .bashrc... | No color in vi when called from python 's script |
Python : I am trying to create custom chunk tags and to extract relations from them . Following is the code that takes me to the cascaded chunk tree.Output - ( S ( NPH Mary/NN ) saw/VBD ( NPH the/DT cat/NN ) sit/VB on/IN ( NPH the/DT mat/NN ) ) Now I am trying to extract relations between the NPH tag values with the te... | Creating relations in sentence using chunk tags ( not NER ) with NLTK | NLP |
Python : I have some text : I 'd like to parse this into its individual words . I quickly looked into the enchant and nltk , but did n't see anything that looked immediately useful . If I had time to invest in this , I 'd look into writing a dynamic program with enchant 's ability to check if a word was english or not ... | Is there an easy way generate a probable list of words from an unspaced sentence in python ? |
Python : Consider I have some data.Lets say it is weather data , of rainfall and temperature for each month.For this example , I will randomly generate is like so : So the data looks something like : I want to draw a Trellis chart of Box plots.I can draw a Trellis Chart of the means like so : And I can draw a box plot ... | Box Plot Trellis |
Python : I have an image im which is an array as given by imread . Say e.g.I have another ( n,4 ) array of windows where each row defines a patch of the image as ( x , y , w , h ) . E.g.I 'd like to extract all of these patches from im as sub-arrays without looping through . My current looping solution is something lik... | Extract multiple windows/patches from an ( image ) array , as defined in another array |
Python : I 'm trying to learn python , and I 'm pretty new at it , and I ca n't figure this one part out.Basically , what I 'm doing now is something that takes the source code of a webpage , and takes out everything that is n't words.Webpages have a lot of \n and \t , and I want something that will find \ and delete e... | Ca n't get single \ in python |
Python : Say I have the following list of numbers : I would like to find every closed interval containing consecutive integers without gaps in this list . If for any number in the list there are multiple such intervals , we only retain the largest of any such intervals . The correct answer above should be : To see this... | Tuples of closed continuous intervals |
Python : I am writing my doctests like this : This works fine for Python version 2.5 , 2.6 & 2.7 but fails for Python 3 with following error : Problem is that if I write my doctests like this : They will work only for Python3 and fail on Python2 version . My question is how do I make it cross version compatible ? <code... | Multi version support for Python doctests |
Python : I 'm writing a parser , and in the process of debugging it , I found that apparently , this is legal Python : and so is this ( ! ) : I do n't blame the parser for getting confused ... I 'm having trouble figuring out how to interpret it ! What exactly does this statement mean ? <code> for [ ] in [ [ ] ] : prin... | What does this Python statement mean ? |
Python : I have a list : I want to iterate consecutive elements in the list such that , when it comes to last element i ' e 8 it pairs with the first element 1.The final output I want is : I tried using this way : But I am getting only this result : How do I make a pair of last element with first ? I have heard about t... | Iterate consecutive elements in a list in Python such that the last element combines with first |
Python : I have tried to somehow get a documentation for a partialmethod to work . My current code isBut if I runand Sphinx lists them using autoclass as undocumented members.I have read https : //docs.python.org/3/library/functools.html # partial-objects and https : //docs.python.org/3/library/functools.html # functoo... | Documentation of functions defined with functools partialmethod |
Python : I am reading about classes in Python ( 3.4 ) and from what I understand it seems that every new object has its own bound methods instances.The output of this is False.This seems to me as a waste of memory . I thought that internally a.foo and b.foo would point somehow internally to one function in memory : A.f... | Does Python really create all bound method for every new instance ? |
Python : I have DataFrame in the following form : I would like to count the most common combination of two values from Product column grouped by ID.So for this example expected result would be : Is this output possible with pandas ? <code> ID Product1 A1 B2 A 3 A3 C 3 D 4 A4 B Combination CountA-B 2A-C 1A-D 1C-D 1 | Counting most common combination of values in dataframe column |
Python : I 'm sure there 's a way of doing this , but I have n't been able to find it . Say I have : Then how can I use map ( add , foo ) such that it passes num1=1 , num2=2 for the first iteration , i.e. , it does add ( 1 , 2 ) , then add ( 3 , 4 ) for the second , etc . ? Trying map ( add , foo ) obviously does add (... | Unpack nested list for arguments to map ( ) |
Python : I am using plt.imshow ( ) to plot values on a grid ( CCD data in my case ) . An example plot : I need to indicate a barrier on it , to show which pixels I care about . This is similar to what I need : I know how to add squares to an image , gridlines to an image , but this knowledge does n't solve the issuue ,... | How to encircle some pixels on a heat map with a continuous , not branched line using Python ? |
Python : I have a pandas column with lists of values of varying length like so : I 'd like to convert them into a matrix format where each possible value represents a column and each row populates a 1 if the value exists and 0 otherwise , like so : I thought the term for this was one hot encoding , but I tried to use t... | Convert pandas column of lists into matrix representation ( One Hot Encoding ) |
Python : My challenge is to plot many sequences of data organized in the column ( where each column is the data for many simualtions for the same identificator ( ID ) ) and index of pandas dataframe is the months of simulation . The problem is in the line created by pandas linking the different simulations in the same ... | How to discontinue a line graph in the plot pandas or matplotlib python |
Python : Why ca n't I use super to get a method of a class 's superclass ? Example : ( Of course this is a trivial case where I could just do A.my_method , but I needed this for a case of diamond-inheritance . ) According to super 's documentation , it seems like what I want should be possible . This is super 's docume... | Python : Why ca n't I use ` super ` on a class ? |
Python : Apologies if this is the wrong place to post this - I 'm unclear what the problem is.When using versions of Python built by Macports 2.3.3 running Mac OX 10.10 , I 'm seeing some really funny behavior . I 've fully re-installed Macports , and replicated this on an iMac as well as a Macbook Air , and created a ... | Python , Macports , and Buffer Problems |
Python : consider the below pd.DataFrameI desire to set 'foo ' and all the sub-indices within it as index . How can I achieve this ? I am grappling with 'set_index'and pd.IndexSlice but still ca n't get to the solution <code> df_index = pd.MultiIndex.from_product ( [ [ 'foo ' , 'bar ' ] , [ 'one ' , 'two ' , 'three ' ]... | pandas set index with multilevel columns |
Python : I have a conceptual question about Python . This is the codeHere , I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item : But when I print the list I get the output # 1 as thisAlso , when I use or instead of and as given belowthe output # 2 I get isI saw a similar l... | Why are 'and/or ' operations in this Python statement behaving unexpectedly ? |
Python : Given the coming deprecation of df.ix [ ... ] How can i replace .ix in this piece of code ? For reference , this is some background on that piece of code <code> df_1 = df.ix [ : , : datetime.time ( 16 , 50 ) ] df_2 = df.ix [ : , datetime.time ( 17 , 0 ) : ] df_3 = df2.shift ( periods = 1 ) df_4 = pd.concat ( [... | How to replace df.ix with df.loc or df.iloc ? |
Python : ( Please note that there 's a question Pandas : group by and Pivot table difference , but this question is different . ) Suppose you start with a DataFrameNow suppose you want to make the index a , the columns b , the values in a cell val , and specify what to do if there are two or more values in a resulting ... | Is There Complete Overlap Between ` pd.pivot_table ` and ` pd.DataFrame.groupby ` + ` pd.DataFrame.unstack ` ? |
Python : I have succesfully installed Adafruit_Gpio package and when i try to run the example file of the bme sensor provided by adafruit , i get the following error : I am on xubuntu for rpi-3 i have run apt-get udpate and restarted the machine neither worked . <code> Traceback ( most recent call last ) : File `` /hom... | Traceback ( most recent call last ) : Adafruit BME 280 Sensor |
Python : I am porting code created in octave into pylab . One of the ported equations gives dramatically different results in python than it does in octave . The best way to explain is to show plots generated by octave and pylab from the same equation . Here is a simplified snippet of the original equation in octave . ... | Same equation , different answers from Pylab and Octave |
Python : So , in Python ( though I think it can be applied to many languages ) , I find myself with something like this quite often : Maybe I 'm being too picky , but I do n't like how the line the_input = raw_input ( `` what to print ? \n '' ) has to get repeated . It decreases maintainability and organization . But I... | small code redundancy within while-loops ( does n't feel clean ) |
Python : Say I 've gotFrom this I want to obtain a matrix X with shape ( len ( Y ) , 3 ) . In this particular case , the first row of X should have a one on the second index and zero otherwhise . The second row of X should have a one on the 0 index and zero otherwise . To be explicit : How do I produce this matrix ? I ... | Construct two dimensional numpy array from indices and values of a one dimensional array |
Python : After reading this and this , which are pretty similar to my question , I still can not understand the following behaviour : When printing id ( a ) and id ( b ) I can see that the variables , to which the values were assigned in separate lines , have different ids , whereas with multiple assignment both values... | Python3 multiple assignment and memory address |
Python : For a new feature in PyInstaller , we need a command line option receiving a string with any separator in it . Here 's the discussion : https : //github.com/pyinstaller/pyinstaller/pull/1990.Example : ? is the separator here , this should be another character . It 's not guaranteed , that the string is quoted ... | Cross-platform , safe to use command line string separator |
Python : Why do these dtypes compare equal but hash different ? Note that Python does promise that : The only required property is that objects which compare equal have the same hash value…My workaround for this problem is to call np.dtype on everything , after which hash values and comparisons are consistent . <code> ... | Why do these dtypes compare equal but hash different ? |
Python : The following codeproduces the following error : Traceback ( most recent call last ) : File `` C : \Program Files ( x86 ) \Google\google_appengine\google\appengine\tools\dev_appserver.py '' , line 4053 , in _HandleRequest self._Dispatch ( dispatcher , self.rfile , outfile , env_dict ) File `` C : \Program File... | How to reference the same Model twice from another one ? |
Python : Let 's say I have a model with a unique field email : Usually if a browser submits a form with email being a value that already exists , it would raise a ValidationError , due to the model form field validation.If two browsers submits the same email at the same time , with email being a value that does n't exi... | Django locking between clean ( ) and save ( ) |
Python : I 'm fairly new to Python , and think this should be a fairly common problem , but ca n't find a solution . I 've already looked at this page and found it helpful for one item , but I 'm struggling to extend the example to multiple items without using a 'for ' loop . I 'm running this bit of code for 250 walke... | Creating list of individual list items multiplied n times |
Python : I tried this : And as a result I got this exception : <code> numbers_dict = dict ( ) num_list = [ 1,2,3,4 ] name_list = [ `` one '' , '' two '' , '' three '' , '' four '' ] numbers_dict [ name for name in name_list ] = num for num in num_list File `` < stdin > '' , line 1numbers_dict [ name for name in name_li... | insert data from two lists to dict with for loop |
Python : I have a list of lists , and I would like to duplicate the effect of itertools.product ( ) without using any element more than once.The list I need to use this on is too large to compute itertools.product and remove the unneeded elements . ( 25 billion permutations from itertools.product , while my desired out... | Python - itertools.product without using element more than once |
Python : I 'm trying to generate dictionaries that include dates which can be asked to be given in specific locales . For example , I might want my function to return this when called with en_US as an argument : And this , when called with hu_HU : Now , based on what I 've found so far , I should be using locale.setloc... | How do I get the correct date format string for a given locale without setting that locale program-wide in Python ? |
Python : I do the followingAnd the following handling in script.py : Looks like something is wrong there . <code> - url : /user/ . * script : script.py class GetUser ( webapp.RequestHandler ) : def get ( self ) : logging.info ( ' ( GET ) Webpage is opened in the browser ' ) self.response.out.write ( 'here I should disp... | How to configure app.yaml to support urls like /user/ < user-id > ? |
Python : Possible Duplicate : Floating point equality in python I have a small `` issue '' about my Python code ( I use version 2.5 right now , in ika game engine ) . I currently script objects for my game , and i would like to know , if its safe to compare two floating point number This way : I will make a short examp... | Python floating point |
Python : I found pandas read_csv method to be faster than numpy loadtxt . Unfortunatly now I find myself in a situation where I have to go back to numpy because loadtxt has the option of setting comments= [ ' # ' , ' @ ' ] . Pandas read_csv method can only take one comment string like comment= ' # ' as far as I can tel... | Why does pandas read_csv not support multiple comments ( # , @ , ... ) ? |
Python : I am writing a function called zip_with with the following signature : It 's like zip , but allows you to aggregate with any arbitrary function . This works fine for an implementation of zip_with that only allows 2 arguments . Is there support for adding type hints for a variable number of arguments ? Specific... | Python type hints for generic *args ( specifically zip or zipWith ) |
Python : I was wondering whether there is a way to refer data from many different arrays to one array , but without copying it.Example : However , in the example above , c is a new array , so that if you modify some element of a or b , it is not modified in c at all.I would like that each index of c ( i.e . c [ 0 ] , c... | Is there any way to make a soft reference or Pointer-like objects using Numpy arrays ? |
Python : Playing around in Python , I found that the following code works as I expected : From a list S , it will recursively drop the first element until the length of S equals b . For instance f ( [ 1,2,3,4,5,6 ] ,3 ) = [ 4,5,6 ] .However , much to my surprise the following solution , that uses the 'ternary hack ' [ ... | Recursion with ternary operator 'hack ' in Python |
Python : My code is as follows . I want the two sleep can share the same time frame and take 1+2*3=7 seconds to run the script.But it seems that something wrong happened so that it still takes 3* ( 1+2 ) second.Is there any idea how to modify the code ? <code> import asyncioasync def g ( ) : for i in range ( 3 ) : awai... | Python async-generator not async |
Python : For older versions of pyramid the setup for sqlalchemy session was done with scooped_session similar to this However I see that newer tutorials as well the pyramid docs 'promotes ' sqlalchemy with no threadlocals where the DBSession is attached to the request object.Is the 'old ' way broken and what is the adv... | Pyramid with SQLAlchemy : scoped or non-scoped database session |
Python : As a result of getting help with a question I had yesterday - Python 2.7 - find and replace from text file , using dictionary , to new text file - I started learning regular expressions today to understand the regular expressions code that @ Blckknght had kindly created for me in his answer . However , it seem... | Python Docs Wrong About Regular Expression `` \b '' ? |
Python : I 'm currently trying to calculate the sum of all sum of subsquares in a 10.000 x 10.000 array of values . As an example , if my array was : I want the result to be : So , as a first try i wrote a very simple python code to do that . As it was in O ( k^2.n^2 ) ( n being the size of the big array and k the size... | How can I vectorize and speed up this large array calculation ? |
Python : I have a list which I want to sort by multiple keys , like : This works fine . However , this results with unnecessary calls to g , which I would like to avoid ( for being potentially slow ) . In other words , I want to partially and lazily evaluate the key.For example , if f is unique over L ( i.e . len ( L )... | Avoiding unnecessary key evaluations when sorting a list |
Python : I 'm trying to build a simple helper utility that will look through my projects and find and return the open ones to me via command line . But my calls to os.listdir return gibberish ( example : '\x82\xa9\x82\xcc\x96I ' ) whenever the folder or filename is in Japanese , and said gibberish ca n't be passed to t... | How can I traverse directories named in Japanese in Python ? |
Python : I am trying to implement a Flask backend endpoint where two images can be uploaded , a background and a foreground ( the foreground has a transparent background ) , and it will paste the foreground on top of the background . I have the following Python code that I have tested with local files and works : Howev... | Alamofire Uploads PNG to Flask with White Background |
Python : the insert works but multiple data enters , when two data are inserted when I try to update , it does not update the recordI just want that when the data is already have record in the database , just update . if not , it will insertthis is my models.pyUPDATEI tried this , the insert works fine , but the update... | django Insert or Update record |
Python : In a Python script , mylibrary.py , I use Protocol Buffers to model data using the following approach : Defining message formats in a .proto file.Use the protocol buffer compiler.Use the Python protocol buffer API to write and read messages in the .py module.I want to implement Cloud Endpoints Framework on App... | Converting proto buffer to ProtoRPC |
Python : I 'm really stuck on why the following code block 1 result in output 1 instead of output 2 ? Code block 1 : The goal of this code is to iterate through an array and wrap each in a parent object . This is a reduction of my actual code which adds all apples to a bag of apples and so forth . My guess is that , fo... | Python Scoping/Static Misunderstanding |
Python : I am working with Pycharm , trying to run scrapy unit tests - and it fails to run.The errors are for missing imports , seems like all imports are failing.e.g.what I did : Get scrapy from githubRun pip to install all dependencies from requirements.txtInstalled TOX , made sure I can run the tests using TOX.Confi... | How to run Scrapy unit tests in Pycharm |
Python : For example , I have an object x that might be None or a string representation of a float . I want to do the following : Except without having to type x twice , as with Ruby 's andand library : <code> do_stuff_with ( float ( x ) if x else None ) require 'andand'do_stuff_with ( x.andand.to_f ) | Is there a Python library ( or pattern ) like Ruby 's andand ? |
Python : In Python , I can create a class method using the @ classmethod decorator : Alternatively , I can use a normal ( instance ) method on a metaclass : As shown by the output of C.f ( ) , these two approaches provide similar functionality.What are the differences between using @ classmethod and using a normal meth... | What are the differences between a ` classmethod ` and a metaclass method ? |
Python : In Python , suppose that I have continuous variables x and y , whose values are bounded between 0 and 1 ( to make it easier ) . My assumption has always been that if I want to convert those variables into ordinal values with bins going like 0,0.01,0.02 , ... ,0.98,0.99,1 one could simply round the original val... | Binning continuous values with round ( ) creates artifacts |
Python : Assuming a command similar to this : Is there any way to cancel that wait_for if the user sends the same command multiple times before actually reacting to the message ? So the bot stop waiting for reactions on previously sent messages and only waits for the last one . <code> @ bot.command ( ) async def test (... | How to cancel a pending wait_for |
Python : I need to take a csv file that looks like this ... and write it out to another csv file to make it look like this ... the spaces are suppose to be blank because nothing goes there and this is the code that I have so far I am new to python and I am not really sure how to use the cvs module . I was thinking of m... | writing csv output python |
Python : I have a string where a character ( ' @ ' ) needs to be replaced by characters from a list of one or more characters `` in order '' and `` periodically '' .So for example I have'ab @ cde @ @ fghi @ jk @ lmno @ @ @ p @ qrs @ tuvwxy @ z'and want'ab1cde23fghi1jk2lmno312p3qrs1tuvwxy2z'for replace_chars = [ ' 1 ' ,... | What 's the best way to `` periodically '' replace characters in a string in Python ? |
Python : I 'm trying to run some tests on the shiny new Python 3.8 and noticed an issue with math.hypot . From the docs : For a two dimensional point ( x , y ) , this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem , sqrt ( x*x + y*y ) .However , these are not equivalent in 3... | Why is sqrt ( x*x + y*y ) ! = math.hypot ( x , y ) in Python 3.8 ? |
Python : I 'm moving a Google App Engine web application outside `` the cloud '' to a standard web framework ( webpy ) and I would like to know how to implement a memcache feature available on Gae.In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours ; in other words I do n'... | Homemade tiny memcache |
Python : I am using from tkinter.ttk import * to override the old windows 98 style with the new windows 8 styled widgets . When I create a menu , it is styled as a new menu : But when I add a submenu , it is styled as a old menu : It looks like this : What I would like is something like this : Am I missing a import her... | TKinter : Can I style submenus to look like normal menus |
Python : I have this spark program and I 'll try to limit it to just the pertinent partsThis program works pretty well on my local machine , however , it does not behave as expected when run on a standalone cluster . It does n't necessarily throw an error , but what it does do it give different output than that which I... | Spark program gives odd results when ran on standalone cluster |
Python : I have two strings of equal length and want to match words that have the same index . I am also attempting to match consecutive matches which is where I am having trouble . For example I have two stringsWhat I am looking for is to get the result : My current code is as follow : Which gives me : Any guidance or... | Python matching words with same index in string |
Python : Say you have some list L and you want to split it into two lists based on some boolean function P. That is , you want one list of all the elements l where P ( l ) is true and another list where P ( l ) is false.I can implement this in Python like so : My question : Is there a functional programming idiom that ... | Is there a functional programming idiom for filtering a list into trues and falses ? |
Python : I 'm using Neo4j 3.1.1 community edition . I 'm trying to fetch roughly 80 million entries from the db via python using the officialy supported python driver . The python script is running against localhost , i.e . on the same machine as Neo4j and not over network . Access to Neo4j works all fine until it come... | How to keep a Neo4j bolt session open ? |
Python : In Matlab , one can evaluate an arbitrary string as code using the eval function . E.g.Is there any way to do the inverse operation ; getting the literal string representation of an arbitrary variable ? That is , recover s from c ? Something likeSuch a repr function is built into Python , but I 've not come ac... | Matlab repr function |
Python : Following Ned Batchelder 's Coverage.py for Django templates blog post and the django_coverage_plugin plugin for measuring code coverage of Django templates . I would really like to see template coverage reports , but the problem is - we have replaced the Django 's the template engine with jinja2 through the c... | Code coverage for jinja2 templates in Django |
Python : The Story : When you parse HTML with BeautifulSoup , class attribute is considered a multi-valued attribute and is handled in a special manner : Remember that a single tag can have multiple values for its “ class ” attribute . When you search for a tag that matches a certain CSS class , you ’ re matching again... | Disable special `` class '' attribute handling |
Python : Please consider the ( example ) code below before I get to my specific question regarding visitor pattern in python : When I run it , it traverse all the nodes-classes iteratively and returns the following : This is all fine but now to my question . You may have noticed that each check-method returns a Boolean... | Visitor pattern ( from bottom to top ) |
Python : We use the AWS managed Elasticsearch service and recently upgraded from 1.5 to 2.3 . We use the elasticsearch-dsl package in python to build our queries and managed to migrate most of our queries , but geo_distance is broken no matter what I try . Mapping : Python code working with elasticsearch-dsl==0.0.11Que... | Unable to locate nested geopoint after updating to elasticsearch 2.3 |
Python : My code : I have several hundred pictures , and in hopes of making my code as concise as possible ( and to expand my python knowledge ) , I was wondering how I write code that automatically takes the files in a folder and makes them a list.I have done similar things in R , but I 'm not sure how to do it in pyt... | Automatically creating a list in Python |
Python : I have basically a list of all the files in a folder , which in a simplified version looks like : Another list : I want to combine these two list into a dictionary , such that : I thought of doing like this but got stuck ! What can I do after this to join the elements into a dictionary , or am I doing this com... | combine two lists into a dictionary if a pattern matches |
Python : I 'm trying to find the factor pair of a number with least sum in O ( 1 ) .Here is the explanation : Here the pair with least sum is 10,10 which is clearly the middle oneHere the required pair is either 3,4 or 4,3.If the given number is a perfect square then the task is pretty simple.The pair would be just sqr... | Getting factors of a number with least sum in O ( 1 ) |
Python : I have a dataframe column with the following format : How can I transform it to the following ? I was thinking of using apply and lambda as a solution but I am not sure how . Edit : In order to recreate this dataframe I use the following code : <code> col1 col2 A [ { 'Id':42 , 'prices ' : [ '30 ' , ’ 78 ’ ] } ... | Pandas Dataframe split multiple key values to different columns |
Python : I have a dataset in a textfile that looks like this.I read this usingAnd got the outputBut I want this read asI 've tried removing delim_whitespace = True and replacing it with delimiter = `` `` but that just combined the first four columns in the output shown above , but it did parse the rest of the data corr... | Reading a text file using Pandas where some rows have empty elements ? |
Python : I am trying to execute this post but I get server error 500 : I think I need to set cookies or something else . Thank you in advance for any help . <code> import requestsbase_url = `` https : //www.assurland.com/ws/CarVehiculeSearch.asmx '' url = `` % s/ % s '' % ( base_url , '' GetCarBodyTypeListByCarAlim '' ... | python requests post query fails : cookies ? |
Python : Can you make this more pythonic by using the map and/or reduce functions ? it just sums the products of every consecutive pair of numbers . <code> topo = ( 14,10,6,7,23,6 ) result = 0for i in range ( len ( topo ) -1 ) : result += topo [ i ] *topo [ i+1 ] | Can this be written as a python reduce function ? |
Python : I propose a example in which a tf.keras model fails to learn from very simple data . I 'm using tensorflow-gpu==2.0.0 , keras==2.3.0 and Python 3.7 . At the end of my post , I give the Python code to reproduce the problem I observed.DataThe samples are Numpy arrays of shape ( 6 , 16 , 16 , 16 , 3 ) . To make t... | Keras model fails to decrease loss |
Python : Comparison operators can be chained in python , so that for example x < y < z should give the result of ( x < y ) and ( y < z ) , except that y is guaranteed to be evaluated only once . The abstract syntax tree of this operation looks like : Pretty printed : But it seems to parse as something like 0 < < 1 2 an... | How to explain the abstract syntax tree of chained comparison operations ? |
Python : I have a very simple function like this one : To which I passI expected that function will modify data z column in place like this : This works fine most of the time , but somehow fails to modify data in others.I double checked things and : I have n't determined any problems with data points which could cause ... | Inconsistent behavior of jitted function |
Python : I am trying to vectorize a loop iteration using NumPy but am struggling to achieve the desired results . I have an array of pixel values , so 3 dimensions , say ( 512,512,3 ) and need to iterate each x , y and calculate another value using a specific index in the third dimension . An example of this code in a ... | Vectorizing loops in NumPy |
Python : This is probably a kinda commonly asked question but I could do with help on this . I have a list of class objects and I 'm trying to figure out how to make it print an item from that class but rather than desplaying in the ; but instead to show a selected attribute of a chosen object of the class . Can anyone... | python - readable list of objects |
Python : I need to write a function that calculates the sum of all numbers n.It helps to imagine the above rows as a 'number triangle . ' The function should take a number , n , which denotes how many numbers as well as which row to use . Row 5 's sum is 65 . How would I get my function to do this computation for any n... | Sum of all numbers |
Python : I 'm am attempting to setup some import hooks through sys.meta_path , in a somewhat similar approach to this SO question . For this , I need to define two functions find_module and load_module as explained in the link above . Here is my load_module function , which works fine for most modules , but fails for P... | Import hooks for PyQt4.QtCore |
Python : I 'm using argparse with several subparsers . I want my program to take options for verbosity anywhere in the args , including the subparser.By default , options for the main parser will throw an error if used for subparsers : I looked into parent parsers , from this answer.For some reason though , none of the... | Argparse : options for subparsers override main if both share parent |
Python : How can I remove the NaN rows from the array below using indices ( since I will need to remove the same rows from a different array.I get the indices of the rows to be removed by using the commandBut using what I would normally use on a 2D array does not produce the desired result , losing the array structure.... | Removing NaN rows from a three dimensional array |
Python : I have a simple test : My problem is that coverage still shows get_approved_member_count line as NOT tested : How do I satisfy the above for coverage ? To run the tests I 'm using Django Nose with Coverage : Console : <code> class ModelTests ( TestCase ) : def test_method ( self ) : instance = Activity ( title... | Using coverage , how do I test this line ? |
Python : I 'm trying to change the length of a Primary Key field from 3 to 6.Model : Migration : However I 'm getting this error message , which I do n't quite understand , why it thinks that I 'm changing it to null . _mysql_exceptions.DataError : ( 1171 , 'All parts of a PRIMARY KEY must be NOT NULL ; if you need NUL... | Alembic : How to change the length of a Primary Key field ? |
Python : I wrote a small script in python where I 'm trying to extract or crop the part of the playing card that represents the artwork only , removing all the rest . I 've been trying various methods of thresholding but could n't get there . Also note that I ca n't simply record manually the position of the artwork be... | Extract artwork from table game card image with OpenCV |
Python : I use Tensorflow 1.14.0 and Keras 2.2.4 . The following code implements a simple neural network : The final val_loss after 20 epochs is 0.7751 . When I uncomment the only comment line to add the batch normalization layer , the val_loss changes to 1.1230.My main problem is way more complicated , but the same th... | batch normalization , yes or no ? |
Python : I 've switched to Python pretty recently and I 'm interested to clean up a very big number of web pages ( around 12k ) ( but can be considered just as easily text files ) by removing some particular tags or some other string patterns . For this I 'm using the re.sub ( .. ) function in Python.My question is if ... | Replacement using multiple regexes or a bigger one in Python |
Python : A Java application sends an XML to a Python application . They are both on the same machine.When I open the received file I can see extra lines ( because of extra CRs ) . What could be the reason for this ? This is the receiver : This is the sender : This is the original file : This is the received : <code> f ... | Python Adds An Extra CR At The End Of The Received Lines |
Python : I 'd like to dynamically import various settings and configurations into my python program - what you 'd typically do with a .ini file or something similar.I started with JSON for the config file syntax , then moved to YAML , but really I 'd like to use Python . It 'll minimize the number of formats and allow ... | Using Python as the config language for a Python program |
Python : I have this code in a fileWhen I run python broken.py , I get the traceback : I do n't really see the problem here . Is n't x defined in the comprehension ? What 's stranger is how this seems to execute without an error when pasted directly into the python interpreter ... EDIT : This works if I use a list comp... | NameError in nested comprehensions |
Python : I want to apply a `` black box '' Python function f to a large array arr . Additional assumptions are : Function f is `` pure '' , e.g . is deterministic with no side effects.Array arr has a small number of unique elements.I can achieve this with a decorator that computes f for each unique element of arr as fo... | Vectorizing a `` pure '' function with numpy , assuming many duplicates |
Python : Suppose I have a pandas dataframe with two columns : ID and Days . DataFrame is sorted by ascending order in both variables . For example : I want to add a third column , which would give a `` session '' number for every ID*day . By `` session '' i mean a sequence of days with difference less than 2 days betwe... | Fast looping through Python dataframe with previous row reference |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.