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 _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val }
0
python dictionary exclude key
Removes dict keys which have have self as value .
cosqa-train-12800
def _remove_dict_keys_with_value(dict_, val): """Removes `dict` keys which have have `self` as value.""" return {k: v for k, v in dict_.items() if v is not val}
def get_object_as_string ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , list ) : return '\r\n\;' . join ( [ get_object_as_string ( item ) for item in obj ] ) attrs = vars ( obj ) as_string = ', ' . join ( "%s: %s" % item for item in attrs . items ( ) ) return as_string
1
best way to stringify python objecct
Converts any object to JSON - like readable format ready to be printed for debugging purposes : param obj : Any object : return : string
cosqa-train-12801
def get_object_as_string(obj): """ Converts any object to JSON-like readable format, ready to be printed for debugging purposes :param obj: Any object :return: string """ if isinstance(obj, str): return obj if isinstance(obj, list): return '\r\n\;'.join([get_object_as_string(item) for item in obj]) attrs = vars(obj) as_string = ', '.join("%s: %s" % item for item in attrs.items()) return as_string
def dict_to_html_attrs ( dict_ ) : res = ' ' . join ( '%s="%s"' % ( k , v ) for k , v in dict_ . items ( ) ) return res
1
python dictionary in html for key, value
Banana banana
cosqa-train-12802
def dict_to_html_attrs(dict_): """ Banana banana """ res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items()) return res
def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin
1
bin edges to be integers python
Convert axis coordinate to bin index .
cosqa-train-12803
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def get_from_human_key ( self , key ) : if key in self . _identifier_map : return self . _identifier_map [ key ] raise KeyError ( key )
1
python dictionary key reference
Return the key ( aka database value ) of a human key ( aka Python identifier ) .
cosqa-train-12804
def get_from_human_key(self, key): """Return the key (aka database value) of a human key (aka Python identifier).""" if key in self._identifier_map: return self._identifier_map[key] raise KeyError(key)
def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin
1
bin means python numpy
Convert axis coordinate to bin index .
cosqa-train-12805
def val_to_bin(edges, x): """Convert axis coordinate to bin index.""" ibin = np.digitize(np.array(x, ndmin=1), edges) - 1 return ibin
def get_single_item ( d ) : assert len ( d ) == 1 , 'Single-item dict must have just one item, not %d.' % len ( d ) return next ( six . iteritems ( d ) )
1
python dictionary only returningone element python
Get an item from a dict which contains just one item .
cosqa-train-12806
def get_single_item(d): """Get an item from a dict which contains just one item.""" assert len(d) == 1, 'Single-item dict must have just one item, not %d.' % len(d) return next(six.iteritems(d))
def get_func_name ( func ) : func_name = getattr ( func , '__name__' , func . __class__ . __name__ ) module_name = func . __module__ if module_name is not None : module_name = func . __module__ return '{}.{}' . format ( module_name , func_name ) return func_name
1
build function name dynamically python
Return a name which includes the module name and function name .
cosqa-train-12807
def get_func_name(func): """Return a name which includes the module name and function name.""" func_name = getattr(func, '__name__', func.__class__.__name__) module_name = func.__module__ if module_name is not None: module_name = func.__module__ return '{}.{}'.format(module_name, func_name) return func_name
def _select_features ( example , feature_list = None ) : feature_list = feature_list or [ "inputs" , "targets" ] return { f : example [ f ] for f in feature_list }
1
python dictionary select and graph feature
Select a subset of features from the example dict .
cosqa-train-12808
def _select_features(example, feature_list=None): """Select a subset of features from the example dict.""" feature_list = feature_list or ["inputs", "targets"] return {f: example[f] for f in feature_list}
def b2u ( string ) : if ( isinstance ( string , bytes ) or ( PY2 and isinstance ( string , str ) ) ) : return string . decode ( 'utf-8' ) return string
1
bytes to string utf8, python
bytes to unicode
cosqa-train-12809
def b2u(string): """ bytes to unicode """ if (isinstance(string, bytes) or (PY2 and isinstance(string, str))): return string.decode('utf-8') return string
def pop ( self , key ) : if key in self . _keys : self . _keys . remove ( key ) super ( ListDict , self ) . pop ( key )
1
python dictionary, remove key
Remove key from dict and return value .
cosqa-train-12810
def pop (self, key): """Remove key from dict and return value.""" if key in self._keys: self._keys.remove(key) super(ListDict, self).pop(key)
def cpp_prog_builder ( build_context , target ) : yprint ( build_context . conf , 'Build CppProg' , target ) workspace_dir = build_context . get_workspace ( 'CppProg' , target . name ) build_cpp ( build_context , target , target . compiler_config , workspace_dir )
1
c++ calll python build
Build a C ++ binary executable
cosqa-train-12811
def cpp_prog_builder(build_context, target): """Build a C++ binary executable""" yprint(build_context.conf, 'Build CppProg', target) workspace_dir = build_context.get_workspace('CppProg', target.name) build_cpp(build_context, target, target.compiler_config, workspace_dir)
def str_dict ( some_dict ) : return { str ( k ) : str ( v ) for k , v in some_dict . items ( ) }
1
python dictonary to string to dict
Convert dict of ascii str / unicode to dict of str if necessary
cosqa-train-12812
def str_dict(some_dict): """Convert dict of ascii str/unicode to dict of str, if necessary""" return {str(k): str(v) for k, v in some_dict.items()}
def total_seconds ( td ) : secs = td . seconds + td . days * 24 * 3600 if td . microseconds : secs += 1 return secs
1
caculating seconds from number of days using datetime in python
convert a timedelta to seconds .
cosqa-train-12813
def total_seconds(td): """convert a timedelta to seconds. This is patterned after timedelta.total_seconds, which is only available in python 27. Args: td: a timedelta object. Returns: total seconds within a timedelta. Rounded up to seconds. """ secs = td.seconds + td.days * 24 * 3600 if td.microseconds: secs += 1 return secs
def calculate_delay ( original , delay ) : original = datetime . strptime ( original , '%H:%M' ) delayed = datetime . strptime ( delay , '%H:%M' ) diff = delayed - original return diff . total_seconds ( ) // 60
1
python diffrent deltatime minutes
Calculate the delay
cosqa-train-12814
def calculate_delay(original, delay): """ Calculate the delay """ original = datetime.strptime(original, '%H:%M') delayed = datetime.strptime(delay, '%H:%M') diff = delayed - original return diff.total_seconds() // 60
def obj_to_string ( obj , top = True ) : obj = prepare_for_json_encoding ( obj ) if type ( obj ) == six . text_type : return obj return json . dumps ( obj )
0
cahng to str type python
Turn an arbitrary object into a unicode string . If complex ( dict / list / tuple ) will be json - encoded .
cosqa-train-12815
def obj_to_string(obj, top=True): """ Turn an arbitrary object into a unicode string. If complex (dict/list/tuple), will be json-encoded. """ obj = prepare_for_json_encoding(obj) if type(obj) == six.text_type: return obj return json.dumps(obj)
def build_docs ( directory ) : os . chdir ( directory ) process = subprocess . Popen ( [ "make" , "html" ] , cwd = directory ) process . communicate ( )
1
python dir doc command
Builds sphinx docs from a given directory .
cosqa-train-12816
def build_docs(directory): """Builds sphinx docs from a given directory.""" os.chdir(directory) process = subprocess.Popen(["make", "html"], cwd=directory) process.communicate()
def glog ( x , l = 2 ) : return np . log ( ( x + np . sqrt ( x ** 2 + l ** 2 ) ) / 2 ) / np . log ( l )
1
calc a log distribution in python
Generalised logarithm
cosqa-train-12817
def glog(x,l = 2): """ Generalised logarithm :param x: number :param p: number added befor logarithm """ return np.log((x+np.sqrt(x**2+l**2))/2)/np.log(l)
def is_writable_by_others ( filename ) : mode = os . stat ( filename ) [ stat . ST_MODE ] return mode & stat . S_IWOTH
1
python dir is writable
Check if file or directory is world writable .
cosqa-train-12818
def is_writable_by_others(filename): """Check if file or directory is world writable.""" mode = os.stat(filename)[stat.ST_MODE] return mode & stat.S_IWOTH
def angle ( vec1 , vec2 ) : dot_vec = dot ( vec1 , vec2 ) mag1 = vec1 . length ( ) mag2 = vec2 . length ( ) result = dot_vec / ( mag1 * mag2 ) return math . acos ( result )
0
calculate angle between two vectors python
Returns the angle between two vectors
cosqa-train-12819
def angle(vec1, vec2): """Returns the angle between two vectors""" dot_vec = dot(vec1, vec2) mag1 = vec1.length() mag2 = vec2.length() result = dot_vec / (mag1 * mag2) return math.acos(result)
def _distance ( coord1 , coord2 ) : xdist = coord1 [ 0 ] - coord2 [ 0 ] ydist = coord1 [ 1 ] - coord2 [ 1 ] return sqrt ( xdist * xdist + ydist * ydist )
1
calculate distance between two geo locations python
Return the distance between two points coord1 and coord2 . These parameters are assumed to be ( x y ) tuples .
cosqa-train-12820
def _distance(coord1, coord2): """ Return the distance between two points, `coord1` and `coord2`. These parameters are assumed to be (x, y) tuples. """ xdist = coord1[0] - coord2[0] ydist = coord1[1] - coord2[1] return sqrt(xdist*xdist + ydist*ydist)
def log_no_newline ( self , msg ) : self . print2file ( self . logfile , False , False , msg )
1
python direct all print output to log file
print the message to the predefined log file without newline
cosqa-train-12821
def log_no_newline(self, msg): """ print the message to the predefined log file without newline """ self.print2file(self.logfile, False, False, msg)
def num_leaves ( tree ) : if tree . is_leaf : return 1 else : return num_leaves ( tree . left_child ) + num_leaves ( tree . right_child )
1
calculate number of nodes in all subtrees python
Determine the number of leaves in a tree
cosqa-train-12822
def num_leaves(tree): """Determine the number of leaves in a tree""" if tree.is_leaf: return 1 else: return num_leaves(tree.left_child) + num_leaves(tree.right_child)
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 discord join voice channel bot
Joins a voice channel
cosqa-train-12823
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 get_table_width ( table ) : columns = transpose_table ( prepare_rows ( table ) ) widths = [ max ( len ( cell ) for cell in column ) for column in columns ] return len ( '+' + '|' . join ( '-' * ( w + 2 ) for w in widths ) + '+' )
1
calculate table columns width python
Gets the width of the table that would be printed . : rtype : int
cosqa-train-12824
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
def conv_block ( inputs , filters , dilation_rates_and_kernel_sizes , * * kwargs ) : return conv_block_internal ( conv , inputs , filters , dilation_rates_and_kernel_sizes , * * kwargs )
1
python disk based convolution
A block of standard 2d convolutions .
cosqa-train-12825
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs): """A block of standard 2d convolutions.""" return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
def _render_table ( data , fields = None ) : return IPython . core . display . HTML ( datalab . utils . commands . HtmlBuilder . render_table ( data , fields ) )
1
python display array in a table
Helper to render a list of dictionaries as an HTML display object .
cosqa-train-12826
def _render_table(data, fields=None): """ Helper to render a list of dictionaries as an HTML display object. """ return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields))
def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings )
1
calculate the average word length in a sentence python
Computes average length of words
cosqa-train-12827
def get_average_length_of_string(strings): """Computes average length of words :param strings: list of words :return: Average length of word on list """ if not strings: return 0 return sum(len(word) for word in strings) / len(strings)
def vector_distance ( a , b ) : a = np . array ( a ) b = np . array ( b ) return np . linalg . norm ( a - b )
1
python distance between two 2d vector
The Euclidean distance between two vectors .
cosqa-train-12828
def vector_distance(a, b): """The Euclidean distance between two vectors.""" a = np.array(a) b = np.array(b) return np.linalg.norm(a - b)
def haversine ( x ) : y = .5 * x y = np . sin ( y ) return y * y
1
calculating sin in angle python
Return the haversine of an angle
cosqa-train-12829
def haversine(x): """Return the haversine of an angle haversine(x) = sin(x/2)**2, where x is an angle in radians """ y = .5*x y = np.sin(y) return y*y
def hamming ( s , t ) : if len ( s ) != len ( t ) : raise ValueError ( 'Hamming distance needs strings of equal length.' ) return sum ( s_ != t_ for s_ , t_ in zip ( s , t ) )
1
python distance similary matrices text
Calculate the Hamming distance between two strings . From Wikipedia article : Iterative with two matrix rows .
cosqa-train-12830
def hamming(s, t): """ Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows. :param s: string 1 :type s: str :param t: string 2 :type s: str :return: Hamming distance :rtype: float """ if len(s) != len(t): raise ValueError('Hamming distance needs strings of equal length.') return sum(s_ != t_ for s_, t_ in zip(s, t))
def convert_ajax_data ( self , field_data ) : data = [ key for key , val in field_data . items ( ) if val ] return data
1
call a list of dictinaries data from ajax in python flask
Due to the way Angular organizes it model when this Form data is sent using Ajax then for this kind of widget the sent data has to be converted into a format suitable for Django s Form validation .
cosqa-train-12831
def convert_ajax_data(self, field_data): """ Due to the way Angular organizes it model, when this Form data is sent using Ajax, then for this kind of widget, the sent data has to be converted into a format suitable for Django's Form validation. """ data = [key for key, val in field_data.items() if val] return data
def get_future_days ( self ) : today = timezone . now ( ) . date ( ) return Day . objects . filter ( date__gte = today )
1
python django date past queryset today
Return only future Day objects .
cosqa-train-12832
def get_future_days(self): """Return only future Day objects.""" today = timezone.now().date() return Day.objects.filter(date__gte=today)
def _nth ( arr , n ) : try : return arr . iloc [ n ] except ( KeyError , IndexError ) : return np . nan
1
call nth column of array in python
Return the nth value of array
cosqa-train-12833
def _nth(arr, n): """ Return the nth value of array If it is missing return NaN """ try: return arr.iloc[n] except (KeyError, IndexError): return np.nan
def get_enum_documentation ( class_name , module_name , enum_class_object ) : documentation = """.. _{module_name}.{class_name}: ``enum {class_name}`` +++++++{plus}++ **module:** ``{module_name}``""" . format ( module_name = module_name , class_name = class_name , plus = '+' * len ( class_name ) , ) if enum_class_object . __doc__ and enum_class_object . __doc__ . strip ( ) : documentation += '\n\n{}' . format ( _clean_literals ( inspect . cleandoc ( enum_class_object . __doc__ ) ) ) documentation += '\n\nConstant Values:\n' for e in enum_class_object : documentation += '\n- ``{}`` (``{}``)' . format ( e . name , repr ( e . value ) . lstrip ( 'u' ) ) return documentation
0
python docstring enum members
cosqa-train-12834
def get_enum_documentation(class_name, module_name, enum_class_object): documentation = """.. _{module_name}.{class_name}: ``enum {class_name}`` +++++++{plus}++ **module:** ``{module_name}``""".format( module_name=module_name, class_name=class_name, plus='+' * len(class_name), ) if enum_class_object.__doc__ and enum_class_object.__doc__.strip(): documentation += '\n\n{}'.format(_clean_literals(inspect.cleandoc(enum_class_object.__doc__))) documentation += '\n\nConstant Values:\n' for e in enum_class_object: documentation += '\n- ``{}`` (``{}``)'.format(e.name, repr(e.value).lstrip('u')) return documentation
def main ( argv = sys . argv , stream = sys . stderr ) : args = parse_args ( argv ) suite = build_suite ( args ) runner = unittest . TextTestRunner ( verbosity = args . verbose , stream = stream ) result = runner . run ( suite ) return get_status ( result )
1
call unittest from a script python
Entry point for tappy command .
cosqa-train-12835
def main(argv=sys.argv, stream=sys.stderr): """Entry point for ``tappy`` command.""" args = parse_args(argv) suite = build_suite(args) runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream) result = runner.run(suite) return get_status(result)
def fill_document ( doc ) : with doc . create ( Section ( 'A section' ) ) : doc . append ( 'Some regular text and some ' ) doc . append ( italic ( 'italic text. ' ) ) with doc . create ( Subsection ( 'A subsection' ) ) : doc . append ( 'Also some crazy characters: $&#{}' )
1
python docx add section to each page
Add a section a subsection and some text to the document .
cosqa-train-12836
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def subn_filter ( s , find , replace , count = 0 ) : return re . gsub ( find , replace , count , s )
1
calling replace in python multiple times
A non - optimal implementation of a regex filter
cosqa-train-12837
def subn_filter(s, find, replace, count=0): """A non-optimal implementation of a regex filter""" return re.gsub(find, replace, count, s)
def fill_document ( doc ) : with doc . create ( Section ( 'A section' ) ) : doc . append ( 'Some regular text and some ' ) doc . append ( italic ( 'italic text. ' ) ) with doc . create ( Subsection ( 'A subsection' ) ) : doc . append ( 'Also some crazy characters: $&#{}' )
1
python docx number a section
Add a section a subsection and some text to the document .
cosqa-train-12838
def fill_document(doc): """Add a section, a subsection and some text to the document. :param doc: the document :type doc: :class:`pylatex.document.Document` instance """ with doc.create(Section('A section')): doc.append('Some regular text and some ') doc.append(italic('italic text. ')) with doc.create(Subsection('A subsection')): doc.append('Also some crazy characters: $&#{}')
def uncamel ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
1
camel naming convention for python
Transform CamelCase naming convention into C - ish convention .
cosqa-train-12839
def uncamel(name): """Transform CamelCase naming convention into C-ish convention.""" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def update_redirect ( self ) : page_history = Stack ( session . get ( "page_history" , [ ] ) ) page_history . push ( request . url ) session [ "page_history" ] = page_history . to_json ( )
1
python don't save history
Call it on your own endpoint s to update the back history navigation . If you bypass it the next submit or back will go over it .
cosqa-train-12840
def update_redirect(self): """ Call it on your own endpoint's to update the back history navigation. If you bypass it, the next submit or back will go over it. """ page_history = Stack(session.get("page_history", [])) page_history.push(request.url) session["page_history"] = page_history.to_json()
def execfile ( fname , variables ) : with open ( fname ) as f : code = compile ( f . read ( ) , fname , 'exec' ) exec ( code , variables )
0
can i compile python cod
This is builtin in python2 but we have to roll our own on py3 .
cosqa-train-12841
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)
def dot_product ( self , other ) : return self . x * other . x + self . y * other . y
1
python dot product implementation
Return the dot product of the given vectors .
cosqa-train-12842
def dot_product(self, other): """ Return the dot product of the given vectors. """ return self.x * other.x + self.y * other.y
def return_letters_from_string ( text ) : out = "" for letter in text : if letter . isalpha ( ) : out += letter return out
1
can i grab each letter in a string python
Get letters from string only .
cosqa-train-12843
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def resize_by_area ( img , size ) : return tf . to_int64 ( tf . image . resize_images ( img , [ size , size ] , tf . image . ResizeMethod . AREA ) )
1
python downsize image antialias
image resize function used by quite a few image problems .
cosqa-train-12844
def resize_by_area(img, size): """image resize function used by quite a few image problems.""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA))
def flat_list ( input_list ) : x = input_list if isinstance ( x , list ) : return [ a for i in x for a in flat_list ( i ) ] else : return [ x ]
1
can lists can be nested arbitrarily deep in python
r Given a list of nested lists of arbitrary depth returns a single level or flat list .
cosqa-train-12845
def flat_list(input_list): r""" Given a list of nested lists of arbitrary depth, returns a single level or 'flat' list. """ x = input_list if isinstance(x, list): return [a for i in x for a in flat_list(i)] else: return [x]
def polyline ( self , arr ) : for i in range ( 0 , len ( arr ) - 1 ) : self . line ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] , arr [ i + 1 ] [ 0 ] , arr [ i + 1 ] [ 1 ] )
0
python draw line chart from array
Draw a set of lines
cosqa-train-12846
def polyline(self, arr): """Draw a set of lines""" for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1])
def save_excel ( self , fd ) : from pylon . io . excel import ExcelWriter ExcelWriter ( self ) . write ( fd )
1
can you open an excel file that python is writing too
Saves the case as an Excel spreadsheet .
cosqa-train-12847
def save_excel(self, fd): """ Saves the case as an Excel spreadsheet. """ from pylon.io.excel import ExcelWriter ExcelWriter(self).write(fd)
def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True )
1
python draw line in control
Draw a horizontal line up to a given length .
cosqa-train-12848
def hline(self, x, y, width, color): """Draw a horizontal line up to a given length.""" self.rect(x, y, width, 1, color, fill=True)
def xmltreefromfile ( filename ) : try : return ElementTree . parse ( filename , ElementTree . XMLParser ( collect_ids = False ) ) except TypeError : return ElementTree . parse ( filename , ElementTree . XMLParser ( ) )
1
can you open and parse xml files in python
Internal function to read an XML file
cosqa-train-12849
def xmltreefromfile(filename): """Internal function to read an XML file""" try: return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False)) except TypeError: return ElementTree.parse(filename, ElementTree.XMLParser())
def drop_empty ( rows ) : return zip ( * [ col for col in zip ( * rows ) if bool ( filter ( bool , col [ 1 : ] ) ) ] )
0
python drop rows containing empty cells
Transpose the columns into rows remove all of the rows that are empty after the first cell then transpose back . The result is that columns that have a header but no data in the body are removed assuming the header is the first row .
cosqa-train-12850
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])
def _delete_keys ( dct , keys ) : c = deepcopy ( dct ) assert isinstance ( keys , list ) for k in keys : c . pop ( k ) return c
0
can you remove keys from a dictionary in python
Returns a copy of dct without keys keys
cosqa-train-12851
def _delete_keys(dct, keys): """Returns a copy of dct without `keys` keys """ c = deepcopy(dct) assert isinstance(keys, list) for k in keys: c.pop(k) return c
def compress ( obj ) : return json . dumps ( obj , sort_keys = True , separators = ( ',' , ':' ) , cls = CustomEncoder )
1
python dump json with custom encoder
Outputs json without whitespace .
cosqa-train-12852
def compress(obj): """Outputs json without whitespace.""" return json.dumps(obj, sort_keys=True, separators=(',', ':'), cls=CustomEncoder)
def cell ( self , rowName , columnName ) : return self . matrix [ self . rowIndices [ rowName ] , self . columnIndices [ columnName ] ]
1
can you return value from python row number and column name
Returns the value of the cell on the given row and column .
cosqa-train-12853
def cell(self, rowName, columnName): """ Returns the value of the cell on the given row and column. """ return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]]
def deserialize_ndarray_npy ( d ) : with io . BytesIO ( ) as f : f . write ( json . loads ( d [ 'npy' ] ) . encode ( 'latin-1' ) ) f . seek ( 0 ) return np . load ( f )
1
python dump ndarray as json
Deserializes a JSONified : obj : numpy . ndarray that was created using numpy s : obj : save function .
cosqa-train-12854
def deserialize_ndarray_npy(d): """ Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's :obj:`save` function. Args: d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created using :obj:`numpy.save`. Returns: An :obj:`ndarray` object. """ with io.BytesIO() as f: f.write(json.loads(d['npy']).encode('latin-1')) f.seek(0) return np.load(f)
def center_text ( text , width = 80 ) : centered = [ ] for line in text . splitlines ( ) : centered . append ( line . center ( width ) ) return "\n" . join ( centered )
0
can you right align and center text on python
Center all lines of the text . It is assumed that all lines width is smaller then B { width } because the line width will not be checked . Args : text ( str ) : Text to wrap . width ( int ) : Maximum number of characters per line . Returns : str : Centered text .
cosqa-train-12855
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Centered text. """ centered = [] for line in text.splitlines(): centered.append(line.center(width)) return "\n".join(centered)
def convert ( self , value , _type ) : return self . type_convertors . get ( _type , lambda x : x ) ( value )
1
python dynamic or static typing recomendation
Convert instances of textx types and match rules to python types .
cosqa-train-12856
def convert(self, value, _type): """ Convert instances of textx types and match rules to python types. """ return self.type_convertors.get(_type, lambda x: x)(value)
def _crop_list_to_size ( l , size ) : for x in range ( size - len ( l ) ) : l . append ( False ) for x in range ( len ( l ) - size ) : l . pop ( ) return l
1
can you set a list to a certain size python
Make a list a certain size
cosqa-train-12857
def _crop_list_to_size(l, size): """Make a list a certain size""" for x in range(size - len(l)): l.append(False) for x in range(len(l) - size): l.pop() return l
def onchange ( self , value ) : log . debug ( 'combo box. selected %s' % value ) self . select_by_value ( value ) return ( value , )
1
python dynamically populating dropdown based upon another dropdown selection
Called when a new DropDownItem gets selected .
cosqa-train-12858
def onchange(self, value): """Called when a new DropDownItem gets selected. """ log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
def datetime_from_timestamp ( timestamp , content ) : return set_date_tzinfo ( datetime . fromtimestamp ( timestamp ) , tz_name = content . settings . get ( 'TIMEZONE' , None ) )
1
cannont compare tz naive and tz aware timestamps python
Helper function to add timezone information to datetime so that datetime is comparable to other datetime objects in recent versions that now also have timezone information .
cosqa-train-12859
def datetime_from_timestamp(timestamp, content): """ Helper function to add timezone information to datetime, so that datetime is comparable to other datetime objects in recent versions that now also have timezone information. """ return set_date_tzinfo( datetime.fromtimestamp(timestamp), tz_name=content.settings.get('TIMEZONE', None))
def parsed_args ( ) : parser = argparse . ArgumentParser ( description = """python runtime functions""" , epilog = "" ) parser . add_argument ( 'command' , nargs = '*' , help = "Name of the function to run with arguments" ) args = parser . parse_args ( ) return ( args , parser )
1
python dynamically read args in functions
cosqa-train-12860
def parsed_args(): parser = argparse.ArgumentParser(description="""python runtime functions""", epilog="") parser.add_argument('command',nargs='*', help="Name of the function to run with arguments") args = parser.parse_args() return (args, parser)
def is_date_type ( cls ) : if not isinstance ( cls , type ) : return False return issubclass ( cls , date ) and not issubclass ( cls , datetime )
1
cant compare date to none type python
Return True if the class is a date type .
cosqa-train-12861
def is_date_type(cls): """Return True if the class is a date type.""" if not isinstance(cls, type): return False return issubclass(cls, date) and not issubclass(cls, datetime)
def arr_to_vector ( arr ) : dim = array_dim ( arr ) tmp_arr = [ ] for n in range ( len ( dim ) - 1 ) : for inner in arr : for i in inner : tmp_arr . append ( i ) arr = tmp_arr tmp_arr = [ ] return arr
1
python each element in the array
Reshape a multidimensional array to a vector .
cosqa-train-12862
def arr_to_vector(arr): """Reshape a multidimensional array to a vector. """ dim = array_dim(arr) tmp_arr = [] for n in range(len(dim) - 1): for inner in arr: for i in inner: tmp_arr.append(i) arr = tmp_arr tmp_arr = [] return arr
def _convert_to_float_if_possible ( s ) : try : ret = float ( s ) except ( ValueError , TypeError ) : ret = s return ret
1
cant covert string to int or float in python
A small helper function to convert a string to a numeric value if appropriate
cosqa-train-12863
def _convert_to_float_if_possible(s): """ A small helper function to convert a string to a numeric value if appropriate :param s: the string to be converted :type s: str """ try: ret = float(s) except (ValueError, TypeError): ret = s return ret
def has_edit_permission ( self , request ) : return request . user . is_authenticated and request . user . is_active and request . user . is_staff
1
python edit pdf access permissions
Can edit this object
cosqa-train-12864
def has_edit_permission(self, request): """ Can edit this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def _snake_to_camel_case ( value ) : words = value . split ( "_" ) return words [ 0 ] + "" . join ( map ( str . capitalize , words [ 1 : ] ) )
1
capitalize element in list function python
Convert snake case string to camel case .
cosqa-train-12865
def _snake_to_camel_case(value): """Convert snake case string to camel case.""" words = value.split("_") return words[0] + "".join(map(str.capitalize, words[1:]))
def has_edit_permission ( self , request ) : return request . user . is_authenticated and request . user . is_active and request . user . is_staff
1
python edit pf access permissions
Can edit this object
cosqa-train-12866
def has_edit_permission(self, request): """ Can edit this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
def py ( self , output ) : import pprint pprint . pprint ( output , stream = self . outfile )
1
capture output of python pprint into a file
Output data as a nicely - formatted python data structure
cosqa-train-12867
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
def get_index ( self , bucket , index , startkey , endkey = None , return_terms = None , max_results = None , continuation = None , timeout = None , term_regex = None ) : raise NotImplementedError
0
python elasticsearch bucket limited to 10
Performs a secondary index query .
cosqa-train-12868
def get_index(self, bucket, index, startkey, endkey=None, return_terms=None, max_results=None, continuation=None, timeout=None, term_regex=None): """ Performs a secondary index query. """ raise NotImplementedError
def cartesian_product ( arrays , flat = True , copy = False ) : arrays = np . broadcast_arrays ( * np . ix_ ( * arrays ) ) if flat : return tuple ( arr . flatten ( ) if copy else arr . flat for arr in arrays ) return tuple ( arr . copy ( ) if copy else arr for arr in arrays )
1
cartesian product of huge array python
Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions . By default arrays are flattened which may be controlled with the flat flag . The array views can be turned into regular arrays with the copy flag .
cosqa-train-12869
def cartesian_product(arrays, flat=True, copy=False): """ Efficient cartesian product of a list of 1D arrays returning the expanded array views for each dimensions. By default arrays are flattened, which may be controlled with the flat flag. The array views can be turned into regular arrays with the copy flag. """ arrays = np.broadcast_arrays(*np.ix_(*arrays)) if flat: return tuple(arr.flatten() if copy else arr.flat for arr in arrays) return tuple(arr.copy() if copy else arr for arr in arrays)
def update_index ( index ) : logger . info ( "Updating search index: '%s'" , index ) client = get_client ( ) responses = [ ] for model in get_index_models ( index ) : logger . info ( "Updating search index model: '%s'" , model . search_doc_type ) objects = model . objects . get_search_queryset ( index ) . iterator ( ) actions = bulk_actions ( objects , index = index , action = "index" ) response = helpers . bulk ( client , actions , chunk_size = get_setting ( "chunk_size" ) ) responses . append ( response ) return responses
1
python elasticsearch index update
Re - index every document in a named index .
cosqa-train-12870
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = model.objects.get_search_queryset(index).iterator() actions = bulk_actions(objects, index=index, action="index") response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size")) responses.append(response) return responses
def C_dict2array ( C ) : return np . hstack ( [ np . asarray ( C [ k ] ) . ravel ( ) for k in C_keys ] )
1
casat a list of dictionaries to a numpy array python
Convert an OrderedDict containing C values to a 1D array .
cosqa-train-12871
def C_dict2array(C): """Convert an OrderedDict containing C values to a 1D array.""" return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
def update_index ( index ) : logger . info ( "Updating search index: '%s'" , index ) client = get_client ( ) responses = [ ] for model in get_index_models ( index ) : logger . info ( "Updating search index model: '%s'" , model . search_doc_type ) objects = model . objects . get_search_queryset ( index ) . iterator ( ) actions = bulk_actions ( objects , index = index , action = "index" ) response = helpers . bulk ( client , actions , chunk_size = get_setting ( "chunk_size" ) ) responses . append ( response ) return responses
0
python elasticsearch put multiple index
Re - index every document in a named index .
cosqa-train-12872
def update_index(index): """Re-index every document in a named index.""" logger.info("Updating search index: '%s'", index) client = get_client() responses = [] for model in get_index_models(index): logger.info("Updating search index model: '%s'", model.search_doc_type) objects = model.objects.get_search_queryset(index).iterator() actions = bulk_actions(objects, index=index, action="index") response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size")) responses.append(response) return responses
def to_str ( obj ) : if not isinstance ( obj , str ) and PY3 and isinstance ( obj , bytes ) : obj = obj . decode ( 'utf-8' ) return obj if isinstance ( obj , string_types ) else str ( obj )
1
cast object of type bytes to string python
Attempts to convert given object to a string object
cosqa-train-12873
def to_str(obj): """Attempts to convert given object to a string object """ if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(obj)
def scan ( client , query = None , scroll = '5m' , raise_on_error = True , preserve_order = False , size = 1000 , * * kwargs ) : if not preserve_order : kwargs [ 'search_type' ] = 'scan' # initial search resp = client . search ( body = query , scroll = scroll , size = size , * * kwargs ) scroll_id = resp . get ( '_scroll_id' ) if scroll_id is None : return first_run = True while True : # if we didn't set search_type to scan initial search contains data if preserve_order and first_run : first_run = False else : resp = client . scroll ( scroll_id , scroll = scroll ) for hit in resp [ 'hits' ] [ 'hits' ] : yield hit # check if we have any errrors if resp [ "_shards" ] [ "failed" ] : logger . warning ( 'Scroll request has failed on %d shards out of %d.' , resp [ '_shards' ] [ 'failed' ] , resp [ '_shards' ] [ 'total' ] ) if raise_on_error : raise ScanError ( 'Scroll request has failed on %d shards out of %d.' % ( resp [ '_shards' ] [ 'failed' ] , resp [ '_shards' ] [ 'total' ] ) ) scroll_id = resp . get ( '_scroll_id' ) # end of scroll if scroll_id is None or not resp [ 'hits' ] [ 'hits' ] : break
1
python elasticsearch querybuilder range
Simple abstraction on top of the : meth : ~elasticsearch . Elasticsearch . scroll api - a simple iterator that yields all hits as returned by underlining scroll requests . By default scan does not return results in any pre - determined order . To have a standard order in the returned documents ( either by score or explicit sort definition ) when scrolling use preserve_order = True . This may be an expensive operation and will negate the performance benefits of using scan . : arg client : instance of : class : ~elasticsearch . Elasticsearch to use : arg query : body for the : meth : ~elasticsearch . Elasticsearch . search api : arg scroll : Specify how long a consistent view of the index should be maintained for scrolled search : arg raise_on_error : raises an exception ( ScanError ) if an error is encountered ( some shards fail to execute ) . By default we raise . : arg preserve_order : don t set the search_type to scan - this will cause the scroll to paginate with preserving the order . Note that this can be an extremely expensive operation and can easily lead to unpredictable results use with caution . : arg size : size ( per shard ) of the batch send at each iteration . Any additional keyword arguments will be passed to the initial : meth : ~elasticsearch . Elasticsearch . search call :: scan ( es query = { query : { match : { title : python }}} index = orders - * doc_type = books )
cosqa-train-12874
def scan(client, query=None, scroll='5m', raise_on_error=True, preserve_order=False, size=1000, **kwargs): """ Simple abstraction on top of the :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that yields all hits as returned by underlining scroll requests. By default scan does not return results in any pre-determined order. To have a standard order in the returned documents (either by score or explicit sort definition) when scrolling, use ``preserve_order=True``. This may be an expensive operation and will negate the performance benefits of using ``scan``. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api :arg scroll: Specify how long a consistent view of the index should be maintained for scrolled search :arg raise_on_error: raises an exception (``ScanError``) if an error is encountered (some shards fail to execute). By default we raise. :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will cause the scroll to paginate with preserving the order. Note that this can be an extremely expensive operation and can easily lead to unpredictable results, use with caution. :arg size: size (per shard) of the batch send at each iteration. Any additional keyword arguments will be passed to the initial :meth:`~elasticsearch.Elasticsearch.search` call:: scan(es, query={"query": {"match": {"title": "python"}}}, index="orders-*", doc_type="books" ) """ if not preserve_order: kwargs['search_type'] = 'scan' # initial search resp = client.search(body=query, scroll=scroll, size=size, **kwargs) scroll_id = resp.get('_scroll_id') if scroll_id is None: return first_run = True while True: # if we didn't set search_type to scan initial search contains data if preserve_order and first_run: first_run = False else: resp = client.scroll(scroll_id, scroll=scroll) for hit in resp['hits']['hits']: yield hit # check if we have any errrors if resp["_shards"]["failed"]: logger.warning( 'Scroll request has failed on %d shards out of %d.', resp['_shards']['failed'], resp['_shards']['total'] ) if raise_on_error: raise ScanError( 'Scroll request has failed on %d shards out of %d.' % (resp['_shards']['failed'], resp['_shards']['total']) ) scroll_id = resp.get('_scroll_id') # end of scroll if scroll_id is None or not resp['hits']['hits']: break
def _datetime_to_date ( arg ) : _arg = parse ( arg ) if isinstance ( _arg , datetime . datetime ) : _arg = _arg . date ( ) return _arg
1
cast something as datetime python
convert datetime / str to date : param arg : : return :
cosqa-train-12875
def _datetime_to_date(arg): """ convert datetime/str to date :param arg: :return: """ _arg = parse(arg) if isinstance(_arg, datetime.datetime): _arg = _arg.date() return _arg
def SegmentMin ( a , ids ) : func = lambda idxs : np . amin ( a [ idxs ] , axis = 0 ) return seg_map ( func , a , ids ) ,
1
python element wise min
Segmented min op .
cosqa-train-12876
def SegmentMin(a, ids): """ Segmented min op. """ func = lambda idxs: np.amin(a[idxs], axis=0) return seg_map(func, a, ids),
def str2bytes ( x ) : if type ( x ) is bytes : return x elif type ( x ) is str : return bytes ( [ ord ( i ) for i in x ] ) else : return str2bytes ( str ( x ) )
1
cast string to bytes python
Convert input argument to bytes
cosqa-train-12877
def str2bytes(x): """Convert input argument to bytes""" if type(x) is bytes: return x elif type(x) is str: return bytes([ ord(i) for i in x ]) else: return str2bytes(str(x))
def deduplicate ( list_object ) : new = [ ] for item in list_object : if item not in new : new . append ( item ) return new
1
python empty list population is confusing
Rebuild list_object removing duplicated and keeping order
cosqa-train-12878
def deduplicate(list_object): """Rebuild `list_object` removing duplicated and keeping order""" new = [] for item in list_object: if item not in new: new.append(item) return new
def center_text ( text , width = 80 ) : centered = [ ] for line in text . splitlines ( ) : centered . append ( line . center ( width ) ) return "\n" . join ( centered )
1
center align python text
Center all lines of the text . It is assumed that all lines width is smaller then B { width } because the line width will not be checked . Args : text ( str ) : Text to wrap . width ( int ) : Maximum number of characters per line . Returns : str : Centered text .
cosqa-train-12879
def center_text(text, width=80): """Center all lines of the text. It is assumed that all lines width is smaller then B{width}, because the line width will not be checked. Args: text (str): Text to wrap. width (int): Maximum number of characters per line. Returns: str: Centered text. """ centered = [] for line in text.splitlines(): centered.append(line.center(width)) return "\n".join(centered)
def to_binary ( s , encoding = 'utf8' ) : if PY3 : # pragma: no cover return s if isinstance ( s , binary_type ) else binary_type ( s , encoding = encoding ) return binary_type ( s )
1
python encoding a string as binary
Portable cast function .
cosqa-train-12880
def to_binary(s, encoding='utf8'): """Portable cast function. In python 2 the ``str`` function which is used to coerce objects to bytes does not accept an encoding argument, whereas python 3's ``bytes`` function requires one. :param s: object to be converted to binary_type :return: binary_type instance, representing s. """ if PY3: # pragma: no cover return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding) return binary_type(s)
def indent ( self ) : blk = IndentBlock ( self , self . _indent ) self . _indent += 1 return blk
1
chained call in python indentation
Begins an indented block . Must be used in a with code block . All calls to the logger inside of the block will be indented .
cosqa-train-12881
def indent(self): """ Begins an indented block. Must be used in a 'with' code block. All calls to the logger inside of the block will be indented. """ blk = IndentBlock(self, self._indent) self._indent += 1 return blk
def safe_unicode ( string ) : if not PY3 : uni = string . replace ( u'\u2019' , "'" ) return uni . encode ( 'utf-8' ) return string
1
python ensure utf 8 encoding
If Python 2 replace non - ascii characters and return encoded string .
cosqa-train-12882
def safe_unicode(string): """If Python 2, replace non-ascii characters and return encoded string.""" if not PY3: uni = string.replace(u'\u2019', "'") return uni.encode('utf-8') return string
def as_float_array ( a ) : return np . asarray ( a , dtype = np . quaternion ) . view ( ( np . double , 4 ) )
1
change array to float python
View the quaternion array as an array of floats
cosqa-train-12883
def as_float_array(a): """View the quaternion array as an array of floats This function is fast (of order 1 microsecond) because no data is copied; the returned quantity is just a "view" of the original. The output view has one more dimension (of size 4) than the input array, but is otherwise the same shape. """ return np.asarray(a, dtype=np.quaternion).view((np.double, 4))
def is_enum_type ( type_ ) : return isinstance ( type_ , type ) and issubclass ( type_ , tuple ( _get_types ( Types . ENUM ) ) )
1
python enum check type
Checks if the given type is an enum type .
cosqa-train-12884
def is_enum_type(type_): """ Checks if the given type is an enum type. :param type_: The type to check :return: True if the type is a enum type, otherwise False :rtype: bool """ return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))
def _str_to_list ( s ) : _list = s . split ( "," ) return list ( map ( lambda i : i . lstrip ( ) , _list ) )
1
change comma separated string to list python
Converts a comma separated string to a list
cosqa-train-12885
def _str_to_list(s): """Converts a comma separated string to a list""" _list = s.split(",") return list(map(lambda i: i.lstrip(), _list))
def metres2latlon ( mx , my , origin_shift = 2 * pi * 6378137 / 2.0 ) : lon = ( mx / origin_shift ) * 180.0 lat = ( my / origin_shift ) * 180.0 lat = 180 / pi * ( 2 * atan ( exp ( lat * pi / 180.0 ) ) - pi / 2.0 ) return lat , lon
1
python epec xyz to lat lon alt
Converts XY point from Spherical Mercator EPSG : 900913 to lat / lon in WGS84 Datum
cosqa-train-12886
def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0): """Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in WGS84 Datum""" lon = (mx / origin_shift) * 180.0 lat = (my / origin_shift) * 180.0 lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0) return lat, lon
def robust_int ( v ) : if isinstance ( v , int ) : return v if isinstance ( v , float ) : return int ( v ) v = str ( v ) . replace ( ',' , '' ) if not v : return None return int ( v )
1
change data type to int python
Parse an int robustly ignoring commas and other cruft .
cosqa-train-12887
def robust_int(v): """Parse an int robustly, ignoring commas and other cruft. """ if isinstance(v, int): return v if isinstance(v, float): return int(v) v = str(v).replace(',', '') if not v: return None return int(v)
async def iso ( self , source ) : from datetime import datetime unix_timestamp = int ( source ) return datetime . fromtimestamp ( unix_timestamp ) . isoformat ( )
0
python epoch to iso
Convert to timestamp .
cosqa-train-12888
async def iso(self, source): """Convert to timestamp.""" from datetime import datetime unix_timestamp = int(source) return datetime.fromtimestamp(unix_timestamp).isoformat()
def set_font_size ( self , size ) : if self . font . font_size == size : pass else : self . font . _set_size ( size )
1
change font height in python
Convenience method for just changing font size .
cosqa-train-12889
def set_font_size(self, size): """Convenience method for just changing font size.""" if self.font.font_size == size: pass else: self.font._set_size(size)
def notin ( arg , values ) : op = ops . NotContains ( arg , values ) return op . to_expr ( )
1
python equivalent to not in
Like isin but checks whether this expression s value ( s ) are not contained in the passed values . See isin docs for full usage .
cosqa-train-12890
def notin(arg, values): """ Like isin, but checks whether this expression's value(s) are not contained in the passed values. See isin docs for full usage. """ op = ops.NotContains(arg, values) return op.to_expr()
def gray2bgr ( img ) : img = img [ ... , None ] if img . ndim == 2 else img out_img = cv2 . cvtColor ( img , cv2 . COLOR_GRAY2BGR ) return out_img
0
change image to grayscale python cv2
Convert a grayscale image to BGR image .
cosqa-train-12891
def gray2bgr(img): """Convert a grayscale image to BGR image. Args: img (ndarray or str): The input image. Returns: ndarray: The converted BGR image. """ img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) return out_img
def hex_escape ( bin_str ) : printable = string . ascii_letters + string . digits + string . punctuation + ' ' return '' . join ( ch if ch in printable else r'0x{0:02x}' . format ( ord ( ch ) ) for ch in bin_str )
0
python escape binary string
Hex encode a binary string
cosqa-train-12892
def hex_escape(bin_str): """ Hex encode a binary string """ printable = string.ascii_letters + string.digits + string.punctuation + ' ' return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)
def round_to_int ( number , precision ) : precision = int ( precision ) rounded = ( int ( number ) + precision / 2 ) // precision * precision return rounded
1
change precision of number python
Round a number to a precision
cosqa-train-12893
def round_to_int(number, precision): """Round a number to a precision""" precision = int(precision) rounded = (int(number) + precision / 2) // precision * precision return rounded
def _escape ( s ) : e = s e = e . replace ( '\\' , '\\\\' ) e = e . replace ( '\n' , '\\n' ) e = e . replace ( '\r' , '\\r' ) e = e . replace ( "'" , "\\'" ) e = e . replace ( '"' , '\\"' ) return e
1
python escape postgres sql string
Helper method that escapes parameters to a SQL query .
cosqa-train-12894
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
def update_scale ( self , value ) : self . plotter . set_scale ( self . x_slider_group . value , self . y_slider_group . value , self . z_slider_group . value )
1
change scale on python plot
updates the scale of all actors in the plotter
cosqa-train-12895
def update_scale(self, value): """ updates the scale of all actors in the plotter """ self.plotter.set_scale(self.x_slider_group.value, self.y_slider_group.value, self.z_slider_group.value)
def _from_dict ( cls , _dict ) : args = { } if 'key' in _dict : args [ 'key' ] = Key . _from_dict ( _dict . get ( 'key' ) ) if 'value' in _dict : args [ 'value' ] = Value . _from_dict ( _dict . get ( 'value' ) ) return cls ( * * args )
1
python et create an object based on a dictionary
Initialize a KeyValuePair object from a json dictionary .
cosqa-train-12896
def _from_dict(cls, _dict): """Initialize a KeyValuePair object from a json dictionary.""" args = {} if 'key' in _dict: args['key'] = Key._from_dict(_dict.get('key')) if 'value' in _dict: args['value'] = Value._from_dict(_dict.get('value')) return cls(**args)
def shape_list ( l , shape , dtype ) : return np . array ( l , dtype = dtype ) . reshape ( shape )
1
change shape of list python
Shape a list of lists into the appropriate shape and data type
cosqa-train-12897
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
def assert_exactly_one_true ( bool_list ) : assert isinstance ( bool_list , list ) counter = 0 for item in bool_list : if item : counter += 1 return counter == 1
0
python evaluate truth of a list of boolean
This method asserts that only one value of the provided list is True .
cosqa-train-12898
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
def str2int ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . str2int ( num )
1
change string of number to int python
helper function for quick base conversions from strings to integers
cosqa-train-12899
def str2int(num, radix=10, alphabet=BASE85): """helper function for quick base conversions from strings to integers""" return NumConv(radix, alphabet).str2int(num)