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 set_input_value ( self , selector , value ) : script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % ( selector , value ) self . evaluate ( script )
0
webdriver python element input set value
Set the value of the input matched by given selector .
cosqa-train-16900
def set_input_value(self, selector, value): """Set the value of the input matched by given selector.""" script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % (selector, value) self.evaluate(script)
def can_access ( self , user ) : return self . class_ . is_admin ( user ) or self . is_ready and self . class_ in user . classes
0
python check if admin privliges
Return whether or not user can access a project .
cosqa-train-16901
def can_access(self, user): """Return whether or not `user` can access a project. The project's is_ready field must be set for a user to access. """ return self.class_.is_admin(user) or \ self.is_ready and self.class_ in user.classes
def state ( self ) : return { 'c' : self . c , 's0' : self . s0 , 's1' : self . s1 , 's2' : self . s2 }
0
what can i store in dict python
Return internal state useful for testing .
cosqa-train-16902
def state(self): """Return internal state, useful for testing.""" return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}
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 ) )
0
what does a dictionary return if empty python
Get an item from a dict which contains just one item .
cosqa-train-16903
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 mpl_outside_legend ( ax , * * kwargs ) : box = ax . get_position ( ) ax . set_position ( [ box . x0 , box . y0 , box . width * 0.75 , box . height ] ) # Put a legend to the right of the current axis ax . legend ( loc = 'upper left' , bbox_to_anchor = ( 1 , 1 ) , * * kwargs )
0
wht the border of legend box is grey color in python plot
Places a legend box outside a matplotlib Axes instance .
cosqa-train-16904
def mpl_outside_legend(ax, **kwargs): """ Places a legend box outside a matplotlib Axes instance. """ box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.75, box.height]) # Put a legend to the right of the current axis ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
def _IsDirectory ( parent , item ) : return tf . io . gfile . isdir ( os . path . join ( parent , item ) )
1
python check if an item is a directory
Helper that returns if parent / item is a directory .
cosqa-train-16905
def _IsDirectory(parent, item): """Helper that returns if parent/item is a directory.""" return tf.io.gfile.isdir(os.path.join(parent, item))
def cli_command_quit ( self , msg ) : if self . state == State . RUNNING and self . sprocess and self . sprocess . proc : self . sprocess . proc . kill ( ) else : sys . exit ( 0 )
0
will my python kill my child
\ kills the child and exits
cosqa-train-16906
def cli_command_quit(self, msg): """\ kills the child and exits """ if self.state == State.RUNNING and self.sprocess and self.sprocess.proc: self.sprocess.proc.kill() else: sys.exit(0)
def contains_geometric_info ( var ) : return isinstance ( var , tuple ) and len ( var ) == 2 and all ( isinstance ( val , ( int , float ) ) for val in var )
1
python check if any variable in list is type
Check whether the passed variable is a tuple with two floats or integers
cosqa-train-16907
def contains_geometric_info(var): """ Check whether the passed variable is a tuple with two floats or integers """ return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
def np_counts ( self ) : counts = defaultdict ( int ) for phrase in self . noun_phrases : counts [ phrase ] += 1 return counts
0
word counts to dictionary in python
Dictionary of noun phrase frequencies in this text .
cosqa-train-16908
def np_counts(self): """Dictionary of noun phrase frequencies in this text. """ counts = defaultdict(int) for phrase in self.noun_phrases: counts[phrase] += 1 return counts
def has_edge ( self , p_from , p_to ) : return p_from in self . _edges and p_to in self . _edges [ p_from ]
0
python check if edge not exists
Returns True when the graph has the given edge .
cosqa-train-16909
def has_edge(self, p_from, p_to): """ Returns True when the graph has the given edge. """ return p_from in self._edges and p_to in self._edges[p_from]
def fft_freqs ( n_fft , fs ) : return np . arange ( 0 , ( n_fft // 2 + 1 ) ) / float ( n_fft ) * float ( fs )
0
working with fft in python
Return frequencies for DFT
cosqa-train-16910
def fft_freqs(n_fft, fs): """Return frequencies for DFT Parameters ---------- n_fft : int Number of points in the FFT. fs : float The sampling rate. """ return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)
def rpc_fix_code ( self , source , directory ) : source = get_source ( source ) return fix_code ( source , directory )
1
wrap c++ code to python code
Formats Python code to conform to the PEP 8 style guide .
cosqa-train-16911
def rpc_fix_code(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code(source, directory)
def is_valid ( number ) : n = str ( number ) if not n . isdigit ( ) : return False return int ( n [ - 1 ] ) == get_check_digit ( n [ : - 1 ] )
0
write a code in python to check the validity of a phone number
determines whether the card number is valid .
cosqa-train-16912
def is_valid(number): """determines whether the card number is valid.""" n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
def contained_in ( filename , directory ) : filename = os . path . normcase ( os . path . abspath ( filename ) ) directory = os . path . normcase ( os . path . abspath ( directory ) ) return os . path . commonprefix ( [ filename , directory ] ) == directory
0
python check if file is in folder
Test if a file is located within the given directory .
cosqa-train-16913
def contained_in(filename, directory): """Test if a file is located within the given directory.""" filename = os.path.normcase(os.path.abspath(filename)) directory = os.path.normcase(os.path.abspath(directory)) return os.path.commonprefix([filename, directory]) == directory
def flatten ( l ) : return sum ( map ( flatten , l ) , [ ] ) if isinstance ( l , list ) or isinstance ( l , tuple ) else [ l ]
0
write a function that flattens a list python
Flatten a nested list .
cosqa-train-16914
def flatten(l): """Flatten a nested list.""" return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )
1
python check if i'm in virtualenv
Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .
cosqa-train-16915
def _pip_exists(self): """Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.""" return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
def get_table ( ports ) : table = PrettyTable ( [ "Name" , "Port" , "Protocol" , "Description" ] ) table . align [ "Name" ] = "l" table . align [ "Description" ] = "l" table . padding_width = 1 for port in ports : table . add_row ( port ) return table
1
write a function that outputs a table in python
This function returns a pretty table used to display the port results .
cosqa-train-16916
def get_table(ports): """ This function returns a pretty table used to display the port results. :param ports: list of found ports :return: the table to display """ table = PrettyTable(["Name", "Port", "Protocol", "Description"]) table.align["Name"] = "l" table.align["Description"] = "l" table.padding_width = 1 for port in ports: table.add_row(port) return table
def is_iterable_of_int ( l ) : if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l )
1
python check if integer inside l ist
r Checks if l is iterable and contains only integral types
cosqa-train-16917
def is_iterable_of_int(l): r""" Checks if l is iterable and contains only integral types """ if not is_iterable(l): return False return all(is_int(value) for value in l)
def _startswith ( expr , pat ) : return _string_op ( expr , Startswith , output_type = types . boolean , _pat = pat )
1
write a python function to check whether a string start with specified characters
Return boolean sequence or scalar indicating whether each string in the sequence or scalar starts with passed pattern . Equivalent to str . startswith () .
cosqa-train-16918
def _startswith(expr, pat): """ Return boolean sequence or scalar indicating whether each string in the sequence or scalar starts with passed pattern. Equivalent to str.startswith(). :param expr: :param pat: Character sequence :return: sequence or scalar """ return _string_op(expr, Startswith, output_type=types.boolean, _pat=pat)
def is_delimiter ( line ) : return bool ( line ) and line [ 0 ] in punctuation and line [ 0 ] * len ( line ) == line
0
python check if it's no punctuation
True if a line consists only of a single punctuation character .
cosqa-train-16919
def is_delimiter(line): """ True if a line consists only of a single punctuation character.""" return bool(line) and line[0] in punctuation and line[0]*len(line) == line
def csv_matrix_print ( classes , table ) : result = "" classes . sort ( ) for i in classes : for j in classes : result += str ( table [ i ] [ j ] ) + "," result = result [ : - 1 ] + "\n" return result [ : - 1 ]
0
write a python matrix into csv
Return matrix as csv data .
cosqa-train-16920
def csv_matrix_print(classes, table): """ Return matrix as csv data. :param classes: classes list :type classes:list :param table: table :type table:dict :return: """ result = "" classes.sort() for i in classes: for j in classes: result += str(table[i][j]) + "," result = result[:-1] + "\n" return result[:-1]
def isin ( value , values ) : for i , v in enumerate ( value ) : if v not in np . array ( values ) [ : , i ] : return False return True
1
python check if key value is not in array of values
Check that value is in values
cosqa-train-16921
def isin(value, values): """ Check that value is in values """ for i, v in enumerate(value): if v not in np.array(values)[:, i]: return False return True
def install_rpm_py ( ) : python_path = sys . executable cmd = '{0} install.py' . format ( python_path ) exit_status = os . system ( cmd ) if exit_status != 0 : raise Exception ( 'Command failed: {0}' . format ( cmd ) )
0
write a python script to build rpm
Install RPM Python binding .
cosqa-train-16922
def install_rpm_py(): """Install RPM Python binding.""" python_path = sys.executable cmd = '{0} install.py'.format(python_path) exit_status = os.system(cmd) if exit_status != 0: raise Exception('Command failed: {0}'.format(cmd))
def all_strings ( arr ) : if not isinstance ( [ ] , list ) : raise TypeError ( "non-list value found where list is expected" ) return all ( isinstance ( x , str ) for x in arr )
1
python check if list of string or one single string
Ensures that the argument is a list that either is empty or contains only strings : param arr : list : return :
cosqa-train-16923
def all_strings(arr): """ Ensures that the argument is a list that either is empty or contains only strings :param arr: list :return: """ if not isinstance([], list): raise TypeError("non-list value found where list is expected") return all(isinstance(x, str) for x in arr)
def write_fits ( self , fitsfile ) : tab = self . create_table ( ) hdu_data = fits . table_to_hdu ( tab ) hdus = [ fits . PrimaryHDU ( ) , hdu_data ] fits_utils . write_hdus ( hdus , fitsfile )
1
write data into fits file python
Write the ROI model to a FITS file .
cosqa-train-16924
def write_fits(self, fitsfile): """Write the ROI model to a FITS file.""" tab = self.create_table() hdu_data = fits.table_to_hdu(tab) hdus = [fits.PrimaryHDU(), hdu_data] fits_utils.write_hdus(hdus, fitsfile)
def we_are_in_lyon ( ) : import socket try : hostname = socket . gethostname ( ) ip = socket . gethostbyname ( hostname ) except socket . gaierror : return False return ip . startswith ( "134.158." )
0
python check if local port is on
Check if we are on a Lyon machine
cosqa-train-16925
def we_are_in_lyon(): """Check if we are on a Lyon machine""" import socket try: hostname = socket.gethostname() ip = socket.gethostbyname(hostname) except socket.gaierror: return False return ip.startswith("134.158.")
def _write_json ( file , contents ) : with open ( file , 'w' ) as f : return json . dump ( contents , f , indent = 2 , sort_keys = True )
0
write dict in json file python
Write a dict to a JSON file .
cosqa-train-16926
def _write_json(file, contents): """Write a dict to a JSON file.""" with open(file, 'w') as f: return json.dump(contents, f, indent=2, sort_keys=True)
def is_empty ( self ) : return all ( isinstance ( c , ParseNode ) and c . is_empty for c in self . children )
1
python check if node is empty
Returns True if this node has no children or if all of its children are ParseNode instances and are empty .
cosqa-train-16927
def is_empty(self): """Returns True if this node has no children, or if all of its children are ParseNode instances and are empty. """ return all(isinstance(c, ParseNode) and c.is_empty for c in self.children)
def _serialize_json ( obj , fp ) : json . dump ( obj , fp , indent = 4 , default = serialize )
0
write json object to file in python
Serialize obj as a JSON formatted stream to fp
cosqa-train-16928
def _serialize_json(obj, fp): """ Serialize ``obj`` as a JSON formatted stream to ``fp`` """ json.dump(obj, fp, indent=4, default=serialize)
def is_archlinux ( ) : if platform . system ( ) . lower ( ) == 'linux' : if platform . linux_distribution ( ) == ( '' , '' , '' ) : # undefined distribution. Fixed in python 3. if os . path . exists ( '/etc/arch-release' ) : return True return False
1
python check if os is windows or linux
return True if the current distribution is running on debian like OS .
cosqa-train-16929
def is_archlinux(): """return True if the current distribution is running on debian like OS.""" if platform.system().lower() == 'linux': if platform.linux_distribution() == ('', '', ''): # undefined distribution. Fixed in python 3. if os.path.exists('/etc/arch-release'): return True return False
def is_password_valid ( password ) : pattern = re . compile ( r"^.{4,75}$" ) return bool ( pattern . match ( password ) )
0
write regex to validate password python
Check if a password is valid
cosqa-train-16930
def is_password_valid(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
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
python check if range of numbers in another range of numbers
Checks whether all number in the sequence s lie inside the interval formed by l and r .
cosqa-train-16931
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 on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )
0
wxpython close dialog manually
Pop - up menu and wx . EVT_CLOSE closing event
cosqa-train-16932
def on_close(self, evt): """ Pop-up menu and wx.EVT_CLOSE closing event """ self.stop() # DoseWatcher if evt.EventObject is not self: # Avoid deadlocks self.Close() # wx.Frame evt.Skip()
def intty ( cls ) : # XXX: temporary hack until we can detect if we are in a pipe or not return True if hasattr ( sys . stdout , 'isatty' ) and sys . stdout . isatty ( ) : return True return False
1
python check if stdin is tty
Check if we are in a tty .
cosqa-train-16933
def intty(cls): """ Check if we are in a tty. """ # XXX: temporary hack until we can detect if we are in a pipe or not return True if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty(): return True return False
def list_view_changed ( self , widget , event , data = None ) : adj = self . scrolled_window . get_vadjustment ( ) adj . set_value ( adj . get_upper ( ) - adj . get_page_size ( ) )
0
wxpython keeps scroll bar lastest
Function shows last rows .
cosqa-train-16934
def list_view_changed(self, widget, event, data=None): """ Function shows last rows. """ adj = self.scrolled_window.get_vadjustment() adj.set_value(adj.get_upper() - adj.get_page_size())
def has_permission ( user , permission_name ) : if user and user . is_superuser : return True return permission_name in available_perm_names ( user )
1
python check if super user
Check if a user has a given permission .
cosqa-train-16935
def has_permission(user, permission_name): """Check if a user has a given permission.""" if user and user.is_superuser: return True return permission_name in available_perm_names(user)
def values ( self ) : lower = float ( self . lowerSpnbx . value ( ) ) upper = float ( self . upperSpnbx . value ( ) ) return ( lower , upper )
1
x limit and y limit in python
Gets the user enter max and min values of where the raster points should appear on the y - axis
cosqa-train-16936
def values(self): """Gets the user enter max and min values of where the raster points should appear on the y-axis :returns: (float, float) -- (min, max) y-values to bound the raster plot by """ lower = float(self.lowerSpnbx.value()) upper = float(self.upperSpnbx.value()) return (lower, upper)
def check_precomputed_distance_matrix ( X ) : tmp = X . copy ( ) tmp [ np . isinf ( tmp ) ] = 1 check_array ( tmp )
0
python check if there are missing values in an array
Perform check_array ( X ) after removing infinite values ( numpy . inf ) from the given distance matrix .
cosqa-train-16937
def check_precomputed_distance_matrix(X): """Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix. """ tmp = X.copy() tmp[np.isinf(tmp)] = 1 check_array(tmp)
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
yield regex function python
Generate all matches found within a string for a regex and yield each match as a string
cosqa-train-16938
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 is_valid_row ( cls , row ) : for k in row . keys ( ) : if row [ k ] is None : return False return True
0
python check if there is a valid data in a column
Indicates whether or not the given row contains valid data .
cosqa-train-16939
def is_valid_row(cls, row): """Indicates whether or not the given row contains valid data.""" for k in row.keys(): if row[k] is None: return False return True
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 check if two images are the same
Checks if two images have the same height and width ( and optionally channels ) .
cosqa-train-16940
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 user_in_all_groups ( user , groups ) : return user_is_superuser ( user ) or all ( user_in_group ( user , group ) for group in groups )
0
python check if user is in a group
Returns True if the given user is in all given groups
cosqa-train-16941
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
1
python functional to check is number
A non - negative integer .
cosqa-train-16942
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
1
python json specific string
string dict / object / value to JSON
cosqa-train-16943
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period
0
how to fetch last month data in python
Returns the last week as a period string
cosqa-train-16944
def get_period_last_3_months() -> str: """ Returns the last week as a period string """ today = Datum() today.today() # start_date = today - timedelta(weeks=13) start_date = today.clone() start_date.subtract_months(3) period = get_period(start_date.date, today.date) return period
def dictlist_convert_to_float ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : try : d [ key ] = float ( d [ key ] ) except ValueError : d [ key ] = None
0
how to make dictionary values float in python
Process an iterable of dictionaries . For each dictionary d convert ( in place ) d [ key ] to a float . If that fails convert it to None .
cosqa-train-16945
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``. """ for d in dict_list: try: d[key] = float(d[key]) except ValueError: d[key] = None
def method_caller ( method_name , * args , * * kwargs ) : def call_method ( target ) : func = getattr ( target , method_name ) return func ( * args , * * kwargs ) return call_method
1
how to pass a function name in python
Return a function that will call a named method on the target object with optional positional and keyword arguments .
cosqa-train-16946
def method_caller(method_name, *args, **kwargs): """ Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring' """ def call_method(target): func = getattr(target, method_name) return func(*args, **kwargs) return call_method
def find_first_in_list ( txt : str , str_list : [ str ] ) -> int : # type: ignore start = len ( txt ) + 1 for item in str_list : if start > txt . find ( item ) > - 1 : start = txt . find ( item ) return start if len ( txt ) + 1 > start > - 1 else - 1
1
python get last occurrence in string
Returns the index of the earliest occurence of an item from a list in a string
cosqa-train-16947
def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore """ Returns the index of the earliest occurence of an item from a list in a string Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3 """ start = len(txt) + 1 for item in str_list: if start > txt.find(item) > -1: start = txt.find(item) return start if len(txt) + 1 > start > -1 else -1
def previous_workday ( dt ) : dt -= timedelta ( days = 1 ) while dt . weekday ( ) > 4 : # Mon-Fri are 0-4 dt -= timedelta ( days = 1 ) return dt
0
python how to get working days before
returns previous weekday used for observances
cosqa-train-16948
def previous_workday(dt): """ returns previous weekday used for observances """ dt -= timedelta(days=1) while dt.weekday() > 4: # Mon-Fri are 0-4 dt -= timedelta(days=1) return dt
def __gt__ ( self , other ) : if isinstance ( other , Address ) : return str ( self ) > str ( other ) raise TypeError
1
greater than string python
Test for greater than .
cosqa-train-16949
def __gt__(self, other): """Test for greater than.""" if isinstance(other, Address): return str(self) > str(other) raise TypeError
def batch_split_sentences ( self , texts : List [ str ] ) -> List [ List [ str ] ] : return [ self . split_sentences ( text ) for text in texts ]
0
how to split sentences on punctuation python
This method lets you take advantage of spacy s batch processing . Default implementation is to just iterate over the texts and call split_sentences .
cosqa-train-16950
def batch_split_sentences(self, texts: List[str]) -> List[List[str]]: """ This method lets you take advantage of spacy's batch processing. Default implementation is to just iterate over the texts and call ``split_sentences``. """ return [self.split_sentences(text) for text in texts]
def listify ( a ) : if a is None : return [ ] elif not isinstance ( a , ( tuple , list , np . ndarray ) ) : return [ a ] return list ( a )
0
turn a list into array python
Convert a scalar a to a list and all iterables to list as well .
cosqa-train-16951
def listify(a): """ Convert a scalar ``a`` to a list and all iterables to list as well. Examples -------- >>> listify(0) [0] >>> listify([1,2,3]) [1, 2, 3] >>> listify('a') ['a'] >>> listify(np.array([1,2,3])) [1, 2, 3] >>> listify('string') ['string'] """ if a is None: return [] elif not isinstance(a, (tuple, list, np.ndarray)): return [a] return list(a)
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
0
get all the column names in python
Get all the database column names for the specified table .
cosqa-train-16952
def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
def list_depth ( list_ , func = max , _depth = 0 ) : depth_list = [ list_depth ( item , func = func , _depth = _depth + 1 ) for item in list_ if util_type . is_listlike ( item ) ] if len ( depth_list ) > 0 : return func ( depth_list ) else : return _depth
1
recursion for depth of nested python lists
Returns the deepest level of nesting within a list of lists
cosqa-train-16953
def list_depth(list_, func=max, _depth=0): """ Returns the deepest level of nesting within a list of lists Args: list_ : a nested listlike object func : depth aggregation strategy (defaults to max) _depth : internal var Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [[[[[1]]], [3]], [[1], [3]], [[1], [3]]] >>> result = (list_depth(list_, _depth=0)) >>> print(result) """ depth_list = [list_depth(item, func=func, _depth=_depth + 1) for item in list_ if util_type.is_listlike(item)] if len(depth_list) > 0: return func(depth_list) else: return _depth
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
0
python get time zone information
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-16954
def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] return dt.tzinfo, tzstr
def inverted_dict ( d ) : return dict ( ( force_hashable ( v ) , k ) for ( k , v ) in viewitems ( dict ( d ) ) )
0
how to create an inverse dictionary python
Return a dict with swapped keys and values
cosqa-train-16955
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False
1
python check if queue is empty
Return True if the queue is full False otherwise ( not reliable! ) .
cosqa-train-16956
def full(self): """Return ``True`` if the queue is full, ``False`` otherwise (not reliable!). Only applicable if :attr:`maxsize` is set. """ return self.maxsize and len(self.list) >= self.maxsize or False
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
1
select top n python
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-16957
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] Parameters ---------- topn : int Returns ------- list """ return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != "" ]
0
python filter out text from a list of words
Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing
cosqa-train-16958
def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]: """Remove empty utterances from a list of utterances Args: utterances: The list of utterance we are processing """ return [utter for utter in utterances if utter.text.strip() != ""]
def get_pij_matrix ( t , diag , A , A_inv ) : return A . dot ( np . diag ( np . exp ( diag * t ) ) ) . dot ( A_inv )
1
transition probability matrix for a random graph implementation in python
Calculates the probability matrix of substitutions i - > j over time t given the normalised generator diagonalisation .
cosqa-train-16959
def get_pij_matrix(t, diag, A, A_inv): """ Calculates the probability matrix of substitutions i->j over time t, given the normalised generator diagonalisation. :param t: time :type t: float :return: probability matrix :rtype: numpy.ndarray """ return A.dot(np.diag(np.exp(diag * t))).dot(A_inv)
def flush ( self ) : if self . _cache_modified_count > 0 : self . storage . write ( self . cache ) self . _cache_modified_count = 0
1
python flush request cache
Flush all unwritten data to disk .
cosqa-train-16960
def flush(self): """ Flush all unwritten data to disk. """ if self._cache_modified_count > 0: self.storage.write(self.cache) self._cache_modified_count = 0
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
0
python compare none with int
A non - negative integer .
cosqa-train-16961
def is_natural(x): """A non-negative integer.""" try: is_integer = int(x) == x except (TypeError, ValueError): return False return is_integer and x >= 0
def _sum_cycles_from_tokens ( self , tokens : List [ str ] ) -> int : return sum ( ( int ( self . _nonnumber_pattern . sub ( '' , t ) ) for t in tokens ) )
1
count of each token from a string in python
Sum the total number of cycles over a list of tokens .
cosqa-train-16962
def _sum_cycles_from_tokens(self, tokens: List[str]) -> int: """Sum the total number of cycles over a list of tokens.""" return sum((int(self._nonnumber_pattern.sub('', t)) for t in tokens))
def __next__ ( self ) : self . current += 1 if self . current > self . total : raise StopIteration else : return self . iterable [ self . current - 1 ]
1
python 3 iterator has next
: return : int
cosqa-train-16963
def __next__(self): """ :return: int """ self.current += 1 if self.current > self.total: raise StopIteration else: return self.iterable[self.current - 1]
def get_margin ( length ) : if length > 23 : margin_left = "\t" chars = 1 elif length > 15 : margin_left = "\t\t" chars = 2 elif length > 7 : margin_left = "\t\t\t" chars = 3 else : margin_left = "\t\t\t\t" chars = 4 return margin_left
0
how to define the range with 5 margin in python
Add enough tabs to align in two columns
cosqa-train-16964
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t" chars = 4 return margin_left
def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )
0
is a json file a python dictinary
Load JSON file
cosqa-train-16965
def from_file(file_path) -> dict: """ Load JSON file """ with io.open(file_path, 'r', encoding='utf-8') as json_stream: return Json.parse(json_stream, True)
def tail ( filename , number_of_bytes ) : with open ( filename , "rb" ) as f : if os . stat ( filename ) . st_size > number_of_bytes : f . seek ( - number_of_bytes , 2 ) return f . read ( )
1
how to check the first n bytes of a file in python
Returns the last number_of_bytes of filename
cosqa-train-16966
def tail(filename, number_of_bytes): """Returns the last number_of_bytes of filename""" with open(filename, "rb") as f: if os.stat(filename).st_size > number_of_bytes: f.seek(-number_of_bytes, 2) return f.read()
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
0
python sql executemany dictionary
Execute the given multiquery .
cosqa-train-16967
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None: """Execute the given multiquery.""" await self._execute(self._cursor.executemany, sql, parameters)
def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )
1
change python object to string
string dict / object / value to JSON
cosqa-train-16968
def string(value) -> str: """ string dict/object/value to JSON """ return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)
def get_timezone ( ) -> Tuple [ datetime . tzinfo , str ] : dt = get_datetime_now ( ) . astimezone ( ) tzstr = dt . strftime ( "%z" ) tzstr = tzstr [ : - 2 ] + ":" + tzstr [ - 2 : ] return dt . tzinfo , tzstr
1
how to get timezone in python
Discover the current time zone and it s standard string representation ( for source { d } ) .
cosqa-train-16969
def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] return dt.tzinfo, tzstr
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
1
python round float to higher int
rounds float to closest int : rtype : int : param n : float
cosqa-train-16970
def proper_round(n): """ rounds float to closest int :rtype: int :param n: float """ return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
1
if value isinteger python
Return true if a value is an integer number .
cosqa-train-16971
def is_integer(value: Any) -> bool: """Return true if a value is an integer number.""" return (isinstance(value, int) and not isinstance(value, bool)) or ( isinstance(value, float) and isfinite(value) and int(value) == value )
def getDimensionForImage ( filename , maxsize ) : try : from PIL import Image except ImportError : return None img = Image . open ( filename ) width , height = img . size if width > maxsize [ 0 ] or height > maxsize [ 1 ] : img . thumbnail ( maxsize ) out . info ( "Downscaled display size from %s to %s" % ( ( width , height ) , img . size ) ) return img . size
1
python get png image dimensions
Return scaled image size in ( width height ) format . The scaling preserves the aspect ratio . If PIL is not found returns None .
cosqa-train-16972
def getDimensionForImage(filename, maxsize): """Return scaled image size in (width, height) format. The scaling preserves the aspect ratio. If PIL is not found returns None.""" try: from PIL import Image except ImportError: return None img = Image.open(filename) width, height = img.size if width > maxsize[0] or height > maxsize[1]: img.thumbnail(maxsize) out.info("Downscaled display size from %s to %s" % ((width, height), img.size)) return img.size
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
0
get the index of last occurance of a string in list python
Index of the last occurrence of x in the sequence .
cosqa-train-16973
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
0
python elementtree remove element
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-16974
def recClearTag(element): """Applies maspy.xml.clearTag() to the tag attribute of the "element" and recursively to all child elements. :param element: an :instance:`xml.etree.Element` """ children = element.getchildren() if len(children) > 0: for child in children: recClearTag(child) element.tag = clearTag(element.tag)
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
0
how to split sentence based on delimiter using python
Split a text into a list of tokens .
cosqa-train-16975
def split(text: str) -> List[str]: """Split a text into a list of tokens. :param text: the text to split :return: tokens """ return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
0
remove multiple characters python
Removes all non - printable characters from a text string
cosqa-train-16976
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
def indices_to_labels ( self , indices : Sequence [ int ] ) -> List [ str ] : return [ ( self . INDEX_TO_LABEL [ index ] ) for index in indices ]
0
how to get index labels python
Converts a sequence of indices into their corresponding labels .
cosqa-train-16977
def indices_to_labels(self, indices: Sequence[int]) -> List[str]: """ Converts a sequence of indices into their corresponding labels.""" return [(self.INDEX_TO_LABEL[index]) for index in indices]
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
0
python how to check if a key doesnt exist
Check whether flyweight object with specified key has already been created .
cosqa-train-16978
def has_key(cls, *args): """ Check whether flyweight object with specified key has already been created. Returns: bool: True if already created, False if not """ key = args if len(args) > 1 else args[0] return key in cls._instances
def get_versions ( reporev = True ) : import sys import platform import qtpy import qtpy . QtCore revision = None if reporev : from spyder . utils import vcs revision , branch = vcs . get_git_revision ( os . path . dirname ( __dir__ ) ) if not sys . platform == 'darwin' : # To avoid a crash with our Mac app system = platform . system ( ) else : system = 'Darwin' return { 'spyder' : __version__ , 'python' : platform . python_version ( ) , # "2.7.3" 'bitness' : 64 if sys . maxsize > 2 ** 32 else 32 , 'qt' : qtpy . QtCore . __version__ , 'qt_api' : qtpy . API_NAME , # PyQt5 'qt_api_ver' : qtpy . PYQT_VERSION , 'system' : system , # Linux, Windows, ... 'release' : platform . release ( ) , # XP, 10.6, 2.2.0, etc. 'revision' : revision , # '9fdf926eccce' }
1
how to switch python version, spyder
Get version information for components used by Spyder
cosqa-train-16979
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
def _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
1
telling python to skip next line
Skip a section
cosqa-train-16980
def _skip_section(self): """Skip a section""" self._last = self._f.readline() while len(self._last) > 0 and len(self._last[0].strip()) == 0: self._last = self._f.readline()
async def cursor ( self ) -> Cursor : return Cursor ( self , await self . _execute ( self . _conn . cursor ) )
1
python sqlite open cursor with
Create an aiosqlite cursor wrapping a sqlite3 cursor object .
cosqa-train-16981
async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor))
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
0
finding the minimum of a certain dataset python
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
cosqa-train-16982
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ x = np.asarray(x) return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
0
top three in list python
Get a list of the top topn features in this : class : . Feature \ .
cosqa-train-16983
def top(self, topn=10): """ Get a list of the top ``topn`` features in this :class:`.Feature`\. Examples -------- .. code-block:: python >>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)]) >>> myFeature.top(1) [('trapezoid', 5)] Parameters ---------- topn : int Returns ------- list """ return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
0
using map inside a for loop in python
Wrapper to make map () behave the same on Py2 and Py3 .
cosqa-train-16984
def mmap(func, iterable): """Wrapper to make map() behave the same on Py2 and Py3.""" if sys.version_info[0] > 2: return [i for i in map(func, iterable)] else: return map(func, iterable)
def extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res
1
python new dictionary from existing dictionary
Merge two dicts and return a new dict . Much like subclassing works .
cosqa-train-16985
def extend(a: dict, b: dict) -> dict: """Merge two dicts and return a new dict. Much like subclassing works.""" res = a.copy() res.update(b) return res
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
1
check if valid date python
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
cosqa-train-16986
def valid_date(x: str) -> bool: """ Retrun ``True`` if ``x`` is a valid YYYYMMDD date; otherwise return ``False``. """ try: if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT): raise ValueError return True except ValueError: return False
def iter_lines ( file_like : Iterable [ str ] ) -> Generator [ str , None , None ] : for line in file_like : line = line . rstrip ( '\r\n' ) if line : yield line
0
skipping empty lines in python
Helper for iterating only nonempty lines without line breaks
cosqa-train-16987
def iter_lines(file_like: Iterable[str]) -> Generator[str, None, None]: """ Helper for iterating only nonempty lines without line breaks""" for line in file_like: line = line.rstrip('\r\n') if line: yield line
def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )
0
python3 string codec detect
Take a str and transform it into a byte array .
cosqa-train-16988
def strtobytes(input, encoding): """Take a str and transform it into a byte array.""" py_version = sys.version_info[0] if py_version >= 3: return _strtobytes_py3(input, encoding) return _strtobytes_py2(input, encoding)
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
0
python elementtree xml remove
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
cosqa-train-16989
def recClearTag(element): """Applies maspy.xml.clearTag() to the tag attribute of the "element" and recursively to all child elements. :param element: an :instance:`xml.etree.Element` """ children = element.getchildren() if len(children) > 0: for child in children: recClearTag(child) element.tag = clearTag(element.tag)
def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )
1
how to evaluate if strings are equal python
Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )
cosqa-train-16990
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
def read ( self , count = 0 ) : return self . f . read ( count ) if count > 0 else self . f . read ( )
1
python read file as one line
Read
cosqa-train-16991
def read(self, count=0): """ Read """ return self.f.read(count) if count > 0 else self.f.read()
def bfx ( value , msb , lsb ) : mask = bitmask ( ( msb , lsb ) ) return ( value & mask ) >> lsb
1
fastest way to take bitwise or python
!
cosqa-train-16992
def bfx(value, msb, lsb): """! @brief Extract a value from a bitfield.""" mask = bitmask((msb, lsb)) return (value & mask) >> lsb
def obj_in_list_always ( target_list , obj ) : for item in set ( target_list ) : if item is not obj : return False return True
1
if element is not in a list in python
>>> l = [ 1 1 1 ] >>> obj_in_list_always ( l 1 ) True >>> l . append ( 2 ) >>> obj_in_list_always ( l 1 ) False
cosqa-train-16993
def obj_in_list_always(target_list, obj): """ >>> l = [1,1,1] >>> obj_in_list_always(l, 1) True >>> l.append(2) >>> obj_in_list_always(l, 1) False """ for item in set(target_list): if item is not obj: return False return True
def lowercase_chars ( string : any ) -> str : return '' . join ( [ c if c . islower ( ) else '' for c in str ( string ) ] )
1
return the string in all lowercase except the last character is uppercase python
Return all ( and only ) the lowercase chars in the given string .
cosqa-train-16994
def lowercase_chars(string: any) -> str: """Return all (and only) the lowercase chars in the given string.""" return ''.join([c if c.islower() else '' for c in str(string)])
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
check in python variable is str
Validates that the object itself is some kinda string
cosqa-train-16995
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def assert_valid_name ( name : str ) -> str : error = is_valid_name_error ( name ) if error : raise error return name
1
how to give name validation from input python
Uphold the spec rules about naming .
cosqa-train-16996
def assert_valid_name(name: str) -> str: """Uphold the spec rules about naming.""" error = is_valid_name_error(name) if error: raise error return name
def datetime_iso_format ( date ) : return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z" . format ( date . year , date . month , date . day , date . hour , date . minute , date . second )
1
python datetime isoformat layout
Return an ISO - 8601 representation of a datetime object .
cosqa-train-16997
def datetime_iso_format(date): """ Return an ISO-8601 representation of a datetime object. """ return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format( date.year, date.month, date.day, date.hour, date.minute, date.second)
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
1
python how to check if something is not a str
Validates that the object itself is some kinda string
cosqa-train-16998
def is_unicode(string): """Validates that the object itself is some kinda string""" str_type = str(type(string)) if str_type.find('str') > 0 or str_type.find('unicode') > 0: return True return False
def gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] : for string in x : yield string . lower ( )
0
lower all items in list python
Args : x : iterable of strings
cosqa-train-16999
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]: """ Args: x: iterable of strings Yields: each string in lower case """ for string in x: yield string.lower()