text
stringlengths
46
37.3k
title
stringlengths
12
162
Python : The title to this may be confusing , but basically I want to be able to do the following : Expected behavior would be that it would open up a python terminal session , then open up xkcd comic 353 , print 'this is so meta ' to the command line , and finally exit the python command line.Basically , I want to be ...
Input python commands on the python command line
Python : I tried to stress my server a little , and something weird happened . I 'm using mod_wsgi , with basic script plugged in : I tried to stress it a little with simple `` hit it all I can '' : And weird thing happened - wget thrown at me reports about error 500 on server.when I checked out apache logs , this is w...
mod_wsgi fails under pressure
Python : My script loops through each line of an input file and performs some actions using the string in each line . Since the tasks performed on each line are independent of each other , I decided to separate the task into threads so that the script does n't have to wait for the task to complete to continue with the ...
What is the safest way to queue multiple threads originating in a loop ?
Python : I have a Python pandas DataFrame in which each element is a float or NaN . For each row , I will need to find the column which holds the nth number of the row . That is , I need to get the column holding the nth element of the row that is not NaN . I know that the nth such column always exists.So if n was 4 an...
For each row , what is the fastest way to find the column holding nth element that is not NaN ?
Python : I 've got a problem with removing \n in my program here is the code tried using .rstrip and other variants but it does nothing for my , this is the result i getthe problem is when i call children [ `` Patricia '' ] i get [ ] , because it recognizes only children [ `` Patricia\n '' ] <code> with open ( filename...
removing \n in dictionary
Python : a follow-up question on this question : i ran the code below on python 3.5 and python 3.6 - with very different results : as stated in the previous question this raises TypeError : type object got multiple values for keyword argument ' b'on python 3.6. but on python 3.5 i get the exception : KeyError : 0moreov...
In-place custom object unpacking different behavior with __getitem__ python 3.5 vs python 3.6
Python : I receive next warning using SciPy fmin_bfgs ( ) optimization in the NeuralNetwork . Everything should be clear and simple , following Backpropagation algorithm.1 Feed Forward training examples.2 Calculate Error term for each Unit.3 Accumulate gradient ( for the first example , I 'm skipping regularization ter...
SciPy optimization Warning in the Neural Network
Python : I 'm playing with django ( I 'm a quite new beginner ) and while surfing the web I read it could be possible to keep our internal camelCase naming conventions inside the mySQL database and also for the models ' name inside models.pyWell , after some days I can conclude it 's better to leave things as they were...
Django migration with `` -- fake-initial '' is not working if AddField referes to `` same '' column
Python : Hi i have written regex to check where ther string have the char like - or . or / or : or AM or PM or space .The follworig regex work for that but i want to make case fail if the string contain the char other than AMP .import reOutput : Edited : Validate ( { 'Date ' : '12122010 ' } ) Date 12122010 False ( Expe...
Regex to check date
Python : Retrieving the order of key-word arguments passed via **kwargs would be extremely useful in the particular project I am working on . It is about making a kind of n-d numpy array with meaningful dimensions ( right now called dimarray ) , particularly useful for geophysical data handling.For now say we have : Wh...
How to retrieve the original order of key-word arguments passed to a function call ?
Python : I feel like I want an `` Everything '' keyword in Python that would have the following properties : Any boolean test of the form x in Everything would always return True , regardless of x.Any attempt to iterate it , such as for x in Everything would raise an exceptionMy motivation is that I would like to have ...
A Python `` Everything '' keyword that always returns True for membership tests
Python : I find myself often wanting to structure my exception classes like this : I have only seen this pattern used in Django ( DoesNotExist ) and it makes so much sense . Is there anything I 'm missing , why most people seem to favor top-level Exceptions ? editI would use these classes for versatile granularity , e....
Are python Exceptions as class attributes a bad thing ?
Python : I am working on fitting statistical models to distributions using matplotlib 's hist function . For example my code fits an exponential distribution using the following code : Which runs fine , but when I modify it to do the same thing for a uniform distribution between a & b , The code crashes , with ValueErr...
What specific requirements does the function passed to scipy.optimize.curve_fit need to fulfill in order to run ?
Python : I have created a form widget that is automatically adding a add new record section at the top of the form , which i do not want to be there . can someone tell me how to disable this ? I just want to display the variables not the add form.forms.pyadmin.pychange_view.htmlpage that is loaded : <code> class Templa...
Django - Remove add new record from form widget >
Python : such asI want to know , when does python combine the constant string as the CONST.If possible , please tell me which source code about this at cpython ( whatever 2.x , 3.x ) . <code> In [ 9 ] : dis.disassemble ( compile ( `` s = '123 ' + '456 ' '' , `` < execfile > '' , `` exec '' ) ) 1 0 LOAD_CONST 3 ( '12345...
When does python compile the constant string letters , to combine the strings into a single constant string ?
Python : I want to define constraint specification language based on Python . For example : Here IntVar is a class describing a variable that can assume any integer value , and Constraint is a class to represent constraints . To implement this I can just overload operator < by defining method __lt__ for class IntVar.Su...
Defining new semantics for expressions in Python
Python : Could n't really find it , but probably it 's me not knowing how to search properly : ( Just wanted to find out what the name is for : type of construct ? <code> [ x for x in some_list ]
What is the name for [ x for x in some_list ] type of construct in python ?
Python : I understand that one way to work with the digits of a number in Python is to convert the number to a string , and then use string methods to slice the resulting `` number '' into groups of `` digits '' . For example , assuming I have a function prime that tests primality , I can confirm that an integer n is b...
Is using ` str ` the correct idiom for working with digits in Python
Python : I am trying to use Mutagen for changing ID3 ( version 2.3 ) cover art for a bunch of MP3 files in the following way : However , the file ( or at least the APIC tag ) remains unchanged , as checked by reading the tag back . In the system file explorer , the file does show an updated Date modified , however . Ho...
Mutagen 's save ( ) does not set or change cover art for MP3 files
Python : Consider the following list of day-of-week-hour pairs in 24H format : and two time points , e.g . : Start : End : Say we need to know how many hours there are between these two datetimes ( either rounding up or down ) for each of the day-of-week-hour pairs specified above.How can I approach this problem in Pyt...
Counting day-of-week-hour pairs between two dates
Python : I started learning how to use theano with lasagne , and started with the mnist example . Now , I want to try my own example : I have a train.csv file , in which every row starts with 0 or 1 which represents the correct answer , followed by 773 0s and 1s which represent the input . I did n't understand how can ...
numpy array from csv file for lasagne
Python : I 'd like to add a polynomial curve to a scatter plot that is rendered using a callback.Following is my callback function which returns the scatter plot.Resulting plot : I am able to add a polyfit line using sklearn.preprocessing.Is there a way to do this in plotly ? <code> @ app.callback ( Output ( 'price-gra...
Plotly : How to add polynomial fit line to plotly go.scatter figure using a DASH callback ?
Python : Lets assume I have a ( text ) file with the following structure ( name , score ) : And so on . My aim is to sum the scores for every name and order them from highest score to lowest score . So in this case , I want the following output : In advance I do not know what names will be in the file.I was wondering i...
Efficiently processing data in text file
Python : In the python idle : But when I put the code in a script and run it , I will get a different result : Why did this happen ? I know that is compares the id of two objects , so why the ids of two objects are same/unique in python script/idle ? I also found that , if I use a small int , for example 1 , instead of...
Different behavior in python script and python idle ?
Python : I want to run tests with multiple builds of a product running them once . Here is example of the code : The first iteration works well , but on the start of the second one an error appears : What is happening ? What result runner calls ? And why does it fail ? Any ideas how to solve the problem ? <code> import...
How to run the same TestSuite multiple times unittest texttestrunner
Python : I was looking into how Python represents string after PEP 393 and I am not understanding the difference between PyASCIIObject and PyCompactUnicodeObject.My understanding is that strings are represented with the following structures : Correct me if I am wrong , but my understanding is that PyASCIIObject is used...
Python > = 3.3 Internal String Representation
Python : Using Spacy , I extract aspect-opinion pairs from a text , based on the grammar rules that I defined . Rules are based on POS tags and dependency tags , which is obtained by token.pos_ and token.dep_ . Below is an example of one of the grammar rules . If I pass the sentence Japan is cool , it returns [ ( 'Japa...
Named Entity Recognition in aspect-opinion extraction using dependency rule matching
Python : I am trying to implement a NaN-safe shuffling procedure in Cython that can shuffle along several axis of a multidimensional matrix of arbitrary dimension.In the simple case of a 1D matrix , one can simply shuffle over all indices with non-NaN values using the Fisher–Yates algorithm : I would like to extend thi...
In-place shuffling of multidimensional arrays
Python : I am trying to create f-distributed random numbers with given degree of freedoms d1 and d2 , and plot both a histogram with f-distributed random numbers , and plot an idealised f-distribution curve , but when I give small values to df 's , the histogram does not show up . I am new at statistics and matplotlib ...
Histogram does not show up in f-distribution plot
Python : When reading the book 'Effective Python ' by Brett Slatkin I noticed that the author suggested that sometimes building a list using a generator function and calling list on the resulting iterator could lead to cleaner , more readable code.So an example : Where a user could callorand get the same result.The sug...
Is it efficient to build a list with a generator function
Python : In python : <code> > > > a = b or { }
What is the official name of this construct ?
Python : I have an autobahn Websocket Server with the typical onX functions in it 's protocol . My problem is that I ca n't find a way to exit onX , while keep doing the various stuff that I wanted to do when the specific message arrived . More specifically in my onMessage function , I sometimes perform an HTTP request...
Autobahn , leave onMessage block
Python : I have : and then I get an error : If I set the two sizes to be the same , then the error goes away . But I 'm wondering if my input_size is some large number , say 15 , and I want to reduce the number of hidden features to 5 , why should n't that work ? <code> def __init__ ( self , feature_dim=15 , hidden_siz...
With a PyTorch LSTM , can I have a different hidden_size than input_size ?
Python : I have a buffer object in C++ that inherits from std : :vector < char > . I want to convert this buffer into a Python string so that I can send it out over the network via Twisted 's protocol.transport.write.Two ways I thought of doing this are ( 1 ) making a string and filling it char by char : and ( 2 ) maki...
Python buffer copy speed - why is array slower than string ?
Python : I am aware that regular queryset or the iterator queryset methods evaluates and returns the entire data-set in one shot .for instance , take this : QuestionIn both methods all the rows are fetched in a single-go.Is there any way in djago that the queryset rows can be fetched one by one from database.Why this w...
Fetching queryset data one by one
Python : After encountering some probable memory leaks in a long running multi threaded script I found out about maxtasksperchild , which can be used in a Multi process pool like this : Is something similar possible for the Threadpool ( multiprocessing.pool.ThreadPool ) ? <code> import multiprocessingwith multiprocessi...
Is it possible to set maxtasksperchild for a threadpool ?
Python : My project looks like this : The contents of the .py files are shown below : main.pyc/run_project.pyc/z/the_module.pyc/z/y/the_module_module.pyc/z/y/the_support_function.pyGitHub repo to make replication easier : running-pycharm-project-at-cmdThe problem : in Pycharm load up the project with running-pycharm-pr...
How do I replicate the way PyCharm is running my Python 3.4 project at the command line ?
Python : I have made a small script in Python to solve various Gym environments with policy gradients.What should be passed backwards to calculate the gradients ? I am using gradient ascent but I could switch it to descent . Some people have defined the reward function as totalReward*log ( probabilities ) . Would that ...
What Loss Or Reward Is Backpropagated In Policy Gradients For Reinforcement Learning ?
Python : Simple repro : This question has an effective duplicate , but the duplicate was not answered , and I dug a bit more into the CPython source as a learning exercise . Warning : i went into the weeds . I 'm really hoping I can get help from a captain who knows those waters . I tried to be as explicit as possible ...
Why does setting a descriptor on a class overwrite the descriptor ?
Python : With SQLAlchemy , I 'm finding that sometimes I mis-type a name of an attribute which is mapped to a column , which results in rather difficult to catch errors : Is there a way to configure the mapped class so assigning to anything which is not mapped to an SQLAlchemy column would raise an exception ? <code> c...
How do I raise an exception when assigning to an attribute which is NOT mapped to an SQLAlchemy column ?
Python : I am running to of the following programs . Importantly , imagine that there is mymodule.py file in the directory where both these programs are located.The first : The second : The first snippet raises ImportError as expected ( after all , the directory where mymodule is located is not in path ) . The second s...
Difference between exec behavior when module is imported or not
Python : I was looking at the source code for the built-in argparse._AppendAction , which implements the `` append '' action , and puzzled over the way it is implemented : To break it down : _ensure_value is like dict.setdefault for attributes . That is , if namespace has an attribute with the name self.dest then it is...
Please explain reasoning behind code snippet from argparse module
Python : Reading the Django docs , it advices to make a custom creation method for a model named Foo by defining it as create_foo in the manager : My question is that why is the previous one preferred to simply overriding the base class 's create method : Imo it seems that only overriding create will prevent anyone fro...
Why define create_foo ( ) in a Django models.Manager instead of overriding create ( ) ?
Python : I 'm trying to use the __defaults__ attribute of a function object to get default values for arguments . It works for this case : but for this it does n't : Why does test.__defaults__ contain None ? How can I get the default value for the parameter in this case ? <code> > > > def test ( x , y=1 ) : pass ... > ...
How can I access the default value for a keyword argument in Python ?
Python : I have created a simple custom MultiValueField and MultiWidget for the purpose of entering a date of birth but allowing separate entry of the day , month and year . The rationale is that the app is for entry of historical data , so one or more of these fields could be unknown . There is also a checkbox that di...
Django Custom MultiWidget Retaining Old Values
Python : Using the snippet below , I have added tab completion to the python interpreter.However , I have encountered a weird behaviour where after hitting TAB , the interpreter would give duplicates as such:108 possibilities ! min 2 , max 4 duplicates.Furthermore , if I subclass dict the total number of possibilities ...
Duplicate output on Python tab completion ( OsX 10.8 )
Python : Using MySQL , I am trying to have a table with a composite key of multiple fields.The issue is that some of the fields are large ( 255 - 1024 length ) , if I try to run the migration , I will get : Instead of increasing the DB 's key length ( or changing some other DB / table settings ) , I found out that I ca...
Django - limit key size on unique_together columns
Python : I have a array of identifiers that have been grouped into threes . For each group , I would like to randomly assign them to one of three sets and to have those assignments stored in another array . So , for a given array of grouped identifiers ( I presort them ) : A possible output would beUltimately , I would...
Permutations over subarray in python
Python : I used shap to determine the feature importance for multiple regression with correlated features . shap offers a chart to get the shap values . Is there also a statistic available ? I am interested in the exact shap values . I read the Github repository and the documentation but I found nothing regarding this ...
Shap statistics
Python : if the customer sign in and he has permission to see the data that the admin has given to him , he will see the data after he sign in , but if the admin does n't give him permission , this message will appear You are not authorized to view this pagein my case no matter what the permission given the admin this ...
Django Group permission how to print it in template
Python : The docs say that : Each class keeps a list of weak references to its immediate subclasses . This method returns a list of all those references still alive . But how does each class obtain a list of weak references to its subclasses in the first place ? In other words , when I createhow does A find out that B ...
How is __subclasses__ method implemented in CPython ?
Python : I 'm getting desperate because I ca n't seem to find a solution for what I thought would be used by everyone out there.I want to test a simple login with selenium and pytest with a live_server url . According to pytest-django doc , a simple fixture called live_server should do the trick ( https : //pytest-djan...
Selenium login test does n't accept pytest fixtures for login or refuses to connect
Python : I have a Python package that only runs on Python 2 . It has the following classifiers in its setup.py : However , if I create a virtualenv with Python 3 , pip happily installs this package.How do I prevent the package being installed ? Should my setup.py throw an error based on sys.version_info ? Can I stop pi...
How do I mark a Python package as Python 2 only ?
Python : Set-upI 'm using PyDrive 2.0 to connect to the Google Drive API.The working directory /Users/mypath/access_google_drive contains the client_secrets.json , which looks like , where I replaced the real client_id and client_secret with xxx.IssueWhen the browser ( Safari 14.0 ) shows Gdrive api link wants to acces...
PyDrive 2.0 – AuthenticationError : No code found in redirect
Python : I want a code that deletes all instances of any number that has been repeated from a list.E.g . : I have tried to remove the duplicated elements in the list already ( by using the `` unique '' function ) , but it leaves a single instance of the element in the list nevertheless ! I went through a lot of StackOv...
How to delete all instances of a repeated number in a list ?
Python : I 've been working on some Python code to be able to get links to social media accounts from government websites , for a research into ease with which municipalities can be contacted . I 've managed to adapt some code to work in 2.7 , which prints all links to facebook , twitter , linkedin and google+ present ...
Using multiple web pages in a web scraper
Python : I would like to handle a NameError exception by injecting the desired missing variable into the frame and then continue the execution from last attempted instruction.The following pseudo-code should illustrate my needs.Read the whole unittest on repl.it NotesAs pointed out by ivan_pozdeev in his answer , this ...
How to continue a frame execution from last attempted instruction after handling an exception ?
Python : Consider a sequence of coin tosses : 1 , 0 , 0 , 1 , 0 , 1 where tail = 0 and head = 1.The desired output is the sequence : 0 , 1 , 2 , 0 , 1 , 0Each element of the output sequence counts the number of tails since the last head.I have tried a naive method : Question : Is there a better method ? <code> def time...
Count number of tails since the last head
Python : I have login history data from User A for a day . My requirement is that at any point in time the User A can have only one valid login . As in the samples below , the user may have attempted to login successfully multiple times , while his first session was still active . So , any logins that happened during t...
Compare current row value to previous row values
Python : This question is spurred from the answers and discussions of this question . The following snippet shows the crux of the question : The questions I have are the following : Why was it decided that the bool value of NotImplemented should be True ? It feels unpythonic.Is there a good reason I am unaware of ? The...
Why is NotImplemented truthy in Python 3 ?
Python : I have the following Pandas dataframe : and the following dict : I would now like to map all the entries in the lists in my dataframe using the dictionary . The result should be the following : How can this be done most efficiently ? <code> 1 [ `` Apple '' , `` Banana '' ] 2 [ `` Kiwi '' ] 3 None4 [ `` Apple '...
Convert elements of list in pandas series using a dict
Python : I am working with an ORM that accepts classes as input and I need to be able to feed it some dynamically generated classes . Currently , I am doing something like this contrived example : While this works fine , it feels off by a bit : for example , both classes print as < class '__main__.Cls ' > on the repl ....
What is the least-bad way to create Python classes at runtime ?
Python : How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully ? Shortly after starting the program , SIGINT ( ctrl + c ) is sent.With max_workers equal or lesser than the the number of tasks everything works . But if max_workers is greater , the output of the above code is as follows : I would like...
How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully ?
Python : I need to find the intersection of a GeoDataFrame with itself through geopandas in QGIS . The code works perfectly in the Anaconda environment but it fails in the QGIS python.Shapefile is available at below link : https : //drive.google.com/file/d/1DQqg7Cf6AokyadkmOE8Y6k41tqDMXdmS/view ? usp=drivesdk Below is ...
geopandas overlay ( ) function not working in QGIS
Python : I have a codebase where I 'm cleaning up some messy decisions by the previous developer . Frequently , he has done something like : ... This , of course , pollutes the name space and makes it difficult to tell where an attribute in the module is originally from.Is there any way to have Python analyze and fix t...
Reversing from module import *
Python : I 'm working on a Python project where a previous developer placed a large portion of the code in the base __init__.py file . I would like to be able to move code out of the file to a new file in a subdirectory.So importing the spam module would use the code in foobar/eggs.py.I would like to keep 100 % compati...
Moving code out of __init__.py but keeping backwards compatibility
Python : I want to make forward forecasting for monthly times series of air pollution data such as what would be 3~6 months ahead of estimation on air pollution index . I tried scikit-learn models for forecasting and fitting data to the model works fine . But what I wanted to do is making a forward period estimate such...
any workaround to do forward forecasting for estimating time series in python ?
Python : Possible Duplicate : Do python 's variable length arguments ( *args ) expand a generator at function call time ? Let 's say you have a function like this : And you call it like that : Will the elements be called lazily or will the generator run through all the possibly millions of elements before the function ...
Are *parameters calls lazy ?
Python : Given this file : http : //mtarchive.geol.iastate.edu/2019/02/18/mrms/ncep/GaugeCorr_QPE_01H/GaugeCorr_QPE_01H_00.00_20190218-150000.grib2.gz… I get different output depending on the software I use.andboth output : However : outputs -3 for all 24,500,000 records.I get the same result if I parse the file using ...
Possible bug in GDAL ?
Python : Trying to find an efficient way to extract all instances of items in an array out of another.For exampleArray 1 is an array of items that need to be extracted out of array 2 . Thus , array 2 should be modified to [ `` 456 '' , `` 789 '' ] I know how to do this , but no in an efficient manner . <code> array1 = ...
Using arrays with other arrays in Python
Python : I need to sum all the numbers in the list . If 0 occurs start subtracting , until another 0 , start adding . For example : This is what I 've tried : <code> [ 1 , 2 , 0 , 3 , 0 , 4 ] - > 1 + 2 - 3 + 4 = 4 [ 0 , 2 , 1 , 0 , 1 , 0 , 2 ] - > -2 - 1 + 1 - 2 = -4 [ 1 , 2 ] - > 1 + 2 = 3 [ 4 , 0 , 2 , 3 ] = 4 - 2 - ...
Sum numbers in a list but change their sign after zero is encountered
Python : I just started learning Python and I 'm confused about this example : If to was initialized once , would n't to not be None the 2nd time it 's called ? I know the code above works but ca n't wrap my head around this `` initialized once '' description . <code> def append_to ( element , to=None ) : if to is None...
Python default params confusion
Python : Does unit test library for python ( especially 3.x , I do n't really care about 2.x ) has decorator to be accessed only by root user ? I have this testing function.blabla function can only be executed by root . I want root user only decorator so normal user will skip this test : Does such decorator exist ? We ...
Unit test for only root user in python
Python : Sorry for the badly explained title . I am trying to parallelise a part of my code and got stuck on a dot product . I am looking for an efficient way of doing what the code below does , I 'm sure there is a simple linear algebra solution but I 'm very stuck : <code> puy = np.arange ( 8 ) .reshape ( 2,4 ) puy2 ...
Numpy Dot Product of two 2-d arrays in numpy to get 3-d array
Python : I try to create a kivy widget from Scatter , which is freely zoomable , but once the mouse button is lifted falls back to the closest zoom level . It works , but it does not update the zoom until the next click . I think I need to bind some event here , but I 'm pretty new to kivy and can not figure it out . H...
Modified kivy scatter widget does not update transformation
Python : Code : Here , I try to replace all the occurrences of 'abc ' with 'XXX ' . Is there a shorter way to do this ? <code> > > > mylist = [ 'abc ' , 'def ' , 'ghi ' ] > > > mylist [ 'abc ' , 'def ' , 'ghi ' ] > > > for i , v in enumerate ( mylist ) : ... if v=='abc ' : ... mylist [ i ] = 'XXX ' ... > > > mylist [ '...
Replacing particular elements in a list
Python : Is it possible to merge strings that start with ' ( ' and end with ' ) ' and then reinsert it into the same list or a new list ? My desired output poke_list = [ ... 'Charizard ( Mega Charizard X ) ' , '78 ' , '130 ' , ... ] <code> poke_list = [ ... 'Charizard ' , ' ( Mega ' , 'Charizard ' , ' X ) ' , '78 ' , '...
How to join strings between parentheses in a list of strings
Python : An error is raised when I try to set the value of an argument of a class who inherits from str . The error occurs only when I try to access the argument with myClass ( arg = 'test ' ) . The error is : The issue is shown in this exemple : Only the last line raises the error . The previous line works well.The pr...
Set the value of an argument in a class who inherits from int or float or str
Python : I want to search a list of strings ( having from 2k upto 10k strings in the list ) in thousands of text files ( there may be as many as 100k text files each having size ranging from 1 KB to 100 MB ) saved in a folder and output a csv file for the matched text filenames.I have developed a code that does the req...
How to make searching a string in text files quicker
Python : My project structure seems to be correct . File script1.py imports script2.py using 'import script2'.I can run code without errors with following commands : Unfortunately , when I try to execute tests using pytest or python -m pytest I get error that there 's no module named script2 ( full message below ) . I ...
ModuleNotFoundError for import within the same package while using pytest
Python : Haskell : Python : It should output the next two values of the list , e.g . 5.0 , 3.4But it outputs 5.0 twice , why ? <code> average x y = ( x + y ) / 2sqrt ' : : ( Ord a , Fractional a ) = > a - > Int - > asqrt ' 0 _ = 0.0sqrt ' 1 _ = 1.0sqrt ' s approximations = ( infsqr ' s ) ! ! approximationsinfsqr ' n = ...
Why does n't this Haskell I translated to Python work properly ?
Python : I have a directed tree , and I would like to get its size . I have no information about its depth or distribution of nodes . There are two major obstacles:1 ) The tree is very large ( ~billions of nodes ) 2 ) Edge traversal is expensive.Are there statistical methods I can use to get an estimate of its size ( n...
Statistic estimation of total nodes in a tree where edge traversal is expensive
Python : I have the following example dataframe : which creates this dataframe : I am trying to `` unmelt '' though not exactly the source and test columns into new dataframe Columns such that it will look like this : It 's my understanding that pivot and melt will do the entire DisplayLabel column and not just some of...
Unmelt only part of a column from pandas dataframe
Python : I 'm creating several classes to use them as state flags ( this is more of an exercise , though I 'm going to use them in a real project ) , just like we use None in Python , i.e.NoneType has several special properties , most importantly it 's a singleton , that is there ca n't be more than one NoneType instan...
Mimic Python 's NoneType
Python : In a program that I 'm writing , I wanted to make a ConfigParser that 's read only so that it can safely be used globally . I did n't realize this , but apparently the SafeConfigParser is an old-style class , thus I had to subclass it like this : If I did n't use object as a mixin , the call to SafeConfigParse...
Is it safe to make an old-style class into a new-style class using Multiple Inheritance ?
Python : I have made a multiplayer Pong game with TCP , UDP and pygame.the modules i 'm using are : pygame , os , logging , threading , random , yaml ( PyYAML ) and socketWhen running the game from the commandline with python2.7 it works well , but the compiled version with py2app gives me a error which is : I have goo...
Game runs well from source , but not from py2app
Python : I need to write XML files using lxml and Python.However , I ca n't figure out whether to use a class to do this or a function . The point being , this is the first time I am developing a proper software and deciding where and why to use a class still seems mysterious.I will illustrate my point.For example , co...
Confused as to use a class or a function : Writing XML files using lxml and Python
Python : I 'm trying to write a binary translator - with a string as an input and its binary representation as output.And I 'm having some difficulties , I wrote in variable the translation for each letter , but they are variables , not strings , so I want to take an input from that matches with the name of the variabl...
Text to Binary in Python
Python : I have an irregularly spaced ( with respect to time frequency ) pandas data frame . I can successfully up-sample the data frame to a daily frequency using the resample command , however my problem is that the resampling ends at the last ( pre-resampled ) data observation . I would like the resampling to span a...
How to resample irregular time series to daily frequency and have it span to today ?
Python : I have a script that can re-write a Python module so that all occurrences of func ( a ) are transfored to func2 ( a is None ) . I now want to support also func ( a , msg ) becoming func2 ( a is None , msg ) , but I ca n't find the pattern that will do this . This following shows my attempt : For each func foun...
pattern to match 1-or-2-arg function call for lib2to3
Python : I have this neural network that I 've trained seen bellow , it works , or at least appears to work , but the problem is with the training . I 'm trying to train it to act as an OR gate , but it never seems to get there , the output tends to looks like this : I have this loss graph : Its strange it appears to b...
Neural network backprop not fully training
Python : I am trying to merge several DataFrames based on a common column . This will be done in a loop and the original DataFrame may not have all of the columns so an outer merge will be necessary . However when I do this over several different DataFrames columns duplicate with suffix _x and _y . I am looking for one...
Merge DataFrames in Python without duplicating columns
Python : I 'm writing a simple string parser which allows regexp-like quantifiers . An input string might look like this : My parser function translates this string to a list of tuples : Now , the tricky bit is that I need a list of all valid combinations that are specified by the quantification . The combinations all ...
More elegant way to implement regexp-like quantifiers
Python : Say I have a decorator which causes the function to print out any exceptions and return None , if an exception happens , instead of failing . Assuming this is a good idea , what 's the preferred naming style ? a ) b ) That is : should it a ) be a command ( the decorator tells the function to do something diffe...
python : should decorator names be actions or descriptions ?
Python : I am trying to extract all slices of length 4 along 0th axis of a 2-dim tensor . So far I can do it mixing pure Python with tensorflow.What would be an efficient way of doing that without using pure Python ? Note that the `` test '' array is actually supposed to be a tensor , thus its shape is n't known before...
How to efficiently extract all slices of given length using tensorflow
Python : I 'm storing contacts between different elements . I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element.Problem backgroundImagine this problem . You have a water molecule which is in contact with other molecules ( if the contact is ...
Refining data stored in SQLite - how to join several contacts ?
Python : I have a custom environment in keras-rl with the following configurations in the constructorAs you can see , my agent will perform 3 actions , depending on the action , a different reward will be calculated in the function step ( ) below : The problem is the fact that , if I print the actions at every episode ...
Define action values in keras-rl
Python : QNetworkAccessManager can do requests asynchronously , and time.sleep ( secs ) can suspend the execution for the given number of seconds . I was confused by the code below . Is t2 here always greater than 10 seconds ? Without using time.sleep ( secs ) in the code here , the finished slot getWebPageSRC was call...
can time.sleep ( secs ) suspend QNetworkAccessManager does request asynchronously ?
Python : I need to get a calculation of some data so , in annotate I put some maths logic with other field but whenever there is 0 it is throwing an error . I need to handle that error in annotate . My code looks like this : In total_billable , there is total_billable_leads variable which may have Zero ( 0 ) then on a ...
Throwing ZeroDivisionError
Python : Here is what I am looking at : I know that int in Python is growable ( can get bigger that 24 bytes ) objects that live on the heap , and I see why that object can be quite large , but is n't a list just a collections of such objects ? Apparently it is not , what is going on here ? <code> In [ 1 ] : import sys...
Why is single int 24 bytes , but in list it tends to 8 bytes