lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Python | I recently discovered a new metadata in my .egg-info/PKG-INFO : Description-Content-Type.When I run : I get : For instance , how can I tell that I use Markdown ( text/markdown ) ? | python setup.py egg_info Description-Content-Type : UNKNOWN | Why do I have Description-Content-Type : UNKNOWN |
Python | Given the following tableI 'm trying to find a clean solution in pandas to subtract away a value , say 30 for example , to end with the following result.I was wondering if pandas had a solution to performing this that did n't require looping through all the rows in a dataframe , something that takes advantage of pandas... | vals0 201 32 23 104 20 vals0 01 02 03 54 20 | Subtract aggregate from Pandas Series/Dataframe |
Python | I am using sklearn.preprocessing.StandardScaler to re-scale my data . I want to use np.std to do the same thing with StandardScaler.However , I find an interesting thing that , with no additional parameter passing in pandas.apply ( fun = np.std ) , the outputs varies between sample std and population std . ( See 2 Prob... | from sklearn import datasetsimport numpy as npfrom sklearn.preprocessing import StandardScaleriris = datasets.load_iris ( ) X_train = iris.data [ : , [ 1 ] ] # my X_train is the first column if iris datasc = StandardScaler ( ) sc.fit ( X_train ) # Using StandardScaler to scale it ! import pandas as pdimport sysprint ( ... | Inconsistent output from Pandas apply function with np.std as function parameter |
Python | I have the following classes : If I do the following I get an error : Is there another way to do this automatically at runtime ? I am using Python 2.7 . | class hello ( object ) : def __init__ ( self ) : passclass bye ( object ) : def __init__ ( self ) : passl = [ hello , bye ] > > > class bigclass ( *l ) : File `` < stdin > '' , line 1 class bigclass ( *l ) : ^SyntaxError : invalid syntax | How do I concatenate many objects into one object using inheritance in python ? ( during runtime ) |
Python | I need an efficient way to merge a list of nodes ( pairs of integers ) . The merge should happen only if there is one common number in the pair and the common number is on the first or the last position ( otherwise its allready connected ) .For example : another example : and yet another example : Currently I 'm using ... | mylist = [ [ 4 , 3 ] , [ 6 , 3 ] ] merge_links ( mylist ) # should output [ 4 , 3 , 6 ] mylist = [ [ 4 , 3 ] , [ 6 , 3 ] , [ 6 , 4 ] ] merge_links ( mylist ) # should output again [ 4 , 3 , 6 ] because both 6 and 4 allready exist in array . mylist = [ [ 4 , 3 ] , [ 6 , 3 ] , [ 6 , 4 ] , [ 6 , 2 ] , [ 7 , 4 ] , [ 4 , 9 ... | Merge pairs on common integer with restrictions |
Python | I did not understand where is the logic in my bug , so I managed to find a minimal example . I defined one class t , and said that something happens when you use the < = operator and that a > =b must compute b < =a.It works fineThen I derived a subclass u from t.When I compare two values , if they are both from t or bo... | class t : def __le__ ( self , other ) : return True def __ge__ ( self , other ) : return ( other < =self ) class u ( t ) : passa=t ( ) b=u ( ) # worksa < =aa > =ab < =bb > =b # worksa > =bb < =a # does n't work RuntimeError : maximum recursion depth exceededa < =bb > =a | python : recursion loop in rich comparison operator |
Python | I am very confused with the python code below : I can tell myself clearly what python doing when creating objects.Can anyone tell me more about what happend ? Thanks ! | > > > class A ( ) : pass ... > > > id ( A ( ) ) == id ( A ( ) ) True > > > id ( A ( ) ) 19873304 > > > id ( A ( ) ) 19873304 > > > A ( ) is A ( ) False > > > a = A ( ) > > > b = A ( ) > > > id ( a ) == id ( b ) False > > > a is bFalse > > > id ( a ) 19873304 > > > id ( b ) 20333272 > > > def f ( ) : ... print id ( A ( ... | why id ( A ( ) ) == id ( A ( ) ) is different to A ( ) is A ( ) ? |
Python | After reading : Dive into Python : Unicode DiscussionI got curious to try printing my name in the indic script . I am using v2.7.2 - I was expecting print name to give me UnicodeError since the defaultencoding is set to ASCII so the auto-coercion to ASCII from Unicode should n't work.What am I missing ? | > > > import sys > > > sys.getdefaultencoding ( ) 'ascii ' > > > name = u'\u0935\u0948\u092D\u0935 ' > > > print nameवैभव | no UnicodeError when using print with a default encoding set to ASCII |
Python | I have a dictionary like the followingHow can I get separate dictionaries based on first letter of value ? like : I started withbut how I will find the whole initial dicitonary element | dict= { 'sku1 ' : ' k-1 ' , 'sku2 ' : ' k-2 ' , 'sku3 ' : ' b-10 ' , 'sku4 ' : ' b-1 ' , 'sku5 ' : ' x-1 ' , 'sku6 ' : ' x-2 ' } dict1= { 'sku5 ' : ' x-1 ' , 'sku6 ' : ' x-2 ' } dict2= { 'sku1 ' : ' k-1 ' , 'sku2 ' : ' k-2 ' } dict2= { 'sku3 ' : ' b-10 ' , 'sku4 ' : ' b-1 ' } for an_item in thevalues_ofdict : Splitted_... | How can I split a dictionary in several dictionaries based on a part of values using Python |
Python | I 'm having a rather hard problem that I just ca n't get fixed.. The idea is to loop through a part of data and find any indentation . ( always spaces ) Every time a line has a bigger indentation than the previous , for example 4 more whitespaces , the first line should be the key for a dictionary and the next values s... | Chassis 1 : Servers : Server 1/1 : Equipped Product Name : EEE UCS B200 M3 Equiped PID : e63-samp-33 Equipped VID : V01 Acknowledged Cores : 16 Acknowledged Adapters : 1 PSU 1 : Presence : Equipped VID : V00 HW Revision : 0 for item in Array : regexpatt = re.search ( `` : $ '' , item ) if regexpatt : keyFound = True br... | Nesting dictionaries while looping through data |
Python | I have a list like this : How can I calculate the size of blocks of values of 1 and 0 in this list ? The resulting list will look like : | list_1 = [ 0 , 1 , 1 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 0 , 1 ] list_2 = [ 1 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , 4 , 4 , 1 , 1 ] | How to calculate the size of blocks of values in a list ? |
Python | I need to define a bunch of flexible structs ( objects with a simple collection of named fields , where you can add new fields later , but I do n't need methods or inheritance or anything like that ) in Python 2.7 . ( The context is that I 'm reading stuff from binary files with struct.unpack_from , then adding further... | class Thing : def __init__ ( self , foo , bar ) : self.foo = foo self.bar = bar | Concise flexible struct definition |
Python | I have a = array ( [ 1 , 2 , 3 , 4 , 5 ] ) and b = array ( [ 10 , 20 , 30 , 40 , 50 ] ) . I want : What 's the most efficient way to do this ? I haveHowever I wonder if there 's a more efficient way than this if a is very large , which would n't require copying b so much ( or vice versa ) . | array ( [ [ -9 , -19 , -29 , -39 , -49 ] , [ -8 , -18 , -28 , -38 , -48 ] , [ -7 , -17 , -27 , -37 , -47 ] , [ -6 , -16 , -26 , -36 , -46 ] , [ -5 , -15 , -25 , -35 , -45 ] ] ) np.transpose ( [ a ] ) - np.tile ( b , ( len ( a ) , 1 ) ) | How to efficiently apply an operator to the cartesian product of two arrays ? |
Python | I need to create a list which returns the difference between the nth and nth + 1 values of another list . Is there any way of simplifying the code below to work for any size lists ? And this will return [ 4,10,15,30 ] | mylist = [ 1,5,15,30,60 ] w = mylist [ 1 ] - mylist [ 0 ] x = mylist [ 2 ] - mylist [ 1 ] y = mylist [ 3 ] - mylist [ 2 ] z = mylist [ 4 ] - mylist [ 3 ] difflist = [ w , x , y , z ] print difflist | Create list by subtracting the nth+1 value from the nth values of another list |
Python | I 'm new to the ML and I was following this tutorial which teaches how to do cryptocurrency predictions based on some futures . My code to do the prediction : But i got the below error : ValueError : Error when checking input : expected lstm_input to have 3 dimensions , but got array with shape ( 69188 , 1 ) I do n't r... | model = load_model ( `` Path//myModel.model '' ) ready_x = preprocess_df ( main_df ) # the function returns array of price sequences and targets ( 0-buy,1-sells ) : return np.array ( X ) , y predictions = [ ] for x in ready_x : l_p = model.predict_classes ( x ) # error occurs on this line predictions.append ( l_p [ 0 ]... | Doing prediction with RNN on Sequential data in keras |
Python | Hi I am having trouble reshaping my df . I have : And I want to convert my df to look like : Not sure how stack ( ) or pivot ( ) would work on a df of this kind . Any help appreciated . | Netflix TV DVD 0.1 0.2 0.3 0.12 0.5 0.15 0.4 0.6 0.8 0.5 0.41 0.41 0.2 Netflix [ 0.1 , 0.12 , 0.4 ] TV [ 0.2 , 0.5 , 0.6 , 0.5 , 0.41 , 0.2 ] DVD [ 0.3 , 0.15 , 0.8 , 0.41 ] | Reshape long to wide using columns names |
Python | This is my first ever post on stackoverflow and am I am total fresher to coding . So , please bear with me . I am working on an experiment which has two sets of data documents . Doc1 is as follows : and so on till 100 topics.In this document , there are words that are either present in all the topics or just present in... | TOPIC : topic_0 5892.0site 0.0371690427699Internet 0.0261371350984online 0.0229124236253web 0.0218940936864say 0.0159538357094image 0.015105227427TOPIC : topic_1 12366.0Mr 0.150331554262s 0.0517548115801say 0.0451237263464TOPIC : topic_2 ... ... ... ... ..TOPIC : topic_3 1066.0say 0.062word 0.182 TOPIC : topic_0 5892.0... | Assign 0 to certain words when the words are not present |
Python | In my code , I load up an entire folder into a list and then try to get rid of every file in the list except the .mp3 files.After I run the file , the code does get rid of some files in the list but keeps these two especifically : [ '00 . Various Artists - Indie Rock Playlist October 2008.m3u ' , '00 . Various Artists ... | import osimport repath = '/home/user/mp3/'dirList = os.listdir ( path ) dirList.sort ( ) i = 0for names in dirList : match = re.search ( r'\.mp3 ' , names ) if match : i = i+1 else : dirList.remove ( names ) print dirListprint i | Why are these strings escaping from my regular expression in python ? |
Python | Suppose I have the following program : If you run it with Python the output is True . My question is the __ne__ method is not implemented , does Python fall on a default one ? if Python fall on a default method to determine whether two objects are equal or not , should n't it call __eq__ and then negate the result ? | class A ( object ) : def __eq__ ( self , other ) : return Truea0 = A ( ) a1 = A ( ) print a0 ! = a1 | Does __ne__ use an overridden __eq__ ? |
Python | Need to get sum of x and y without + operator.I trid to sum two number using adder.If we xor x and y ( x ^ y ) , we will get summation without carry . From x & y we can get carry . To add this carry in summation , call add function again . but its not give answer . where is the error in my code.Error : File `` main.py ... | def add ( a , b ) : if a == 0 : return b return add ( a^b , a & b ) x = 10y = 20print ( add ( 10 , 20 ) ) return add ( a^b , a & b ) File `` main.py '' , line 4 , in add return add ( a^b , a & b ) File `` main.py '' , line 4 , in add return add ( a^b , a & b ) File `` main.py '' , line 4 , in add return add ( a^b , a &... | Summation without + operator in python |
Python | I feel that this is very simple and I 'm close to solution , but I got stacked , and ca n't find suggestion in the Internet.I have list that looks like : In general , each element of the list has the form : namex @ some_number.I want to make dictionary in pretty way , that has key = namex and value = some_number . I ca... | my_list = [ 'name1 @ 1111 ' , 'name2 @ 2222 ' , 'name3 @ 3333 ' ] md = { } for item in arguments : md [ item.split ( ' @ ' ) [ 0 ] ] = item.split ( ' @ ' ) [ 1 ] md2 = dict ( ( k , v ) for k , v in item.split ( ' @ ' ) for item in arguments ) | Create dictionary from splitted strings from list of strings |
Python | I have following two python lists.I want to create a dictionary with elements from first list as keys and with following constraints : if key does not exists in second list then the value will be False.if key exists in second list with variants then the value will be False.Eg : ( i ) while checking 123 , if 1234 , 1234... | prob_tokens = [ '119 ' , '120 ' , '123 ' , '1234 ' , '12345 ' ] complete_tokens = [ '112 ' , '120 ' , '121 ' , '123 ' , '1233 ' , '1234 ' , '1235 ' , '12345 ' ] min_len_sec_list = 3max_len_sec_list = 5 { '119 ' : False , '120 ' : True , '123 ' : False , '1234 ' : False , '12345 ' : True } | Creating custom dictionary from two lists |
Python | Following this question , I 'd like to know if there any difference in writingandI have tried both and they seem to return the same results in my code but nowhere in the documentation does it say that they 're the same thing ( as with __exact ) .Can I safely assume the two forms are equal ? Where is it documented ? | .filter ( league_pk__in= [ 1,2,3 ] ) .filter ( league= [ 1,2,3 ] ) | In Django filter statement what 's the difference between __in and equal sign ( = ) ? |
Python | I am doing this following : Can you shorten this code by doing something like : | if ycoords [ 0 ] > 0 and ycoords [ 1 ] > 0 and ycoords [ 2 ] > 0 : # do stuff if ( ycoords [ 0 ] and ycoords [ 1 ] and ycoords [ 2 ] ) > 0 : # do stuff | Linking up statements using the 'and ' keyword |
Python | I want to extract the links from the following site but it does include pagination : I want to extract link under the MoreInfo Button : I 'm using the following snippet : when i run the above script i got this error** ( I 'm not too much familiar with regex as well just exploring the concept ) ** : Please suggest me th... | import timeimport requestsimport csvfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.action_chains import ActionChainsimport rebrowser = webdriver... | How can i extract the links from the site that contains pagination ? ( using selenium ) |
Python | I 'm looking to compute floor ( log ( n , b ) ) where n and b are both integers . Directly implementing this function fails for even slightly large values of n and bFor example , floor_log ( 100**3 , 100 ) evaluates to 2 instead of the correct value 3.I was able to come up with a working function which repeatedly divid... | # direct implementationdef floor_log ( n , b ) : return math.floor ( math.log ( n , b ) ) # loop based implementationdef floor_log ( n , b ) : val = 0 n = n // b while n > 0 : val += 1 n = n // b return val | Better way to compute floor of log ( n , b ) for integers n and b ? |
Python | I ca n't use the debugger in ipython after importing anything pyqt related . If I do n't import anything and debug an error post-mortem likeall is well , but if I start ipython3 with the pyqt5 backend I getI am not developing with qt , I only use it as the backend for matplotlib . I know that this question is very vagu... | $ ipython3In [ 1 ] : abc -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -NameError Traceback ( most recent call last ) < ipython-input-1-03cfd743661f > in < module > -- -- > 1 abcNameError : name 'abc ' is not definedIn [ 2 ] : % debug > < ipython-input-1-... | ipython debugger is flooded with Qt errors after pylab import |
Python | I am implementing a C function as an extension for Python . Inside abstract.h , I found the following : When I try to get iterators using PyObject_GetIter on obviously non-iterable objects like a number , I get the error SystemError : < built-in function xxx > returned a result with an error set.I would like to handle ... | /* ==== Iterators ================================================ *//* Takes an object and returns an iterator for it . This is typically a new iterator but if the argument is an iterator , this returns itself . */PyAPI_FUNC ( PyObject * ) PyObject_GetIter ( PyObject * ) ; /* Returns 1 if the object 'obj ' provides it... | How to test if PyObject has an iterator |
Python | I am trying to convert this feedparser.py ( on github ) to python3 . I am having trouble understanding what this line is doing , right now it throws a syntax error : what operator is < > . Is there a Python3 equivalent ? | [ line 640 ] if tag.find ( ' : ' ) < > -1 : | converting < > operator to python3 |
Python | I was playing around with the _ underscore in the Python interpreter and wanted to try if it has the same behavior in code . I have used the underscore in code as a 'Do n't care'-variable , like this : And in the interpreter to get the last stored value , like this : Now I tried to execute the following example code : ... | _ , a = someFunction ( ) > > > 2 + 24 > > > a = _ > > > a4 for i in range ( 5 ) : 2 + 1 a = _print ( a ) > > > for i in range ( 5 ) : ... 2 + 1 ... a = _ ... 33333 > > > print ( a ) 3 C : \Users\..\Python files > python underscore.pyTraceback ( most recent call last ) : File `` underscore.py '' , line 3 , in < module >... | What is the difference between the underscore in code and in the interpreter ? |
Python | Let us suppose the following code ( from imblearn example on pipelines ) I want to make it sure that when executing the pipeline.predict ( X_test ) the sampling procedures enn and renn will not be executed ( but of course the pca must be executed ) .First , it is clear to me that over- , under- , and mixed-sampling are... | ... # Instanciate a PCA object for the sake of easy visualisationpca = PCA ( n_components=2 ) # Create the samplersenn = EditedNearestNeighbours ( ) renn = RepeatedEditedNearestNeighbours ( ) # Create the classifierknn = KNN ( 1 ) # Make the splitsX_train , X_test , y_train , y_test = tts ( X , y , random_state=42 ) # ... | Does imblearn pipeline turn off sampling for testing ? |
Python | I used the % memit magic function to measure memory usage : OK so there seems to be an intermediate step where xrange ( n ) is instantiated into a full list . But what if I cut my list into 10 sublists , and union them one by one ? This would be more memory efficient , right ? Well , that did n't go as expected . Why d... | In [ 1 ] : % memit n = pow ( 10 , 7 ) ; range ( n ) peak memory : 568 MiB , increment : 272 MiBIn [ 2 ] : % memit n = pow ( 10 , 7 ) ; set ( xrange ( n ) ) peak memory : 824 MiB , increment : 447 MiB In [ 3 ] : % memit n = pow ( 10 , 7 ) ; reduce ( set.union , ( set ( xrange ( p , n , 10 ) ) for p in range ( 10 ) ) ) p... | Memory usage : creating one big set vs merging many small sets |
Python | In unit test code in C++ , when I need to compare two vectors , I create temporary vector to store expected values . Can I make it one line ? In python , I can generate a list with `` [ ... ] '' . | std : :vector < int > expected ( { 5,2,3 , 15 } ) ; EXPECT_TRUE ( Util : :sameTwoVectors ( result , expected ) ) ; sameTwoVectors ( members , [ 5,2,3,15 ] ) | Making unnamed container in c++ for temporary comparison in unit test |
Python | If I have a dictionary , as follows : how can i return a new dictionary with the following resultI want the sub-dictionaries ( is this the right term ? ) of 'key1 ' and 'key2 ' have the same keys | { 'key1 ' : { 'foo ' : 1233 , 'bar ' : 1234 , 'baz ' : 122 } , 'key2 ' : { 'foo ' : 113 , 'bar ' : 333 } } { 'key1 ' : { 'foo ' : 1233 , 'bar ' : 1234 } , 'key2 ' : { 'foo ' : 113 , 'bar ' : 333 } } | new dictionary with common subkey |
Python | This might be an easy question but I can not get the result that I want ! I have a text like the one below : I am using regex in python and I want to get all the numbers between these characters `` « `` `` » '' that is 1 . 2. and 3 . I tried something like this : or this : and many others but none of them return what I... | text = 'To get to the destination follow this direction1 . First turn left and thentext text text2 . Secondly you have to some text heresome text hereFor the second instruction follow the text below : « 1 . some text some text some texttext text text.2 . some text some text text text text.3 . some text some text text t... | find all digits between a character in python |
Python | I want to lookup and compare efficiently the string elements in a list and then remove those which are parts of other string elements in the list ( with the same beginning point ) I intend to get a list which looks like this : In other words , I want to keep the longest string element from those elements which start wi... | list1 = [ ' a boy ran ' , 'green apples are worse ' , ' a boy ran towards the mill ' , ' this is another sentence ' , ' a boy ran towards the mill and fell ' , ... .. ] list2 = [ 'green apples are worse ' , ' this is another sentence ' , ' a boy ran towards the mill and fell ' , ... .. ] | Remove string element in a list of strings if the first characters match with another string element in the list |
Python | I want to insert some data into a table and I want the multiple insertion to be as fast as possible . I use sqlalchemy library for Python . I want to know if my insertion is optimal , or there is a better way to do that.Here is my code : | from sqlalchemy import * from sqlalchemy import schema metadata = schema.MetaData ( ) engine = create_engine ( 'sqlite : /// : memory : ' , echo=True ) users = Table ( 'users ' , metadata , Column ( 'id ' , Integer , primary_key=True ) , Column ( 'firstname ' , String ( 40 ) ) , Column ( 'lastname ' , Integer ) , ) met... | Is the insertion optimal ? |
Python | I 'm writing a class in Python and I 'm writing a __str__ ( ) function so my print statements can print string representations of instances of that class . Is there ever a reason to directly do something like this : It feels like since there are other neater ways to do this , it would be a bad idea ( or at least , not ... | myObj = Foo ( params ) doSomething ( myObj.__str__ ( ) ) | Should I ever directly call object.__str__ ( ) ? |
Python | I have an unending series with no equation , and is random , something like this , Note that I 'm getting this list as a stream , and I do not know future values , and I do not know min and max of X.How do I find out the inverted normal N ( X ) for any x in X , such that , N ( x ) -- > 0 if x -- > inf N ( x ) -- > 1 if... | X = 1 , 456 , 555 , 556 , 557 , 789 ... # pythondef invnorm ( x ) : denom = 1 + math.exp ( -x ) return 2 - ( 2/denom ) invnorm ( 200 ) Out [ 8 ] : 0.0invnorm ( 20 ) Out [ 9 ] : 4.1223073843355e-09invnorm ( 2 ) Out [ 10 ] : 0.23840584404423537invnorm ( 1 ) Out [ 11 ] : 0.5378828427399902 | Normalizing a random unending unknown series ? |
Python | Given the following ( arbitrary ) lap times : We 're doing a go-kart endurance race , and the idea , rather than allowing team picking is to write a tool to process the initial qualifying times and then spit out the closest-matched groupings.My initial investigation makes me feel like this is a clique graphing type sit... | John : 47.20Mark : 51.14Shellie : 49.95Scott : 48.80Jack : 46.60Cheryl : 52.70Martin : 57.65Karl : 55.45Yong : 52.30Lynetta : 59.90Sueann : 49.24Tempie : 47.88Mack : 51.11Kecia : 53.20Jayson : 48.90Sanjuanita : 45.90Rosita : 54.43Lyndia : 52.38Deloris : 49.90Sophie : 44.31Fleta : 58.12Tai : 61.23Cassaundra : 49.38 Oren... | How to programatically group lap times into teams to minimize difference ? |
Python | I have a matrix . e.g.a 10 x 15 matrixI am looking for all connected non-zeros and their maximum value . Please see this figure.So the desire output is : It is being difficult to develop a proper algorithm to write further it in fortran or in shell script . I am thinking of the following algorithm , but ca n't able to ... | $ cat input.txt2 3 4 5 10 0 2 2 0 1 0 0 0 1 00 3 4 6 2 0 2 0 0 0 0 1 2 3 400 0 0 2 3 0 3 0 3 1 2 3 1 0 01 2 0 4 0 3 4 0 4 1 2 0 0 1 10 0 0 0 0 0 10 3 4 12 4 5 12 3 1026 3 4 5 10 0 2 2 4 1 0 0 0 1 00 30 4 6 2 0 2 0 0 0 0 1 2 3 400 0 0 2 3 0 0 0 0 1 0 3 1 0 01 2 10 4 0 0 4 0 4 1 2 0 0 1 10 0 0 0 0 0 0 3 0 0 4 5 0 3 10 ou... | Count the number of connected non-zeros along rows and columns but not diagonaly in a Matrix in shell script |
Python | While reading about the unification of types I stumbled on the fact that built-in types have method_descriptors and builtin_function_or_methods instead of methods and functions , why ? There is no good reason for class A to subclass list , I just wanted to show that the types differ . | > > > list.append < method 'append ' of 'list ' objects > > > > type ( list.append ) < class 'method_descriptor ' > > > > [ ] .append < built-in method append of list object at 0x7f0c4214aef0 > > > > type ( [ ] .append ) < class 'builtin_function_or_method ' > > > > class A ( list ) : ... def append ( self ) : pass ...... | Inconsistence among built-in types and user defined |
Python | We know that this creates a class : And , in Python 3 , due to new style classes , X automatically inherits from object , but in Python 2 , it does n't : And we also know that we can dynamically create such a class using type factory : However , if we omit the object in the bases tuple just as we did with class syntax ... | class X : a = 1 > > > X.__bases__ # Python 2 ( ) > > > X.__bases__ # Python 3 ( < class 'object ' > , ) X = type ( `` X '' , ( object , ) , { `` a '' :1 } ) name^ ^bases ^ `` class '' body X = type ( `` X '' , ( ) , { `` a '' :1 } ) ^ empty bases tuple > > > X.__bases__ # Python 2 ( < type 'object ' > , ) > > > X.__bas... | object is subclassed during dynamic type creation but not during classic class definition in python2 |
Python | I came across the following question and was wondering what would be an elegant way to solve it.Let 's say we have two strings : The only difference between those strings is $ ( fruit ) and apples.So , I can find the fruit is apples , and a dict { fruit : apples } could be returned.Another example would be : I would li... | string1 = `` I love to eat $ ( fruit ) '' string2 = `` I love to eat apples '' string1 = `` I have $ ( food1 ) , $ ( food2 ) , $ ( food3 ) for lunch '' string2 = `` I have rice , soup , vegetables for lunch '' ex.string1 = `` I want to go to $ ( place ) '' string2 = `` I want to go to North America '' result : { place ... | How to map the differences between two strings ? |
Python | My input are lists of indices like how can I convert them into fixed length indicator vectors ? | [ 1,3 ] , [ 0,1,2 ] [ 0 , 1 , 0 , 1 ] , [ 1 , 1 , 1 , 0 ] | in tensorflow , how do I convert a list of indices to an indicator vector ? |
Python | I have a list lst = [ 1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4 ] I 'm expecting the following output : I want to keep the first occurrence of the item and replace all other occurrences of the same item with empty strings.I tried the following approach . But I 'm looking for some simpler or better approaches . | out = [ 1 , '' '' , '' '' ,2 , '' '' , '' '' , '' '' ,3 , '' '' , '' '' , '' '' , '' '' ,4 , '' '' , '' '' , '' '' , '' '' , '' '' , '' '' , '' '' , '' '' ] ` def splrep ( lst ) : from collections import Counter C = Counter ( lst ) flst = [ [ k , ] *v for k , v in C.items ( ) ] nl = [ ] for i in flst : nl1 = [ ] for j ... | Replace duplicate items from list while keeping the first occurrence |
Python | I have two distribution with different spread , sayI want to make an histogram of them where the maximum is at the same level.If I make normalised histograms with density=True parameter , it will make that area of both histograms will be 1 , bit it wont change the fact that maximums are different.What I want is to make... | a=N.random.normal ( 0,0.5,500 ) b=N.random.normal ( 1,3.,500 ) P.hist ( a , histtype='step ' , lw=2 , cumulative=True ) P.hist ( b , histtype='step ' , color= ' r ' , lw=2 , density=True ) | Python - How to have same maximum on multiple histograms |
Python | I would like to find items in a list that have duplicate endings within the last 3 characters of the stringI know how to find duplicates using the code below , but need help with code how to find that the last strings of `` sara '' and `` tamara '' are the same so that one of the items can be copied to a duplicate_find... | names = [ `` tom '' , `` john '' , `` sara '' , `` tamara '' , `` tom '' ] single_finds = [ ] duplicate_finds = [ ] for i in names : if i in single_finds : duplicate_finds.append ( i ) else : single_finds.append ( i ) print ( single_finds ) print ( duplicate_finds ) [ 'tom ' , 'john ' , 'sara ' , 'tamara ' ] [ 'tom ' ] | find duplicates of items endings in a list |
Python | So , I have this listand , I want to join them in a way such as : I tried lots of methods but nothing seemed to work . Any suggestions ? | l = [ 'abc ' , 'retro ' , `` , `` , 'images ' , 'cool ' , `` , 'end ' ] l = [ 'abc retro ' , `` , `` , 'images cool ' , `` , 'end ' ] | Python joining list elements in a tricky way |
Python | I have two numpy array ( 2 dimensional ) e.g.What is the most elegant way of getting a matrix like this : Where element ( i , j ) is 1 if all ( a1 [ i , : ] == a2 [ j , : ] ) and otherwise 0 ( everything involving two for loops I do n't consider elegant ) | a1 = array ( [ [ `` a '' , '' b '' ] , [ `` a '' , '' c '' ] , [ `` b '' , '' b '' ] , [ `` a '' , '' b '' ] ] ) a2 = array ( [ [ `` a '' , '' b '' ] , [ `` b '' , '' b '' ] , [ `` c '' , '' a '' ] , [ `` a '' , '' c '' ] ] ) array ( [ [ 1,0,0,0 ] , [ 0,0,0,1 ] , [ 0,1,0,0 ] , [ 1,0,0,0 ] ] ) | How to make this kind of equality array fast ( in numpy ) ? |
Python | trying modify a decorator not to use a weakref , I stumbled across the following behaviour : This seems very odd to me , as I 'd expect both cases to behave the same . Furthermore , from my understanding of reference counting and object lifetime , I was convinced that in both cases the object should be freed.I have tes... | import weakrefclass descriptor ( object ) : def __get__ ( self , instance , owner ) : return proxy ( instance ) class proxy ( object ) : def __init__ ( self , instance ) : self.instance = instance def __iadd__ ( self , other ) : return selfclass A ( object ) : descr = descriptor ( ) def is_leaky ( test_fn ) : a = A ( )... | Memory leak when invoking __iadd__ via __get__ without using temporary |
Python | So in R , I 'd use an optimized apply function for this , but I 've read now that the Panda 's apply function is an abstracted loop and is perhaps even slower than one , and it shows in the performance . On my machine , it took 30 mins to process 60k rows . So essentially I 'm looking to calculate a moving average base... | df [ 'SMA ' ] = df.apply ( SMA , axis=1 ) def SMA ( row ) : Subset = df [ ( df [ 'group ' ] ==row [ 'group ' ] ) & ( df [ 't ' ] < =row [ 't ' ] ) ] .reset_index ( ) Subset2 = Subset [ len ( Subset.index ) - ( 2 ) : len ( Subset.index ) ] return df [ 'val ' ] .mean ( ) t group val moving average1 A 1 NA2 A 2 1.53 A 3 2... | Is there a better/more efficient way to do this ( vectorised ) ? Very slow performance with Pandas apply |
Python | Let 's suppose that I have this in python : and if we suppose that I want to split this string every 10 characters but without splitting a word then I want to have this : or this ( without the whitespaces at the splittings ) : Therefore , the split should be done exactly before the word which would have been splitted o... | orig_string = ' I am a string in python ' strings = [ ' I am a ' , 'string in ' , 'python ' ] strings = [ ' I am a ' , 'string in ' , 'python ' ] false_strings = [ ' I am a str ' , 'ing in pyt ' , 'hon ' ] | Split string every n characters but without splitting a word |
Python | This looks like a repeated question but I tried the solution that already exists and none seems to work so far for me . .this solution gives a hint but it works only for a regular geometry . I have a rather complicated geometry from which I extract boundary points which are unsorted . Below is a picture of the geometry... | import numpy as nppts = np.array ( [ [ 30. , -6.25 ] , [ 30. , -8.10127917 ] , [ 0. , -6.25 ] , [ 34.14082772 , -6.75584268 ] , [ 36.49784598 , -10 . ] , [ 44.43561524 , -10 . ] , [ 100. , -10 . ] , [ 100. , 10 . ] , [ 84.1244615 , -10 . ] , [ 84.1244615 , 10 . ] , [ 36.49784598 , 10 . ] , [ 34.14082772 , 6.75584268 ] ... | sorting a complicated collection of 2d euclidian points in in clockwise/counterclockwise fashion to form a closed ring |
Python | Below is a simple function to remove duplicates in a list while preserving order . I 've tried it and it actually works , so the problem here is my understanding . It seems to me that the second time you run uniq.remove ( item ) for a given item , it will return an error ( KeyError or ValueError I think ? ) because tha... | def unique ( seq ) : uniq = set ( seq ) return [ item for item in seq if item in uniq and not uniq.remove ( item ) ] | I think this should raise an error , but it does n't |
Python | Let L be a list L = [ A_1 , A_2 , ... , A_n ] , and each of the A_i are numpy.int32 arrays of length 1024 . ( Most of the time 1000 < n < 4000 ) .After some profiling , I have seen that one the most time consuming operation is the summation : PS : I do n't think I can define a 2D array of size 1024 x n because n is not... | def summation ( ) : # L is a global variable , modified outside of this function b = numpy.zeros ( 1024 , numpy.int32 ) for a in L : b += a return b | Cython optimize the critical part of a numpy array summation |
Python | Since the range object produces values on demand , does it mean that anytime a range is indexed , the iteration protocol is invoked up to that index ? What I mean is when : Since R [ 5 ] is n't stored in memory , is it calculated every time by creating a new iterator ? If not , how is it possible to index a range objec... | > > > R = range ( 1,11 ) > > > print ( R [ 5 ] ) 6 | Is the iteration protocol used when indexing a range object ? |
Python | I have binary images where rectangles are placed randomly and I want to get the positions and sizes of those rectangles . If possible I want the minimal number of rectangles necessary to exactly recreate the image.On the left is my original image and on the right the image I get after applying scipys.find_objects ( ) (... | import scipy # image = scipy.ndimage.zoom ( image , 9 , order=0 ) labels , n = scipy.ndimage.measurements.label ( image , np.ones ( ( 3 , 3 ) ) ) bboxes = scipy.ndimage.measurements.find_objects ( labels ) img_new = np.zeros_like ( image ) for bb in bboxes : img_new [ bb [ 0 ] , bb [ 1 ] ] = 1 import numpy as np def ra... | Find minimal number of rectangles in the image |
Python | I have the following piece of code that I would like to optimize using numpy , preferably removing the loop . I ca n't see how to approach it , so any suggesting would be helpful.indices is a ( N,2 ) numpy array of integers , N can be a few millions . What the code does is finding the repeated indices in the first colu... | index_sets = [ ] uniques , counts = np.unique ( indices [ : ,0 ] , return_counts=True ) potentials = uniques [ counts > 1 ] for p in potentials : correspondents = indices [ ( indices [ : ,0 ] == p ) ,1 ] combs = np.vstack ( list ( combinations ( correspondents , 2 ) ) ) combs = np.hstack ( ( np.tile ( p , ( combs.shape... | Optimizing/removing loop |
Python | How to merge the condition in array formatlike | lines = [ line for line in open ( 'text.txt ' ) if '|E| ' in line and 'GetPastPaymentInfo ' in line and 'CheckData ' not in line and 'UpdatePrintStatus ' not in line ] lines = [ line for line in open ( 'text.txt ' ) if [ '|E| ' , 'GetPastPaymentInfo ' ] in line and [ 'CheckData ' , 'UpdatePrintStatus ' ] not in line ] | Python multiple condition IN string |
Python | The code is below : To compute dW more efficiently , how to vectorize this for loop ? | import numpy as npX = np.array ( range ( 15 ) ) .reshape ( 5,3 ) # X 's element value is meaninglessflag = np.random.randn ( 5,4 ) y = np.array ( [ 0 , 1 , 2 , 3 , 0 ] ) # Y 's element value in range ( flag.shape [ 1 ] ) and Y.shape [ 0 ] equals X.shape [ 0 ] dW = np.zeros ( ( 3 , 4 ) ) # dW.shape equals ( X.shape [ 1 ... | How can I vectorize this for loop in numpy ? |
Python | I have two dataframes like this : and would now like to use df1 to fill df2 usinghowever , I getsite-packages/pandas/core/generic.py in _where ( self , cond , other , inplace , axis , level , errors , try_cast ) 8694other._get_axis ( i ) .equals ( ax ) for i , ax in enumerate ( self.axes ) 8695 ) : - > 8696 raise Inval... | import pandas as pdimport numpy as npdf1 = pd.DataFrame ( { 'key1 ' : list ( 'ABAACCA ' ) , 'key2 ' : list ( '1675987 ' ) , 'prop1 ' : list ( 'xyzuynb ' ) , 'prop2 ' : list ( 'mnbbbas ' ) } ) .set_index ( [ 'key1 ' , 'key2 ' ] ) df2 = pd.DataFrame ( { 'key1 ' : list ( 'ABCCADD ' ) , 'key2 ' : list ( '1598787 ' ) , 'pro... | Using fillna with two multi-index dataframes throws InvalidIndexError |
Python | Here 's an example of what I mean : Outputs approximately 3 seconds on my computer , regardless of the setup ( x=5 vs x=15 , no difference ) If I were to use much shorter code , one that first decreases x -= 10 and only then checks if x < 0 , I will get much worse results : It outputs around 6 seconds , again regardles... | s = `` '' '' if x > 10 : x -= 10else : x = 0 '' '' '' import timeitprint ( timeit.timeit ( s , setup= '' x=5 '' , number=99999999 ) ) s = `` '' '' x -= 10if x < 0 : x = 0 '' '' '' import timeitprint ( timeit.timeit ( s , setup= '' x=5 '' , number=99999999 ) ) | Why is ` if ` so much faster when checked before a statement than after a statement ? |
Python | I am testing my flask application endpoint and measuring the performance on a single machine . That particular endpoint has a decorator called decrypt_request . The implementation of this decorator looks like this : The endpoint looks something like that : Upon performing some load test I found out that the average RPS... | 1 . Read X-Session-Key header ( encrypted by public key ) 2 . Import RSA key3 . Create a cryptor and decrypt the session key ( RSA ) 4 . Read data from the request body ( which is encrypted by the above session key ) 5 . Decrypt the request body using the session key ( AES ) @ app.route ( '/test ' , methods= [ 'POST ' ... | Pycryptodome RSA decryption causes massive performance downgrade ( RPS ) |
Python | Say we want a list of n 0/1 elements with exactly k instances of 1 . Is there a one line comprehension or a more pythonic way to do this than the following ? | def random_include ( n , k ) : ret = [ ] to_include = set ( random.sample ( [ i for i in range ( n ) ] , k ) ) for i in range ( n ) : if i in to_include : ret.append ( 1 ) ret.append ( 0 ) | Pythonic random list of booleans of length n with exactly k Trues |
Python | I would like a more pythonic way for the following branch if any : Is there any ternary operator for that ? | if a < b : a.append ( 'value ' ) elif a==b : b.append ( 'value ' ) else : do nothing | Is there a more elegant pythonic way of expressing the following condional expression ? |
Python | I want to delete duplicated dictionary objects from a List of dictionaries.I do n't want the dict element that has the same 'plate ' element with another dict element in the list . I want it only once.My output should be like this : This is my code , but I 'm not getting the exact result.This gives me the output : whic... | datalist = [ { 'plate ' : `` 01 '' , 'confidence ' : `` 80 '' } , { 'plate ' : `` 01 '' , 'confidence ' : `` 60 '' } , { 'plate ' : `` 02 '' , 'confidence ' : `` 91 '' } , { 'plate ' : `` 02 '' , 'confidence ' : `` 91 '' } , ] datalist = [ { 'plate ' : `` 01 '' , 'confidence ' : `` 80 '' } , { 'plate ' : `` 02 '' , 'co... | How to delete duplicated dictionary objects from a List of dictionaries |
Python | I am currently getting : This comes out of a function im using and i need to turn the above into a list in the format below : I tried list ( y ) but this does not work , because it returns : How exactly would I do this ? ? | y= [ [ 0.16666667 ] [ -0.16666667 ] [ 0.16666667 ] ] x= [ 0.16666667 , -0.16666667,0.16666667 ] [ array ( [ 0.16666667 ] ) , array ( [ -0.16666667 ] ) , array ( [ 0.16666667 ] ) ] | Trying to converting a matrix 1*3 into a list |
Python | I have some C code that uses both numpy and R. On Windows , it compiles with MSVC to a .dll which can be dynamically loaded from R and passes all the tests . However , I fail to make it work on Debian.To investigate the problem I created the following minimal-ish example : I can compile it withwhere Rdll.lib was create... | # include < Python.h > # include < Rinternals.h > # include < numpy/arrayobject.h > SEXP main ( ) { Py_Initialize ( ) ; import_array ( ) ; SEXP one = PROTECT ( allocVector ( INTSXP , 1 ) ) ; INTEGER ( one ) [ 0 ] = 1 ; npy_intp dims [ 1 ] = { 1 } ; int data [ 1 ] = { 1 } ; PyObject *another = PyArray_SimpleNewFromData ... | Compiling C code that uses both R and numpy on Linux |
Python | I am trying to add a dropdown menu to a plotly line graph that updates the graph data source when selected . My data has 3 columns and looks as such : The Country column contains the 4 countries in the United Kingdom and is used for creating the separate lines for each using the color parameter . I have 4 different dat... | 1 Country Average House Price ( £ ) Date0 Northern Ireland 47101.0 1992-04-011 Northern Ireland 49911.0 1992-07-012 Northern Ireland 50174.0 1992-10-013 Northern Ireland 46664.0 1993-01-014 Northern Ireland 48247.0 1993-04-01 lineplt = px.line ( data_frame = all_dwellings , x='Date ' , y='Average House Price ( £ ) ' , ... | Plotly : How to update plotly data using dropdown list for line graph ? |
Python | I would like to make the following sum given two lists : The result should be the sum of the every b element of a like : b [ 0 ] = 2 so the first sum result should be : sum ( a [ 0:2 ] ) b [ 1 ] = 3 so the second sum result should be : sum ( a [ 2:5 ] ) b [ 2 ] = 5 so the third sum result should be : sum ( a [ 5:10 ] )... | a = [ 0,1,2,3,4,5,6,7,8,9 ] b = [ 2,3,5 ] | Sums of variable size chunks of a list where sizes are given by other list |
Python | I am using Flask server with python.I have an integer pics_to_show . Every time a request is recieved , the user recieves pics_to_show integer . And pics_to_show gets decremented by 1.pics_to_show is an integer that ` s shared with all website users . I could make a database to save it , but I want something simpler an... | class GlobalSate : def __init__ ( self , path_to_file ) : self.path = path_to_file try : open ( path_to_file ) except FileNotFoundError : f = open ( path_to_file , ' x ' ) f.write ( ' { } ' ) def __getitem__ ( self , key ) : file = self.load_file ( ) data = json.loads ( file.read ( ) ) return data [ key ] def __setitem... | How to save and edit server rendering data ? |
Python | The function attribute do_something.n is incremented each time you call the function . It bothered me that I declared the attribute do_something.n=0 outside the function.I answered the question Using queue.PriorityQueue , not caring about comparisons using a `` function-attribute '' to provide a unique counter for usag... | def do_something ( ) : do_something.n += 1 return do_something.n # need to declare do_something.n before usign it , else # AttributeError : 'function ' object has no attribute ' n ' # on first call of do_something ( ) occuresdo_something.n = 0for _ in range ( 10 ) : print ( do_something ( ) ) # prints 1 to 10 | Is there a way to add an attribute to a function as part of the function definition ? |
Python | Why does printing an exception instance print the value of exc.args instead of representing exc directly ? The docs call it a convenience but it 's actually an inconvenience in practice.Ca n't tell the difference between *args and a tuple : Ca n't reliably discern type : And the lovely `` invisible '' exception : Which... | > > > print ( Exception ( 123 , 456 ) ) ( 123 , 456 ) > > > print ( Exception ( ( 123 , 456 ) ) ) ( 123 , 456 ) > > > print ( Exception ( '123 ' ) ) 123 > > > print ( Exception ( 123 ) ) 123 > > > print ( Exception ( ) ) > > > > > > class MyError ( Exception ) : ... `` '' '' an error in MyLibrary '' '' '' ... > > > pri... | Why does Exception proxy __str__ onto the args ? |
Python | I 'm using a bidirectional association_proxy to associate properties Group.members and User.groups . I 'm having issues with removing a member from Group.members . In particular , Group.members.remove will successfully remove an entry from Group.members , but will leave a None in place of the corresponding entry in Use... | import sqlalchemy as safrom sqlalchemy.orm import Sessionfrom sqlalchemy.ext.associationproxy import association_proxyfrom sqlalchemy.ext.declarative import declarative_baseBase = declarative_base ( ) class Group ( Base ) : __tablename__ = 'group ' id = sa.Column ( sa.Integer , autoincrement=True , primary_key=True ) n... | Automagically propagating deletion when using a bidirectional association_proxy |
Python | I have 3 matrices ( np arrays ) : A is of shape ( n , m ) ; B is of shape ( m , k ) ; and C is of shape ( n , k ) Matrix C has only values from the set { -1,0,1 } and it 's an `` indicator '' of some sort : if C [ i , j ] ==1 then I want to add the i-th row of A to the j-th column of b ; and if C [ i , j ] == ( -1 ) th... | C = np.array ( [ [ -1 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , -1 ] , [ 0 , 0 , 0 , 0 , -1 ] , [ -1 , 0 , 0 , 1 , 1 ] ] ) a , b = np.where ( C==1 ) # here a= [ 0,3,3 ] and b= [ 4,3,4 ] A [ a , : ] = [ [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] , [ 3 , 3 , 3 , 3 , 3 , 3 , 3 ] , [ 3 , 3 , 3 , 3 , 3 , 3 , 3 ] ] B [ : ,b ] += A [ a ] # B ... | numpy summing matrix-rows by indices |
Python | I 'm trying to fetch some numbers from a webpage using requests . The numbers available in there are in images . The script I 've written so far can show the numbers as I 've used PIL library but ca n't print them.website addressNumbers visible in there just above the submit button are like : I 've tried so far : How c... | import ioimport requestsfrom PIL import Imagefrom bs4 import BeautifulSoupfrom urllib.parse import urljoinbase = 'http : //horoscope.horoscopezen.com/'url = 'http : //horoscope.horoscopezen.com/archive2.asp ? day=2 & month=1 & year=2022 & sign=1 # .Xy07M4oza1v'def get_numbers ( link ) : r = requests.get ( link ) soup =... | Ca n't fetch some numbers from a website using requests |
Python | I have this Python 3 pseudo-code : Now , I am kind of annoyed at the long signature and repetition in f2 ( ) and would like to encapsulate that into f1 ( ) : Now , my question is : if I run f1 ( ) a thousand times , does the interpreter have to parse f2 ( ) a thousand times or is it smart enough to create a reusable re... | def f1 ( ) : a , b , c , d , e , f = some_other_fn ( ) if ( condition ) : f2 ( a , b , c , d , e , f ) def f2 ( a , b , c , d , e , f ) : complex_set_of_operations_with ( a , b , c , d , e , f ) for i in range ( 1000 ) : f ( 1 ) def f1 ( ) : def f2 ( ) : complex_set_of_operations_with ( a , b , c , d , e , f ) a , b , ... | Python : encapsulation in frequently called function |
Python | Normally numpy.var ( ) is different than numpy.nanvar ( ) when there are missing values , the same for numpy.std ( ) and numpy.nanstd ( ) . However : Results : Why are both the same ? There is nothing about missing values in the documentation of np.var ( ) or np.std ( ) . | df = pd.DataFrame ( { ' A ' : [ 1,2,3,4,5,6,7,8,9,10 , np.NaN , np.NaN , np.NaN ] } ) print ( `` np.var ( ) `` + `` : `` + str ( np.var ( df [ `` A '' ] ) ) ) print ( `` np.nanvar ( ) `` + `` : `` + str ( np.nanvar ( df [ `` A '' ] ) ) ) print ( `` np.std ( ) `` + `` : `` + str ( np.std ( df [ `` A '' ] ) ) ) print ( `... | nanfunctions and regular functions behaving the same on Pandas type |
Python | Why does n't this work ? The modified message is not used , even though it remains on the exception instance . Is there a working pattern for the above ? Behaviour should be like my current workaround below : I 'm aware of exception chaining in python3 , it looks nice but unfortunately does n't work in python2 . So wha... | try : 1/0except ZeroDivisionError as e : e.message += ' , you fool ! ' raise try : 1/0except ZeroDivisionError as e : args = e.args if not args : arg0 = `` else : arg0 = args [ 0 ] arg0 += ' , you fool ! ' e.args = ( arg0 , ) + args [ 1 : ] raise | Why does n't it work to append information in the exception message ? |
Python | I try to restrict the 'parameter ' type to be int or list like the function ' f ' below . However , Pycharm does not show a warning at the line f ( `` weewfwef '' ) about wrong parameter type , which means this ( parameter : [ int , list ] ) is not correct.In Python , is it possible to restrict the type of a python fun... | def f ( parameter : [ int , list ] ) : if len ( str ( parameter ) ) < = 3 : return 3 else : return [ 1 ] if __name__ == '__main__ ' : f ( `` weewfwef '' ) | In Python , is it possible to restrict the type of a function parameter to two possible types ? |
Python | I am trying to create a countdown with a circle . The circle will show how much time has passed compared to the amount of time given . So if the countdown is 10 seconds and 5 have passed , half circle will have been drawn . I 've come up with this code : So fps = 60 and in each frame I am drawing 2 * pi / countdown * f... | from math import piimport pygamepygame.init ( ) ( x , y ) = ( 800 , 600 ) screen = pygame.display.set_mode ( ( x , y ) ) clock = pygame.time.Clock ( ) radius = 50 # Just to place the circle in the center later ontop_left_corner = ( ( x / 2 ) - ( radius / 2 ) , ( y / 2 ) - ( radius / 2 ) ) outer_rect = pygame.Rect ( top... | Complete drawing a circle in a specific amount of time |
Python | Normally , if you attempt to assign past the end of an array in numpy , the non-existent elements are disregarded.However , the same operation entirely past the end of the array `` succeeds '' if only one element is assigned : This only works if the RHS has one element : Why is this the case ? How is it possible not to... | > > > x = np.zeros ( 5 ) > > > x [ 3:6 ] = np.arange ( 5 ) [ 2:5 ] Traceback ( most recent call last ) : File `` < stdin > '' , line 1 , in < module > ValueError : could not broadcast input array from shape ( 3 ) into shape ( 2 ) > > > x [ 5 : ] = np.arange ( 5 ) [ 4 : ] > > > x [ 5 : ] = np.arange ( 5 ) [ 4:100 ] > > ... | Numpy strange behavior past end of array |
Python | While looking at the source code of the asyncore module I came across this method . I 'll include it here without context , as it seems to be quite self contained : My question : Why is num_sent first set to 0 , but then immediately set again to another value ? If i 'd found this anywhere but in the python source code ... | def initiate_send ( self ) : num_sent = 0 num_sent = dispatcher.send ( self , self.out_buffer [ :512 ] ) self.out_buffer = self.out_buffer [ num_sent : ] | Why give a local variable an initial value immediately before assigning to it ? |
Python | I want to remove vowels in a string , for simplicity I have only included small letters in below codethis is working fine , however i am wondering how to approach the scenario where I want to also remove y in a string including vowels if it has any vowel to the left or righte.g after running the function on `` may '' i... | for x in `` aeiou '' : st = st.replace ( i , '' '' ) return st | removing `` y '' immediately before or after any vowel in a string in python |
Python | I am struggling with this little thingy . Suppose : output something like : Zipping right now : How do I achieve a cyclic zipping on values ? I can achieve this long way having multi-loops . One-liner would be cool : D . | field_name = [ 'name ' , 'age ' , 'sex ' ] field_values = [ 'john ' , '24 ' , 'M ' , 'jane ' , '26 ' , ' F ' ] { 'name ' : [ 'john ' , 'jane ' ] , 'age ' : [ '24 ' , '26 ' ] , 'sex ' : [ 'M ' , ' F ' ] } dict_sample_fields = dict ( zip ( field_name , field_value ) ) # output { 'name ' : 'john ' , 'age ' : '24 ' , 'sex ... | Zipping two arrays of n and 2n length to form a dictionary |
Python | I 'm migrating an application that formerly ran on IBM 's DoCloud to their new API based off of Watson . Since our application does n't have data formatted in CSV nor a separation between the model and data layers it seemed simpler to upload an LP file along with a model file that reads the LP file and solves it . I ca... | import osimport sysfrom os.path import splitextimport pandasfrom docplex.mp.model_reader import ModelReaderfrom docplex.util.environment import get_environmentfrom six import iteritemsdef loadModelFiles ( ) : `` '' '' Load the input CSVs and extract the model and param data from it `` '' '' env = get_environment ( ) in... | IBM Watson CPLEX Shows no Variables , no Solution when solving LP file |
Python | I have a code understanding problem related to python : I ca n't figure out how are those two 'for ' supposed to work.Sadly the command reference does n't show such an usage example , and I ca n't really tell if it -really- means that one for is the left side assignment of the other ? Additionally , what could the bott... | def convex_hull ( pts ) : `` '' '' Returns the points on the convex hull of pts in CCW order . '' '' '' for m in ( 2 ** ( 2 ** t ) for t in xrange ( len ( pts ) ) ) : hulls = [ _graham_scan ( pts [ i : i + m ] ) for i in xrange ( 0 , len ( pts ) , m ) ] //more code | Python conversion madness |
Python | Given an input text arrayshould be converted to a JSONAlthough this is a simple algorithm , I 'm forced to create temporary variables which is usually considered non-pythonic.The code with ugly temporary variablesCan i make my code less ugly and accomplish the same without having to create many temporary variables in p... | input_array = [ 'JUNK ' , 'Mon ' , 'JUNK ' , '10am ' , 'JUNK ' , '- ' , ' 5pm ' , '6pm ' , '- ' , '9pm ' , 'JUNK ' , 'Tue ' , '10am ' , '- ' , 'JUNK ' , '5pm ' ] [ { `` weekday_name '' : `` monday '' , `` starting_time '' : `` 10am '' , `` ending_time '' : `` 5pm '' } , { `` weekday_name '' : `` monday '' , `` starting... | python algorithm to be done in a pythonic fashion ? |
Python | Say I have a list of strings and a dictionary specifying replacements : E.g . and a list of strings , where each string can possibly include keys from the above dictionary , e.g : How can I apply the replacements to the list ? What would be a Pythonic way to do this ? | my_replacements = { ' 1/2 ' : 'half ' , ' 1/4 ' : 'quarter ' , ' 3/4 ' : 'three quarters ' } [ ' I own 1/2 bottle ' , 'Give me 3/4 of the profit ' ] | Applying a dictionary of string replacements to a list of strings |
Python | The code below worked with the previous csv that I used , both csv 's have the same amount of columns , and the columns have the same name.Data for the csv that worked hereData for csv that didnt hereWhat does this error mean ? Why am I getting this error ? Error | from pandas import read_csvfrom pandas import DataFramefrom pandas import Grouperfrom matplotlib import pyplotseries = read_csv ( 'carringtonairtemp.csv ' , header=0 , index_col=0 , parse_dates=True , squeeze=True ) groups = series.groupby ( Grouper ( freq= ' A ' ) ) years = DataFrame ( ) for name , group in groups : y... | How to convert a dataframe from long to wide , with values grouped by year in the index ? |
Python | I encountered a strange behavior of np.ndarray.tobytes ( ) that makes me doubt that it is working deterministically , at least for arrays of dtype=object.In the sample code , a list of mixed python objects ( [ 1 , [ 2 ] ] ) is first converted to a numpy array , and then transformed to a byte sequence using tobytes ( ) ... | import numpy as npprint ( np.array ( [ 1 , [ 2 ] ] ) .dtype ) # = > objectprint ( np.array ( [ 1 , [ 2 ] ] ) .tobytes ( ) ) # = > b'0h\xa3\t\x01\x00\x00\x00H { ! -\x01\x00\x00\x00'print ( np.array ( [ 1 , [ 2 ] ] ) .tobytes ( ) ) # = > b'0h\xa3\t\x01\x00\x00\x00\x88\x9d ) -\x01\x00\x00\x00 ' np.random.seed ( 42 ) ; pri... | How does np.ndarray.tobytes ( ) work for dtype `` object '' ? |
Python | I 'm trying to translate one of my Java projects to Python and I 'm having trouble with one certain line . The Java code is : What I think this is supposed to be in python is ... but I am getting an error SyntaxError : invalid syntax.How can I translate this Java to Python ? | if ( ++j == 9 ) return true ; if ( j += 1 ) ==9 : return True | ++i operator in Python |
Python | So i try to follow the documentation from django itself how to create CSV file , i copaste the code but it didnt work , it should be the browser download the somefilename.csv when it success , is there anything wrong ? or do i need to set something in settings.py ? Here 's the code ( HTML and Views ) Views.pyi just wan... | < div class= '' col-lg-12 '' > < div class= '' form-panel '' > < form action= '' # '' class= '' form-horizontal style-form '' id= '' form1 '' > < div class= '' form-group '' > < label class= '' control-label col-md-3 '' > Campaign Name < /label > < div class= '' col-md-3 col-xs-11 '' > < input id = `` campaign_name '' ... | Cant create CSV file with django although already copaste from the documentation |
Python | I 'm experimenting with python and am stuck trying to understand the error messages in the context of what I am doing.I 'm playing around with comprehensions and trying to find a pattern to create a list/dictionary comprehension with more than one input set ( assuming this is possible ) : Note : Here the word input set... | from random import randintmydict = { k : 0 for k in range ( 10 ) } result = { randint ( 0,9 ) : v + 1 for v in mydict.values ( ) } from random import randintmydict = { k : 0 for k in range ( 10 ) } result = { k : v + 1 for k , v in ( randint ( 0,9 ) , mydict.values ( ) ) } result = { k : v + 1 for *v , k in ( mydict.va... | Comprehensions with multiple input sets |
Python | Is there a way to get the number of actual parameters passed to a functionwithout changing its signature to accept *args ? | def foo ( a , optional=42 ) : if ? ? ? ? print `` 1 arg '' else : print `` 2 args '' foo ( 11 ) # should print 1 argfoo ( 22 , 42 ) # should print 2 args | Number of actual function arguments |
Python | I have a dictionary contains lists of values and a list : I want to compare the value in the dictionary with the list1 and make a counter for the keys if the value of each key appeared in the list : the output should like this : here is my code : any help ? Thanks in advance | dict1= { 'first ' : [ 'hi ' , 'nice ' ] , 'second ' : [ 'night ' , 'moon ' ] } list1= [ 'nice ' , 'moon ' , 'hi ' ] first 2 second 1 count = 0 for list_item in list1 : for dict_v in dict1.values ( ) : if list_item.split ( ) == dict_v : count+= 1 print ( dict.keys , count ) | compare a list with values in dictionary |
Python | What is the most effective way to check if a list contains only empty values ( not if a list is empty , but a list of empty elements ) ? I am using the famously pythonic implicit booleaness method in a for loop : Anything better around ? | def checkEmpty ( lst ) : for element in lst : if element : return False break else : return True | Checking for lists of empty values |
Python | This problem arose from a failing test that refused to fail locally , and would only fail on our CI server.It turned out some rather dodgy object comparison was being unintentionally done.I 'm now rather curious as to why the behavior is so different between two installations of the same Python version ( 2.7.9 ) .This ... | import operatorclass Thing ( dict ) : def __int__ ( self , number ) : return self [ 'number ' ] def __gt__ ( self , other ) : return self [ 'number ' ] > otherthing = Thing ( { 'number ' : 2 } ) for o in [ operator.lt , operator.le , operator.eq , operator.ne , operator.ge , operator.gt ] : print o print o ( 0.01 , thi... | Inconsistent object comparison behaviour when inheriting from dict |
Python | Tiddlywiki uses internally a space-separated tags for making a list of tags . But it uses [ [ and ] ] to limit multi-word tags.That is , a list of foo , ram doo , bar and very cool becomes in tiddlywiki a string like that : How can I transform that into python list that look like : '' foo [ [ ram doo ] ] bar '' .split ... | `` foo [ [ ram doo ] ] bar [ [ very cool ] ] '' [ 'foo ' , 'ram doo ' , 'bar ' , 'very cool ' ] | Pass from tiddlywiki list to python list |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.