code_tokens
stringlengths
60
3.94k
label
int64
0
1
doc
stringlengths
16
98
docstring_tokens
stringlengths
0
1.41k
idx
stringlengths
13
17
code
stringlengths
87
6.4k
def get_buffer ( self , data_np , header , format , output = None ) : if not have_pil : raise Exception ( "Install PIL to use this method" ) image = PILimage . fromarray ( data_np ) buf = output if buf is None : buf = BytesIO ( ) image . save ( buf , format ) return buf
1
python image buffer save
Get image as a buffer in ( format ) . Format should be jpeg png etc .
cosqa-train-15500
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output if buf is None: buf = BytesIO() image.save(buf, format) return buf
def getScreenDims ( self ) : width = ale_lib . getScreenWidth ( self . obj ) height = ale_lib . getScreenHeight ( self . obj ) return ( width , height )
1
get screen resolution in python
returns a tuple that contains ( screen_width screen_height )
cosqa-train-15501
def getScreenDims(self): """returns a tuple that contains (screen_width,screen_height) """ width = ale_lib.getScreenWidth(self.obj) height = ale_lib.getScreenHeight(self.obj) return (width,height)
def is_same_shape ( self , other_im , check_channels = False ) : if self . height == other_im . height and self . width == other_im . width : if check_channels and self . channels != other_im . channels : return False return True return False
1
python image determine if two images are equivalent
Checks if two images have the same height and width ( and optionally channels ) .
cosqa-train-15502
def is_same_shape(self, other_im, check_channels=False): """ Checks if two images have the same height and width (and optionally channels). Parameters ---------- other_im : :obj:`Image` image to compare check_channels : bool whether or not to check equality of the channels Returns ------- bool True if the images are the same shape, False otherwise """ if self.height == other_im.height and self.width == other_im.width: if check_channels and self.channels != other_im.channels: return False return True return False
def unique_list_dicts ( dlist , key ) : return list ( dict ( ( val [ key ] , val ) for val in dlist ) . values ( ) )
0
get sorted keys with python dictionary
Return a list of dictionaries which are sorted for only unique entries .
cosqa-train-15503
def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """ return list(dict((val[key], val) for val in dlist).values())
def region_from_segment ( image , segment ) : x , y , w , h = segment return image [ y : y + h , x : x + w ]
0
python image segment overlay
given a segment ( rectangle ) and an image returns it s corresponding subimage
cosqa-train-15504
def region_from_segment(image, segment): """given a segment (rectangle) and an image, returns it's corresponding subimage""" x, y, w, h = segment return image[y:y + h, x:x + w]
def readwav ( filename ) : from scipy . io . wavfile import read as readwav samplerate , signal = readwav ( filename ) return signal , samplerate
1
get spectrogram from wav python
Read a WAV file and returns the data and sample rate
cosqa-train-15505
def readwav(filename): """Read a WAV file and returns the data and sample rate :: from spectrum.io import readwav readwav() """ from scipy.io.wavfile import read as readwav samplerate, signal = readwav(filename) return signal, samplerate
def url_read_text ( url , verbose = True ) : data = url_read ( url , verbose ) text = data . decode ( 'utf8' ) return text
0
get text from url python
r Directly reads text data from url
cosqa-train-15506
def url_read_text(url, verbose=True): r""" Directly reads text data from url """ data = url_read(url, verbose) text = data.decode('utf8') return text
def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , "src" ) ] + sys . path pass return
1
python include file in super directory
Sets up the python include paths to include src
cosqa-train-15507
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
def mean ( inlist ) : sum = 0 for item in inlist : sum = sum + item return sum / float ( len ( inlist ) )
0
get the average in a list using python
Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) .
cosqa-train-15508
def mean(inlist): """ Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist) """ sum = 0 for item in inlist: sum = sum + item return sum / float(len(inlist))
def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , "src" ) ] + sys . path pass return
1
python include files in other folders
Sets up the python include paths to include src
cosqa-train-15509
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
def end_block ( self ) : self . current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self . auto_added_line : self . writeln ( ) self . auto_added_line = True
0
python indentation after append
Ends an indentation block leaving an empty line afterwards
cosqa-train-15510
def end_block(self): """Ends an indentation block, leaving an empty line afterwards""" self.current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self.auto_added_line: self.writeln() self.auto_added_line = True
def find_nearest_index ( arr , value ) : arr = np . array ( arr ) index = ( abs ( arr - value ) ) . argmin ( ) return index
0
get the index of the minimum value in an array python
For a given value the function finds the nearest value in the array and returns its index .
cosqa-train-15511
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
def end_block ( self ) : self . current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self . auto_added_line : self . writeln ( ) self . auto_added_line = True
0
python indentation string next line
Ends an indentation block leaving an empty line afterwards
cosqa-train-15512
def end_block(self): """Ends an indentation block, leaving an empty line afterwards""" self.current_indent -= 1 # If we did not add a new line automatically yet, now it's the time! if not self.auto_added_line: self.writeln() self.auto_added_line = True
def argsort_indices ( a , axis = - 1 ) : a = np . asarray ( a ) ind = list ( np . ix_ ( * [ np . arange ( d ) for d in a . shape ] ) ) ind [ axis ] = a . argsort ( axis ) return tuple ( ind )
1
get the index while sorting array python descending
Like argsort but returns an index suitable for sorting the the original array even if that array is multidimensional
cosqa-train-15513
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def hstrlen ( self , name , key ) : with self . pipe as pipe : return pipe . hstrlen ( self . redis_key ( name ) , key )
1
get the length of dictioanry key python
Return the number of bytes stored in the value of key within hash name
cosqa-train-15514
def hstrlen(self, name, key): """ Return the number of bytes stored in the value of ``key`` within hash ``name`` """ with self.pipe as pipe: return pipe.hstrlen(self.redis_key(name), key)
def get_index_nested ( x , i ) : for ind in range ( len ( x ) ) : if i == x [ ind ] : return ind return - 1
1
python index of first match
Description : Returns the first index of the array ( vector ) x containing the value i . Parameters : x : one - dimensional array i : search value
cosqa-train-15515
def get_index_nested(x, i): """ Description: Returns the first index of the array (vector) x containing the value i. Parameters: x: one-dimensional array i: search value """ for ind in range(len(x)): if i == x[ind]: return ind return -1
def _get_column_by_db_name ( cls , name ) : return cls . _columns . get ( cls . _db_map . get ( name , name ) )
0
get the name of a column python
Returns the column mapped by db_field name
cosqa-train-15516
def _get_column_by_db_name(cls, name): """ Returns the column, mapped by db_field name """ return cls._columns.get(cls._db_map.get(name, name))
def __init__ ( self , capacity = 10 ) : super ( ) . __init__ ( ) self . _array = [ None ] * capacity self . _front = 0 self . _rear = 0
0
python initialize array of 10 size
Initialize python List with capacity of 10 or user given input . Python List type is a dynamic array so we have to restrict its dynamic nature to make it work like a static array .
cosqa-train-15517
def __init__(self, capacity=10): """ Initialize python List with capacity of 10 or user given input. Python List type is a dynamic array, so we have to restrict its dynamic nature to make it work like a static array. """ super().__init__() self._array = [None] * capacity self._front = 0 self._rear = 0
def get_previous_month ( self ) : end = utils . get_month_start ( ) - relativedelta ( days = 1 ) end = utils . to_datetime ( end ) start = utils . get_month_start ( end ) return start , end
0
get the next 3 months date for a date column in python
Returns date range for the previous full month .
cosqa-train-15518
def get_previous_month(self): """Returns date range for the previous full month.""" end = utils.get_month_start() - relativedelta(days=1) end = utils.to_datetime(end) start = utils.get_month_start(end) return start, end
def __init__ ( self ) : self . state = self . STATE_INITIALIZING self . state_start = time . time ( )
1
python initialize variable of an object
Initialize the state of the object
cosqa-train-15519
def __init__(self): """Initialize the state of the object""" self.state = self.STATE_INITIALIZING self.state_start = time.time()
def listified_tokenizer ( source ) : io_obj = io . StringIO ( source ) return [ list ( a ) for a in tokenize . generate_tokens ( io_obj . readline ) ]
1
get tokens of textfile in python
Tokenizes * source * and returns the tokens as a list of lists .
cosqa-train-15520
def listified_tokenizer(source): """Tokenizes *source* and returns the tokens as a list of lists.""" io_obj = io.StringIO(source) return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]
def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns
0
python inner functions and scope
Execute a normal python statement in user namespace .
cosqa-train-15521
def ex(self, cmd): """Execute a normal python statement in user namespace.""" with self.builtin_trap: exec cmd in self.user_global_ns, self.user_ns
def unique_element ( ll ) : seen = { } result = [ ] for item in ll : if item in seen : continue seen [ item ] = 1 result . append ( item ) return result
0
get unique items from list in python
returns unique elements from a list preserving the original order
cosqa-train-15522
def unique_element(ll): """ returns unique elements from a list preserving the original order """ seen = {} result = [] for item in ll: if item in seen: continue seen[item] = 1 result.append(item) return result
def prepend_line ( filepath , line ) : with open ( filepath ) as f : lines = f . readlines ( ) lines . insert ( 0 , line ) with open ( filepath , 'w' ) as f : f . writelines ( lines )
1
python insert a line to beginning of a file
Rewrite a file adding a line to its beginning .
cosqa-train-15523
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def _get_device_id ( self , bus ) : _dbus = bus . get ( SERVICE_BUS , PATH ) devices = _dbus . devices ( ) if self . device is None and self . device_id is None and len ( devices ) == 1 : return devices [ 0 ] for id in devices : self . _dev = bus . get ( SERVICE_BUS , DEVICE_PATH + "/%s" % id ) if self . device == self . _dev . name : return id return None
1
get usb device id python
Find the device id
cosqa-train-15524
def _get_device_id(self, bus): """ Find the device id """ _dbus = bus.get(SERVICE_BUS, PATH) devices = _dbus.devices() if self.device is None and self.device_id is None and len(devices) == 1: return devices[0] for id in devices: self._dev = bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % id) if self.device == self._dev.name: return id return None
def add_parent ( self , parent ) : parent . add_child ( self ) self . parent = parent return parent
0
python insert parent child
Adds self as child of parent then adds parent .
cosqa-train-15525
def add_parent(self, parent): """ Adds self as child of parent, then adds parent. """ parent.add_child(self) self.parent = parent return parent
def print ( * a ) : try : _print ( * a ) return a [ 0 ] if len ( a ) == 1 else a except : _print ( * a )
1
gettting none with printing a function python
print just one that returns what you give it instead of None
cosqa-train-15526
def print(*a): """ print just one that returns what you give it instead of None """ try: _print(*a) return a[0] if len(a) == 1 else a except: _print(*a)
def add_noise ( Y , sigma ) : return Y + np . random . normal ( 0 , sigma , Y . shape )
0
python inserting noise into independent variables
Adds noise to Y
cosqa-train-15527
def add_noise(Y, sigma): """Adds noise to Y""" return Y + np.random.normal(0, sigma, Y.shape)
def plot_target ( target , ax ) : ax . scatter ( target [ 0 ] , target [ 1 ] , target [ 2 ] , c = "red" , s = 80 )
1
give other color to scatter plot python
Ajoute la target au plot
cosqa-train-15528
def plot_target(target, ax): """Ajoute la target au plot""" ax.scatter(target[0], target[1], target[2], c="red", s=80)
def props ( cls ) : return { k : v for ( k , v ) in inspect . getmembers ( cls ) if type ( v ) is Argument }
0
python inspect functions args
Class method that returns all defined arguments within the class . Returns : A dictionary containing all action defined arguments ( if any ) .
cosqa-train-15529
def props(cls): """ Class method that returns all defined arguments within the class. Returns: A dictionary containing all action defined arguments (if any). """ return {k:v for (k, v) in inspect.getmembers(cls) if type(v) is Argument}
def are_in_interval ( s , l , r , border = 'included' ) : return numpy . all ( [ IntensityRangeStandardization . is_in_interval ( x , l , r , border ) for x in s ] )
0
given a list of ranges in python check if number
Checks whether all number in the sequence s lie inside the interval formed by l and r .
cosqa-train-15530
def are_in_interval(s, l, r, border = 'included'): """ Checks whether all number in the sequence s lie inside the interval formed by l and r. """ return numpy.all([IntensityRangeStandardization.is_in_interval(x, l, r, border) for x in s])
def get_public_members ( obj ) : return { attr : getattr ( obj , attr ) for attr in dir ( obj ) if not attr . startswith ( "_" ) and not hasattr ( getattr ( obj , attr ) , '__call__' ) }
0
python inspect properties of an object
Retrieves a list of member - like objects ( members or properties ) that are publically exposed .
cosqa-train-15531
def get_public_members(obj): """ Retrieves a list of member-like objects (members or properties) that are publically exposed. :param obj: The object to probe. :return: A list of strings. """ return {attr: getattr(obj, attr) for attr in dir(obj) if not attr.startswith("_") and not hasattr(getattr(obj, attr), '__call__')}
def format_time ( time ) : h , r = divmod ( time / 1000 , 3600 ) m , s = divmod ( r , 60 ) return "%02d:%02d:%02d" % ( h , m , s )
1
given number format striptime into hours and minutes python
Formats the given time into HH : MM : SS
cosqa-train-15532
def format_time(time): """ Formats the given time into HH:MM:SS """ h, r = divmod(time / 1000, 3600) m, s = divmod(r, 60) return "%02d:%02d:%02d" % (h, m, s)
def extract_vars_above ( * names ) : callerNS = sys . _getframe ( 2 ) . f_locals return dict ( ( k , callerNS [ k ] ) for k in names )
1
python inspect variables from calling frame
Extract a set of variables by name from another frame .
cosqa-train-15533
def extract_vars_above(*names): """Extract a set of variables by name from another frame. Similar to extractVars(), but with a specified depth of 1, so that names are exctracted exactly from above the caller. This is simply a convenience function so that the very common case (for us) of skipping exactly 1 frame doesn't have to construct a special dict for keyword passing.""" callerNS = sys._getframe(2).f_locals return dict((k,callerNS[k]) for k in names)
def b ( s ) : return s if isinstance ( s , bytes ) else s . encode ( locale . getpreferredencoding ( ) )
0
globally set encoding python
Encodes Unicode strings to byte strings if necessary .
cosqa-train-15534
def b(s): """ Encodes Unicode strings to byte strings, if necessary. """ return s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())
def from_dict ( cls , d ) : return cls ( * * { k : v for k , v in d . items ( ) if k in cls . ENTRIES } )
1
python instence object from dict
Create an instance from a dictionary .
cosqa-train-15535
def from_dict(cls, d): """Create an instance from a dictionary.""" return cls(**{k: v for k, v in d.items() if k in cls.ENTRIES})
def go_to_parent_directory ( self ) : self . chdir ( osp . abspath ( osp . join ( getcwd_or_home ( ) , os . pardir ) ) )
1
go to a parent directory python
Go to parent directory
cosqa-train-15536
def go_to_parent_directory(self): """Go to parent directory""" self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
def gettext ( self , string , domain = None , * * variables ) : t = self . get_translations ( domain ) return t . ugettext ( string ) % variables
1
googletrans to translate one column to a new column in english python
Translate a string with the current locale .
cosqa-train-15537
def gettext(self, string, domain=None, **variables): """Translate a string with the current locale.""" t = self.get_translations(domain) return t.ugettext(string) % variables
def MatrixInverse ( a , adj ) : return np . linalg . inv ( a if not adj else _adjoint ( a ) ) ,
1
python inverse matrix function
Matrix inversion op .
cosqa-train-15538
def MatrixInverse(a, adj): """ Matrix inversion op. """ return np.linalg.inv(a if not adj else _adjoint(a)),
def _get_local_ip ( ) : return set ( [ x [ 4 ] [ 0 ] for x in socket . getaddrinfo ( socket . gethostname ( ) , 80 , socket . AF_INET ) ] ) . pop ( )
1
grab local machine ip in python
Get the local ip of this device
cosqa-train-15539
def _get_local_ip(): """ Get the local ip of this device :return: Ip of this computer :rtype: str """ return set([x[4][0] for x in socket.getaddrinfo( socket.gethostname(), 80, socket.AF_INET )]).pop()
def __call__ ( self , args ) : window , ij = args return self . user_func ( srcs , window , ij , global_args ) , window
0
python invoke variable of other function
Execute the user function .
cosqa-train-15540
def __call__(self, args): """Execute the user function.""" window, ij = args return self.user_func(srcs, window, ij, global_args), window
def l2_norm ( params ) : flattened , _ = flatten ( params ) return np . dot ( flattened , flattened )
1
gradient of the l2 norm in python
Computes l2 norm of params by flattening them into a vector .
cosqa-train-15541
def l2_norm(params): """Computes l2 norm of params by flattening them into a vector.""" flattened, _ = flatten(params) return np.dot(flattened, flattened)
def _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items )
1
python is not none or not is none
Whether the item is a placeholder or contains a placeholder .
cosqa-train-15542
def _not_none(items): """Whether the item is a placeholder or contains a placeholder.""" if not isinstance(items, (tuple, list)): items = (items,) return all(item is not _none for item in items)
def connect ( self , A , B , distance = 1 ) : self . connect1 ( A , B , distance ) if not self . directed : self . connect1 ( B , A , distance )
1
graph undirected is connected python
Add a link from A and B of given distance and also add the inverse link if the graph is undirected .
cosqa-train-15543
def connect(self, A, B, distance=1): """Add a link from A and B of given distance, and also add the inverse link if the graph is undirected.""" self.connect1(A, B, distance) if not self.directed: self.connect1(B, A, distance)
def url_read_text ( url , verbose = True ) : data = url_read ( url , verbose ) text = data . decode ( 'utf8' ) return text
0
python is text a url
r Directly reads text data from url
cosqa-train-15544
def url_read_text(url, verbose=True): r""" Directly reads text data from url """ data = url_read(url, verbose) text = data.decode('utf8') return text
def draw_graph ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . graph_attr [ "rankdir" ] = "LR" A . draw ( filename , prog = "dot" )
0
graphy not display in python
Draw a networkx graph with Pygraphviz .
cosqa-train-15545
def draw_graph(G: nx.DiGraph, filename: str): """ Draw a networkx graph with Pygraphviz. """ A = to_agraph(G) A.graph_attr["rankdir"] = "LR" A.draw(filename, prog="dot")
def check_int ( integer ) : if not isinstance ( integer , str ) : return False if integer [ 0 ] in ( '-' , '+' ) : return integer [ 1 : ] . isdigit ( ) return integer . isdigit ( )
0
python isdigit saying undefined
Check if number is integer or not .
cosqa-train-15546
def check_int(integer): """ Check if number is integer or not. :param integer: Number as str :return: Boolean """ if not isinstance(integer, str): return False if integer[0] in ('-', '+'): return integer[1:].isdigit() return integer.isdigit()
def search_script_directory ( self , path ) : for subdir , dirs , files in os . walk ( path ) : for file_name in files : if file_name . endswith ( ".py" ) : self . search_script_file ( subdir , file_name )
0
grep all python files
Recursively loop through a directory to find all python script files . When one is found it is analyzed for import statements : param path : string : return : generator
cosqa-train-15547
def search_script_directory(self, path): """ Recursively loop through a directory to find all python script files. When one is found, it is analyzed for import statements :param path: string :return: generator """ for subdir, dirs, files in os.walk(path): for file_name in files: if file_name.endswith(".py"): self.search_script_file(subdir, file_name)
def on_windows ( ) : if bjam . variable ( "NT" ) : return True elif bjam . variable ( "UNIX" ) : uname = bjam . variable ( "JAMUNAME" ) if uname and uname [ 0 ] . startswith ( "CYGWIN" ) : return True return False
1
python isn't running in cygwin
Returns true if running on windows whether in cygwin or not .
cosqa-train-15548
def on_windows (): """ Returns true if running on windows, whether in cygwin or not. """ if bjam.variable("NT"): return True elif bjam.variable("UNIX"): uname = bjam.variable("JAMUNAME") if uname and uname[0].startswith("CYGWIN"): return True return False
def quote ( self , s ) : if six . PY2 : from pipes import quote else : from shlex import quote return quote ( s )
0
handling single quote in string using python
Return a shell - escaped version of the string s .
cosqa-train-15549
def quote(self, s): """Return a shell-escaped version of the string s.""" if six.PY2: from pipes import quote else: from shlex import quote return quote(s)
def parse_timestamp ( timestamp ) : dt = dateutil . parser . parse ( timestamp ) return dt . astimezone ( dateutil . tz . tzutc ( ) )
0
python iso8601 timezone format
Parse ISO8601 timestamps given by github API .
cosqa-train-15550
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) )
1
have python line continue on to next line
Advances to next line .
cosqa-train-15551
def advance_one_line(self): """Advances to next line.""" current_line = self._current_token.line_number while current_line == self._current_token.line_number: self._current_token = ConfigParser.Token(*next(self._token_generator))
def generate_chunks ( string , num_chars ) : for start in range ( 0 , len ( string ) , num_chars ) : yield string [ start : start + num_chars ]
1
python iterate chunks of string
Yield num_chars - character chunks from string .
cosqa-train-15552
def generate_chunks(string, num_chars): """Yield num_chars-character chunks from string.""" for start in range(0, len(string), num_chars): yield string[start:start+num_chars]
def end_table_header ( self ) : if self . header : msg = "Table already has a header" raise TableError ( msg ) self . header = True self . append ( Command ( r'endhead' ) )
0
how add table to header doc python
r End the table header which will appear on every page .
cosqa-train-15553
def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead'))
def __iter__ ( self ) : for node in chain ( * imap ( iter , self . children ) ) : yield node yield self
0
python iterate over immediate children
Iterate through tree leaves first
cosqa-train-15554
def __iter__(self): """ Iterate through tree, leaves first following http://stackoverflow.com/questions/6914803/python-iterator-through-tree-with-list-of-children """ for node in chain(*imap(iter, self.children)): yield node yield self
def is_symbol ( string ) : return ( is_int ( string ) or is_float ( string ) or is_constant ( string ) or is_unary ( string ) or is_binary ( string ) or ( string == '(' ) or ( string == ')' ) )
0
how can i check if a character is in python
Return true if the string is a mathematical symbol .
cosqa-train-15555
def is_symbol(string): """ Return true if the string is a mathematical symbol. """ return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == '(') or (string == ')') )
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
1
python iterate regex matches
Generate all matches found within a string for a regex and yield each match as a string
cosqa-train-15556
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
def tab ( self , output ) : import csv csvwriter = csv . writer ( self . outfile , dialect = csv . excel_tab ) csvwriter . writerows ( output )
0
how can i export result to excel python toxlsx
Output data in excel - compatible tab - delimited format
cosqa-train-15557
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
def _skip_frame ( self ) : for line in self . _f : if line == 'ITEM: ATOMS\n' : break for i in range ( self . num_atoms ) : next ( self . _f )
0
python iterate through file skip
Skip the next time frame
cosqa-train-15558
def _skip_frame(self): """Skip the next time frame""" for line in self._f: if line == 'ITEM: ATOMS\n': break for i in range(self.num_atoms): next(self._f)
def _change_height ( self , ax , new_value ) : for patch in ax . patches : current_height = patch . get_height ( ) diff = current_height - new_value # we change the bar height patch . set_height ( new_value ) # we recenter the bar patch . set_y ( patch . get_y ( ) + diff * .5 )
0
how can i fix the width of bar in bargraph matplotlib python
Make bars in horizontal bar chart thinner
cosqa-train-15559
def _change_height(self, ax, new_value): """Make bars in horizontal bar chart thinner""" for patch in ax.patches: current_height = patch.get_height() diff = current_height - new_value # we change the bar height patch.set_height(new_value) # we recenter the bar patch.set_y(patch.get_y() + diff * .5)
def json_iter ( path ) : with open ( path , 'r' ) as f : for line in f . readlines ( ) : yield json . loads ( line )
0
python iterate through json line by line
iterator for JSON - per - line in a file pattern
cosqa-train-15560
def json_iter (path): """ iterator for JSON-per-line in a file pattern """ with open(path, 'r') as f: for line in f.readlines(): yield json.loads(line)
def _clean_up_name ( self , name ) : for n in self . naughty : name = name . replace ( n , '_' ) return name
1
how can i remove name titles in python
Cleans up the name according to the rules specified in this exact function . Uses self . naughty a list of naughty characters .
cosqa-train-15561
def _clean_up_name(self, name): """ Cleans up the name according to the rules specified in this exact function. Uses self.naughty, a list of naughty characters. """ for n in self.naughty: name = name.replace(n, '_') return name
def group_by ( iterable , key_func ) : groups = ( list ( sub ) for key , sub in groupby ( iterable , key_func ) ) return zip ( groups , groups )
0
python iterator group by
Wrap itertools . groupby to make life easier .
cosqa-train-15562
def group_by(iterable, key_func): """Wrap itertools.groupby to make life easier.""" groups = ( list(sub) for key, sub in groupby(iterable, key_func) ) return zip(groups, groups)
def round_to_n ( x , n ) : return round ( x , - int ( np . floor ( np . log10 ( x ) ) ) + ( n - 1 ) )
0
how can i round decimals in python
Round to sig figs
cosqa-train-15563
def round_to_n(x, n): """ Round to sig figs """ return round(x, -int(np.floor(np.log10(x))) + (n - 1))
def next ( self ) : # File-like object. result = self . readline ( ) if result == self . _empty_buffer : raise StopIteration return result
1
python iterator not empty
This is to support iterators over a file - like object .
cosqa-train-15564
def next (self): # File-like object. """This is to support iterators over a file-like object. """ result = self.readline() if result == self._empty_buffer: raise StopIteration return result
def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )
0
how can i use cheang round to float in python
Given a float returns a rounded int . Should give the same result on both Py2 / 3
cosqa-train-15565
def intround(value): """Given a float returns a rounded int. Should give the same result on both Py2/3 """ return int(decimal.Decimal.from_float( value).to_integral_value(decimal.ROUND_HALF_EVEN))
def reset ( self ) : self . __iterator , self . __saved = itertools . tee ( self . __saved )
0
python iterator object support deletion
Resets the iterator to the start .
cosqa-train-15566
def reset(self): """ Resets the iterator to the start. Any remaining values in the current iteration are discarded. """ self.__iterator, self.__saved = itertools.tee(self.__saved)
def web ( host , port ) : from . webserver . web import get_app get_app ( ) . run ( host = host , port = port )
0
how can run python script with web
Start web application
cosqa-train-15567
def web(host, port): """Start web application""" from .webserver.web import get_app get_app().run(host=host, port=port)
def assert_single_element ( iterable ) : it = iter ( iterable ) first_item = next ( it ) try : next ( it ) except StopIteration : return first_item raise ValueError ( "iterable {!r} has more than one element." . format ( iterable ) )
1
python iterator returns triplet i want just one of the elements
Get the single element of iterable or raise an error .
cosqa-train-15568
def assert_single_element(iterable): """Get the single element of `iterable`, or raise an error. :raise: :class:`StopIteration` if there is no element. :raise: :class:`ValueError` if there is more than one element. """ it = iter(iterable) first_item = next(it) try: next(it) except StopIteration: return first_item raise ValueError("iterable {!r} has more than one element.".format(iterable))
def strToBool ( val ) : if isinstance ( val , str ) : val = val . lower ( ) return val in [ 'true' , 'on' , 'yes' , True ]
0
how conveter 1 to boolean python
Helper function to turn a string representation of true into boolean True .
cosqa-train-15569
def strToBool(val): """ Helper function to turn a string representation of "true" into boolean True. """ if isinstance(val, str): val = val.lower() return val in ['true', 'on', 'yes', True]
def _fill ( self ) : try : self . _head = self . _iterable . next ( ) except StopIteration : self . _head = None
0
python iterator set back to beginning
Advance the iterator without returning the old head .
cosqa-train-15570
def _fill(self): """Advance the iterator without returning the old head.""" try: self._head = self._iterable.next() except StopIteration: self._head = None
def __get_xml_text ( root ) : txt = "" for e in root . childNodes : if ( e . nodeType == e . TEXT_NODE ) : txt += e . data return txt
1
how do i acess the text of xml using python
Return the text for the given root node ( xml . dom . minidom ) .
cosqa-train-15571
def __get_xml_text(root): """ Return the text for the given root node (xml.dom.minidom). """ txt = "" for e in root.childNodes: if (e.nodeType == e.TEXT_NODE): txt += e.data return txt
def iterparse ( source , events = ( 'end' , ) , remove_comments = True , * * kw ) : return ElementTree . iterparse ( source , events , SourceLineParser ( ) , * * kw )
0
python iterparse parse tag
Thin wrapper around ElementTree . iterparse
cosqa-train-15572
def iterparse(source, events=('end',), remove_comments=True, **kw): """Thin wrapper around ElementTree.iterparse""" return ElementTree.iterparse(source, events, SourceLineParser(), **kw)
def get_encoding ( binary ) : try : from chardet import detect except ImportError : LOGGER . error ( "Please install the 'chardet' module" ) sys . exit ( 1 ) encoding = detect ( binary ) . get ( 'encoding' ) return 'iso-8859-1' if encoding == 'CP949' else encoding
1
how do i check the encoding format of file python
Return the encoding type .
cosqa-train-15573
def get_encoding(binary): """Return the encoding type.""" try: from chardet import detect except ImportError: LOGGER.error("Please install the 'chardet' module") sys.exit(1) encoding = detect(binary).get('encoding') return 'iso-8859-1' if encoding == 'CP949' else encoding
def iter_with_last ( iterable ) : # Ensure it's an iterator and get the first field iterable = iter ( iterable ) prev = next ( iterable ) for item in iterable : # Lag by one item so I know I'm not at the end yield False , prev prev = item # Last item yield True , prev
0
python itertools last values
: return : generator of tuples ( isLastFlag item )
cosqa-train-15574
def iter_with_last(iterable): """ :return: generator of tuples (isLastFlag, item) """ # Ensure it's an iterator and get the first field iterable = iter(iterable) prev = next(iterable) for item in iterable: # Lag by one item so I know I'm not at the end yield False, prev prev = item # Last item yield True, prev
def conv_dict ( self ) : return dict ( integer = self . integer , real = self . real , no_type = self . no_type )
1
how do i create a dict type in python programmatically
dictionary of conversion
cosqa-train-15575
def conv_dict(self): """dictionary of conversion""" return dict(integer=self.integer, real=self.real, no_type=self.no_type)
def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )
1
python iunittest assert data type
Assert that a value must be a given type .
cosqa-train-15576
def _assert_is_type(name, value, value_type): """Assert that a value must be a given type.""" if not isinstance(value, value_type): if type(value_type) is tuple: types = ', '.join(t.__name__ for t in value_type) raise ValueError('{0} must be one of ({1})'.format(name, types)) else: raise ValueError('{0} must be {1}' .format(name, value_type.__name__))
def help_for_command ( command ) : help_text = pydoc . text . document ( command ) # remove backspaces return re . subn ( '.\\x08' , '' , help_text ) [ 0 ]
0
how do i get help for methods in python
Get the help text ( signature + docstring ) for a command ( function ) .
cosqa-train-15577
def help_for_command(command): """Get the help text (signature + docstring) for a command (function).""" help_text = pydoc.text.document(command) # remove backspaces return re.subn('.\\x08', '', help_text)[0]
def render_template ( env , filename , values = None ) : if not values : values = { } tmpl = env . get_template ( filename ) return tmpl . render ( values )
1
python jinja templates from string
Render a jinja template
cosqa-train-15578
def render_template(env, filename, values=None): """ Render a jinja template """ if not values: values = {} tmpl = env.get_template(filename) return tmpl.render(values)
def get_absolute_path ( * args ) : directory = os . path . dirname ( os . path . abspath ( __file__ ) ) return os . path . join ( directory , * args )
1
how do i make relative directory name in python
Transform relative pathnames into absolute pathnames .
cosqa-train-15579
def get_absolute_path(*args): """Transform relative pathnames into absolute pathnames.""" directory = os.path.dirname(os.path.abspath(__file__)) return os.path.join(directory, *args)
def render_template ( template_name , * * context ) : tmpl = jinja_env . get_template ( template_name ) context [ "url_for" ] = url_for return Response ( tmpl . render ( context ) , mimetype = "text/html" )
0
python jinja2 for index
Render a template into a response .
cosqa-train-15580
def render_template(template_name, **context): """Render a template into a response.""" tmpl = jinja_env.get_template(template_name) context["url_for"] = url_for return Response(tmpl.render(context), mimetype="text/html")
def execfile ( fname , variables ) : with open ( fname ) as f : code = compile ( f . read ( ) , fname , 'exec' ) exec ( code , variables )
0
how do you compile a text file in python
This is builtin in python2 but we have to roll our own on py3 .
cosqa-train-15581
def execfile(fname, variables): """ This is builtin in python2, but we have to roll our own on py3. """ with open(fname) as f: code = compile(f.read(), fname, 'exec') exec(code, variables)
async def join ( self , ctx , * , channel : discord . VoiceChannel ) : if ctx . voice_client is not None : return await ctx . voice_client . move_to ( channel ) await channel . connect ( )
1
python join a discord server
Joins a voice channel
cosqa-train-15582
async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
def gaussian_variogram_model ( m , d ) : psill = float ( m [ 0 ] ) range_ = float ( m [ 1 ] ) nugget = float ( m [ 2 ] ) return psill * ( 1. - np . exp ( - d ** 2. / ( range_ * 4. / 7. ) ** 2. ) ) + nugget
0
how do you determine the probability from a gaussian model in python
Gaussian model m is [ psill range nugget ]
cosqa-train-15583
def gaussian_variogram_model(m, d): """Gaussian model, m is [psill, range, nugget]""" psill = float(m[0]) range_ = float(m[1]) nugget = float(m[2]) return psill * (1. - np.exp(-d**2./(range_*4./7.)**2.)) + nugget
def _grammatical_join_filter ( l , arg = None ) : if not arg : arg = " and |, " try : final_join , initial_joins = arg . split ( "|" ) except ValueError : final_join = arg initial_joins = ", " return grammatical_join ( l , initial_joins , final_join )
1
python join a string list with grammar
: param l : List of strings to join : param arg : A pipe - separated list of final_join ( and ) and initial_join ( ) strings . For example : return : A string that grammatically concatenates the items in the list .
cosqa-train-15584
def _grammatical_join_filter(l, arg=None): """ :param l: List of strings to join :param arg: A pipe-separated list of final_join (" and ") and initial_join (", ") strings. For example :return: A string that grammatically concatenates the items in the list. """ if not arg: arg = " and |, " try: final_join, initial_joins = arg.split("|") except ValueError: final_join = arg initial_joins = ", " return grammatical_join(l, initial_joins, final_join)
def fast_exit ( code ) : sys . stdout . flush ( ) sys . stderr . flush ( ) os . _exit ( code )
1
how do you exit from python code
Exit without garbage collection this speeds up exit by about 10ms for things like bash completion .
cosqa-train-15585
def fast_exit(code): """Exit without garbage collection, this speeds up exit by about 10ms for things like bash completion. """ sys.stdout.flush() sys.stderr.flush() os._exit(code)
def flatten_dict_join_keys ( dct , join_symbol = " " ) : return dict ( flatten_dict ( dct , join = lambda a , b : a + join_symbol + b ) )
1
python join for dict
Flatten dict with defined key join symbol .
cosqa-train-15586
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def get_unique_indices ( df , axis = 1 ) : return dict ( zip ( df . columns . names , dif . columns . levels ) )
1
how do you get unique values of index python
cosqa-train-15587
def get_unique_indices(df, axis=1): """ :param df: :param axis: :return: """ return dict(zip(df.columns.names, dif.columns.levels))
def flatten_dict_join_keys ( dct , join_symbol = " " ) : return dict ( flatten_dict ( dct , join = lambda a , b : a + join_symbol + b ) )
1
python join items in dict
Flatten dict with defined key join symbol .
cosqa-train-15588
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def lcumsum ( inlist ) : newlist = copy . deepcopy ( inlist ) for i in range ( 1 , len ( newlist ) ) : newlist [ i ] = newlist [ i ] + newlist [ i - 1 ] return newlist
0
how do you tell python to take a sum of a list
Returns a list consisting of the cumulative sum of the items in the passed list .
cosqa-train-15589
def lcumsum (inlist): """ Returns a list consisting of the cumulative sum of the items in the passed list. Usage: lcumsum(inlist) """ newlist = copy.deepcopy(inlist) for i in range(1,len(newlist)): newlist[i] = newlist[i] + newlist[i-1] return newlist
def get_join_cols ( by_entry ) : left_cols = [ ] right_cols = [ ] for col in by_entry : if isinstance ( col , str ) : left_cols . append ( col ) right_cols . append ( col ) else : left_cols . append ( col [ 0 ] ) right_cols . append ( col [ 1 ] ) return left_cols , right_cols
0
python join list only recongnize one seprator
helper function used for joins builds left and right join list for join function
cosqa-train-15590
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right_cols.append(col[1]) return left_cols, right_cols
def _comment ( string ) : lines = [ line . strip ( ) for line in string . splitlines ( ) ] return "# " + ( "%s# " % linesep ) . join ( lines )
0
how do you turn blocks of code to comments in python
return string as a comment
cosqa-train-15591
def _comment(string): """return string as a comment""" lines = [line.strip() for line in string.splitlines()] return "# " + ("%s# " % linesep).join(lines)
def unique ( iterable ) : seen = set ( ) return [ x for x in iterable if x not in seen and not seen . add ( x ) ]
1
how does python set avoid duplicates
Returns a list copy in which each item occurs only once ( in - order ) .
cosqa-train-15592
def unique(iterable): """ Returns a list copy in which each item occurs only once (in-order). """ seen = set() return [x for x in iterable if x not in seen and not seen.add(x)]
def json_dumps ( self , obj ) : return json . dumps ( obj , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) )
1
python json dump in order
Serializer for consistency
cosqa-train-15593
def json_dumps(self, obj): """Serializer for consistency""" return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
def join ( mapping , bind , values ) : return [ ' ' . join ( [ six . text_type ( v ) for v in values if v is not None ] ) ]
0
how join lists and strings in python
Merge all the strings . Put space between them .
cosqa-train-15594
def join(mapping, bind, values): """ Merge all the strings. Put space between them. """ return [' '.join([six.text_type(v) for v in values if v is not None])]
def json_dumps ( self , obj ) : return json . dumps ( obj , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) )
0
python json dump nesting
Serializer for consistency
cosqa-train-15595
def json_dumps(self, obj): """Serializer for consistency""" return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
def kill ( self ) : if self . process : self . process . kill ( ) self . process . wait ( )
0
how kill a python execution windows
Kill the browser .
cosqa-train-15596
def kill(self): """Kill the browser. This is useful when the browser is stuck. """ if self.process: self.process.kill() self.process.wait()
def to_json ( obj ) : i = StringIO . StringIO ( ) w = Writer ( i , encoding = 'UTF-8' ) w . write_value ( obj ) return i . getvalue ( )
0
python json dumps without encoding
Return a json string representing the python object obj .
cosqa-train-15597
def to_json(obj): """Return a json string representing the python object obj.""" i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
0
how to access an object using its id python
Return a JSSObject for the element with ID id_
cosqa-train-15598
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
def parse_json ( filename ) : # Regular expression for comments comment_re = re . compile ( '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?' , re . DOTALL | re . MULTILINE ) with open ( filename ) as f : content = '' . join ( f . readlines ( ) ) ## Looking for comments match = comment_re . search ( content ) while match : # single line comment content = content [ : match . start ( ) ] + content [ match . end ( ) : ] match = comment_re . search ( content ) # Return json file return json . loads ( content )
0
python json file parse comment jstyleson
Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or / * ... * /
cosqa-train-15599
def parse_json(filename): """ Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or /* ... */ """ # Regular expression for comments comment_re = re.compile( '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE ) with open(filename) as f: content = ''.join(f.readlines()) ## Looking for comments match = comment_re.search(content) while match: # single line comment content = content[:match.start()] + content[match.end():] match = comment_re.search(content) # Return json file return json.loads(content)