text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
Python : When I runit locks my system up until I can do a Ctrl+C if I run it as a Python script from the shell , and running it from the interpreter made me have to hard shutdown my laptop.However , works fine and gives the expected result.Why does this happen ? At first , I thought it might be because I was trying to ... | Why does this Python code ( compositing a list extension with a map of itself ) make my system freeze up ? |
Python : I was looking at some code with two __import__ statements , and the second __import__ statement does n't work unless the first one has already been run.The directory structure is like this : The code has two __import__ statements : The first one makes sense - it is roughly the equivalent of doingbut allows for... | Why does one __import__ statement affect the validity of the next one ? |
Python : I have a decorator that takes a function and returns the same function with some added attributes : How do I type hint the return value of decorator ? I want the type hint to convey two pieces of information : the return value is a Callablethe return value has attributes attr1 and attr2If I write a protocol , ... | How to combine a custom protocol with the Callable protocol ? |
Python : I 've got a situation where I have several items I 'd like to open using a with block . In my case , these are external hardware devices which require some clean-up when closed -- but that does n't really matter for the point at hand.Assuming a class something like : I would ( given a fixed number of Controlle... | Is it possible to open an arbitrary number of items using ` with ` in python ? |
Python : I 'm coming from a C++ background to pythonI have been declaring member variables and setting them in a C++esqe way like so : Then I noticed in some open source code , that the initial declaration my_member = [ ] was completely left out and only created in the constructor.Which obviously is possible as python ... | Declaring members only in constructor |
Python : How would I use a Contextmanager for instance variables ? E.g.Let 's assume I 've got some Connection class , that must be closed on destruction . If I were to implement it as a ContextManager I could do.and it would get automatically closed on destruction . But what if I wanted to use it in a __init__ of anot... | How to use contextmanagers for instance variables |
Python : I ca n't find bytearray method or similar in Raku doc as in Python . In Python , the bytearray defined as this : Return a new array of bytes . The bytearray class is a mutable sequence of integers in the range 0 < = x < 256 . It has most of the usual methods of mutable sequences , described in Mutable Sequence... | Does Perl 6 have an equivalent to Python 's bytearray method ? |
Python : I need help to match 2 strings and replace with empty string ' ' . Appreciate your help as i am still new in Python and coding : Will always have 27 lines starting with first lineSecond is : <code> crypto pki certificate chain TP-self-signed-1357590403 +30820330 30820218 A0030201 02020101 300D0609 2A864886 F70... | Regex to match and replace string with multiple lines Python |
Python : I have 3 different DataFrames ( 1 master DataFrame and 2 additional DataFrames ) . I am trying to add a column to my master DataFrame , with the elements of the column being different cell values in the other two DataFrames . I am using two columns of the master DataFrame to figure out which of the 2 DataFrame... | How to efficiently get cell values from multiple DataFrames to insert into a master DataFrame |
Python : Problem description : I have a class C inheriting from mixins A and B.I want a new class , C_ , having all the methods/attributes defined in the class C but with B swapped with B_ ( same API ) in the inheritance scheme ( one possible use of this is easy mocking ) . All classes are new style classes.I got what ... | Is that OK to use the MRO in order to override a mixin ? |
Python : I have a list with strings called names , I need to search each element in the names list with each element from the pattern list . Found several guides that can loop through for a individual string but not for a list of strings Thank you in advance ! Desired output : <code> a = [ x for x in names if 'st ' in ... | Search list of string elements that match another list of string elements |
Python : When I run ionic start helloWorld blank , I receive the following error : The above command worked without error when I tried it last ( a few months ago ) . Now I 've tried updating ionic , but still same error.I had recently used Anaconda to get python3 . So I 'm afraid this might be related to that . I tried... | Ionic `` Error with start undefined '' after python3 |
Python : Situation : We know that the below will check if the script has been called directly.Problem : The else clause is only a generic one and will run as long as the script was not called directly.Question : Is there any way to get which file it was imported in , if it is not called directly ? Additional informatio... | How to find which file was the `` initiator '' Python |
Python : I inadvertently ran across a phenomenon that has me a bit perplexed . I was using IDLE for some quick testing , and I had some very simple code like this ( which I have simplified for the purpose of illustration ) : Now I ran this code like so ( several times , with the same basic results ) : My first hunch wa... | Why does periodically pressing the enter key substantially speed up my code ? |
Python : Due to some restrictions in a project I 'm working on , I had to replace Django 's QuerySet class with a custom one.QuerySet objects can have their methods chained ( eg QuerySet ( ) .filter ( ... ) .exclude ( ... ) and so on ) , so in my implementation , every method simply returns self . So my class looks lik... | Python - Chaining methods : returning ` self ` vs returning a new cloned object |
Python : The sqlalchemy core query builder appears to unnest and relocate CTE queries to the `` top '' of the compiled sql.I 'm converting an existing Postgres query that selects deeply joined data as a single JSON object . The syntax is pretty contrived but it significantly reduces network overhead for large queries .... | SQLAlchemy Nested CTE Query |
Python : I am trying to create a game using livewires in which there are multiple levels . In each level , the screen will need to be a different size , so either I can create a new screen , or I can resize it . When I tried a new screen , like this ( mcve ) : I get the error : games.screen.width and height can not be ... | Python livewires resize screen |
Python : In Python , varargs collection seems to work quite differently from how sequence unpacking works in assignment statements . I 'm trying to understand the reason for this potentially confusing difference . I 'm sure there is a good reason , but what is it ? The function call results in the following error : Que... | Why does * work differently in assignment statements versus function calls ? |
Python : In numpy I would like to make a 2d arrray ( r , by 2**r ) where the columns are all possible binary columns . For example , if height of the columns is 5 , the columns would be My solution isThis seems very ugly . Is there a more elegant way ? <code> [ 0,0,0,0,0 ] , [ 0,0,0,0,1 ] , [ 0,0,0,1,0 ] , [ 0,0,0,1,1 ... | An elegant way to make a 2d array with all possible columns |
Python : Today , I used math.log ( ) function to get the logarithm of 4913 to the given base 17 . The answer is 3 , but when I ran the code below , I got 2.9999999999999996.1 ) Is it because math.log ( x , b ) 's calculation is log ( x ) / log ( b ) ? 2 ) Is there any solution to get the correct answer 3 ? <code> impor... | Wrong answer from math.log ( python 3 ) |
Python : Why does this return 3 instead of 6 , if bool ( i ) returns True for all values i not equal to 0 ? <code> [ 1 , 1 , 1 , 2 , 2 , 3 ] .count ( True ) > > > 3 | Integer to boolean conversion in count ( ) method |
Python : I have a Gtk.TreeView here . Most but not all of the items should be able to be dragged & dropped . In this example the first item should not be able to be dragged & dropped but it should be selectable.How can I realize this ? Maybe I have to use the drag-begin signal and stop the drag in there . But I do n't ... | Cancel a Drag & Drop for some specific items in a Gtk.TreeView |
Python : I am trying to add a tuple of a ( number , ( tuple ) ) , but it drops the outer tuple.How do I change the code so that l1 comes out looking like L2 ? It appears to drop the outer tuple and convert it to list elements ? How do I stop that ? Better yet , why is it happening ? l1 comes out as [ 1.0 , ( 2.0 , 3.0 ... | Add number , then tuple to list as a tuple , but it drops outer tuple |
Python : I 'm using xmltodict to parse an XML config . The XML has structures where an element can occur in 1 to n instances , where both are valid : and I 'm parsing this with xmltodict as follows : and it gives back a single unicode or a list ( depending the items found ) , so I always need to add an extra check to e... | Handle 1 to n elements |
Python : What is the most reliable way for adding pretty-printing support to custom python3 classes ? For interactive data evaluation I found pretty-printing support quite important . However , both iPython 's pretty-printer IPython.lib.pretty.pprint and the standard-library pprint.pprint support only builtin structure... | How to support pretty-printing in custom python 3 classes ? |
Python : I 'm puzzled by this behaviour of memory allocation of sets : Why using a set as argument doubles the amount of memory used by the resulting set ? The result in both cases is identical to the original set : Note that the same happens using a normal iterator : And with the update method : At first I thought tha... | Why does union consume more memory if the argument is a set ? |
Python : I use pytest in my .travis.yml to check my code.I would like to check the README.rst , too.I found readme_renderer via this StackO answerNow I ask myself how to integrate this into my current tests.The docs of readme_renderer suggest this , but I have not clue how to integrate this into my setup : <code> pytho... | How to integrate checking of readme in pytest |
Python : Is there a way to take ... ... and turn it into ... I was able to do it with np.apply_along_axis ... and with for loops ... but they are too slow . Is there a faster way ? Thanks in advance . <code> > > > x = np.array ( [ 0 , 8 , 10 , 15 , 50 ] ) .reshape ( ( -1 , 1 ) ) ; ncols = 5 array ( [ [ 0 , 1 , 2 , 3 , ... | Numpy : Array of ` arange ` s |
Python : If I do this : Is ' a ' destroyed immediately after leaving foo ? Or does it wait for some GC to happen ? <code> def foo ( ) : a = SomeObject ( ) | Are there stack based variables in Python ? |
Python : I have a list of lists as follows.I want to get the count of each word in the sentences list . So , my output should look as follows.I am currently doing it as follows.However , it is not efficient at all for long lists . I have a really long list with about 1 million sentences in the list . It took me two day... | Count strings in nested list |
Python : I want to connect EC2 using pysftp library via AWS Lambda . I use below code to connect.I have put .pem file along with deployment package in AWS Lambda . See this image : Sometimes it works sometime not , like sometimes it says .pem file not found.How to deal with it ? Is there any way to access .pem file or ... | How to connect EC2 using pysftp via AWS Lambda without .pem file or alternate to .pem file |
Python : Is there any way to write both commands and their output to an external file ? Let 's say I have a script outtest.py : Now if I want to capture its output only I know I can just do : However , this will only give me an outtest.txt file with e.g . : What I 'm looking for is a way to get an output file like : Or... | Python write both commands and their output to a file |
Python : I have two numpy arraysand I want to generate array C : I have tried some ways.. but they seem very inefficient . Is there any way this can be done efficiently ? <code> A= array ( [ [ 1,2,3,4 ] , [ 5,6,7,8 ] , [ 9,10,11,12 ] ] ) B = array ( [ 10,20,30 ] ) C = array ( [ 11,12,13,14 ] , [ 25,26,27,28 ] , [ 39,40... | Adding value of single numpy array to all columns in other numpy array |
Python : This is more of an 'interesting ' phenomena I encountered in a Python module that I 'm trying to understand , rather than a request for help ( though a solution would also be useful ) .Yeah , so the fuzzy module totally violates the immutability of strings in Python . Is it able to do this because it is a C-ex... | String immutability in CPython violated |
Python : One of the answers to this question isif the length of s > 5 , then ' y ' is printed otherwise ' n ' is . Please explain how/why this works . Thanks.I understand that this is not a recommended approach but I 'd like to understand why it works . <code> print len ( s ) > 5 and ' y ' or ' n'print ( len ( s ) > 5 ... | why is the construct x = ( Condition and A or B ) used ? |
Python : Why does pandas behave differently when setting or getting items in a series with erroneous number of indexes : Edit : Reported . <code> df = pd.DataFrame ( { ' a ' : [ 10 ] } ) # df [ ' a ' ] is a series , can be indexed with 1 index only # will raise IndexingError , as expecteddf [ ' a ' ] .iloc [ 0 , 0 ] df... | Why pandas silently ignores .iloc [ i , j ] assignment with too many indices ? |
Python : I am using pygraphviz to create a large number of graphs for different configurations of data . I have found that no matter what information is put in the graph the program will crash after drawing the 170th graph . There are no error messages generated the program just stops . Is there something that needs to... | Pygraphviz crashes after drawing 170 graphs |
Python : I 'm trying to scrape an xml file with BeautifulSoup 4.4.0 that has tag names in camelCase and find_all does n't seem to be able to find them . Example code : The output I get is : What 's the correct way to look up camel cased/uppercased tag names ? <code> from bs4 import BeautifulSoupxml = `` '' '' < hello >... | find_all with camelCase tag names with BeautifulSoup 4 |
Python : I need to derive all the combinations out of it as below.and so on . There could be any level of nesting herePlease let me know how to achieve thisSomething that I tried is pasted below but definitely was reaching nowhere Which resulted in <code> my_dict = { ' a ' : [ 1,2 ] , ' b ' : [ 3 ] , ' c ' : { 'd ' : [... | Split python dictionary to result in all combinations of values |
Python : In my model.py , i have define a class : In url.py ( Project url ) In url.py ( app url ) In index.htmlWhile reloading , it gives <code> def get_absolute_url ( self ) : return reverse ( `` posts : detail '' , kwargs= { `` id '' : self.id } ) urlpatterns = [ url ( r'^admin/ ' , admin.site.urls ) , url ( r'^posts... | NoReverseMatch at /posts/ while using absolute url in django |
Python : Say I have the following dataframe : As can be seen I am starting column D with 100 at the last row.I am trying to code a calculation for column D so starting from the bottom row ( row 19 ) when a BUY or SELL is shown on column B then the number on column D is locked ( eg the 100 ) and used for a calculation b... | Dataframe cell to be locked and used for a running balance calculation conditional of result on another cell on same row |
Python : First I build a new DataFrame frame . Then create a new frame2 by filtering some data from frame . Now I want to assign some value to frame2 : but I got this warning : why I keep got this warning although I used the recommended .loc syntax ? what i supposed to do to avoid this warning ? <code> import numpy as ... | pandas SettingWithCopyWarning after trying .loc |
Python : BackgroundI have two numpy arrays which I 'd like to use to carry out some comparison operations in the most efficient/fast way possible . Both contain only unsigned ints . pairs is a n x 2 x 3 array , which holds a long list of paired 3D coordinates ( for some nomenclature , the pairs array contains a set of ... | Efficient Python implementation of numpy array comparisons |
Python : I have a function that must never be called with the same value simultaneously from two threads . To enforce this , I have a defaultdict that spawns new threading.Locks for a given key . Thus , my code looks similar to this : The problem is that I can not figure out how to safely delete the lock from the defau... | Garbage-collect a lock once no threads are asking for it |
Python : If I try to compile a function , containing an array of conditions , with numba 's jit-compiler , it takes very long . The program looks essentially likewhere I have excluded everything that will not alter the compilation time significantly . The problem arises if I use more than 20 elements . Despite that , t... | The compilation of an array of conditions with numba.jit takes a long time |
Python : If I define the __iter__ method as follows , it wo n't work : Result : As you can see , calling A ( ) .__iter__ ( ) works , but A ( ) is not iterable.However if I define __iter__ for the class , then it will work : Does anyone know why python has been designed like this ? i.e . why __iter__ as instance variabl... | Why ` __iter__ ` does not work when defined as an instance variable ? |
Python : I have this dataframe : The operation consists of grouping by column 'entity ' doing a count operation based on a two logical conditions applied to a column 'value ' and column 'type ' . In my case , I have to count the values greater than 3 in the column 'name ' and are not equal to 'medium ' in the column 't... | Groupby based on a multiple logical conditions applied to a different columns DataFrame |
Python : I have written the following code in Python , in order to estimate the value of Pi . It is called Monte Carlo method . Obviously by increasing the number of samples the code becomes slower and I assume that the slowest part of the code is in the sampling part . How can I make it faster ? Do you suggest other (... | How to increase the performance for estimating ` Pi ` in Python |
Python : Can I place : inside __init__.py on the top level dir on my package and garantee that the absolute_import will be applied to all code that runs inside that package or sub-packages ? Or should I put that directive in each model that does an absolute import ? I maintain a Python package and I 'm trying to keep m... | How to force my whole package to use a __future__ directive ? |
Python : Pylint is yelling at me for putting a from .views import *at the end of my __init__.pysaying imports should be placed at the top of the module.If I place it at the top of __init__.py then Flask ca n't find my routes ( views ) so that does n't work . Page does n't load , 404 error . Loads fine when routes are i... | Is a Python module import at the bottom ok ? |
Python : While cythonizing some PyQt5 code , I was encountering TypeError : method ( ) takes exactly 1 positional argument ( 2 given ) .Strangely , replacing PyQt5 with PySide2 seems to not cause this behavior . I was hoping someone could help me understand why this is happening.NOTE : running directly from source does... | Understanding inconsistent cythonized code behavior - PyQt5 vs. PySide2 |
Python : I have a function with several helper functions . That 's fairly common case . I want to group them in a common context for readability and I 'm wondering how to do it right.they take ~15 linesonly the main function is called from somewhere elseno plans on reusing the helper functions in the near futureSimplif... | How to group functions without side effects ? |
Python : While investigating this question , I came across this strange behavior of single-argument super : Calling super ( some_class ) .__init__ ( ) works inside of a method of some_class ( or a subclass thereof ) , but throws an exception when called anywhere else.Code sample : The exception being thrown isI do n't ... | Does any magic happen when I call ` super ( some_cls ) ` ? |
Python : I have used defer.inlineCallbacks in my code as I find it much easier to read and debug than using addCallbacks.I am using PB and I have hit a problem when returning data to the client . The data is about 18Mb in size and I get a failed BananaError because of the length of the string being returned.What I want... | Twisted inlineCallbacks and remote generators |
Python : I 'm sure there is a really simple answer to this but I ca n't find it after searching around for a while.The above code works perfectly , the condition on the if statement seems a bit long-winded so I tried : which is shorter but does n't work . I worked out that it does n't work because `` O '' is a boolean ... | Using `` or '' in if statement conditions |
Python : How does evaluating + 5 work ( spoiler alert : result is 5 ) ? Is n't the + working by calling the __add__ method on something ? 5 would be `` other '' in : So what is the `` void '' that allows adding 5 ? void.__add__ ( 5 ) Another clue is that : throws the error : <code> > > > other = 5 > > > x = 1 > > > x._... | How is it possible to evaluate +5 in Python ? |
Python : I want to create a nested JSON based on this CSV File ( it 's only a snippet ) In this formThis is my codeAs you can see all countries except one country do n't get the data from the csv . Where is the mistake . How can I export the json ? I 'm actually copying the printed into my text Editor <code> Datum , Po... | Nested JSON from CSV |
Python : Apologies for the vague question name , but I 'm not really sure how to call this operation.I have the following data frame : This data represents a `` ranking '' of each of the options , A , B and C for each row . So , for example , in row 2 , C was the best , then A , then B. I would like to construct the ``... | Turning values into columns |
Python : I was staring at a piece of Python code I produced , which , though correct , is ugly . Is there a more pythonic way of doing this ? The problem is the repetition of the method calls for get_pixel and set_pixel . For your information : Also note that I 'd like to preserve code clarity and cleanness . <code> r ... | Pythonic way of repeating a method call on different finite arguments |
Python : It looks like , for Cython 's cdef-classes , using class special methods is sometimes faster than identical `` usual '' method , for example __setitem__ is 3 times faster than setitem : and now : This neither the `` normal '' behavior for Python , for which the special functions are even somewhat slower ( and ... | Why is __setitem__ much faster than an equivalent `` normal '' method for cdef-classes ? |
Python : There are 2 files named compare 1.txt and compare2.txt having random numbers in non-sequential ordercat compare1.txtcat compare2.txtAimOutput list of all the numbers which are present in compare1 but not in compare 2 and vice versaIf any number has zero in its prefix , ignore zeros while comparing ( basically ... | How to compare 2 files having random numbers in non sequential order ? |
Python : I want to split the contents of a CSS file into code blocks and push each block of code into a list using Python 3.5.So , given this CSS : We can clearly tell that it has multiple styles and / or types of indentation meaning the CSS has to be tidied to get this : How can I use Python to read a tidied string of... | How can I split code-blocks into a list ? |
Python : I have a dataframe and 2 separate dictionaries . Both dictionaries have the same keys but have different values . dict_1 has key-value pairs where the values are unique ids that correspond with the dataframe df . I want to be able to use the 2 dictionaries and the unique ids from the dict_1 to append the value... | Use dictionary data to append data to pandas dataframe |
Python : I 've made a classproperty descriptor and whenever I use a function decorated with it , I get multiple pylint inspection errors.Here is a sample class with a sample decorated function : Thanks to the descriptor , I can call Bar.foo and get the string foo returned.Unfortunately , whenever I use functions like t... | How to disable pylint inspections for anything that uses my function ? |
Python : The following code prints a warning , as expected : However , when using eval , the warning message does not appear : Why do warnings behave differently in these two situations ? <code> > > > import warnings > > > def f ( ) : ... warnings.warn ( 'Deprecated ' , DeprecationWarning ) ... print ( 'In function f (... | In Python , why do warnings not appear when using ` eval ` ? |
Python : I 've implemented a genetic algorithm trained neural network with a mutation operator like so : And chromosomes are initialized randomly initially : When performing crossover , offspring chromosomes can only ever have genes within the interval [ -1 , 1 ] because parent chromosomes also only have genes in that ... | How can a genetic algorithm optimize a neural network 's weights without knowing the search volume ? |
Python : Consider a pandas df with columns containing tuples of equal length.What 's the easiest way to unfold this vertically as follows ? : <code> L1 = [ [ 'ID1 ' , ( 'key1a ' , 'key1b ' , 'key1c ' ) , ( 'value1a ' , 'value1b ' , 'value1c ' ) ] , [ 'ID2 ' , ( 'key2a ' , 'key2b ' , 'key2c ' ) , ( 'value2a ' , 'value2b... | Pandas : Melting columns containing tuples |
Python : Consider the collection of floating-point numbers of the form 0.xx5 between 0.0 and 1.0 : [ 0.005 , 0.015 , 0.025 , 0.035 , ... , 0.985 , 0.995 ] I can make a list of all 100 such numbers easily in Python : Let 's look at the first few and last few values to check we did n't make any mistakes : Now I want to r... | Explain a surprising parity in the rounding direction of apparent ties in the interval [ 0 , 1 ] |
Python : I need to create an object that would raise a custom exception , UnusableObjectError , when it is used in any way ( creating it should not create an exception though ) . I came up with the code below which seems to behave as expected . ( some improvements made , as suggested by Duncan in comments ) Questions :... | Object that raises exception when used in any way |
Python : Following the instructions on the PyCall.jl readme , I am tying to use a pipenv python when using PyCall for my julia project ( in it 's own environment ) . In a terminal , I have activated the python environment using pipenv shell , and then located the pathfile of the pipenv version of python . PyCall has al... | PyCall unable to use pipenv version of python InitError : Incompatible ` libpython ` detected |
Python : Consider this ( all commands run on an 64bit Arch Linux system ) : Perl ( v5.24.0 ) awk ( GNU Awk 4.1.3 ) R ( 3.3.1 ) bcPython 2 ( 2.7.12 ) Python 3 ( 3.5.2 ) So , Perl , gawk and R agree , as do bc and Pyhon 2 . Nevertheless , between the 6 tools tested , I got 4 different results . I understand that this has... | Why do 4 different languages give 4 different results here ? |
Python : I 'm looking at some Python numpy code , which contains lines like ( From what I hopefully correctly understand , 1. is equivalent to 1.0 ) .Is there any reason to do this over a = 1 and x *= -1 ? I can understand it if I 'm going to be dividing a and x by an integer later on , so that I do n't have to worry a... | Advantage of using `` x *= -1 . '' over `` x *= -1 '' ? |
Python : I need to find the row indices of all rows in a numpy array that differ only by sign . For example if I have the array : I would want the output to be [ ( 0,2 ) , ( 1,4 ) ] I know how to find unique rows , numpy.unique , so my intuition was to append the array to the negation of itself , i.e . numpy.concatenat... | find pairs of rows in numpy array that differ only by sign |
Python : I 'm trying to create a process that can run jobs on a cron schedule of 0/5 8-17 * * 1-5 and here is my test code : But it is not stopping after 5pm . Please help if I 'm using the cron arguments incorrectly . <code> import argparsefrom apscheduler.schedulers.background import BackgroundSchedulerimport datetim... | How to set hour range and minute interval using APScheduler |
Python : Let 's say I have the following pandas DataFrame : So , there are odd rows in the DataFrame for Bob , namely rows 3 , 4 , and 5 . These values are consistently # , not 12 . Row 1 shows that Bob should be 12 , not # . In this example , it 's straightforward to fix this with replace ( ) : However , this would n'... | How to replace certain rows by shared column values in pandas DataFrame ? |
Python : Is there a better way to do this ? I was thinking of using a function because I have a lot of these in my code , Was curious if there was a shorter comprehensible way to do it . <code> if a > 1 : a = 1if a < 0 : a = 0 | Pythonic way to limit ranges on a variable ? |
Python : I want to use IFileOperation to copy files from python code - It 's fast ( er than python ) You get a nice dialogDoes n't block PythonOn Windows 10 , Python 3.8 - does n't seem to exist.How can I reach IFileOperation ( Not the deprecated SHFileOperation API ) using ctypes ? <code> import ctypesctypes.windll.sh... | How to use IFileOperation from ctypes |
Python : Lets assume I have one list and another tuple both of them are already sorted : What I would need is to add all the elements from B into A in such a way that A remains sorted.Solution I could come with was : assuming A of size m , and B of size n ; this solution would take O ( mxn ) in worst case , how can I m... | Better way for concatenating two sorted list of integers |
Python : 2 days ago I was first introduced to Python ( and programming in general ) . Today I 'm stuck . I 've spent hours trying to find an answer to what I suspect is a problem so trivial , nobody else has yet been stuck here : ) The boss wants me to manually clean up HUGE .xml files into something more human readabl... | Python - How to nest file read loops ? |
Python : I have a numpy array in Python which is n-by-n ( in the example is 3-by-3 ) and contains zero values in all the diagonal positions . e.gIs it possible to sort the array without modifying the diagonal positions so as to look like the one below ? Because all of the sorting functions will take into account the ``... | Sort array in Python without modifying specific element positions |
Python : If it were just checking whether letters in a test_string are also in a control_string , I would not have had this problem.I will simply use the code below.But I also face a rather convoluted task of discerning whether the overlapping letters in the control_string are in the same sequential order as those in t... | check if letters of a string are in sequential order in another string |
Python : Is there a way to store commands in Python ? For example , to store a bash command I can put : Is there a way to store a command , for example something like this : which will work in the Python command prompt whenever/wherever it is opened ? Thank you . <code> # in .bash_profilealias myproject= '' cd /path/to... | How can I permanently store commands in the Python REPL/prompt ? |
Python : The coderuns on both Python 2 and Python 3 , but prints different results . Is this change documented anywhere ? ( A pointer to a mailing list discussion would also be fine -- I ask this purely out of curiosity . ) <code> x = 3def f ( ) : exec ( `` x = 2 '' ) print ( x ) f ( ) | Variables declared in exec'ed code do n't become local in Python 3 – documentation ? |
Python : I have a a program where circles can bounce into one another . I followed the directions from here for rotating the vectors and scaling the magnitudes based on the collision angle : http : //www.vobarian.com/collisions/2dcollisions2.pdfI wrote this code in python ( the 0 index indicates the x coordinate ) : Th... | I ca n't find what 's wrong with this circle bounce calculation in python |
Python : I was reading the __init__ method of the Counter class , and saw this : I was n't sure what it meant by descriptor , so I checked the python data model document and found this : In general , a descriptor is an object attribute with “ binding behavior ” , one whose attribute access has been overridden by method... | Why is the __init__ method of Counter referred to as a descriptor ? |
Python : I know this goes against the definition of random numbers , but still I require this for my project.For instance , I want to generate an array with 5 random elements in range ( 0 , 200 ) .Now , I want each of the elements to have a difference of at least 15 between them.So the random array should look somethin... | How to generate random numbers with each random number having a difference of at least x with all other elements ? |
Python : I have : This works for the first iteration , but then I get an error for the next iteration : Is there something I 'm doing wrong ? <code> context = torch.tensor ( context , dtype=torch.long , device=self.device ) context = context.unsqueeze ( 0 ) generated = context with torch.no_grad ( ) : past_outputs = No... | How to use the past with HuggingFace Transformers GPT-2 ? |
Python : Perhaps this is also something for Cross Validated , but I am interested in how to do it in Python.I have a Pandas DataFrame containing a dataset D of instances which all have some continuous value x. x is distributed in a certain way , say uniform , could be anything.I want to draw n samples from D for which ... | Pandas : Sampling from a DataFrame according to a target distribution |
Python : I want to exhaustively analyse subroutines for sorting small arrays and need a way to generate all uniquely ordered arrays of a particular length.In Python , that would be lists with non-negative integers as elements and preferably using smallest integers when possible . For example , N = 3 : [ 1,1,1 ] and [ 2... | Python : Generate all uniquely ordered lists of length N |
Python : Consider the array aI can create b which contains the permutation to sort each column.I can sort a with bThat was the primer to illustrate the output I 'm looking for . I want an array b that has the required permutation for sorting the corresponding column in a when also considering a lexsort with another arr... | Broadcast 1D array against 2D array for lexsort : Permutation for sorting each column independently when considering yet another vector |
Python : Answering this question , some others and I were actually wrong by considering that the following would work : Say one hasWhat is the reason behindwhile one hasor orIs it the degeneracy in term of dimensions which causes this . <code> test = [ [ [ 0 ] , 1 ] , [ [ 1 ] , 1 ] ] import numpy as npnptest = np.array... | What is going on behind this numpy selection behavior ? |
Python : I found a programming problem I was unable to solve . I have been given a set A of integers . For all numbers x in A , find the smallest positive integer y such that the digits of x*y are increasing or decreasing and the product x*y is the smallest possible . For example , if A= ( 363 , 726 , 1089 ) then n= ( ... | How to find smallest positive integers to make digits monotonic ? |
Python : I am trying to figure out how to count up to a certain integer ( as a range ) alternating between two different numbers like 2 and 3 . So that the output would be 2 5 7 10 12 15 etc.I started off trying to alter a simple while loop like the following to take two values : But it just ends up counting up to 100 ... | Python 3 - Counting up with two different values |
Python : This is super , super slow for some reason.There are a total of 2000 results.Below is an example of a result document ( from Mongo ) . All other results are similar in length.The whole process takings about 15 seconds ... what the hell ? How can I speed it up ? : ) Edit : I realize that when I print the count ... | This takes a long time ... how do I speed this dictionary up ? ( python ) |
Python : I need to turn a two column Dataframe to a list grouped by one of the columns . I have done it successfully in pandas : But now I am trying to do the same thing in pySpark as follows : and I am getting the error : I have tried several commands but I simply can not get it right . And the spark dokumentation doe... | turning pandas to pyspark expression |
Python : The data is here : The Python code , incorporating recent changes , is as follows . There is no attempt to loop through different boards as my intermediate attempt . This data is just produced by a search all query . which produces , as before , the correct dictionary where the scoring is correct but there are... | making a calculation with the elements of an elasticsearch json object , of a contract bridge score , using Python |
Python : I want to calculate the least squares estimate for given data.There are a few ways to do this , one is to use numpy 's least squares : Where X is a matrix and y a vector of compatible dimension ( type float64 ) . Second way is to calculate the result directly using the formula : My problem : there are cases wh... | Why does numpy least squares result diverge from using the direct formula ? |
Python : I have a list of sentences of a few topics ( two ) like the below : As you can see there is similarity in sentences.I am trying to relate multiple sentences and visualise the characteristics of them by using a graph ( directed ) . The graph is built from a similarity matrix , by applying row ordering of senten... | Graph to connect sentences |
Python : I 've been learning the basics of Python for a short while , and thought I 'd go ahead and try to put something together , but appear to have hit a stumbling block ( despite looking just about everywhere to see where I may be going wrong ) .I 'm trying to grab a table i.e . from here : https : //www.oddschecke... | Extracting data from list in Python , after BeautifulSoup scrape , and creating Pandas table |
Python : CodeOutputGoalI am intending to split the list , grab the 1st and 2nd words for each section , and put them into a new list.QuestionWhy is my output giving me a weird output ? Where am I going wrong ? Desired OutputMy desired output should look like this : Grabbing the 1st and 2nd words and put them into 1 lis... | How to fill a new list while iterating over another list ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.