[ { "idx": "cosqa-train-12467", "doc": "sort by a token in string python", "code": "def _process_and_sort(s, force_ascii, full_process=True):\n \"\"\"Return a cleaned string with token sorted.\"\"\"\n # pull tokens\n ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s\n tokens = ts.split()\n\n # sort tokens and join\n sorted_string = u\" \".join(sorted(tokens))\n return sorted_string.strip()", "code_tokens": "def _process_and_sort ( s , force_ascii , full_process = True ) : # pull tokens ts = utils . full_process ( s , force_ascii = force_ascii ) if full_process else s tokens = ts . split ( ) # sort tokens and join sorted_string = u\" \" . join ( sorted ( tokens ) ) return sorted_string . strip ( )", "docstring_tokens": "Return a cleaned string with token sorted .", "label": 1, "retrieval_idx": 4833, "negative": "Call an external binary and return its stdout ." }, { "idx": "cosqa-train-14641", "doc": "python check file is readonly", "code": "def is_readable(filename):\n \"\"\"Check if file is a regular file and is readable.\"\"\"\n return os.path.isfile(filename) and os.access(filename, os.R_OK)", "code_tokens": "def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )", "docstring_tokens": "Check if file is a regular file and is readable .", "label": 1, "retrieval_idx": 2445, "negative": "Pop the heap value from the heap ." }, { "idx": "cosqa-train-13074", "doc": "declaring empty numpy array in python", "code": "def empty(self, name, **kwargs):\n \"\"\"Create an array. Keyword arguments as per\n :func:`zarr.creation.empty`.\"\"\"\n return self._write_op(self._empty_nosync, name, **kwargs)", "code_tokens": "def empty ( self , name , * * kwargs ) : return self . _write_op ( self . _empty_nosync , name , * * kwargs )", "docstring_tokens": "Create an array . Keyword arguments as per : func : zarr . creation . empty .", "label": 1, "retrieval_idx": 4923, "negative": "View the quaternion array as an array of floats" }, { "idx": "cosqa-train-14677", "doc": "test for iterable is string in python", "code": "def is_iterable_but_not_string(obj):\n \"\"\"\n Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n \"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "code_tokens": "def is_iterable_but_not_string ( obj ) : return hasattr ( obj , '__iter__' ) and not isinstance ( obj , str ) and not isinstance ( obj , bytes )", "docstring_tokens": "Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) .", "label": 1, "retrieval_idx": 1640, "negative": "Check if arg is a valid file that already exists on the file system ." }, { "idx": "cosqa-train-9500", "doc": "python print results of query loop", "code": "def print_runs(query):\n \"\"\" Print all rows in this result query. \"\"\"\n\n if query is None:\n return\n\n for tup in query:\n print((\"{0} @ {1} - {2} id: {3} group: {4}\".format(\n tup.end, tup.experiment_name, tup.project_name,\n tup.experiment_group, tup.run_group)))", "code_tokens": "def print_runs ( query ) : if query is None : return for tup in query : print ( ( \"{0} @ {1} - {2} id: {3} group: {4}\" . format ( tup . end , tup . experiment_name , tup . project_name , tup . experiment_group , tup . run_group ) ) )", "docstring_tokens": "Print all rows in this result query .", "label": 1, "retrieval_idx": 4258, "negative": "Run the unit tests ." }, { "idx": "cosqa-train-1335", "doc": "how to save header of fits file to export python", "code": "def write_fits(self, fitsfile):\n \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n tab = self.create_table()\n hdu_data = fits.table_to_hdu(tab)\n hdus = [fits.PrimaryHDU(), hdu_data]\n fits_utils.write_hdus(hdus, fitsfile)", "code_tokens": "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 )", "docstring_tokens": "Write the ROI model to a FITS file .", "label": 1, "retrieval_idx": 1138, "negative": "Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing" }, { "idx": "cosqa-train-19221", "doc": "python calc page align", "code": "def page_align_content_length(length):\n # type: (int) -> int\n \"\"\"Compute page boundary alignment\n :param int length: content length\n :rtype: int\n :return: aligned byte boundary\n \"\"\"\n mod = length % _PAGEBLOB_BOUNDARY\n if mod != 0:\n return length + (_PAGEBLOB_BOUNDARY - mod)\n return length", "code_tokens": "def page_align_content_length ( length ) : # type: (int) -> int mod = length % _PAGEBLOB_BOUNDARY if mod != 0 : return length + ( _PAGEBLOB_BOUNDARY - mod ) return length", "docstring_tokens": "Compute page boundary alignment : param int length : content length : rtype : int : return : aligned byte boundary", "label": 1, "retrieval_idx": 6173, "negative": "Return whether this collection contains all items ." }, { "idx": "cosqa-train-971", "doc": "python numpy array as float", "code": "def as_float_array(a):\n \"\"\"View the quaternion array as an array of floats\n\n This function is fast (of order 1 microsecond) because no data is\n copied; the returned quantity is just a \"view\" of the original.\n\n The output view has one more dimension (of size 4) than the input\n array, but is otherwise the same shape.\n\n \"\"\"\n return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "code_tokens": "def as_float_array ( a ) : return np . asarray ( a , dtype = np . quaternion ) . view ( ( np . double , 4 ) )", "docstring_tokens": "View the quaternion array as an array of floats", "label": 1, "retrieval_idx": 854, "negative": "Note that the Executor must be close () d elsewhere or join () will never return ." }, { "idx": "cosqa-train-18162", "doc": "input string that replaces occurences python", "code": "def __replace_all(repls: dict, input: str) -> str:\n \"\"\" Replaces from a string **input** all the occurrences of some\n symbols according to mapping **repls**.\n\n :param dict repls: where #key is the old character and\n #value is the one to substitute with;\n :param str input: original string where to apply the\n replacements;\n :return: *(str)* the string with the desired characters replaced\n \"\"\"\n return re.sub('|'.join(re.escape(key) for key in repls.keys()),\n lambda k: repls[k.group(0)], input)", "code_tokens": "def __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )", "docstring_tokens": "Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .", "label": 1, "retrieval_idx": 5637, "negative": "A handy wrapper to get a remote file content" }, { "idx": "cosqa-train-14635", "doc": "python check all items in list are ints", "code": "def is_iterable_of_int(l):\n r\"\"\" Checks if l is iterable and contains only integral types \"\"\"\n if not is_iterable(l):\n return False\n\n return all(is_int(value) for value in l)", "code_tokens": "def is_iterable_of_int ( l ) : if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l )", "docstring_tokens": "r Checks if l is iterable and contains only integral types", "label": 1, "retrieval_idx": 1613, "negative": "Probability density function ( normal distribution )" }, { "idx": "cosqa-train-9770", "doc": "how to save variable to text file python", "code": "def save(variable, filename):\n \"\"\"Save variable on given path using Pickle\n \n Args:\n variable: what to save\n path (str): path of the output\n \"\"\"\n fileObj = open(filename, 'wb')\n pickle.dump(variable, fileObj)\n fileObj.close()", "code_tokens": "def save ( variable , filename ) : fileObj = open ( filename , 'wb' ) pickle . dump ( variable , fileObj ) fileObj . close ( )", "docstring_tokens": "Save variable on given path using Pickle Args : variable : what to save path ( str ) : path of the output", "label": 1, "retrieval_idx": 1135, "negative": ": type aws_access_key_id : string : param aws_access_key_id : Your AWS Access Key ID" }, { "idx": "cosqa-train-11848", "doc": "how to skip an index in a for loop python", "code": "def stop_at(iterable, idx):\n \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n for i, item in enumerate(iterable):\n if i == idx: return\n yield item", "code_tokens": "def stop_at ( iterable , idx ) : for i , item in enumerate ( iterable ) : if i == idx : return yield item", "docstring_tokens": "Stops iterating before yielding the specified idx .", "label": 1, "retrieval_idx": 2047, "negative": "Extract from the given iterable of lines the list of words ." }, { "idx": "cosqa-train-13623", "doc": "how to create a tokenization code in python", "code": "def token(name):\n \"\"\"Marker for a token\n\n :param str name: Name of tokenizer\n \"\"\"\n\n def wrap(f):\n tokenizers.append((name, f))\n return f\n\n return wrap", "code_tokens": "def token ( name ) : def wrap ( f ) : tokenizers . append ( ( name , f ) ) return f return wrap", "docstring_tokens": "Marker for a token", "label": 1, "retrieval_idx": 4516, "negative": "parse_query_string : very simplistic . won t do the right thing with list values" }, { "idx": "cosqa-train-19558", "doc": "python raise without parentheses", "code": "def assert_or_raise(stmt: bool, exception: Exception,\n *exception_args, **exception_kwargs) -> None:\n \"\"\"\n If the statement is false, raise the given exception.\n \"\"\"\n if not stmt:\n raise exception(*exception_args, **exception_kwargs)", "code_tokens": "def assert_or_raise ( stmt : bool , exception : Exception , * exception_args , * * exception_kwargs ) -> None : if not stmt : raise exception ( * exception_args , * * exception_kwargs )", "docstring_tokens": "If the statement is false raise the given exception .", "label": 1, "retrieval_idx": 6088, "negative": "Returns whether a path names an existing directory we can list and read files from ." }, { "idx": "cosqa-train-7659", "doc": "how to seperate list with commas python", "code": "def _return_comma_list(self, l):\n \"\"\" get a list and return a string with comma separated list values\n Examples ['to', 'ta'] will return 'to,ta'.\n \"\"\"\n if isinstance(l, (text_type, int)):\n return l\n\n if not isinstance(l, list):\n raise TypeError(l, ' should be a list of integers, \\\nnot {0}'.format(type(l)))\n\n str_ids = ','.join(str(i) for i in l)\n\n return str_ids", "code_tokens": "def _return_comma_list ( self , l ) : if isinstance ( l , ( text_type , int ) ) : return l if not isinstance ( l , list ) : raise TypeError ( l , ' should be a list of integers, \\\nnot {0}' . format ( type ( l ) ) ) str_ids = ',' . join ( str ( i ) for i in l ) return str_ids", "docstring_tokens": "get a list and return a string with comma separated list values Examples [ to ta ] will return to ta .", "label": 1, "retrieval_idx": 3842, "negative": "Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process" }, { "idx": "cosqa-train-6056", "doc": "python asynchronous function call return", "code": "def asynchronous(function, event):\n \"\"\"\n Runs the function asynchronously taking care of exceptions.\n \"\"\"\n thread = Thread(target=synchronous, args=(function, event))\n thread.daemon = True\n thread.start()", "code_tokens": "def asynchronous ( function , event ) : thread = Thread ( target = synchronous , args = ( function , event ) ) thread . daemon = True thread . start ( )", "docstring_tokens": "Runs the function asynchronously taking care of exceptions .", "label": 1, "retrieval_idx": 318, "negative": "function : to be called with each stream element as its only argument" }, { "idx": "cosqa-train-11671", "doc": "how to make a seconds to time in python", "code": "def time2seconds(t):\n \"\"\"Returns seconds since 0h00.\"\"\"\n return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6", "code_tokens": "def time2seconds ( t ) : return t . hour * 3600 + t . minute * 60 + t . second + float ( t . microsecond ) / 1e6", "docstring_tokens": "Returns seconds since 0h00 .", "label": 1, "retrieval_idx": 3713, "negative": "Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket" }, { "idx": "cosqa-train-14597", "doc": "python cast true or false as numbers", "code": "def _to_numeric(val):\n \"\"\"\n Helper function for conversion of various data types into numeric representation.\n \"\"\"\n if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):\n return val\n return float(val)", "code_tokens": "def _to_numeric ( val ) : if isinstance ( val , ( int , float , datetime . datetime , datetime . timedelta ) ) : return val return float ( val )", "docstring_tokens": "Helper function for conversion of various data types into numeric representation .", "label": 1, "retrieval_idx": 1299, "negative": "Make a list unique retaining order of initial appearance ." }, { "idx": "cosqa-train-2166", "doc": "add milliseconds to datetime python", "code": "def datetime_to_ms(dt):\n \"\"\"\n Converts a datetime to a millisecond accuracy timestamp\n \"\"\"\n seconds = calendar.timegm(dt.utctimetuple())\n return seconds * 1000 + int(dt.microsecond / 1000)", "code_tokens": "def datetime_to_ms ( dt ) : seconds = calendar . timegm ( dt . utctimetuple ( ) ) return seconds * 1000 + int ( dt . microsecond / 1000 )", "docstring_tokens": "Converts a datetime to a millisecond accuracy timestamp", "label": 1, "retrieval_idx": 115, "negative": "Initiates a graceful stop of the processes" }, { "idx": "cosqa-train-7579", "doc": "how to read the last n lines of a program on python", "code": "def get_readline_tail(self, n=10):\n \"\"\"Get the last n items in readline history.\"\"\"\n end = self.shell.readline.get_current_history_length() + 1\n start = max(end-n, 1)\n ghi = self.shell.readline.get_history_item\n return [ghi(x) for x in range(start, end)]", "code_tokens": "def get_readline_tail ( self , n = 10 ) : end = self . shell . readline . get_current_history_length ( ) + 1 start = max ( end - n , 1 ) ghi = self . shell . readline . get_history_item return [ ghi ( x ) for x in range ( start , end ) ]", "docstring_tokens": "Get the last n items in readline history .", "label": 1, "retrieval_idx": 2729, "negative": "Get the current desktop . Uses _NET_CURRENT_DESKTOP of the EWMH spec ." }, { "idx": "cosqa-train-11454", "doc": "python mysql get list of table columns", "code": "def get_table_columns(dbconn, tablename):\n \"\"\"\n Return a list of tuples specifying the column name and type\n \"\"\"\n cur = dbconn.cursor()\n cur.execute(\"PRAGMA table_info('%s');\" % tablename)\n info = cur.fetchall()\n cols = [(i[1], i[2]) for i in info]\n return cols", "code_tokens": "def get_table_columns ( dbconn , tablename ) : cur = dbconn . cursor ( ) cur . execute ( \"PRAGMA table_info('%s');\" % tablename ) info = cur . fetchall ( ) cols = [ ( i [ 1 ] , i [ 2 ] ) for i in info ] return cols", "docstring_tokens": "Return a list of tuples specifying the column name and type", "label": 1, "retrieval_idx": 277, "negative": "Like pretty but print to stdout ." }, { "idx": "cosqa-train-17712", "doc": "how to get domain part of a url in python", "code": "def url_host(url: str) -> str:\n \"\"\"\n Parses hostname from URL.\n :param url: URL\n :return: hostname\n \"\"\"\n from urllib.parse import urlparse\n res = urlparse(url)\n return res.netloc.split(':')[0] if res.netloc else ''", "code_tokens": "def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''", "docstring_tokens": "Parses hostname from URL . : param url : URL : return : hostname", "label": 1, "retrieval_idx": 5694, "negative": "Takes JSON formatted data converting it into native Python objects" }, { "idx": "cosqa-train-18531", "doc": "python flatten a nested dictionaary", "code": "def flatten_multidict(multidict):\n \"\"\"Return flattened dictionary from ``MultiDict``.\"\"\"\n return dict([(key, value if len(value) > 1 else value[0])\n for (key, value) in multidict.iterlists()])", "code_tokens": "def flatten_multidict ( multidict ) : return dict ( [ ( key , value if len ( value ) > 1 else value [ 0 ] ) for ( key , value ) in multidict . iterlists ( ) ] )", "docstring_tokens": "Return flattened dictionary from MultiDict .", "label": 1, "retrieval_idx": 5724, "negative": "A handy wrapper to get a remote file content" }, { "idx": "cosqa-train-3393", "doc": "python session set get", "code": "def _session_set(self, key, value):\n \"\"\"\n Saves a value to session.\n \"\"\"\n\n self.session[self._session_key(key)] = value", "code_tokens": "def _session_set ( self , key , value ) : self . session [ self . _session_key ( key ) ] = value", "docstring_tokens": "Saves a value to session .", "label": 1, "retrieval_idx": 2346, "negative": "" }, { "idx": "cosqa-dev-5", "doc": "python save graph into file", "code": "def to_dotfile(G: nx.DiGraph, filename: str):\n \"\"\" Output a networkx graph to a DOT file. \"\"\"\n A = to_agraph(G)\n A.write(filename)", "code_tokens": "def to_dotfile ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . write ( filename )", "docstring_tokens": "Output a networkx graph to a DOT file .", "label": 1, "retrieval_idx": 3702, "negative": "Return the fully - qualified name of a function ." }, { "idx": "cosqa-train-10817", "doc": "chmod python windows to remove file", "code": "def rmfile(path):\n \"\"\"Ensure file deleted also on *Windows* where read-only files need special treatment.\"\"\"\n if osp.isfile(path):\n if is_win:\n os.chmod(path, 0o777)\n os.remove(path)", "code_tokens": "def rmfile ( path ) : if osp . isfile ( path ) : if is_win : os . chmod ( path , 0o777 ) os . remove ( path )", "docstring_tokens": "Ensure file deleted also on * Windows * where read - only files need special treatment .", "label": 1, "retrieval_idx": 4551, "negative": "Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays ." }, { "idx": "cosqa-train-6390", "doc": "add suffixes on concat python", "code": "def add_suffix(fullname, suffix):\n \"\"\" Add suffix to a full file name\"\"\"\n name, ext = os.path.splitext(fullname)\n return name + '_' + suffix + ext", "code_tokens": "def add_suffix ( fullname , suffix ) : name , ext = os . path . splitext ( fullname ) return name + '_' + suffix + ext", "docstring_tokens": "Add suffix to a full file name", "label": 1, "retrieval_idx": 2100, "negative": "Reads cplex file and returns glpk problem ." }, { "idx": "cosqa-train-11396", "doc": "how to check python object iterable", "code": "def is_iterable_but_not_string(obj):\n \"\"\"\n Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).\n \"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)", "code_tokens": "def is_iterable_but_not_string ( obj ) : return hasattr ( obj , '__iter__' ) and not isinstance ( obj , str ) and not isinstance ( obj , bytes )", "docstring_tokens": "Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) .", "label": 1, "retrieval_idx": 1640, "negative": "Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists ." }, { "idx": "cosqa-train-8122", "doc": "python 3 tkinter open file dialog", "code": "def askopenfilename(**kwargs):\n \"\"\"Return file name(s) from Tkinter's file open dialog.\"\"\"\n try:\n from Tkinter import Tk\n import tkFileDialog as filedialog\n except ImportError:\n from tkinter import Tk, filedialog\n root = Tk()\n root.withdraw()\n root.update()\n filenames = filedialog.askopenfilename(**kwargs)\n root.destroy()\n return filenames", "code_tokens": "def askopenfilename ( * * kwargs ) : try : from Tkinter import Tk import tkFileDialog as filedialog except ImportError : from tkinter import Tk , filedialog root = Tk ( ) root . withdraw ( ) root . update ( ) filenames = filedialog . askopenfilename ( * * kwargs ) root . destroy ( ) return filenames", "docstring_tokens": "Return file name ( s ) from Tkinter s file open dialog .", "label": 1, "retrieval_idx": 3956, "negative": "Intersect dictionaries d1 and d2 by key * and * value ." }, { "idx": "cosqa-train-11614", "doc": "how to indent self python", "code": "def _pad(self):\n \"\"\"Pads the output with an amount of indentation appropriate for the number of open element.\n\n This method does nothing if the indent value passed to the constructor is falsy.\n \"\"\"\n if self._indent:\n self.whitespace(self._indent * len(self._open_elements))", "code_tokens": "def _pad ( self ) : if self . _indent : self . whitespace ( self . _indent * len ( self . _open_elements ) )", "docstring_tokens": "Pads the output with an amount of indentation appropriate for the number of open element .", "label": 1, "retrieval_idx": 4150, "negative": "Add suffix to a full file name" }, { "idx": "cosqa-train-10474", "doc": "tracking centroid of an object python", "code": "def compute_centroid(points):\n \"\"\" Computes the centroid of set of points\n\n Args:\n points (:obj:`list` of :obj:`Point`)\n Returns:\n :obj:`Point`\n \"\"\"\n lats = [p[1] for p in points]\n lons = [p[0] for p in points]\n return Point(np.mean(lats), np.mean(lons), None)", "code_tokens": "def compute_centroid ( points ) : lats = [ p [ 1 ] for p in points ] lons = [ p [ 0 ] for p in points ] return Point ( np . mean ( lats ) , np . mean ( lons ) , None )", "docstring_tokens": "Computes the centroid of set of points", "label": 1, "retrieval_idx": 4486, "negative": "A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right ." }, { "idx": "cosqa-train-10122", "doc": "python3 ctypes return float array", "code": "def cfloat32_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes float pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):\n return np.fromiter(cptr, dtype=np.float32, count=length)\n else:\n raise RuntimeError('Expected float pointer')", "code_tokens": "def cfloat32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_float ) ) : return np . fromiter ( cptr , dtype = np . float32 , count = length ) else : raise RuntimeError ( 'Expected float pointer' )", "docstring_tokens": "Convert a ctypes float pointer array to a numpy array .", "label": 1, "retrieval_idx": 82, "negative": "Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists ." }, { "idx": "cosqa-train-13872", "doc": "how to make paragraphs in python", "code": "def paragraph(separator='\\n\\n', wrap_start='', wrap_end='',\n html=False, sentences_quantity=3):\n \"\"\"Return a random paragraph.\"\"\"\n return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,\n wrap_end=wrap_end, html=html,\n sentences_quantity=sentences_quantity)", "code_tokens": "def paragraph ( separator = '\\n\\n' , wrap_start = '' , wrap_end = '' , html = False , sentences_quantity = 3 ) : return paragraphs ( quantity = 1 , separator = separator , wrap_start = wrap_start , wrap_end = wrap_end , html = html , sentences_quantity = sentences_quantity )", "docstring_tokens": "Return a random paragraph .", "label": 1, "retrieval_idx": 5074, "negative": "Under UNIX : is a keystroke available?" }, { "idx": "cosqa-train-17177", "doc": "python rest requests delete", "code": "def delete(self, endpoint: str, **kwargs) -> dict:\n \"\"\"HTTP DELETE operation to API endpoint.\"\"\"\n\n return self._request('DELETE', endpoint, **kwargs)", "code_tokens": "def delete ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'DELETE' , endpoint , * * kwargs )", "docstring_tokens": "HTTP DELETE operation to API endpoint .", "label": 1, "retrieval_idx": 5719, "negative": "hacky inference of kwargs keys" }, { "idx": "cosqa-train-5418", "doc": "python replace month number", "code": "def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):\n \"\"\"Replace month strings occurrences with month number.\"\"\"\n num, abbr = get_month_from_date_str(date_str, lang)\n return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE)", "code_tokens": "def replace_month_abbr_with_num ( date_str , lang = DEFAULT_DATE_LANG ) : num , abbr = get_month_from_date_str ( date_str , lang ) return re . sub ( abbr , str ( num ) , date_str , flags = re . IGNORECASE )", "docstring_tokens": "Replace month strings occurrences with month number .", "label": 1, "retrieval_idx": 2762, "negative": "An iterable of column names for a particular table or view ." }, { "idx": "cosqa-train-9873", "doc": "how to tell what type of data object is in python", "code": "def is_integer(obj):\n \"\"\"Is this an integer.\n\n :param object obj:\n :return:\n \"\"\"\n if PYTHON3:\n return isinstance(obj, int)\n return isinstance(obj, (int, long))", "code_tokens": "def is_integer ( obj ) : if PYTHON3 : return isinstance ( obj , int ) return isinstance ( obj , ( int , long ) )", "docstring_tokens": "Is this an integer .", "label": 1, "retrieval_idx": 2128, "negative": "Is an object iterable like a list ( and not a string ) ?" }, { "idx": "cosqa-train-13440", "doc": "python jsonschema validate schema file", "code": "def _validate(data, schema, ac_schema_safe=True, **options):\n \"\"\"\n See the descritpion of :func:`validate` for more details of parameters and\n return value.\n\n Validate target object 'data' with given schema object.\n \"\"\"\n try:\n jsonschema.validate(data, schema, **options)\n\n except (jsonschema.ValidationError, jsonschema.SchemaError,\n Exception) as exc:\n if ac_schema_safe:\n return (False, str(exc)) # Validation was failed.\n raise\n\n return (True, '')", "code_tokens": "def _validate ( data , schema , ac_schema_safe = True , * * options ) : try : jsonschema . validate ( data , schema , * * options ) except ( jsonschema . ValidationError , jsonschema . SchemaError , Exception ) as exc : if ac_schema_safe : return ( False , str ( exc ) ) # Validation was failed. raise return ( True , '' )", "docstring_tokens": "See the descritpion of : func : validate for more details of parameters and return value .", "label": 1, "retrieval_idx": 5004, "negative": "calculate the fill similarity over the image" }, { "idx": "cosqa-train-18685", "doc": "get wechat access token python", "code": "def access_token(self):\n \"\"\" WeChat access token \"\"\"\n access_token = self.session.get(self.access_token_key)\n if access_token:\n if not self.expires_at:\n # user provided access_token, just return it\n return access_token\n\n timestamp = time.time()\n if self.expires_at - timestamp > 60:\n return access_token\n\n self.fetch_access_token()\n return self.session.get(self.access_token_key)", "code_tokens": "def access_token ( self ) : access_token = self . session . get ( self . access_token_key ) if access_token : if not self . expires_at : # user provided access_token, just return it return access_token timestamp = time . time ( ) if self . expires_at - timestamp > 60 : return access_token self . fetch_access_token ( ) return self . session . get ( self . access_token_key )", "docstring_tokens": "WeChat access token", "label": 1, "retrieval_idx": 6100, "negative": "Print list of namedtuples into a table using prtfmt ." }, { "idx": "cosqa-train-12523", "doc": "python change str value to int", "code": "def str2int(num, radix=10, alphabet=BASE85):\n \"\"\"helper function for quick base conversions from strings to integers\"\"\"\n return NumConv(radix, alphabet).str2int(num)", "code_tokens": "def str2int ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . str2int ( num )", "docstring_tokens": "helper function for quick base conversions from strings to integers", "label": 1, "retrieval_idx": 1831, "negative": "Get a list of the public data attributes ." }, { "idx": "cosqa-train-7800", "doc": "implementing drag and drop python", "code": "def drag_and_drop(self, droppable):\n \"\"\"\n Performs drag a element to another elmenet.\n\n Currently works only on Chrome driver.\n \"\"\"\n self.scroll_to()\n ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()", "code_tokens": "def drag_and_drop ( self , droppable ) : self . scroll_to ( ) ActionChains ( self . parent . driver ) . drag_and_drop ( self . _element , droppable . _element ) . perform ( )", "docstring_tokens": "Performs drag a element to another elmenet .", "label": 1, "retrieval_idx": 547, "negative": "If the statement is false raise the given exception ." }, { "idx": "cosqa-train-9131", "doc": "get unique list from two lists python", "code": "def unique_list(lst):\n \"\"\"Make a list unique, retaining order of initial appearance.\"\"\"\n uniq = []\n for item in lst:\n if item not in uniq:\n uniq.append(item)\n return uniq", "code_tokens": "def unique_list ( lst ) : uniq = [ ] for item in lst : if item not in uniq : uniq . append ( item ) return uniq", "docstring_tokens": "Make a list unique retaining order of initial appearance .", "label": 1, "retrieval_idx": 351, "negative": "Python s input () is blocking which means the event loop we set above can t be running while we re blocking there . This method will let the loop run while we wait for input ." }, { "idx": "cosqa-train-5981", "doc": "python 3 not runnning in git bash", "code": "def check_git():\n \"\"\"Check if git command is available.\"\"\"\n try:\n with open(os.devnull, \"wb\") as devnull:\n subprocess.check_call([\"git\", \"--version\"], stdout=devnull, stderr=devnull)\n except:\n raise RuntimeError(\"Please make sure git is installed and on your path.\")", "code_tokens": "def check_git ( ) : try : with open ( os . devnull , \"wb\" ) as devnull : subprocess . check_call ( [ \"git\" , \"--version\" ] , stdout = devnull , stderr = devnull ) except : raise RuntimeError ( \"Please make sure git is installed and on your path.\" )", "docstring_tokens": "Check if git command is available .", "label": 1, "retrieval_idx": 632, "negative": ": param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str" }, { "idx": "cosqa-train-15181", "doc": "create unknown number of names to print in python", "code": "def prt_nts(data_nts, prtfmt=None, prt=sys.stdout, nt_fields=None, **kws):\n \"\"\"Print list of namedtuples into a table using prtfmt.\"\"\"\n prt_txt(prt, data_nts, prtfmt, nt_fields, **kws)", "code_tokens": "def prt_nts ( data_nts , prtfmt = None , prt = sys . stdout , nt_fields = None , * * kws ) : prt_txt ( prt , data_nts , prtfmt , nt_fields , * * kws )", "docstring_tokens": "Print list of namedtuples into a table using prtfmt .", "label": 1, "retrieval_idx": 5286, "negative": "Return a dataframe that is a cross between dataframes df1 and df2" }, { "idx": "cosqa-train-13426", "doc": "python json if element exists", "code": "def task_property_present_predicate(service, task, prop):\n \"\"\" True if the json_element passed is present for the task specified.\n \"\"\"\n try:\n response = get_service_task(service, task)\n except Exception as e:\n pass\n\n return (response is not None) and (prop in response)", "code_tokens": "def task_property_present_predicate ( service , task , prop ) : try : response = get_service_task ( service , task ) except Exception as e : pass return ( response is not None ) and ( prop in response )", "docstring_tokens": "True if the json_element passed is present for the task specified .", "label": 1, "retrieval_idx": 1785, "negative": "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 )" }, { "idx": "cosqa-train-16586", "doc": "number of unique values in list python", "code": "def count_list(the_list):\n \"\"\"\n Generates a count of the number of times each unique item appears in a list\n \"\"\"\n count = the_list.count\n result = [(item, count(item)) for item in set(the_list)]\n result.sort()\n return result", "code_tokens": "def count_list ( the_list ) : count = the_list . count result = [ ( item , count ( item ) ) for item in set ( the_list ) ] result . sort ( ) return result", "docstring_tokens": "Generates a count of the number of times each unique item appears in a list", "label": 1, "retrieval_idx": 320, "negative": "Fill NaNs with the previous value the next value or if all are NaN then 1 . 0" }, { "idx": "cosqa-train-13950", "doc": "how to randomize items in a list in python", "code": "def get_randomized_guid_sample(self, item_count):\n \"\"\" Fetch a subset of randomzied GUIDs from the whitelist \"\"\"\n dataset = self.get_whitelist()\n random.shuffle(dataset)\n return dataset[:item_count]", "code_tokens": "def get_randomized_guid_sample ( self , item_count ) : dataset = self . get_whitelist ( ) random . shuffle ( dataset ) return dataset [ : item_count ]", "docstring_tokens": "Fetch a subset of randomzied GUIDs from the whitelist", "label": 1, "retrieval_idx": 2328, "negative": "Returns all dates between two dates ." }, { "idx": "cosqa-train-19258", "doc": "python windows check for keypress", "code": "def _kbhit_unix() -> bool:\n \"\"\"\n Under UNIX: is a keystroke available?\n \"\"\"\n dr, dw, de = select.select([sys.stdin], [], [], 0)\n return dr != []", "code_tokens": "def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]", "docstring_tokens": "Under UNIX : is a keystroke available?", "label": 1, "retrieval_idx": 5666, "negative": "Process an iterable of dictionaries . For each dictionary d change ( in place ) d [ key ] to value ." }, { "idx": "cosqa-train-14549", "doc": "python bind scrollbar to canvas", "code": "def set_scrollregion(self, event=None):\n \"\"\" Set the scroll region on the canvas\"\"\"\n self.canvas.configure(scrollregion=self.canvas.bbox('all'))", "code_tokens": "def set_scrollregion ( self , event = None ) : self . canvas . configure ( scrollregion = self . canvas . bbox ( 'all' ) )", "docstring_tokens": "Set the scroll region on the canvas", "label": 1, "retrieval_idx": 2648, "negative": "Return a legal python name for the given name for use as a unit key ." }, { "idx": "cosqa-train-13999", "doc": "python setlevel how to only record error", "code": "def print_fatal_results(results, level=0):\n \"\"\"Print fatal errors that occurred during validation runs.\n \"\"\"\n print_level(logger.critical, _RED + \"[X] Fatal Error: %s\", level, results.error)", "code_tokens": "def print_fatal_results ( results , level = 0 ) : print_level ( logger . critical , _RED + \"[X] Fatal Error: %s\" , level , results . error )", "docstring_tokens": "Print fatal errors that occurred during validation runs .", "label": 1, "retrieval_idx": 5088, "negative": "Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process" }, { "idx": "cosqa-dev-442", "doc": "format string with *args python", "code": "def safe_format(s, **kwargs):\n \"\"\"\n :type s str\n \"\"\"\n return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))", "code_tokens": "def safe_format ( s , * * kwargs ) : return string . Formatter ( ) . vformat ( s , ( ) , defaultdict ( str , * * kwargs ) )", "docstring_tokens": ": type s str", "label": 1, "retrieval_idx": 338, "negative": "Set x - axis limits of a subplot ." }, { "idx": "cosqa-train-17869", "doc": "python get hostip from url", "code": "def url_host(url: str) -> str:\n \"\"\"\n Parses hostname from URL.\n :param url: URL\n :return: hostname\n \"\"\"\n from urllib.parse import urlparse\n res = urlparse(url)\n return res.netloc.split(':')[0] if res.netloc else ''", "code_tokens": "def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''", "docstring_tokens": "Parses hostname from URL . : param url : URL : return : hostname", "label": 1, "retrieval_idx": 5694, "negative": "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 )" }, { "idx": "cosqa-train-11505", "doc": "python numpy masked vailding", "code": "def asMaskedArray(self):\n \"\"\" Creates converts to a masked array\n \"\"\"\n return ma.masked_array(data=self.data, mask=self.mask, fill_value=self.fill_value)", "code_tokens": "def asMaskedArray ( self ) : return ma . masked_array ( data = self . data , mask = self . mask , fill_value = self . fill_value )", "docstring_tokens": "Creates converts to a masked array", "label": 1, "retrieval_idx": 4210, "negative": "Return the number of active CPUs on a Darwin system ." }, { "idx": "cosqa-train-14720", "doc": "python child widget close signal", "code": "def closeEvent(self, e):\n \"\"\"Qt slot when the window is closed.\"\"\"\n self.emit('close_widget')\n super(DockWidget, self).closeEvent(e)", "code_tokens": "def closeEvent ( self , e ) : self . emit ( 'close_widget' ) super ( DockWidget , self ) . closeEvent ( e )", "docstring_tokens": "Qt slot when the window is closed .", "label": 1, "retrieval_idx": 1949, "negative": "Transparently unzip the file handle" }, { "idx": "cosqa-train-17314", "doc": "python read from csv into numpy array", "code": "def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array\n \"\"\"Convert a CSV object to a numpy array.\n\n Args:\n string_like (str): CSV string.\n dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the\n contents of each column, individually. This argument can only be used to\n 'upcast' the array. For downcasting, use the .astype(t) method.\n Returns:\n (np.array): numpy array\n \"\"\"\n stream = StringIO(string_like)\n return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "code_tokens": "def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )", "docstring_tokens": "Convert a CSV object to a numpy array .", "label": 1, "retrieval_idx": 5746, "negative": "Pads the output with an amount of indentation appropriate for the number of open element ." }, { "idx": "cosqa-train-19154", "doc": "cast string to bytearray python", "code": "def to_bytes(data: Any) -> bytearray:\n \"\"\"\n Convert anything to a ``bytearray``.\n \n See\n \n - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n \"\"\" # noqa\n if isinstance(data, int):\n return bytearray([data])\n return bytearray(data, encoding='latin-1')", "code_tokens": "def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )", "docstring_tokens": "Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1", "label": 1, "retrieval_idx": 5708, "negative": "Runs the function asynchronously taking care of exceptions ." }, { "idx": "cosqa-train-12100", "doc": "load str into python object", "code": "def loads(s, model=None, parser=None):\n \"\"\"Deserialize s (a str) to a Python object.\"\"\"\n with StringIO(s) as f:\n return load(f, model=model, parser=parser)", "code_tokens": "def loads ( s , model = None , parser = None ) : with StringIO ( s ) as f : return load ( f , model = model , parser = parser )", "docstring_tokens": "Deserialize s ( a str ) to a Python object .", "label": 1, "retrieval_idx": 1197, "negative": "Removes stopwords contained in a list of words ." }, { "idx": "cosqa-train-13463", "doc": "python ldap get all groups a user belongs to", "code": "def get_groups(self, username):\n \"\"\"Get all groups of a user\"\"\"\n username = ldap.filter.escape_filter_chars(self._byte_p2(username))\n userdn = self._get_user(username, NO_ATTR)\n\n searchfilter = self.group_filter_tmpl % {\n 'userdn': userdn,\n 'username': username\n }\n\n groups = self._search(searchfilter, NO_ATTR, self.groupdn)\n ret = []\n for entry in groups:\n ret.append(self._uni(entry[0]))\n return ret", "code_tokens": "def get_groups ( self , username ) : username = ldap . filter . escape_filter_chars ( self . _byte_p2 ( username ) ) userdn = self . _get_user ( username , NO_ATTR ) searchfilter = self . group_filter_tmpl % { 'userdn' : userdn , 'username' : username } groups = self . _search ( searchfilter , NO_ATTR , self . groupdn ) ret = [ ] for entry in groups : ret . append ( self . _uni ( entry [ 0 ] ) ) return ret", "docstring_tokens": "Get all groups of a user", "label": 1, "retrieval_idx": 5009, "negative": "Create a list of items seperated by seps ." }, { "idx": "cosqa-train-19108", "doc": "python check type if string", "code": "def is_unicode(string):\n \"\"\"Validates that the object itself is some kinda string\"\"\"\n str_type = str(type(string))\n\n if str_type.find('str') > 0 or str_type.find('unicode') > 0:\n return True\n\n return False", "code_tokens": "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", "docstring_tokens": "Validates that the object itself is some kinda string", "label": 1, "retrieval_idx": 5589, "negative": "Returns whether a path names an existing executable file ." }, { "idx": "cosqa-train-10931", "doc": "python get current globals", "code": "def caller_locals():\n \"\"\"Get the local variables in the caller's frame.\"\"\"\n import inspect\n frame = inspect.currentframe()\n try:\n return frame.f_back.f_back.f_locals\n finally:\n del frame", "code_tokens": "def caller_locals ( ) : import inspect frame = inspect . currentframe ( ) try : return frame . f_back . f_back . f_locals finally : del frame", "docstring_tokens": "Get the local variables in the caller s frame .", "label": 1, "retrieval_idx": 4156, "negative": "Return a list of tuples specifying the column name and type" }, { "idx": "cosqa-train-6946", "doc": "get child loggers python", "code": "def _get_loggers():\n \"\"\"Return list of Logger classes.\"\"\"\n from .. import loader\n modules = loader.get_package_modules('logger')\n return list(loader.get_plugins(modules, [_Logger]))", "code_tokens": "def _get_loggers ( ) : from . . import loader modules = loader . get_package_modules ( 'logger' ) return list ( loader . get_plugins ( modules , [ _Logger ] ) )", "docstring_tokens": "Return list of Logger classes .", "label": 1, "retrieval_idx": 1928, "negative": "Print list of namedtuples into a table using prtfmt ." }, { "idx": "cosqa-train-19023", "doc": "how to know if a text file is empty in python", "code": "def _cnx_is_empty(in_file):\n \"\"\"Check if cnr or cns files are empty (only have a header)\n \"\"\"\n with open(in_file) as in_handle:\n for i, line in enumerate(in_handle):\n if i > 0:\n return False\n return True", "code_tokens": "def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True", "docstring_tokens": "Check if cnr or cns files are empty ( only have a header )", "label": 1, "retrieval_idx": 5672, "negative": "Return True if object is defined" }, { "idx": "cosqa-train-15782", "doc": "python normal distribution p values", "code": "def EvalGaussianPdf(x, mu, sigma):\n \"\"\"Computes the unnormalized PDF of the normal distribution.\n\n x: value\n mu: mean\n sigma: standard deviation\n \n returns: float probability density\n \"\"\"\n return scipy.stats.norm.pdf(x, mu, sigma)", "code_tokens": "def EvalGaussianPdf ( x , mu , sigma ) : return scipy . stats . norm . pdf ( x , mu , sigma )", "docstring_tokens": "Computes the unnormalized PDF of the normal distribution .", "label": 1, "retrieval_idx": 376, "negative": "Convert a one - hot encoded array back to string" }, { "idx": "cosqa-train-17937", "doc": "python ctypes array of arrays", "code": "def GetAllPixelColors(self) -> ctypes.Array:\n \"\"\"\n Return `ctypes.Array`, an iterable array of int values in argb.\n \"\"\"\n return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height)", "code_tokens": "def GetAllPixelColors ( self ) -> ctypes . Array : return self . GetPixelColorsOfRect ( 0 , 0 , self . Width , self . Height )", "docstring_tokens": "Return ctypes . Array an iterable array of int values in argb .", "label": 1, "retrieval_idx": 5961, "negative": "Returns all dates between two dates ." }, { "idx": "cosqa-train-14548", "doc": "scale 1d array python to between 0 and 1", "code": "def _rescale_array(self, array, scale, zero):\n \"\"\"\n Scale the input array\n \"\"\"\n if scale != 1.0:\n sval = numpy.array(scale, dtype=array.dtype)\n array *= sval\n if zero != 0.0:\n zval = numpy.array(zero, dtype=array.dtype)\n array += zval", "code_tokens": "def _rescale_array ( self , array , scale , zero ) : if scale != 1.0 : sval = numpy . array ( scale , dtype = array . dtype ) array *= sval if zero != 0.0 : zval = numpy . array ( zero , dtype = array . dtype ) array += zval", "docstring_tokens": "Scale the input array", "label": 1, "retrieval_idx": 5183, "negative": "Get the local variables in the caller s frame ." }, { "idx": "cosqa-train-12156", "doc": "python upper case lower case converter", "code": "def upcaseTokens(s,l,t):\n \"\"\"Helper parse action to convert tokens to upper case.\"\"\"\n return [ tt.upper() for tt in map(_ustr,t) ]", "code_tokens": "def upcaseTokens ( s , l , t ) : return [ tt . upper ( ) for tt in map ( _ustr , t ) ]", "docstring_tokens": "Helper parse action to convert tokens to upper case .", "label": 1, "retrieval_idx": 878, "negative": "Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}" }, { "idx": "cosqa-train-8061", "doc": "ply python expression evaluator", "code": "def build(self, **kwargs):\n \"\"\"Build the lexer.\"\"\"\n self.lexer = ply.lex.lex(object=self, **kwargs)", "code_tokens": "def build ( self , * * kwargs ) : self . lexer = ply . lex . lex ( object = self , * * kwargs )", "docstring_tokens": "Build the lexer .", "label": 1, "retrieval_idx": 3942, "negative": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ..." }, { "idx": "cosqa-train-13196", "doc": "python hashlib calc sha1 of file", "code": "def _get_file_sha1(file):\n \"\"\"Return the SHA1 hash of the given a file-like object as ``file``.\n This will seek the file back to 0 when it's finished.\n\n \"\"\"\n bits = file.read()\n file.seek(0)\n h = hashlib.new('sha1', bits).hexdigest()\n return h", "code_tokens": "def _get_file_sha1 ( file ) : bits = file . read ( ) file . seek ( 0 ) h = hashlib . new ( 'sha1' , bits ) . hexdigest ( ) return h", "docstring_tokens": "Return the SHA1 hash of the given a file - like object as file . This will seek the file back to 0 when it s finished .", "label": 1, "retrieval_idx": 4951, "negative": "Return all child objects in nested lists of strings ." }, { "idx": "cosqa-train-11579", "doc": "python pdb no capture std output", "code": "def set_trace():\n \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "code_tokens": "def set_trace ( ) : # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py pdb . Pdb ( stdout = sys . __stdout__ ) . set_trace ( sys . _getframe ( ) . f_back )", "docstring_tokens": "Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ .", "label": 1, "retrieval_idx": 900, "negative": "Read text from file automatically detect encoding . chardet required ." }, { "idx": "cosqa-train-17702", "doc": "python how to write a factorial", "code": "def factorial(n, mod=None):\n \"\"\"Calculates factorial iteratively.\n If mod is not None, then return (n! % mod)\n Time Complexity - O(n)\"\"\"\n if not (isinstance(n, int) and n >= 0):\n raise ValueError(\"'n' must be a non-negative integer.\")\n if mod is not None and not (isinstance(mod, int) and mod > 0):\n raise ValueError(\"'mod' must be a positive integer\")\n result = 1\n if n == 0:\n return 1\n for i in range(2, n+1):\n result *= i\n if mod:\n result %= mod\n return result", "code_tokens": "def factorial ( n , mod = None ) : if not ( isinstance ( n , int ) and n >= 0 ) : raise ValueError ( \"'n' must be a non-negative integer.\" ) if mod is not None and not ( isinstance ( mod , int ) and mod > 0 ) : raise ValueError ( \"'mod' must be a positive integer\" ) result = 1 if n == 0 : return 1 for i in range ( 2 , n + 1 ) : result *= i if mod : result %= mod return result", "docstring_tokens": "Calculates factorial iteratively . If mod is not None then return ( n! % mod ) Time Complexity - O ( n )", "label": 1, "retrieval_idx": 5904, "negative": "WeChat access token" }, { "idx": "cosqa-train-11019", "doc": "python get the last column", "code": "def get_last_row(dbconn, tablename, n=1, uuid=None):\n \"\"\"\n Returns the last `n` rows in the table\n \"\"\"\n return fetch(dbconn, tablename, n, uuid, end=True)", "code_tokens": "def get_last_row ( dbconn , tablename , n = 1 , uuid = None ) : return fetch ( dbconn , tablename , n , uuid , end = True )", "docstring_tokens": "Returns the last n rows in the table", "label": 1, "retrieval_idx": 587, "negative": "Runs the function asynchronously taking care of exceptions ." }, { "idx": "cosqa-train-13220", "doc": "python how to change file extension", "code": "def lower_ext(abspath):\n \"\"\"Convert file extension to lowercase.\n \"\"\"\n fname, ext = os.path.splitext(abspath)\n return fname + ext.lower()", "code_tokens": "def lower_ext ( abspath ) : fname , ext = os . path . splitext ( abspath ) return fname + ext . lower ( )", "docstring_tokens": "Convert file extension to lowercase .", "label": 1, "retrieval_idx": 1489, "negative": "Return the fully - qualified name of a function ." }, { "idx": "cosqa-train-6758", "doc": "python get process memory info", "code": "def machine_info():\n \"\"\"Retrieve core and memory information for the current machine.\n \"\"\"\n import psutil\n BYTES_IN_GIG = 1073741824.0\n free_bytes = psutil.virtual_memory().total\n return [{\"memory\": float(\"%.1f\" % (free_bytes / BYTES_IN_GIG)), \"cores\": multiprocessing.cpu_count(),\n \"name\": socket.gethostname()}]", "code_tokens": "def machine_info ( ) : import psutil BYTES_IN_GIG = 1073741824.0 free_bytes = psutil . virtual_memory ( ) . total return [ { \"memory\" : float ( \"%.1f\" % ( free_bytes / BYTES_IN_GIG ) ) , \"cores\" : multiprocessing . cpu_count ( ) , \"name\" : socket . gethostname ( ) } ]", "docstring_tokens": "Retrieve core and memory information for the current machine .", "label": 1, "retrieval_idx": 3055, "negative": "Return list of Logger classes ." }, { "idx": "cosqa-dev-481", "doc": "check if 2 string are equal python", "code": "def indexes_equal(a: Index, b: Index) -> bool:\n \"\"\"\n Are two indexes equal? Checks by comparing ``str()`` versions of them.\n (AM UNSURE IF THIS IS ENOUGH.)\n \"\"\"\n return str(a) == str(b)", "code_tokens": "def indexes_equal ( a : Index , b : Index ) -> bool : return str ( a ) == str ( b )", "docstring_tokens": "Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )", "label": 1, "retrieval_idx": 5584, "negative": "Time execution of function . Returns ( res seconds ) ." }, { "idx": "cosqa-train-11094", "doc": "flask python create one table sqlalchemy", "code": "def create_db(app, appbuilder):\n \"\"\"\n Create all your database objects (SQLAlchemy specific).\n \"\"\"\n from flask_appbuilder.models.sqla import Base\n\n _appbuilder = import_application(app, appbuilder)\n engine = _appbuilder.get_session.get_bind(mapper=None, clause=None)\n Base.metadata.create_all(engine)\n click.echo(click.style(\"DB objects created\", fg=\"green\"))", "code_tokens": "def create_db ( app , appbuilder ) : from flask_appbuilder . models . sqla import Base _appbuilder = import_application ( app , appbuilder ) engine = _appbuilder . get_session . get_bind ( mapper = None , clause = None ) Base . metadata . create_all ( engine ) click . echo ( click . style ( \"DB objects created\" , fg = \"green\" ) )", "docstring_tokens": "Create all your database objects ( SQLAlchemy specific ) .", "label": 1, "retrieval_idx": 3549, "negative": "Advance the iterator without returning the old head ." }, { "idx": "cosqa-train-8731", "doc": "clean output folder in python", "code": "def cleanup():\n \"\"\"Cleanup the output directory\"\"\"\n if _output_dir and os.path.exists(_output_dir):\n log.msg_warn(\"Cleaning up output directory at '{output_dir}' ...\"\n .format(output_dir=_output_dir))\n if not _dry_run:\n shutil.rmtree(_output_dir)", "code_tokens": "def cleanup ( ) : if _output_dir and os . path . exists ( _output_dir ) : log . msg_warn ( \"Cleaning up output directory at '{output_dir}' ...\" . format ( output_dir = _output_dir ) ) if not _dry_run : shutil . rmtree ( _output_dir )", "docstring_tokens": "Cleanup the output directory", "label": 1, "retrieval_idx": 4094, "negative": "An iterable of column names for a particular table or view ." }, { "idx": "cosqa-train-19285", "doc": "python print nodes binary tree", "code": "def debugTreePrint(node,pfx=\"->\"):\n \"\"\"Purely a debugging aid: Ascii-art picture of a tree descended from node\"\"\"\n print pfx,node.item\n for c in node.children:\n debugTreePrint(c,\" \"+pfx)", "code_tokens": "def debugTreePrint ( node , pfx = \"->\" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , \" \" + pfx )", "docstring_tokens": "Purely a debugging aid : Ascii - art picture of a tree descended from node", "label": 1, "retrieval_idx": 5626, "negative": "Is this a string ." }, { "idx": "cosqa-train-15941", "doc": "python query string parsing", "code": "def urlencoded(body, charset='ascii', **kwargs):\n \"\"\"Converts query strings into native Python objects\"\"\"\n return parse_query_string(text(body, charset=charset), False)", "code_tokens": "def urlencoded ( body , charset = 'ascii' , * * kwargs ) : return parse_query_string ( text ( body , charset = charset ) , False )", "docstring_tokens": "Converts query strings into native Python objects", "label": 1, "retrieval_idx": 2540, "negative": "Return an enum from a name Args : enum_name ( str ) : name of the enum Returns : Enum" }, { "idx": "cosqa-train-15200", "doc": "cycle through a folder of images python", "code": "def each_img(dir_path):\n \"\"\"\n Iterates through each image in the given directory. (not recursive)\n :param dir_path: Directory path where images files are present\n :return: Iterator to iterate through image files\n \"\"\"\n for fname in os.listdir(dir_path):\n if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'):\n yield fname", "code_tokens": "def each_img ( dir_path ) : for fname in os . listdir ( dir_path ) : if fname . endswith ( '.jpg' ) or fname . endswith ( '.png' ) or fname . endswith ( '.bmp' ) : yield fname", "docstring_tokens": "Iterates through each image in the given directory . ( not recursive ) : param dir_path : Directory path where images files are present : return : Iterator to iterate through image files", "label": 1, "retrieval_idx": 2248, "negative": "Process an iterable of dictionaries . For each dictionary d change ( in place ) d [ key ] to value ." }, { "idx": "cosqa-train-17344", "doc": "check if a date is valid python", "code": "def valid_date(x: str) -> bool:\n \"\"\"\n Retrun ``True`` if ``x`` is a valid YYYYMMDD date;\n otherwise return ``False``.\n \"\"\"\n try:\n if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):\n raise ValueError\n return True\n except ValueError:\n return False", "code_tokens": "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", "docstring_tokens": "Retrun True if x is a valid YYYYMMDD date ; otherwise return False .", "label": 1, "retrieval_idx": 5581, "negative": "Get the value of a local variable somewhere in the call stack ." }, { "idx": "cosqa-train-5599", "doc": "python spherical bessel functions", "code": "def sbessely(x, N):\n \"\"\"Returns a vector of spherical bessel functions yn:\n\n x: The argument.\n N: values of n will run from 0 to N-1.\n\n \"\"\"\n\n out = np.zeros(N, dtype=np.float64)\n\n out[0] = -np.cos(x) / x\n out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x\n\n for n in xrange(2, N):\n out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2]\n\n return out", "code_tokens": "def sbessely ( x , N ) : out = np . zeros ( N , dtype = np . float64 ) out [ 0 ] = - np . cos ( x ) / x out [ 1 ] = - np . cos ( x ) / ( x ** 2 ) - np . sin ( x ) / x for n in xrange ( 2 , N ) : out [ n ] = ( ( 2.0 * n - 1.0 ) / x ) * out [ n - 1 ] - out [ n - 2 ] return out", "docstring_tokens": "Returns a vector of spherical bessel functions yn : x : The argument . N : values of n will run from 0 to N - 1 .", "label": 1, "retrieval_idx": 3223, "negative": "Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) ." }, { "idx": "cosqa-train-19367", "doc": "how to check a file is empty in python", "code": "def _cnx_is_empty(in_file):\n \"\"\"Check if cnr or cns files are empty (only have a header)\n \"\"\"\n with open(in_file) as in_handle:\n for i, line in enumerate(in_handle):\n if i > 0:\n return False\n return True", "code_tokens": "def _cnx_is_empty ( in_file ) : with open ( in_file ) as in_handle : for i , line in enumerate ( in_handle ) : if i > 0 : return False return True", "docstring_tokens": "Check if cnr or cns files are empty ( only have a header )", "label": 1, "retrieval_idx": 5672, "negative": "Finds the longest path in a dag between two nodes" }, { "idx": "cosqa-train-14104", "doc": "python stop process multiprocessing", "code": "def stop(self, timeout=None):\n \"\"\" Initiates a graceful stop of the processes \"\"\"\n\n self.stopping = True\n\n for process in list(self.processes):\n self.stop_process(process, timeout=timeout)", "code_tokens": "def stop ( self , timeout = None ) : self . stopping = True for process in list ( self . processes ) : self . stop_process ( process , timeout = timeout )", "docstring_tokens": "Initiates a graceful stop of the processes", "label": 1, "retrieval_idx": 4659, "negative": "Python 3 input () / Python 2 raw_input ()" }, { "idx": "cosqa-train-9279", "doc": "python make sure all words are separated by a single space", "code": "def sanitize_word(s):\n \"\"\"Remove non-alphanumerical characters from metric word.\n And trim excessive underscores.\n \"\"\"\n s = re.sub('[^\\w-]+', '_', s)\n s = re.sub('__+', '_', s)\n return s.strip('_')", "code_tokens": "def sanitize_word ( s ) : s = re . sub ( '[^\\w-]+' , '_' , s ) s = re . sub ( '__+' , '_' , s ) return s . strip ( '_' )", "docstring_tokens": "Remove non - alphanumerical characters from metric word . And trim excessive underscores .", "label": 1, "retrieval_idx": 2339, "negative": "Return true if a value is a finite number ." }, { "idx": "cosqa-train-12138", "doc": "making a multidimensional array of only 1 in python", "code": "def A(*a):\n \"\"\"convert iterable object into numpy array\"\"\"\n return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "code_tokens": "def A ( * a ) : return np . array ( a [ 0 ] ) if len ( a ) == 1 else [ np . array ( o ) for o in a ]", "docstring_tokens": "convert iterable object into numpy array", "label": 1, "retrieval_idx": 856, "negative": "create random string of selected size" }, { "idx": "cosqa-train-15519", "doc": "python initialize variable of an object", "code": "def __init__(self):\n \"\"\"Initialize the state of the object\"\"\"\n self.state = self.STATE_INITIALIZING\n self.state_start = time.time()", "code_tokens": "def __init__ ( self ) : self . state = self . STATE_INITIALIZING self . state_start = time . time ( )", "docstring_tokens": "Initialize the state of the object", "label": 1, "retrieval_idx": 4075, "negative": "Turn an SQLAlchemy model into a dict of field names and values ." }, { "idx": "cosqa-train-6551", "doc": "python elasticsearch limit results", "code": "def scan(client, query=None, scroll='5m', raise_on_error=True,\n preserve_order=False, size=1000, **kwargs):\n \"\"\"\n Simple abstraction on top of the\n :meth:`~elasticsearch.Elasticsearch.scroll` api - a simple iterator that\n yields all hits as returned by underlining scroll requests.\n By default scan does not return results in any pre-determined order. To\n have a standard order in the returned documents (either by score or\n explicit sort definition) when scrolling, use ``preserve_order=True``. This\n may be an expensive operation and will negate the performance benefits of\n using ``scan``.\n :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use\n :arg query: body for the :meth:`~elasticsearch.Elasticsearch.search` api\n :arg scroll: Specify how long a consistent view of the index should be\n maintained for scrolled search\n :arg raise_on_error: raises an exception (``ScanError``) if an error is\n encountered (some shards fail to execute). By default we raise.\n :arg preserve_order: don't set the ``search_type`` to ``scan`` - this will\n cause the scroll to paginate with preserving the order. Note that this\n can be an extremely expensive operation and can easily lead to\n unpredictable results, use with caution.\n :arg size: size (per shard) of the batch send at each iteration.\n Any additional keyword arguments will be passed to the initial\n :meth:`~elasticsearch.Elasticsearch.search` call::\n scan(es,\n query={\"query\": {\"match\": {\"title\": \"python\"}}},\n index=\"orders-*\",\n doc_type=\"books\"\n )\n \"\"\"\n if not preserve_order:\n kwargs['search_type'] = 'scan'\n # initial search\n resp = client.search(body=query, scroll=scroll, size=size, **kwargs)\n\n scroll_id = resp.get('_scroll_id')\n if scroll_id is None:\n return\n\n first_run = True\n while True:\n # if we didn't set search_type to scan initial search contains data\n if preserve_order and first_run:\n first_run = False\n else:\n resp = client.scroll(scroll_id, scroll=scroll)\n\n for hit in resp['hits']['hits']:\n yield hit\n\n # check if we have any errrors\n if resp[\"_shards\"][\"failed\"]:\n logger.warning(\n 'Scroll request has failed on %d shards out of %d.',\n resp['_shards']['failed'], resp['_shards']['total']\n )\n if raise_on_error:\n raise ScanError(\n 'Scroll request has failed on %d shards out of %d.' %\n (resp['_shards']['failed'], resp['_shards']['total'])\n )\n\n scroll_id = resp.get('_scroll_id')\n # end of scroll\n if scroll_id is None or not resp['hits']['hits']:\n break", "code_tokens": "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", "docstring_tokens": "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 )", "label": 1, "retrieval_idx": 1953, "negative": "Warn if nans exist in a numpy array ." }, { "idx": "cosqa-train-5203", "doc": "how to force exit python without raise", "code": "def __exit__(self, type, value, traceback):\n \"\"\"When the `with` statement ends.\"\"\"\n\n if not self.asarfile:\n return\n\n self.asarfile.close()\n self.asarfile = None", "code_tokens": "def __exit__ ( self , type , value , traceback ) : if not self . asarfile : return self . asarfile . close ( ) self . asarfile = None", "docstring_tokens": "When the with statement ends .", "label": 1, "retrieval_idx": 3086, "negative": "Parse file specified by constructor ." }, { "idx": "cosqa-train-10049", "doc": "python weak reference to bound method", "code": "def attr_cache_clear(self):\n node = extract_node(\"\"\"def cache_clear(self): pass\"\"\")\n return BoundMethod(proxy=node, bound=self._instance.parent.scope())", "code_tokens": "def attr_cache_clear ( self ) : node = extract_node ( \"\"\"def cache_clear(self): pass\"\"\" ) return BoundMethod ( proxy = node , bound = self . _instance . parent . scope ( ) )", "docstring_tokens": "", "label": 1, "retrieval_idx": 4389, "negative": "Create a Listbox with a vertical scrollbar ." }, { "idx": "cosqa-train-10725", "doc": "calling index iterable python", "code": "def stop_at(iterable, idx):\n \"\"\"Stops iterating before yielding the specified idx.\"\"\"\n for i, item in enumerate(iterable):\n if i == idx: return\n yield item", "code_tokens": "def stop_at ( iterable , idx ) : for i , item in enumerate ( iterable ) : if i == idx : return yield item", "docstring_tokens": "Stops iterating before yielding the specified idx .", "label": 1, "retrieval_idx": 2047, "negative": "simple method to determine if a url is relative or absolute" }, { "idx": "cosqa-train-12736", "doc": "python datetime maybe undefined", "code": "def date_to_datetime(x):\n \"\"\"Convert a date into a datetime\"\"\"\n if not isinstance(x, datetime) and isinstance(x, date):\n return datetime.combine(x, time())\n return x", "code_tokens": "def date_to_datetime ( x ) : if not isinstance ( x , datetime ) and isinstance ( x , date ) : return datetime . combine ( x , time ( ) ) return x", "docstring_tokens": "Convert a date into a datetime", "label": 1, "retrieval_idx": 1753, "negative": "Add executable permissions to the file" }, { "idx": "cosqa-train-8954", "doc": "python go to next page", "code": "def accel_next(self, *args):\n \"\"\"Callback to go to the next tab. Called by the accel key.\n \"\"\"\n if self.get_notebook().get_current_page() + 1 == self.get_notebook().get_n_pages():\n self.get_notebook().set_current_page(0)\n else:\n self.get_notebook().next_page()\n return True", "code_tokens": "def accel_next ( self , * args ) : if self . get_notebook ( ) . get_current_page ( ) + 1 == self . get_notebook ( ) . get_n_pages ( ) : self . get_notebook ( ) . set_current_page ( 0 ) else : self . get_notebook ( ) . next_page ( ) return True", "docstring_tokens": "Callback to go to the next tab . Called by the accel key .", "label": 1, "retrieval_idx": 3706, "negative": "True if the json_element passed is present for the task specified ." }, { "idx": "cosqa-train-6854", "doc": "filling null value sin data frame in python", "code": "def clean_dataframe(df):\n \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n df = df.fillna(method='ffill')\n df = df.fillna(0.0)\n return df", "code_tokens": "def clean_dataframe ( df ) : df = df . fillna ( method = 'ffill' ) df = df . fillna ( 0.0 ) return df", "docstring_tokens": "Fill NaNs with the previous value the next value or if all are NaN then 1 . 0", "label": 1, "retrieval_idx": 889, "negative": "Check if file is a regular file and is readable ." }, { "idx": "cosqa-train-5484", "doc": "python run external command and get output", "code": "def check_output(args, env=None, sp=subprocess):\n \"\"\"Call an external binary and return its stdout.\"\"\"\n log.debug('calling %s with env %s', args, env)\n output = sp.check_output(args=args, env=env)\n log.debug('output: %r', output)\n return output", "code_tokens": "def check_output ( args , env = None , sp = subprocess ) : log . debug ( 'calling %s with env %s' , args , env ) output = sp . check_output ( args = args , env = env ) log . debug ( 'output: %r' , output ) return output", "docstring_tokens": "Call an external binary and return its stdout .", "label": 1, "retrieval_idx": 114, "negative": "Returns whether a path names an existing executable file ." }, { "idx": "cosqa-train-13589", "doc": "how to compile python program to use in c++", "code": "def cpp_prog_builder(build_context, target):\n \"\"\"Build a C++ binary executable\"\"\"\n yprint(build_context.conf, 'Build CppProg', target)\n workspace_dir = build_context.get_workspace('CppProg', target.name)\n build_cpp(build_context, target, target.compiler_config, workspace_dir)", "code_tokens": "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 )", "docstring_tokens": "Build a C ++ binary executable", "label": 1, "retrieval_idx": 801, "negative": "Qt slot when the window is closed ." }, { "idx": "cosqa-train-13360", "doc": "python img to bytearray", "code": "def to_bytes(self):\n\t\t\"\"\"Convert the entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)", "code_tokens": "def to_bytes ( self ) : chunks = [ PNG_SIGN ] chunks . extend ( c [ 1 ] for c in self . chunks ) return b\"\" . join ( chunks )", "docstring_tokens": "Convert the entire image to bytes . : rtype : bytes", "label": 1, "retrieval_idx": 4466, "negative": "Given a float returns a rounded int . Should give the same result on both Py2 / 3" }, { "idx": "cosqa-train-9903", "doc": "how to use access token oauth python", "code": "def fetch_token(self, **kwargs):\n \"\"\"Exchange a code (and 'state' token) for a bearer token\"\"\"\n return super(AsanaOAuth2Session, self).fetch_token(self.token_url, client_secret=self.client_secret, **kwargs)", "code_tokens": "def fetch_token ( self , * * kwargs ) : return super ( AsanaOAuth2Session , self ) . fetch_token ( self . token_url , client_secret = self . client_secret , * * kwargs )", "docstring_tokens": "Exchange a code ( and state token ) for a bearer token", "label": 1, "retrieval_idx": 2605, "negative": "returns a dictionary of arg_name : default_values for the input function" }, { "idx": "cosqa-train-15551", "doc": "have python line continue on to next line", "code": "def advance_one_line(self):\n \"\"\"Advances to next line.\"\"\"\n\n current_line = self._current_token.line_number\n while current_line == self._current_token.line_number:\n self._current_token = ConfigParser.Token(*next(self._token_generator))", "code_tokens": "def advance_one_line ( self ) : current_line = self . _current_token . line_number while current_line == self . _current_token . line_number : self . _current_token = ConfigParser . Token ( * next ( self . _token_generator ) )", "docstring_tokens": "Advances to next line .", "label": 1, "retrieval_idx": 34, "negative": "Convert datetime to epoch seconds ." }, { "idx": "cosqa-train-10234", "doc": "precision of ints in python", "code": "def round_to_int(number, precision):\n \"\"\"Round a number to a precision\"\"\"\n precision = int(precision)\n rounded = (int(number) + precision / 2) // precision * precision\n return rounded", "code_tokens": "def round_to_int ( number , precision ) : precision = int ( precision ) rounded = ( int ( number ) + precision / 2 ) // precision * precision return rounded", "docstring_tokens": "Round a number to a precision", "label": 1, "retrieval_idx": 60, "negative": "Print emphasized good the given txt message" }, { "idx": "cosqa-train-5838", "doc": "modify the dice roll program to call a function for the die roll s python", "code": "def roll_dice():\n \"\"\"\n Roll a die.\n\n :return: None\n \"\"\"\n sums = 0 # will return the sum of the roll calls.\n while True:\n roll = random.randint(1, 6)\n sums += roll\n if(input(\"Enter y or n to continue: \").upper()) == 'N':\n print(sums) # prints the sum of the roll calls\n break", "code_tokens": "def roll_dice ( ) : sums = 0 # will return the sum of the roll calls. while True : roll = random . randint ( 1 , 6 ) sums += roll if ( input ( \"Enter y or n to continue: \" ) . upper ( ) ) == 'N' : print ( sums ) # prints the sum of the roll calls break", "docstring_tokens": "Roll a die .", "label": 1, "retrieval_idx": 3313, "negative": "Replace month strings occurrences with month number ." }, { "idx": "cosqa-train-10253", "doc": "python 'namespace' object is not iterable", "code": "def __add_namespaceinfo(self, ni):\n \"\"\"Internal method to directly add a _NamespaceInfo object to this\n set. No sanity checks are done (e.g. checking for prefix conflicts),\n so be sure to do it yourself before calling this.\"\"\"\n self.__ns_uri_map[ni.uri] = ni\n for prefix in ni.prefixes:\n self.__prefix_map[prefix] = ni", "code_tokens": "def __add_namespaceinfo ( self , ni ) : self . __ns_uri_map [ ni . uri ] = ni for prefix in ni . prefixes : self . __prefix_map [ prefix ] = ni", "docstring_tokens": "Internal method to directly add a _NamespaceInfo object to this set . No sanity checks are done ( e . g . checking for prefix conflicts ) so be sure to do it yourself before calling this .", "label": 1, "retrieval_idx": 4431, "negative": "Add a blank row with only an index value to self . df . This is done inplace ." }, { "idx": "cosqa-train-3453", "doc": "how to specify seed for python random", "code": "def generate_seed(seed):\n \"\"\"Generate seed for random number generator\"\"\"\n if seed is None:\n random.seed()\n seed = random.randint(0, sys.maxsize)\n random.seed(a=seed)\n\n return seed", "code_tokens": "def generate_seed ( seed ) : if seed is None : random . seed ( ) seed = random . randint ( 0 , sys . maxsize ) random . seed ( a = seed ) return seed", "docstring_tokens": "Generate seed for random number generator", "label": 1, "retrieval_idx": 1994, "negative": "Transform an underscore_case string to a mixedCase string" }, { "idx": "cosqa-train-10014", "doc": "python use default arg", "code": "def arg_default(*args, **kwargs):\n \"\"\"Return default argument value as given by argparse's add_argument().\n\n The argument is passed through a mocked-up argument parser. This way, we\n get default parameters even if the feature is called directly and not\n through the CLI.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(*args, **kwargs)\n args = vars(parser.parse_args([]))\n _, default = args.popitem()\n return default", "code_tokens": "def arg_default ( * args , * * kwargs ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( * args , * * kwargs ) args = vars ( parser . parse_args ( [ ] ) ) _ , default = args . popitem ( ) return default", "docstring_tokens": "Return default argument value as given by argparse s add_argument () .", "label": 1, "retrieval_idx": 1432, "negative": "Python s input () is blocking which means the event loop we set above can t be running while we re blocking there . This method will let the loop run while we wait for input ." }, { "idx": "cosqa-train-17635", "doc": "python change array dtype to int", "code": "def to_int64(a):\n \"\"\"Return view of the recarray with all int32 cast to int64.\"\"\"\n # build new dtype and replace i4 --> i8\n def promote_i4(typestr):\n if typestr[1:] == 'i4':\n typestr = typestr[0]+'i8'\n return typestr\n\n dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]\n return a.astype(dtype)", "code_tokens": "def to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )", "docstring_tokens": "Return view of the recarray with all int32 cast to int64 .", "label": 1, "retrieval_idx": 5736, "negative": "Strip the whitespace from all column names in the given DataFrame and return the result ." }, { "idx": "cosqa-train-10859", "doc": "python forcible close socket before opening", "code": "def close(self):\n \"\"\"Send a close message to the external process and join it.\"\"\"\n try:\n self._conn.send((self._CLOSE, None))\n self._conn.close()\n except IOError:\n # The connection was already closed.\n pass\n self._process.join()", "code_tokens": "def close ( self ) : try : self . _conn . send ( ( self . _CLOSE , None ) ) self . _conn . close ( ) except IOError : # The connection was already closed. pass self . _process . join ( )", "docstring_tokens": "Send a close message to the external process and join it .", "label": 1, "retrieval_idx": 4558, "negative": "Whether path is a directory to which the user has write access ." }, { "idx": "cosqa-train-11902", "doc": "python series'value non zero index", "code": "def reduce_fn(x):\n \"\"\"\n Aggregation function to get the first non-zero value.\n \"\"\"\n values = x.values if pd and isinstance(x, pd.Series) else x\n for v in values:\n if not is_nan(v):\n return v\n return np.NaN", "code_tokens": "def reduce_fn ( x ) : values = x . values if pd and isinstance ( x , pd . Series ) else x for v in values : if not is_nan ( v ) : return v return np . NaN", "docstring_tokens": "Aggregation function to get the first non - zero value .", "label": 1, "retrieval_idx": 621, "negative": "Show the received object as precise as possible ." }, { "idx": "cosqa-train-11300", "doc": "how to add a number to certain elements of an array numpy python", "code": "def _increment(arr, indices):\n \"\"\"Increment some indices in a 1D vector of non-negative integers.\n Repeated indices are taken into account.\"\"\"\n arr = _as_array(arr)\n indices = _as_array(indices)\n bbins = np.bincount(indices)\n arr[:len(bbins)] += bbins\n return arr", "code_tokens": "def _increment ( arr , indices ) : arr = _as_array ( arr ) indices = _as_array ( indices ) bbins = np . bincount ( indices ) arr [ : len ( bbins ) ] += bbins return arr", "docstring_tokens": "Increment some indices in a 1D vector of non - negative integers . Repeated indices are taken into account .", "label": 1, "retrieval_idx": 4629, "negative": "Get a list of the public data attributes ." }, { "idx": "cosqa-train-12149", "doc": "python unit test and coverage at same time", "code": "def coverage(ctx, opts=\"\"):\n \"\"\"\n Execute all tests (normal and slow) with coverage enabled.\n \"\"\"\n return test(ctx, coverage=True, include_slow=True, opts=opts)", "code_tokens": "def coverage ( ctx , opts = \"\" ) : return test ( ctx , coverage = True , include_slow = True , opts = opts )", "docstring_tokens": "Execute all tests ( normal and slow ) with coverage enabled .", "label": 1, "retrieval_idx": 4778, "negative": "Isolates x from its equivalence class ." }, { "idx": "cosqa-train-987", "doc": "python only list files with specific extension", "code": "def glob_by_extensions(directory, extensions):\n \"\"\" Returns files matched by all extensions in the extensions list \"\"\"\n directorycheck(directory)\n files = []\n xt = files.extend\n for ex in extensions:\n xt(glob.glob('{0}/*.{1}'.format(directory, ex)))\n return files", "code_tokens": "def glob_by_extensions ( directory , extensions ) : directorycheck ( directory ) files = [ ] xt = files . extend for ex in extensions : xt ( glob . glob ( '{0}/*.{1}' . format ( directory , ex ) ) ) return files", "docstring_tokens": "Returns files matched by all extensions in the extensions list", "label": 1, "retrieval_idx": 868, "negative": "Labels plots and saves file" }, { "idx": "cosqa-train-11054", "doc": "python global type hinting", "code": "def is_builtin_type(tp):\n \"\"\"Checks if the given type is a builtin one.\n \"\"\"\n return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", "code_tokens": "def is_builtin_type ( tp ) : return hasattr ( __builtins__ , tp . __name__ ) and tp is getattr ( __builtins__ , tp . __name__ )", "docstring_tokens": "Checks if the given type is a builtin one .", "label": 1, "retrieval_idx": 534, "negative": "Check if something quacks like a list ." }, { "idx": "cosqa-train-9558", "doc": "how to make a function in python to take the average of list numbers", "code": "def calc_list_average(l):\n \"\"\"\n Calculates the average value of a list of numbers\n Returns a float\n \"\"\"\n total = 0.0\n for value in l:\n total += value\n return total / len(l)", "code_tokens": "def calc_list_average ( l ) : total = 0.0 for value in l : total += value return total / len ( l )", "docstring_tokens": "Calculates the average value of a list of numbers Returns a float", "label": 1, "retrieval_idx": 2957, "negative": "Update the dev_info data from a dictionary ." }, { "idx": "cosqa-train-15051", "doc": "check if two arrays are equal python", "code": "def numpy_aware_eq(a, b):\n \"\"\"Return whether two objects are equal via recursion, using\n :func:`numpy.array_equal` for comparing numpy arays.\n \"\"\"\n if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):\n return np.array_equal(a, b)\n if ((isinstance(a, Iterable) and isinstance(b, Iterable)) and\n not isinstance(a, str) and not isinstance(b, str)):\n if len(a) != len(b):\n return False\n return all(numpy_aware_eq(x, y) for x, y in zip(a, b))\n return a == b", "code_tokens": "def numpy_aware_eq ( a , b ) : if isinstance ( a , np . ndarray ) or isinstance ( b , np . ndarray ) : return np . array_equal ( a , b ) if ( ( isinstance ( a , Iterable ) and isinstance ( b , Iterable ) ) and not isinstance ( a , str ) and not isinstance ( b , str ) ) : if len ( a ) != len ( b ) : return False return all ( numpy_aware_eq ( x , y ) for x , y in zip ( a , b ) ) return a == b", "docstring_tokens": "Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays .", "label": 1, "retrieval_idx": 180, "negative": "Ensure file deleted also on * Windows * where read - only files need special treatment ." }, { "idx": "cosqa-train-5478", "doc": "python round down numpy", "code": "def round_array(array_in):\n \"\"\"\n arr_out = round_array(array_in)\n\n Rounds an array and recasts it to int. Also works on scalars.\n \"\"\"\n if isinstance(array_in, ndarray):\n return np.round(array_in).astype(int)\n else:\n return int(np.round(array_in))", "code_tokens": "def round_array ( array_in ) : if isinstance ( array_in , ndarray ) : return np . round ( array_in ) . astype ( int ) else : return int ( np . round ( array_in ) )", "docstring_tokens": "arr_out = round_array ( array_in )", "label": 1, "retrieval_idx": 1487, "negative": "Returns all column names and their data types as a list ." }, { "idx": "cosqa-dev-421", "doc": "python pywin32 screenshoot refresh", "code": "def win32_refresh_window(cls):\n \"\"\"\n Call win32 API to refresh the whole Window.\n\n This is sometimes necessary when the application paints background\n for completion menus. When the menu disappears, it leaves traces due\n to a bug in the Windows Console. Sending a repaint request solves it.\n \"\"\"\n # Get console handle\n handle = windll.kernel32.GetConsoleWindow()\n\n RDW_INVALIDATE = 0x0001\n windll.user32.RedrawWindow(handle, None, None, c_uint(RDW_INVALIDATE))", "code_tokens": "def win32_refresh_window ( cls ) : # Get console handle handle = windll . kernel32 . GetConsoleWindow ( ) RDW_INVALIDATE = 0x0001 windll . user32 . RedrawWindow ( handle , None , None , c_uint ( RDW_INVALIDATE ) )", "docstring_tokens": "Call win32 API to refresh the whole Window .", "label": 1, "retrieval_idx": 4699, "negative": "Determine whether a system service is available" }, { "idx": "cosqa-train-13319", "doc": "get largest date from a list python", "code": "def _latest_date(self, query, datetime_field_name):\n \"\"\"Given a QuerySet and the name of field containing datetimes, return the\n latest (most recent) date.\n\n Return None if QuerySet is empty.\n\n \"\"\"\n return list(\n query.aggregate(django.db.models.Max(datetime_field_name)).values()\n )[0]", "code_tokens": "def _latest_date ( self , query , datetime_field_name ) : return list ( query . aggregate ( django . db . models . Max ( datetime_field_name ) ) . values ( ) ) [ 0 ]", "docstring_tokens": "Given a QuerySet and the name of field containing datetimes return the latest ( most recent ) date .", "label": 1, "retrieval_idx": 4978, "negative": "Checks if key exists in datastore . True if yes False if no ." }, { "idx": "cosqa-train-11348", "doc": "python lock no blocking", "code": "def lock(self, block=True):\n\t\t\"\"\"\n\t\tLock connection from being used else where\n\t\t\"\"\"\n\t\tself._locked = True\n\t\treturn self._lock.acquire(block)", "code_tokens": "def lock ( self , block = True ) : self . _locked = True return self . _lock . acquire ( block )", "docstring_tokens": "Lock connection from being used else where", "label": 1, "retrieval_idx": 739, "negative": "Function to split every line in a list and retain spaces for a rejoin : param orig_list : Original list : return : A List with split lines" }, { "idx": "cosqa-train-19073", "doc": "delete item from a set python", "code": "def remove_once(gset, elem):\n \"\"\"Remove the element from a set, lists or dict.\n \n >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n >>> print L, S, D\n [] set([]) {}\n\n Returns the element if it was removed. Raises one of the exceptions in \n :obj:`RemoveError` otherwise.\n \"\"\"\n remove = getattr(gset, 'remove', None)\n if remove is not None: remove(elem)\n else: del gset[elem]\n return elem", "code_tokens": "def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem", "docstring_tokens": "Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}", "label": 1, "retrieval_idx": 5741, "negative": "Hides the main window of the terminal and sets the visible flag to False ." }, { "idx": "cosqa-train-16040", "doc": "how to make a sentence into underscores with python", "code": "def us2mc(string):\n \"\"\"Transform an underscore_case string to a mixedCase string\"\"\"\n return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string)", "code_tokens": "def us2mc ( string ) : return re . sub ( r'_([a-z])' , lambda m : ( m . group ( 1 ) . upper ( ) ) , string )", "docstring_tokens": "Transform an underscore_case string to a mixedCase string", "label": 1, "retrieval_idx": 358, "negative": "Qt slot when the window is closed ." }, { "idx": "cosqa-train-9920", "doc": "python timestamp remove timezone", "code": "def convert_tstamp(response):\n\t\"\"\"\n\tConvert a Stripe API timestamp response (unix epoch) to a native datetime.\n\n\t:rtype: datetime\n\t\"\"\"\n\tif response is None:\n\t\t# Allow passing None to convert_tstamp()\n\t\treturn response\n\n\t# Overrides the set timezone to UTC - I think...\n\ttz = timezone.utc if settings.USE_TZ else None\n\n\treturn datetime.datetime.fromtimestamp(response, tz)", "code_tokens": "def convert_tstamp ( response ) : if response is None : # Allow passing None to convert_tstamp() return response # Overrides the set timezone to UTC - I think... tz = timezone . utc if settings . USE_TZ else None return datetime . datetime . fromtimestamp ( response , tz )", "docstring_tokens": "Convert a Stripe API timestamp response ( unix epoch ) to a native datetime .", "label": 1, "retrieval_idx": 1581, "negative": "Remove a file from an AWS S3 bucket ." }, { "idx": "cosqa-train-9697", "doc": "python sanic change all object id to string", "code": "def generate_id(self, obj):\n \"\"\"Generate unique document id for ElasticSearch.\"\"\"\n object_type = type(obj).__name__.lower()\n return '{}_{}'.format(object_type, self.get_object_id(obj))", "code_tokens": "def generate_id ( self , obj ) : object_type = type ( obj ) . __name__ . lower ( ) return '{}_{}' . format ( object_type , self . get_object_id ( obj ) )", "docstring_tokens": "Generate unique document id for ElasticSearch .", "label": 1, "retrieval_idx": 4302, "negative": "Update the dev_info data from a dictionary ." }, { "idx": "cosqa-train-9318", "doc": "python mock mark a test as expected failure", "code": "def assert_called(_mock_self):\n \"\"\"assert that the mock was called at least once\n \"\"\"\n self = _mock_self\n if self.call_count == 0:\n msg = (\"Expected '%s' to have been called.\" %\n self._mock_name or 'mock')\n raise AssertionError(msg)", "code_tokens": "def assert_called ( _mock_self ) : self = _mock_self if self . call_count == 0 : msg = ( \"Expected '%s' to have been called.\" % self . _mock_name or 'mock' ) raise AssertionError ( msg )", "docstring_tokens": "assert that the mock was called at least once", "label": 1, "retrieval_idx": 4220, "negative": "Hacked run function which installs the trace ." }, { "idx": "cosqa-train-13071", "doc": "python get current users desktop", "code": "def get_current_desktop(self):\n \"\"\"\n Get the current desktop.\n Uses ``_NET_CURRENT_DESKTOP`` of the EWMH spec.\n \"\"\"\n desktop = ctypes.c_long(0)\n _libxdo.xdo_get_current_desktop(self._xdo, ctypes.byref(desktop))\n return desktop.value", "code_tokens": "def get_current_desktop ( self ) : desktop = ctypes . c_long ( 0 ) _libxdo . xdo_get_current_desktop ( self . _xdo , ctypes . byref ( desktop ) ) return desktop . value", "docstring_tokens": "Get the current desktop . Uses _NET_CURRENT_DESKTOP of the EWMH spec .", "label": 1, "retrieval_idx": 4922, "negative": "arr_out = round_array ( array_in )" }, { "idx": "cosqa-train-6354", "doc": "python connect to redis in other docker container", "code": "def __connect():\n \"\"\"\n Connect to a redis instance.\n \"\"\"\n global redis_instance\n if use_tcp_socket:\n redis_instance = redis.StrictRedis(host=hostname, port=port)\n else:\n redis_instance = redis.StrictRedis(unix_socket_path=unix_socket)", "code_tokens": "def __connect ( ) : global redis_instance if use_tcp_socket : redis_instance = redis . StrictRedis ( host = hostname , port = port ) else : redis_instance = redis . StrictRedis ( unix_socket_path = unix_socket )", "docstring_tokens": "Connect to a redis instance .", "label": 1, "retrieval_idx": 2168, "negative": "Use the S3 SWAG backend ." }, { "idx": "cosqa-train-7773", "doc": "python subplot second y axis", "code": "def show_yticklabels(self, row, column):\n \"\"\"Show the y-axis tick labels for a subplot.\n\n :param row,column: specify the subplot.\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.show_yticklabels()", "code_tokens": "def show_yticklabels ( self , row , column ) : subplot = self . get_subplot_at ( row , column ) subplot . show_yticklabels ( )", "docstring_tokens": "Show the y - axis tick labels for a subplot .", "label": 1, "retrieval_idx": 2426, "negative": "Is an object iterable like a list ( and not a string ) ?" }, { "idx": "cosqa-train-18714", "doc": "python function to detect first element of list", "code": "def find_first_in_list(txt: str, str_list: [str]) -> int: # type: ignore\n \"\"\"\n Returns the index of the earliest occurence of an item from a list in a string\n\n Ex: find_first_in_list('foobar', ['bar', 'fin']) -> 3\n \"\"\"\n start = len(txt) + 1\n for item in str_list:\n if start > txt.find(item) > -1:\n start = txt.find(item)\n return start if len(txt) + 1 > start > -1 else -1", "code_tokens": "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", "docstring_tokens": "Returns the index of the earliest occurence of an item from a list in a string", "label": 1, "retrieval_idx": 5545, "negative": "Set the scroll region on the canvas" }, { "idx": "cosqa-train-5201", "doc": "how to flip a matrix in python", "code": "def imflip(img, direction='horizontal'):\n \"\"\"Flip an image horizontally or vertically.\n\n Args:\n img (ndarray): Image to be flipped.\n direction (str): The flip direction, either \"horizontal\" or \"vertical\".\n\n Returns:\n ndarray: The flipped image.\n \"\"\"\n assert direction in ['horizontal', 'vertical']\n if direction == 'horizontal':\n return np.flip(img, axis=1)\n else:\n return np.flip(img, axis=0)", "code_tokens": "def imflip ( img , direction = 'horizontal' ) : assert direction in [ 'horizontal' , 'vertical' ] if direction == 'horizontal' : return np . flip ( img , axis = 1 ) else : return np . flip ( img , axis = 0 )", "docstring_tokens": "Flip an image horizontally or vertically .", "label": 1, "retrieval_idx": 538, "negative": "r Checks if l is iterable and contains only integral types" }, { "idx": "cosqa-train-15243", "doc": "python full name of object from global", "code": "def _fullname(o):\n \"\"\"Return the fully-qualified name of a function.\"\"\"\n return o.__module__ + \".\" + o.__name__ if o.__module__ else o.__name__", "code_tokens": "def _fullname ( o ) : return o . __module__ + \".\" + o . __name__ if o . __module__ else o . __name__", "docstring_tokens": "Return the fully - qualified name of a function .", "label": 1, "retrieval_idx": 354, "negative": "Only return cursor instance if configured for multiselect" }, { "idx": "cosqa-train-17087", "doc": "check if input is an integer or boolean python", "code": "def is_integer(value: Any) -> bool:\n \"\"\"Return true if a value is an integer number.\"\"\"\n return (isinstance(value, int) and not isinstance(value, bool)) or (\n isinstance(value, float) and isfinite(value) and int(value) == value\n )", "code_tokens": "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 )", "docstring_tokens": "Return true if a value is an integer number .", "label": 1, "retrieval_idx": 5567, "negative": "Saves the updated model to the current entity db ." }, { "idx": "cosqa-train-14642", "doc": "storing columns as array python", "code": "def to_array(self):\n \"\"\"Convert the table to a structured NumPy array.\"\"\"\n dt = np.dtype(list(zip(self.labels, (c.dtype for c in self.columns))))\n arr = np.empty_like(self.columns[0], dt)\n for label in self.labels:\n arr[label] = self[label]\n return arr", "code_tokens": "def to_array ( self ) : dt = np . dtype ( list ( zip ( self . labels , ( c . dtype for c in self . columns ) ) ) ) arr = np . empty_like ( self . columns [ 0 ] , dt ) for label in self . labels : arr [ label ] = self [ label ] return arr", "docstring_tokens": "Convert the table to a structured NumPy array .", "label": 1, "retrieval_idx": 5209, "negative": "Convert a byte value to boolean ( 0 or 1 ) if the global flag strictBool is True" }, { "idx": "cosqa-train-15173", "doc": "create column in python by joining columns", "code": "def join_cols(cols):\n \"\"\"Join list of columns into a string for a SQL query\"\"\"\n return \", \".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols", "code_tokens": "def join_cols ( cols ) : return \", \" . join ( [ i for i in cols ] ) if isinstance ( cols , ( list , tuple , set ) ) else cols", "docstring_tokens": "Join list of columns into a string for a SQL query", "label": 1, "retrieval_idx": 306, "negative": "A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right ." }, { "idx": "cosqa-train-16155", "doc": "how to remove blank lines in python file", "code": "def lines(input):\n \"\"\"Remove comments and empty lines\"\"\"\n for raw_line in input:\n line = raw_line.strip()\n if line and not line.startswith('#'):\n yield strip_comments(line)", "code_tokens": "def lines ( input ) : for raw_line in input : line = raw_line . strip ( ) if line and not line . startswith ( '#' ) : yield strip_comments ( line )", "docstring_tokens": "Remove comments and empty lines", "label": 1, "retrieval_idx": 964, "negative": "Get trace_id from flask request headers ." }, { "idx": "cosqa-train-11638", "doc": "how to know size of queue in python", "code": "def qsize(self):\n \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n self.mutex.acquire()\n n = self._qsize()\n self.mutex.release()\n return n", "code_tokens": "def qsize ( self ) : self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n", "docstring_tokens": "Return the approximate size of the queue ( not reliable! ) .", "label": 1, "retrieval_idx": 425, "negative": "Logs out the current session by removing it from the cache . This is expected to only occur when a session has" }, { "idx": "cosqa-train-9868", "doc": "python substring index of", "code": "def get_substring_idxs(substr, string):\n \"\"\"\n Return a list of indexes of substr. If substr not found, list is\n empty.\n\n Arguments:\n substr (str): Substring to match.\n string (str): String to match in.\n\n Returns:\n list of int: Start indices of substr.\n \"\"\"\n return [match.start() for match in re.finditer(substr, string)]", "code_tokens": "def get_substring_idxs ( substr , string ) : return [ match . start ( ) for match in re . finditer ( substr , string ) ]", "docstring_tokens": "Return a list of indexes of substr . If substr not found list is empty .", "label": 1, "retrieval_idx": 1832, "negative": "" }, { "idx": "cosqa-train-19683", "doc": "comparing int to none python", "code": "def is_natural(x):\n \"\"\"A non-negative integer.\"\"\"\n try:\n is_integer = int(x) == x\n except (TypeError, ValueError):\n return False\n return is_integer and x >= 0", "code_tokens": "def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0", "docstring_tokens": "A non - negative integer .", "label": 1, "retrieval_idx": 5540, "negative": "Aggregation function to get the first non - zero value ." }, { "idx": "cosqa-train-7857", "doc": "json to protobuf python", "code": "def toJson(protoObject, indent=None):\n \"\"\"\n Serialises a protobuf object as json\n \"\"\"\n # Using the internal method because this way we can reformat the JSON\n js = json_format.MessageToDict(protoObject, False)\n return json.dumps(js, indent=indent)", "code_tokens": "def toJson ( protoObject , indent = None ) : # Using the internal method because this way we can reformat the JSON js = json_format . MessageToDict ( protoObject , False ) return json . dumps ( js , indent = indent )", "docstring_tokens": "Serialises a protobuf object as json", "label": 1, "retrieval_idx": 2465, "negative": "Performs drag a element to another elmenet ." }, { "idx": "cosqa-train-11626", "doc": "how to join 2 data frames in python", "code": "def cross_join(df1, df2):\n \"\"\"\n Return a dataframe that is a cross between dataframes\n df1 and df2\n\n ref: https://github.com/pydata/pandas/issues/5401\n \"\"\"\n if len(df1) == 0:\n return df2\n\n if len(df2) == 0:\n return df1\n\n # Add as lists so that the new index keeps the items in\n # the order that they are added together\n all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n df1['key'] = 1\n df2['key'] = 1\n return pd.merge(df1, df2, on='key').loc[:, all_columns]", "code_tokens": "def cross_join ( df1 , df2 ) : if len ( df1 ) == 0 : return df2 if len ( df2 ) == 0 : return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd . Index ( list ( df1 . columns ) + list ( df2 . columns ) ) df1 [ 'key' ] = 1 df2 [ 'key' ] = 1 return pd . merge ( df1 , df2 , on = 'key' ) . loc [ : , all_columns ]", "docstring_tokens": "Return a dataframe that is a cross between dataframes df1 and df2", "label": 1, "retrieval_idx": 793, "negative": "Covert numpy array to tensorflow tensor" }, { "idx": "cosqa-train-18817", "doc": "how to product of a list in python", "code": "def dotproduct(X, Y):\n \"\"\"Return the sum of the element-wise product of vectors x and y.\n >>> dotproduct([1, 2, 3], [1000, 100, 10])\n 1230\n \"\"\"\n return sum([x * y for x, y in zip(X, Y)])", "code_tokens": "def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )", "docstring_tokens": "Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230", "label": 1, "retrieval_idx": 5599, "negative": "Returns Gaussian smoothed image ." }, { "idx": "cosqa-train-9034", "doc": "get all dates between range datetime python", "code": "def dates_in_range(start_date, end_date):\n \"\"\"Returns all dates between two dates.\n\n Inclusive of the start date but not the end date.\n\n Args:\n start_date (datetime.date)\n end_date (datetime.date)\n\n Returns:\n (list) of datetime.date objects\n \"\"\"\n return [\n start_date + timedelta(n)\n for n in range(int((end_date - start_date).days))\n ]", "code_tokens": "def dates_in_range ( start_date , end_date ) : return [ start_date + timedelta ( n ) for n in range ( int ( ( end_date - start_date ) . days ) ) ]", "docstring_tokens": "Returns all dates between two dates .", "label": 1, "retrieval_idx": 573, "negative": "Write the ROI model to a FITS file ." }, { "idx": "cosqa-train-12370", "doc": "python access file on remote", "code": "def get_remote_content(filepath):\n \"\"\" A handy wrapper to get a remote file content \"\"\"\n with hide('running'):\n temp = BytesIO()\n get(filepath, temp)\n content = temp.getvalue().decode('utf-8')\n return content.strip()", "code_tokens": "def get_remote_content ( filepath ) : with hide ( 'running' ) : temp = BytesIO ( ) get ( filepath , temp ) content = temp . getvalue ( ) . decode ( 'utf-8' ) return content . strip ( )", "docstring_tokens": "A handy wrapper to get a remote file content", "label": 1, "retrieval_idx": 1848, "negative": "Takes JSON formatted data converting it into native Python objects" }, { "idx": "cosqa-train-9399", "doc": "how to download txt file from internet in python", "code": "def get_dates_link(url):\n \"\"\" download the dates file from the internet and parse it as a dates file\"\"\"\n urllib.request.urlretrieve(url, \"temp.txt\")\n dates = get_dates_file(\"temp.txt\")\n os.remove(\"temp.txt\")\n return dates", "code_tokens": "def get_dates_link ( url ) : urllib . request . urlretrieve ( url , \"temp.txt\" ) dates = get_dates_file ( \"temp.txt\" ) os . remove ( \"temp.txt\" ) return dates", "docstring_tokens": "download the dates file from the internet and parse it as a dates file", "label": 1, "retrieval_idx": 4235, "negative": "Closes and waits for subprocess to exit ." }, { "idx": "cosqa-train-12507", "doc": "stopwords list remove python", "code": "def _removeStopwords(text_list):\n \"\"\"\n Removes stopwords contained in a list of words.\n\n :param text_string: A list of strings.\n :type text_string: list.\n\n :returns: The input ``text_list`` with stopwords removed.\n :rtype: list\n \"\"\"\n\n output_list = []\n\n for word in text_list:\n if word.lower() not in _stopwords:\n output_list.append(word)\n\n return output_list", "code_tokens": "def _removeStopwords ( text_list ) : output_list = [ ] for word in text_list : if word . lower ( ) not in _stopwords : output_list . append ( word ) return output_list", "docstring_tokens": "Removes stopwords contained in a list of words .", "label": 1, "retrieval_idx": 1153, "negative": "Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists ." }, { "idx": "cosqa-train-7885", "doc": "limit on open file handles in python", "code": "def _increase_file_handle_limit():\n \"\"\"Raise the open file handles permitted by the Dusty daemon process\n and its child processes. The number we choose here needs to be within\n the OS X default kernel hard limit, which is 10240.\"\"\"\n logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n resource.setrlimit(resource.RLIMIT_NOFILE,\n (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))", "code_tokens": "def _increase_file_handle_limit ( ) : logging . info ( 'Increasing file handle limit to {}' . format ( constants . FILE_HANDLE_LIMIT ) ) resource . setrlimit ( resource . RLIMIT_NOFILE , ( constants . FILE_HANDLE_LIMIT , resource . RLIM_INFINITY ) )", "docstring_tokens": "Raise the open file handles permitted by the Dusty daemon process and its child processes . The number we choose here needs to be within the OS X default kernel hard limit which is 10240 .", "label": 1, "retrieval_idx": 2901, "negative": "Stops iterating before yielding the specified idx ." }, { "idx": "cosqa-train-6745", "doc": "determine the longest sentence in corpus in nlp python ocde", "code": "def get_longest_orf(orfs):\n \"\"\"Find longest ORF from the given list of ORFs.\"\"\"\n sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0]\n return sorted_orf", "code_tokens": "def get_longest_orf ( orfs ) : sorted_orf = sorted ( orfs , key = lambda x : len ( x [ 'sequence' ] ) , reverse = True ) [ 0 ] return sorted_orf", "docstring_tokens": "Find longest ORF from the given list of ORFs .", "label": 1, "retrieval_idx": 3106, "negative": "Computes all the integer factors of the number n" }, { "idx": "cosqa-train-8615", "doc": "python deterministic dictionary printing", "code": "def pprint_for_ordereddict():\n \"\"\"\n Context manager that causes pprint() to print OrderedDict objects as nicely\n as standard Python dictionary objects.\n \"\"\"\n od_saved = OrderedDict.__repr__\n try:\n OrderedDict.__repr__ = dict.__repr__\n yield\n finally:\n OrderedDict.__repr__ = od_saved", "code_tokens": "def pprint_for_ordereddict ( ) : od_saved = OrderedDict . __repr__ try : OrderedDict . __repr__ = dict . __repr__ yield finally : OrderedDict . __repr__ = od_saved", "docstring_tokens": "Context manager that causes pprint () to print OrderedDict objects as nicely as standard Python dictionary objects .", "label": 1, "retrieval_idx": 920, "negative": "Captures screen area of this region at least the part that is on the screen" }, { "idx": "cosqa-train-10233", "doc": "remove namespace from xml tag python", "code": "def strip_xml_namespace(root):\n \"\"\"Strip out namespace data from an ElementTree.\n\n This function is recursive and will traverse all\n subnodes to the root element\n\n @param root: the root element\n\n @return: the same root element, minus namespace\n \"\"\"\n try:\n root.tag = root.tag.split('}')[1]\n except IndexError:\n pass\n\n for element in root.getchildren():\n strip_xml_namespace(element)", "code_tokens": "def strip_xml_namespace ( root ) : try : root . tag = root . tag . split ( '}' ) [ 1 ] except IndexError : pass for element in root . getchildren ( ) : strip_xml_namespace ( element )", "docstring_tokens": "Strip out namespace data from an ElementTree .", "label": 1, "retrieval_idx": 2580, "negative": "Removes trailing whitespace on each line ." }, { "idx": "cosqa-train-13207", "doc": "fill is null with other columns python", "code": "def clean_dataframe(df):\n \"\"\"Fill NaNs with the previous value, the next value or if all are NaN then 1.0\"\"\"\n df = df.fillna(method='ffill')\n df = df.fillna(0.0)\n return df", "code_tokens": "def clean_dataframe ( df ) : df = df . fillna ( method = 'ffill' ) df = df . fillna ( 0.0 ) return df", "docstring_tokens": "Fill NaNs with the previous value the next value or if all are NaN then 1 . 0", "label": 1, "retrieval_idx": 889, "negative": "" }, { "idx": "cosqa-train-8216", "doc": "python async input from gui", "code": "async def async_input(prompt):\n \"\"\"\n Python's ``input()`` is blocking, which means the event loop we set\n above can't be running while we're blocking there. This method will\n let the loop run while we wait for input.\n \"\"\"\n print(prompt, end='', flush=True)\n return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()", "code_tokens": "async def async_input ( prompt ) : print ( prompt , end = '' , flush = True ) return ( await loop . run_in_executor ( None , sys . stdin . readline ) ) . rstrip ( )", "docstring_tokens": "Python s input () is blocking which means the event loop we set above can t be running while we re blocking there . This method will let the loop run while we wait for input .", "label": 1, "retrieval_idx": 975, "negative": "Strip out namespace data from an ElementTree ." }, { "idx": "cosqa-train-9515", "doc": "how to identify the index of an element of a set in python", "code": "def find_geom(geom, geoms):\n \"\"\"\n Returns the index of a geometry in a list of geometries avoiding\n expensive equality checks of `in` operator.\n \"\"\"\n for i, g in enumerate(geoms):\n if g is geom:\n return i", "code_tokens": "def find_geom ( geom , geoms ) : for i , g in enumerate ( geoms ) : if g is geom : return i", "docstring_tokens": "Returns the index of a geometry in a list of geometries avoiding expensive equality checks of in operator .", "label": 1, "retrieval_idx": 1272, "negative": "Return the SHA1 hash of the given a file - like object as file . This will seek the file back to 0 when it s finished ." }, { "idx": "cosqa-train-12351", "doc": "python 3 print object string", "code": "def _get_pretty_string(obj):\n \"\"\"Return a prettier version of obj\n\n Parameters\n ----------\n obj : object\n Object to pretty print\n\n Returns\n -------\n s : str\n Pretty print object repr\n \"\"\"\n sio = StringIO()\n pprint.pprint(obj, stream=sio)\n return sio.getvalue()", "code_tokens": "def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )", "docstring_tokens": "Return a prettier version of obj", "label": 1, "retrieval_idx": 1942, "negative": "Adds points and converts to topojson string ." }, { "idx": "cosqa-train-13120", "doc": "python get most recent file containing string", "code": "def newest_file(file_iterable):\n \"\"\"\n Returns the name of the newest file given an iterable of file names.\n\n \"\"\"\n return max(file_iterable, key=lambda fname: os.path.getmtime(fname))", "code_tokens": "def newest_file ( file_iterable ) : return max ( file_iterable , key = lambda fname : os . path . getmtime ( fname ) )", "docstring_tokens": "Returns the name of the newest file given an iterable of file names .", "label": 1, "retrieval_idx": 958, "negative": "Converts and image to matrix ( one pixel per line )" }, { "idx": "cosqa-train-14086", "doc": "python sqlite3 delete doesn't delete records", "code": "def truncate_table(self, tablename):\n \"\"\"\n SQLite3 doesn't support direct truncate, so we just use delete here\n \"\"\"\n self.get(tablename).remove()\n self.db.commit()", "code_tokens": "def truncate_table ( self , tablename ) : self . get ( tablename ) . remove ( ) self . db . commit ( )", "docstring_tokens": "SQLite3 doesn t support direct truncate so we just use delete here", "label": 1, "retrieval_idx": 5107, "negative": "Returns the string name of an enum value ." }, { "idx": "cosqa-train-8166", "doc": "python apply function to iterator", "code": "def find_all(self, string, callback):\n\t\t\"\"\"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t\"\"\"\n\t\tfor index, output in self.iter(string):\n\t\t\tcallback(index, output)", "code_tokens": "def find_all ( self , string , callback ) : for index , output in self . iter ( string ) : callback ( index , output )", "docstring_tokens": "Wrapper on iter method callback gets an iterator result", "label": 1, "retrieval_idx": 3963, "negative": "Hides the main window of the terminal and sets the visible flag to False ." }, { "idx": "cosqa-train-12637", "doc": "use python next to iterate through", "code": "def __next__(self, reward, ask_id, lbl):\n \"\"\"For Python3 compatibility of generator.\"\"\"\n return self.next(reward, ask_id, lbl)", "code_tokens": "def __next__ ( self , reward , ask_id , lbl ) : return self . next ( reward , ask_id , lbl )", "docstring_tokens": "For Python3 compatibility of generator .", "label": 1, "retrieval_idx": 1968, "negative": "Set the scroll region on the canvas" }, { "idx": "cosqa-train-7547", "doc": "how to print all the variables in an object python", "code": "def var_dump(*obs):\n\t\"\"\"\n\t shows structured information of a object, list, tuple etc\n\t\"\"\"\n\ti = 0\n\tfor x in obs:\n\t\t\n\t\tstr = var_dump_output(x, 0, ' ', '\\n', True)\n\t\tprint (str.strip())\n\t\t\n\t\t#dump(x, 0, i, '', object)\n\t\ti += 1", "code_tokens": "def var_dump ( * obs ) : i = 0 for x in obs : str = var_dump_output ( x , 0 , ' ' , '\\n' , True ) print ( str . strip ( ) ) #dump(x, 0, i, '', object) i += 1", "docstring_tokens": "shows structured information of a object list tuple etc", "label": 1, "retrieval_idx": 2570, "negative": "Convert a CSV object to a numpy array ." }, { "idx": "cosqa-train-18478", "doc": "how to determine the index interval for given range of array python", "code": "def _infer_interval_breaks(coord):\n \"\"\"\n >>> _infer_interval_breaks(np.arange(5))\n array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5])\n\n Taken from xarray.plotting.plot module\n \"\"\"\n coord = np.asarray(coord)\n deltas = 0.5 * (coord[1:] - coord[:-1])\n first = coord[0] - deltas[0]\n last = coord[-1] + deltas[-1]\n return np.r_[[first], coord[:-1] + deltas, [last]]", "code_tokens": "def _infer_interval_breaks ( coord ) : coord = np . asarray ( coord ) deltas = 0.5 * ( coord [ 1 : ] - coord [ : - 1 ] ) first = coord [ 0 ] - deltas [ 0 ] last = coord [ - 1 ] + deltas [ - 1 ] return np . r_ [ [ first ] , coord [ : - 1 ] + deltas , [ last ] ]", "docstring_tokens": ">>> _infer_interval_breaks ( np . arange ( 5 )) array ( [ - 0 . 5 0 . 5 1 . 5 2 . 5 3 . 5 4 . 5 ] )", "label": 1, "retrieval_idx": 6063, "negative": "Return scaled image size in ( width height ) format . The scaling preserves the aspect ratio . If PIL is not found returns None ." }, { "idx": "cosqa-train-17091", "doc": "python print numpy array with string", "code": "def array2string(arr: numpy.ndarray) -> str:\n \"\"\"Format numpy array as a string.\"\"\"\n shape = str(arr.shape)[1:-1]\n if shape.endswith(\",\"):\n shape = shape[:-1]\n return numpy.array2string(arr, threshold=11) + \"%s[%s]\" % (arr.dtype, shape)", "code_tokens": "def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( \",\" ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + \"%s[%s]\" % ( arr . dtype , shape )", "docstring_tokens": "Format numpy array as a string .", "label": 1, "retrieval_idx": 5651, "negative": "Removes all blank lines in @string" }, { "idx": "cosqa-train-14536", "doc": "python assert value is of type", "code": "def _assert_is_type(name, value, value_type):\n \"\"\"Assert that a value must be a given type.\"\"\"\n if not isinstance(value, value_type):\n if type(value_type) is tuple:\n types = ', '.join(t.__name__ for t in value_type)\n raise ValueError('{0} must be one of ({1})'.format(name, types))\n else:\n raise ValueError('{0} must be {1}'\n .format(name, value_type.__name__))", "code_tokens": "def _assert_is_type ( name , value , value_type ) : if not isinstance ( value , value_type ) : if type ( value_type ) is tuple : types = ', ' . join ( t . __name__ for t in value_type ) raise ValueError ( '{0} must be one of ({1})' . format ( name , types ) ) else : raise ValueError ( '{0} must be {1}' . format ( name , value_type . __name__ ) )", "docstring_tokens": "Assert that a value must be a given type .", "label": 1, "retrieval_idx": 1519, "negative": "Add dots ." }, { "idx": "cosqa-train-11450", "doc": "python multiproccessing map with multiple inputs", "code": "def imapchain(*a, **kwa):\n \"\"\" Like map but also chains the results. \"\"\"\n\n imap_results = map( *a, **kwa )\n return itertools.chain( *imap_results )", "code_tokens": "def imapchain ( * a , * * kwa ) : imap_results = map ( * a , * * kwa ) return itertools . chain ( * imap_results )", "docstring_tokens": "Like map but also chains the results .", "label": 1, "retrieval_idx": 3696, "negative": "Try to get a number out of a string and cast it ." }, { "idx": "cosqa-train-14502", "doc": "python add suffix to filename", "code": "def add_suffix(fullname, suffix):\n \"\"\" Add suffix to a full file name\"\"\"\n name, ext = os.path.splitext(fullname)\n return name + '_' + suffix + ext", "code_tokens": "def add_suffix ( fullname , suffix ) : name , ext = os . path . splitext ( fullname ) return name + '_' + suffix + ext", "docstring_tokens": "Add suffix to a full file name", "label": 1, "retrieval_idx": 2100, "negative": "Get the parent directory of a filename ." }, { "idx": "cosqa-train-14904", "doc": "best way to deal with pagination in python", "code": "def paginate(self, request, offset=0, limit=None):\n \"\"\"Paginate queryset.\"\"\"\n return self.collection.offset(offset).limit(limit), self.collection.count()", "code_tokens": "def paginate ( self , request , offset = 0 , limit = None ) : return self . collection . offset ( offset ) . limit ( limit ) , self . collection . count ( )", "docstring_tokens": "Paginate queryset .", "label": 1, "retrieval_idx": 4271, "negative": "Python 3 input () / Python 2 raw_input ()" }, { "idx": "cosqa-train-18641", "doc": "finding factors in python and return list", "code": "def factors(n):\n \"\"\"\n Computes all the integer factors of the number `n`\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> from utool.util_alg import * # NOQA\n >>> import utool as ut\n >>> result = sorted(ut.factors(10))\n >>> print(result)\n [1, 2, 5, 10]\n\n References:\n http://stackoverflow.com/questions/6800193/finding-all-the-factors\n \"\"\"\n return set(reduce(list.__add__,\n ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))", "code_tokens": "def factors ( n ) : return set ( reduce ( list . __add__ , ( [ i , n // i ] for i in range ( 1 , int ( n ** 0.5 ) + 1 ) if n % i == 0 ) ) )", "docstring_tokens": "Computes all the integer factors of the number n", "label": 1, "retrieval_idx": 6090, "negative": "Push a new value into heap ." }, { "idx": "cosqa-train-4338", "doc": "best way to read xml in python", "code": "def xmltreefromfile(filename):\n \"\"\"Internal function to read an XML file\"\"\"\n try:\n return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))\n except TypeError:\n return ElementTree.parse(filename, ElementTree.XMLParser())", "code_tokens": "def xmltreefromfile ( filename ) : try : return ElementTree . parse ( filename , ElementTree . XMLParser ( collect_ids = False ) ) except TypeError : return ElementTree . parse ( filename , ElementTree . XMLParser ( ) )", "docstring_tokens": "Internal function to read an XML file", "label": 1, "retrieval_idx": 89, "negative": "A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right ." }, { "idx": "cosqa-train-9678", "doc": "how to put a string in a yaml file python", "code": "def generate_yaml_file(filename, contents):\n \"\"\"Creates a yaml file with the given content.\"\"\"\n with open(filename, 'w') as file:\n file.write(yaml.dump(contents, default_flow_style=False))", "code_tokens": "def generate_yaml_file ( filename , contents ) : with open ( filename , 'w' ) as file : file . write ( yaml . dump ( contents , default_flow_style = False ) )", "docstring_tokens": "Creates a yaml file with the given content .", "label": 1, "retrieval_idx": 4299, "negative": "Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing" }, { "idx": "cosqa-train-920", "doc": "python move cursor to secific line", "code": "def _go_to_line(editor, line):\n \"\"\"\n Move cursor to this line in the current buffer.\n \"\"\"\n b = editor.application.current_buffer\n b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)", "code_tokens": "def _go_to_line ( editor , line ) : b = editor . application . current_buffer b . cursor_position = b . document . translate_row_col_to_index ( max ( 0 , int ( line ) - 1 ) , 0 )", "docstring_tokens": "Move cursor to this line in the current buffer .", "label": 1, "retrieval_idx": 814, "negative": "When the with statement ends ." }, { "idx": "cosqa-dev-72", "doc": "token to id python", "code": "def strids2ids(tokens: Iterable[str]) -> List[int]:\n \"\"\"\n Returns sequence of integer ids given a sequence of string ids.\n\n :param tokens: List of integer tokens.\n :return: List of word ids.\n \"\"\"\n return list(map(int, tokens))", "code_tokens": "def strids2ids ( tokens : Iterable [ str ] ) -> List [ int ] : return list ( map ( int , tokens ) )", "docstring_tokens": "Returns sequence of integer ids given a sequence of string ids .", "label": 1, "retrieval_idx": 6012, "negative": "Connect to a redis instance ." }, { "idx": "cosqa-train-19357", "doc": "python urlparse get domain", "code": "def get_domain(url):\n \"\"\"\n Get domain part of an url.\n\n For example: https://www.python.org/doc/ -> https://www.python.org\n \"\"\"\n parse_result = urlparse(url)\n domain = \"{schema}://{netloc}\".format(\n schema=parse_result.scheme, netloc=parse_result.netloc)\n return domain", "code_tokens": "def get_domain ( url ) : parse_result = urlparse ( url ) domain = \"{schema}://{netloc}\" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain", "docstring_tokens": "Get domain part of an url .", "label": 1, "retrieval_idx": 5798, "negative": "Get a list of the public data attributes ." }, { "idx": "cosqa-train-7880", "doc": "python turn a string into a number", "code": "def get_number(s, cast=int):\n \"\"\"\n Try to get a number out of a string, and cast it.\n \"\"\"\n import string\n d = \"\".join(x for x in str(s) if x in string.digits)\n return cast(d)", "code_tokens": "def get_number ( s , cast = int ) : import string d = \"\" . join ( x for x in str ( s ) if x in string . digits ) return cast ( d )", "docstring_tokens": "Try to get a number out of a string and cast it .", "label": 1, "retrieval_idx": 40, "negative": "Is this an integer ." }, { "idx": "cosqa-train-18111", "doc": "python check if all are type string in a column", "code": "def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool:\n \"\"\"\n Is the SQLAlchemy column type a string type?\n \"\"\"\n coltype = _coltype_to_typeengine(coltype)\n return isinstance(coltype, sqltypes.String)", "code_tokens": "def is_sqlatype_string ( coltype : Union [ TypeEngine , VisitableType ] ) -> bool : coltype = _coltype_to_typeengine ( coltype ) return isinstance ( coltype , sqltypes . String )", "docstring_tokens": "Is the SQLAlchemy column type a string type?", "label": 1, "retrieval_idx": 5597, "negative": "Saves a value to session ." }, { "idx": "cosqa-train-12805", "doc": "bin means python numpy", "code": "def val_to_bin(edges, x):\n \"\"\"Convert axis coordinate to bin index.\"\"\"\n ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n return ibin", "code_tokens": "def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin", "docstring_tokens": "Convert axis coordinate to bin index .", "label": 1, "retrieval_idx": 521, "negative": "Hacked run function which installs the trace ." }, { "idx": "cosqa-train-14553", "doc": "python boto3 delete key from s3", "code": "def remove_file_from_s3(awsclient, bucket, key):\n \"\"\"Remove a file from an AWS S3 bucket.\n\n :param awsclient:\n :param bucket:\n :param key:\n :return:\n \"\"\"\n client_s3 = awsclient.get_client('s3')\n response = client_s3.delete_object(Bucket=bucket, Key=key)", "code_tokens": "def remove_file_from_s3 ( awsclient , bucket , key ) : client_s3 = awsclient . get_client ( 's3' ) response = client_s3 . delete_object ( Bucket = bucket , Key = key )", "docstring_tokens": "Remove a file from an AWS S3 bucket .", "label": 1, "retrieval_idx": 1455, "negative": "Joins a voice channel" }, { "idx": "cosqa-train-19466", "doc": "random walk steps python", "code": "def returned(n):\n\t\"\"\"Generate a random walk and return True if the walker has returned to\n\tthe origin after taking `n` steps.\n\t\"\"\"\n\t## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk\n\tfor pos in randwalk() >> drop(1) >> takei(xrange(n-1)):\n\t\tif pos == Origin:\n\t\t\treturn True\n\treturn False", "code_tokens": "def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False", "docstring_tokens": "Generate a random walk and return True if the walker has returned to the origin after taking n steps .", "label": 1, "retrieval_idx": 5912, "negative": "Check if given string is a punctuation" }, { "idx": "cosqa-train-8586", "doc": "python delete objects inside of objects", "code": "def _removeTags(tags, objects):\n \"\"\" Removes tags from objects \"\"\"\n for t in tags:\n for o in objects:\n o.tags.remove(t)\n\n return True", "code_tokens": "def _removeTags ( tags , objects ) : for t in tags : for o in objects : o . tags . remove ( t ) return True", "docstring_tokens": "Removes tags from objects", "label": 1, "retrieval_idx": 1103, "negative": "Returns whether a path names an existing executable file ." }, { "idx": "cosqa-train-8348", "doc": "truncate seconds from a timestamp in python code", "code": "def RoundToSeconds(cls, timestamp):\n \"\"\"Takes a timestamp value and rounds it to a second precision.\"\"\"\n leftovers = timestamp % definitions.MICROSECONDS_PER_SECOND\n scrubbed = timestamp - leftovers\n rounded = round(float(leftovers) / definitions.MICROSECONDS_PER_SECOND)\n\n return int(scrubbed + rounded * definitions.MICROSECONDS_PER_SECOND)", "code_tokens": "def RoundToSeconds ( cls , timestamp ) : leftovers = timestamp % definitions . MICROSECONDS_PER_SECOND scrubbed = timestamp - leftovers rounded = round ( float ( leftovers ) / definitions . MICROSECONDS_PER_SECOND ) return int ( scrubbed + rounded * definitions . MICROSECONDS_PER_SECOND )", "docstring_tokens": "Takes a timestamp value and rounds it to a second precision .", "label": 1, "retrieval_idx": 3242, "negative": "Equivalent of the apply () builtin function . It blocks till the result is ready ." }, { "idx": "cosqa-train-7002", "doc": "python json load unorde", "code": "def read_json(location):\n \"\"\"Open and load JSON from file.\n\n location (Path): Path to JSON file.\n RETURNS (dict): Loaded JSON content.\n \"\"\"\n location = ensure_path(location)\n with location.open('r', encoding='utf8') as f:\n return ujson.load(f)", "code_tokens": "def read_json ( location ) : location = ensure_path ( location ) with location . open ( 'r' , encoding = 'utf8' ) as f : return ujson . load ( f )", "docstring_tokens": "Open and load JSON from file .", "label": 1, "retrieval_idx": 1300, "negative": "Cleanup the output directory" }, { "idx": "cosqa-train-10094", "doc": "python yaml expected single document", "code": "def yaml_to_param(obj, name):\n\t\"\"\"\n\tReturn the top-level element of a document sub-tree containing the\n\tYAML serialization of a Python object.\n\t\"\"\"\n\treturn from_pyvalue(u\"yaml:%s\" % name, unicode(yaml.dump(obj)))", "code_tokens": "def yaml_to_param ( obj , name ) : return from_pyvalue ( u\"yaml:%s\" % name , unicode ( yaml . dump ( obj ) ) )", "docstring_tokens": "Return the top - level element of a document sub - tree containing the YAML serialization of a Python object .", "label": 1, "retrieval_idx": 1355, "negative": "Computes all the integer factors of the number n" }, { "idx": "cosqa-train-8758", "doc": "python filter object at", "code": "def __init__(self, function):\n\t\t\"\"\"function: to be called with each stream element as its\n\t\tonly argument\n\t\t\"\"\"\n\t\tsuper(filter, self).__init__()\n\t\tself.function = function", "code_tokens": "def __init__ ( self , function ) : super ( filter , self ) . __init__ ( ) self . function = function", "docstring_tokens": "function : to be called with each stream element as its only argument", "label": 1, "retrieval_idx": 4102, "negative": "composion of preprocessing functions" }, { "idx": "cosqa-train-9368", "doc": "python nonetype object has no attributte", "code": "def listlike(obj):\n \"\"\"Is an object iterable like a list (and not a string)?\"\"\"\n \n return hasattr(obj, \"__iter__\") \\\n and not issubclass(type(obj), str)\\\n and not issubclass(type(obj), unicode)", "code_tokens": "def listlike ( obj ) : return hasattr ( obj , \"__iter__\" ) and not issubclass ( type ( obj ) , str ) and not issubclass ( type ( obj ) , unicode )", "docstring_tokens": "Is an object iterable like a list ( and not a string ) ?", "label": 1, "retrieval_idx": 94, "negative": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ..." }, { "idx": "cosqa-train-16286", "doc": "python tkinter how to create scrollable canvas", "code": "def _set_scroll_v(self, *args):\n \"\"\"Scroll both categories Canvas and scrolling container\"\"\"\n self._canvas_categories.yview(*args)\n self._canvas_scroll.yview(*args)", "code_tokens": "def _set_scroll_v ( self , * args ) : self . _canvas_categories . yview ( * args ) self . _canvas_scroll . yview ( * args )", "docstring_tokens": "Scroll both categories Canvas and scrolling container", "label": 1, "retrieval_idx": 1083, "negative": "Probability density function ( normal distribution )" }, { "idx": "cosqa-train-11132", "doc": "geojson to topojson python", "code": "def to_topojson(self):\n \"\"\"Adds points and converts to topojson string.\"\"\"\n topojson = self.topojson\n topojson[\"objects\"][\"points\"] = {\n \"type\": \"GeometryCollection\",\n \"geometries\": [point.to_topojson() for point in self.points.all()],\n }\n return json.dumps(topojson)", "code_tokens": "def to_topojson ( self ) : topojson = self . topojson topojson [ \"objects\" ] [ \"points\" ] = { \"type\" : \"GeometryCollection\" , \"geometries\" : [ point . to_topojson ( ) for point in self . points . all ( ) ] , } return json . dumps ( topojson )", "docstring_tokens": "Adds points and converts to topojson string .", "label": 1, "retrieval_idx": 4600, "negative": "Convert comma - delimited list / string into a list of strings" }, { "idx": "cosqa-train-16972", "doc": "python get png image dimensions", "code": "def getDimensionForImage(filename, maxsize):\n \"\"\"Return scaled image size in (width, height) format.\n The scaling preserves the aspect ratio.\n If PIL is not found returns None.\"\"\"\n try:\n from PIL import Image\n except ImportError:\n return None\n img = Image.open(filename)\n width, height = img.size\n if width > maxsize[0] or height > maxsize[1]:\n img.thumbnail(maxsize)\n out.info(\"Downscaled display size from %s to %s\" % ((width, height), img.size))\n return img.size", "code_tokens": "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", "docstring_tokens": "Return scaled image size in ( width height ) format . The scaling preserves the aspect ratio . If PIL is not found returns None .", "label": 1, "retrieval_idx": 5568, "negative": "Transparently unzip the file handle" }, { "idx": "cosqa-train-6652", "doc": "python flask separate functions get and post", "code": "def handleFlaskPostRequest(flaskRequest, endpoint):\n \"\"\"\n Handles the specified flask request for one of the POST URLS\n Invokes the specified endpoint to generate a response.\n \"\"\"\n if flaskRequest.method == \"POST\":\n return handleHttpPost(flaskRequest, endpoint)\n elif flaskRequest.method == \"OPTIONS\":\n return handleHttpOptions()\n else:\n raise exceptions.MethodNotAllowedException()", "code_tokens": "def handleFlaskPostRequest ( flaskRequest , endpoint ) : if flaskRequest . method == \"POST\" : return handleHttpPost ( flaskRequest , endpoint ) elif flaskRequest . method == \"OPTIONS\" : return handleHttpOptions ( ) else : raise exceptions . MethodNotAllowedException ( )", "docstring_tokens": "Handles the specified flask request for one of the POST URLS Invokes the specified endpoint to generate a response .", "label": 1, "retrieval_idx": 310, "negative": "Python s input () is blocking which means the event loop we set above can t be running while we re blocking there . This method will let the loop run while we wait for input ." }, { "idx": "cosqa-train-18214", "doc": "return year from date python", "code": "def year(date):\n \"\"\" Returns the year.\n\n :param date:\n The string date with this format %m/%d/%Y\n :type date:\n String\n\n :returns:\n int\n\n :example:\n >>> year('05/1/2015')\n 2015\n \"\"\"\n try:\n fmt = '%m/%d/%Y'\n return datetime.strptime(date, fmt).timetuple().tm_year\n except ValueError:\n return 0", "code_tokens": "def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0", "docstring_tokens": "Returns the year .", "label": 1, "retrieval_idx": 5670, "negative": "Return true if a value is an integer number ." }, { "idx": "cosqa-train-13715", "doc": "how to get all modes python", "code": "def __iter__(self):\n \"\"\"\n Returns the list of modes.\n\n :return:\n \"\"\"\n return iter([v for k, v in sorted(self._modes.items())])", "code_tokens": "def __iter__ ( self ) : return iter ( [ v for k , v in sorted ( self . _modes . items ( ) ) ] )", "docstring_tokens": "Returns the list of modes .", "label": 1, "retrieval_idx": 5046, "negative": "Removes stopwords contained in a list of words ." }, { "idx": "cosqa-train-17708", "doc": "integer and returns a random bitstring of size python", "code": "def binary(length):\n \"\"\"\n returns a a random string that represent a binary representation\n\n :param length: number of bits\n \"\"\"\n num = randint(1, 999999)\n mask = '0' * length\n return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]", "code_tokens": "def binary ( length ) : num = randint ( 1 , 999999 ) mask = '0' * length return ( mask + '' . join ( [ str ( num >> i & 1 ) for i in range ( 7 , - 1 , - 1 ) ] ) ) [ - length : ]", "docstring_tokens": "returns a a random string that represent a binary representation", "label": 1, "retrieval_idx": 5717, "negative": "returns a dictionary of arg_name : default_values for the input function" }, { "idx": "cosqa-train-11584", "doc": "how to get the encoding of a file python", "code": "def smartread(path):\n \"\"\"Read text from file, automatically detect encoding. ``chardet`` required.\n \"\"\"\n with open(path, \"rb\") as f:\n content = f.read()\n result = chardet.detect(content)\n return content.decode(result[\"encoding\"])", "code_tokens": "def smartread ( path ) : with open ( path , \"rb\" ) as f : content = f . read ( ) result = chardet . detect ( content ) return content . decode ( result [ \"encoding\" ] )", "docstring_tokens": "Read text from file automatically detect encoding . chardet required .", "label": 1, "retrieval_idx": 4685, "negative": "Transform an underscore_case string to a mixedCase string" }, { "idx": "cosqa-train-14776", "doc": "python connect to aws rds", "code": "def connect_rds(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):\n \"\"\"\n :type aws_access_key_id: string\n :param aws_access_key_id: Your AWS Access Key ID\n\n :type aws_secret_access_key: string\n :param aws_secret_access_key: Your AWS Secret Access Key\n\n :rtype: :class:`boto.rds.RDSConnection`\n :return: A connection to RDS\n \"\"\"\n from boto.rds import RDSConnection\n return RDSConnection(aws_access_key_id, aws_secret_access_key, **kwargs)", "code_tokens": "def connect_rds ( aws_access_key_id = None , aws_secret_access_key = None , * * kwargs ) : from boto . rds import RDSConnection return RDSConnection ( aws_access_key_id , aws_secret_access_key , * * kwargs )", "docstring_tokens": ": type aws_access_key_id : string : param aws_access_key_id : Your AWS Access Key ID", "label": 1, "retrieval_idx": 5229, "negative": "Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays ." }, { "idx": "cosqa-train-12714", "doc": "python cv2 check if image is empty", "code": "def is_empty(self):\n \"\"\"Checks for an empty image.\n \"\"\"\n if(((self.channels == []) and (not self.shape == (0, 0))) or\n ((not self.channels == []) and (self.shape == (0, 0)))):\n raise RuntimeError(\"Channels-shape mismatch.\")\n return self.channels == [] and self.shape == (0, 0)", "code_tokens": "def is_empty ( self ) : if ( ( ( self . channels == [ ] ) and ( not self . shape == ( 0 , 0 ) ) ) or ( ( not self . channels == [ ] ) and ( self . shape == ( 0 , 0 ) ) ) ) : raise RuntimeError ( \"Channels-shape mismatch.\" ) return self . channels == [ ] and self . shape == ( 0 , 0 )", "docstring_tokens": "Checks for an empty image .", "label": 1, "retrieval_idx": 2948, "negative": "Convert to snake case ." }, { "idx": "cosqa-train-11606", "doc": "how to hide a window using a button in python", "code": "def hide(self):\n \"\"\"Hides the main window of the terminal and sets the visible\n flag to False.\n \"\"\"\n if not HidePrevention(self.window).may_hide():\n return\n self.hidden = True\n self.get_widget('window-root').unstick()\n self.window.hide()", "code_tokens": "def hide ( self ) : if not HidePrevention ( self . window ) . may_hide ( ) : return self . hidden = True self . get_widget ( 'window-root' ) . unstick ( ) self . window . hide ( )", "docstring_tokens": "Hides the main window of the terminal and sets the visible flag to False .", "label": 1, "retrieval_idx": 3119, "negative": "Softsign op ." }, { "idx": "cosqa-train-13550", "doc": "python marshmallow validation schema from parent", "code": "def validate(schema, data, owner=None):\n \"\"\"Validate input data with input schema.\n\n :param Schema schema: schema able to validate input data.\n :param data: data to validate.\n :param Schema owner: input schema parent schema.\n :raises: Exception if the data is not validated.\n \"\"\"\n schema._validate(data=data, owner=owner)", "code_tokens": "def validate ( schema , data , owner = None ) : schema . _validate ( data = data , owner = owner )", "docstring_tokens": "Validate input data with input schema .", "label": 1, "retrieval_idx": 4707, "negative": "Paginate queryset ." }, { "idx": "cosqa-train-13211", "doc": "fillna with string for specific columnin python", "code": "def stringify_col(df, col_name):\n \"\"\"\n Take a dataframe and string-i-fy a column of values.\n Turn nan/None into \"\" and all other values into strings.\n\n Parameters\n ----------\n df : dataframe\n col_name : string\n \"\"\"\n df = df.copy()\n df[col_name] = df[col_name].fillna(\"\")\n df[col_name] = df[col_name].astype(str)\n return df", "code_tokens": "def stringify_col ( df , col_name ) : df = df . copy ( ) df [ col_name ] = df [ col_name ] . fillna ( \"\" ) df [ col_name ] = df [ col_name ] . astype ( str ) return df", "docstring_tokens": "Take a dataframe and string - i - fy a column of values . Turn nan / None into and all other values into strings .", "label": 1, "retrieval_idx": 1462, "negative": "Call an external binary and return its stdout ." }, { "idx": "cosqa-train-1345", "doc": "how to separate list elements by white space python", "code": "def split_strings_in_list_retain_spaces(orig_list):\n \"\"\"\n Function to split every line in a list, and retain spaces for a rejoin\n :param orig_list: Original list\n :return:\n A List with split lines\n\n \"\"\"\n temp_list = list()\n for line in orig_list:\n line_split = __re.split(r'(\\s+)', line)\n temp_list.append(line_split)\n\n return temp_list", "code_tokens": "def split_strings_in_list_retain_spaces ( orig_list ) : temp_list = list ( ) for line in orig_list : line_split = __re . split ( r'(\\s+)' , line ) temp_list . append ( line_split ) return temp_list", "docstring_tokens": "Function to split every line in a list and retain spaces for a rejoin : param orig_list : Original list : return : A List with split lines", "label": 1, "retrieval_idx": 1146, "negative": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ..." }, { "idx": "cosqa-train-13635", "doc": "how to default value in python", "code": "def safe_int(val, default=None):\n \"\"\"\n Returns int() of val if val is not convertable to int use default\n instead\n\n :param val:\n :param default:\n \"\"\"\n\n try:\n val = int(val)\n except (ValueError, TypeError):\n val = default\n\n return val", "code_tokens": "def safe_int ( val , default = None ) : try : val = int ( val ) except ( ValueError , TypeError ) : val = default return val", "docstring_tokens": "Returns int () of val if val is not convertable to int use default instead", "label": 1, "retrieval_idx": 2494, "negative": "Populate the ranks key ." }, { "idx": "cosqa-train-8623", "doc": "python dict keys lowercase", "code": "def keys_to_snake_case(camel_case_dict):\n \"\"\"\n Make a copy of a dictionary with all keys converted to snake case. This is just calls to_snake_case on\n each of the keys in the dictionary and returns a new dictionary.\n\n :param camel_case_dict: Dictionary with the keys to convert.\n :type camel_case_dict: Dictionary.\n\n :return: Dictionary with the keys converted to snake case.\n \"\"\"\n return dict((to_snake_case(key), value) for (key, value) in camel_case_dict.items())", "code_tokens": "def keys_to_snake_case ( camel_case_dict ) : return dict ( ( to_snake_case ( key ) , value ) for ( key , value ) in camel_case_dict . items ( ) )", "docstring_tokens": "Make a copy of a dictionary with all keys converted to snake case . This is just calls to_snake_case on each of the keys in the dictionary and returns a new dictionary .", "label": 1, "retrieval_idx": 173, "negative": "Finds the longest path in a dag between two nodes" }, { "idx": "cosqa-train-10955", "doc": "python get index of list values that equal", "code": "def equal(list1, list2):\n \"\"\" takes flags returns indexes of True values \"\"\"\n return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]", "code_tokens": "def equal ( list1 , list2 ) : return [ item1 == item2 for item1 , item2 in broadcast_zip ( list1 , list2 ) ]", "docstring_tokens": "takes flags returns indexes of True values", "label": 1, "retrieval_idx": 480, "negative": "Log - normal function from scipy" }, { "idx": "cosqa-train-9658", "doc": "python requests logging not work", "code": "def process_request(self, request, response):\n \"\"\"Logs the basic endpoint requested\"\"\"\n self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))", "code_tokens": "def process_request ( self , request , response ) : self . logger . info ( 'Requested: {0} {1} {2}' . format ( request . method , request . relative_uri , request . content_type ) )", "docstring_tokens": "Logs the basic endpoint requested", "label": 1, "retrieval_idx": 2496, "negative": "Fetch a subset of randomzied GUIDs from the whitelist" }, { "idx": "cosqa-train-12001", "doc": "python static files flask", "code": "def glr_path_static():\n \"\"\"Returns path to packaged static files\"\"\"\n return os.path.abspath(os.path.join(os.path.dirname(__file__), '_static'))", "code_tokens": "def glr_path_static ( ) : return os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '_static' ) )", "docstring_tokens": "Returns path to packaged static files", "label": 1, "retrieval_idx": 2404, "negative": "Takes JSON formatted data converting it into native Python objects" }, { "idx": "cosqa-train-19618", "doc": "rest json schema validation python", "code": "def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:\n \"\"\"\n Wraps jsonschema.validate, returning the same object passed in.\n\n Args:\n request: The deserialized-from-json request.\n schema: The jsonschema schema to validate against.\n\n Raises:\n jsonschema.ValidationError\n \"\"\"\n jsonschema_validate(request, schema)\n return request", "code_tokens": "def validate ( request : Union [ Dict , List ] , schema : dict ) -> Union [ Dict , List ] : jsonschema_validate ( request , schema ) return request", "docstring_tokens": "Wraps jsonschema . validate returning the same object passed in .", "label": 1, "retrieval_idx": 6156, "negative": "Suppress warning about untrusted SSL certificate ." }, { "idx": "cosqa-train-10560", "doc": "write in bold and read in color of the print mesaage in python", "code": "def good(txt):\n \"\"\"Print, emphasized 'good', the given 'txt' message\"\"\"\n\n print(\"%s# %s%s%s\" % (PR_GOOD_CC, get_time_stamp(), txt, PR_NC))\n sys.stdout.flush()", "code_tokens": "def good ( txt ) : print ( \"%s# %s%s%s\" % ( PR_GOOD_CC , get_time_stamp ( ) , txt , PR_NC ) ) sys . stdout . flush ( )", "docstring_tokens": "Print emphasized good the given txt message", "label": 1, "retrieval_idx": 362, "negative": "Reads cplex file and returns glpk problem ." }, { "idx": "cosqa-train-14241", "doc": "python type cast to bigint", "code": "def _from_bytes(bytes, byteorder=\"big\", signed=False):\n \"\"\"This is the same functionality as ``int.from_bytes`` in python 3\"\"\"\n return int.from_bytes(bytes, byteorder=byteorder, signed=signed)", "code_tokens": "def _from_bytes ( bytes , byteorder = \"big\" , signed = False ) : return int . from_bytes ( bytes , byteorder = byteorder , signed = signed )", "docstring_tokens": "This is the same functionality as int . from_bytes in python 3", "label": 1, "retrieval_idx": 1205, "negative": "Create ctypes pointer to object ." }, { "idx": "cosqa-train-8782", "doc": "converts matrix to pictures by python", "code": "def im2mat(I):\n \"\"\"Converts and image to matrix (one pixel per line)\"\"\"\n return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))", "code_tokens": "def im2mat ( I ) : return I . reshape ( ( I . shape [ 0 ] * I . shape [ 1 ] , I . shape [ 2 ] ) )", "docstring_tokens": "Converts and image to matrix ( one pixel per line )", "label": 1, "retrieval_idx": 1120, "negative": "Add subparser" }, { "idx": "cosqa-train-11687", "doc": "python random selection from function", "code": "def sometimesish(fn):\n \"\"\"\n Has a 50/50 chance of calling a function\n \"\"\"\n def wrapped(*args, **kwargs):\n if random.randint(1, 2) == 1:\n return fn(*args, **kwargs)\n\n return wrapped", "code_tokens": "def sometimesish ( fn ) : def wrapped ( * args , * * kwargs ) : if random . randint ( 1 , 2 ) == 1 : return fn ( * args , * * kwargs ) return wrapped", "docstring_tokens": "Has a 50 / 50 chance of calling a function", "label": 1, "retrieval_idx": 1398, "negative": "Wipes compiled and cached python files . To simulate : pynt clean [ dry_run = y ]" }, { "idx": "cosqa-train-13450", "doc": "python keep processpool open until tasks complete", "code": "def wait(self, timeout=None):\n \"\"\"\n Block until all jobs in the ThreadPool are finished. Beware that this can\n make the program run into a deadlock if another thread adds new jobs to the\n pool!\n\n # Raises\n Timeout: If the timeout is exceeded.\n \"\"\"\n\n if not self.__running:\n raise RuntimeError(\"ThreadPool ain't running\")\n self.__queue.wait(timeout)", "code_tokens": "def wait ( self , timeout = None ) : if not self . __running : raise RuntimeError ( \"ThreadPool ain't running\" ) self . __queue . wait ( timeout )", "docstring_tokens": "Block until all jobs in the ThreadPool are finished . Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool!", "label": 1, "retrieval_idx": 5005, "negative": "Check if given string is a punctuation" }, { "idx": "cosqa-train-10307", "doc": "running a def a specified amount of time python 3", "code": "def seconds(num):\n \"\"\"\n Pause for this many seconds\n \"\"\"\n now = pytime.time()\n end = now + num\n until(end)", "code_tokens": "def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )", "docstring_tokens": "Pause for this many seconds", "label": 1, "retrieval_idx": 2450, "negative": "Add suffix to a full file name" }, { "idx": "cosqa-train-19371", "doc": "python str to dateal time", "code": "def str_to_time(time_str: str) -> datetime.datetime:\n \"\"\"\n Convert human readable string to datetime.datetime.\n \"\"\"\n pieces: Any = [int(piece) for piece in time_str.split('-')]\n return datetime.datetime(*pieces)", "code_tokens": "def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )", "docstring_tokens": "Convert human readable string to datetime . datetime .", "label": 1, "retrieval_idx": 5606, "negative": "Get the parent directory of a filename ." }, { "idx": "cosqa-train-12569", "doc": "python check if file is executable", "code": "def is_executable(path):\n \"\"\"Returns whether a path names an existing executable file.\"\"\"\n return os.path.isfile(path) and os.access(path, os.X_OK)", "code_tokens": "def is_executable ( path ) : return os . path . isfile ( path ) and os . access ( path , os . X_OK )", "docstring_tokens": "Returns whether a path names an existing executable file .", "label": 1, "retrieval_idx": 2939, "negative": "Generate seed for random number generator" }, { "idx": "cosqa-train-17715", "doc": "python how to check the queue lenght", "code": "def full(self):\n \"\"\"Return ``True`` if the queue is full, ``False``\n otherwise (not reliable!).\n\n Only applicable if :attr:`maxsize` is set.\n\n \"\"\"\n return self.maxsize and len(self.list) >= self.maxsize or False", "code_tokens": "def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False", "docstring_tokens": "Return True if the queue is full False otherwise ( not reliable! ) .", "label": 1, "retrieval_idx": 5555, "negative": "Transform a range of years ( two ints ) to a DateRange object ." }, { "idx": "cosqa-train-16490", "doc": "query server objects ldap in python", "code": "def search(self, filterstr, attrlist):\n \"\"\"Query the configured LDAP server.\"\"\"\n return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr,\n attrlist=attrlist, page_size=self.settings.PAGE_SIZE)", "code_tokens": "def search ( self , filterstr , attrlist ) : return self . _paged_search_ext_s ( self . settings . BASE , ldap . SCOPE_SUBTREE , filterstr = filterstr , attrlist = attrlist , page_size = self . settings . PAGE_SIZE )", "docstring_tokens": "Query the configured LDAP server .", "label": 1, "retrieval_idx": 5470, "negative": "Set up neccessary environment variables" }, { "idx": "cosqa-train-15089", "doc": "python docx document section different page", "code": "def fill_document(doc):\n \"\"\"Add a section, a subsection and some text to the document.\n\n :param doc: the document\n :type doc: :class:`pylatex.document.Document` instance\n \"\"\"\n with doc.create(Section('A section')):\n doc.append('Some regular text and some ')\n doc.append(italic('italic text. '))\n\n with doc.create(Subsection('A subsection')):\n doc.append('Also some crazy characters: $&#{}')", "code_tokens": "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: $&#{}' )", "docstring_tokens": "Add a section a subsection and some text to the document .", "label": 1, "retrieval_idx": 1938, "negative": "https : // picamera . readthedocs . io / en / release - 1 . 13 / recipes1 . html#capturing - to - a - pil - image" }, { "idx": "cosqa-train-10557", "doc": "write a json object to file python", "code": "def _serialize_json(obj, fp):\n \"\"\" Serialize ``obj`` as a JSON formatted stream to ``fp`` \"\"\"\n json.dump(obj, fp, indent=4, default=serialize)", "code_tokens": "def _serialize_json ( obj , fp ) : json . dump ( obj , fp , indent = 4 , default = serialize )", "docstring_tokens": "Serialize obj as a JSON formatted stream to fp", "label": 1, "retrieval_idx": 1198, "negative": "Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}" }, { "idx": "cosqa-train-19263", "doc": "how to compute the minimum value of a tensor in python", "code": "def last_location_of_minimum(x):\n \"\"\"\n Returns the last location of the minimal value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN", "code_tokens": "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", "docstring_tokens": "Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .", "label": 1, "retrieval_idx": 5578, "negative": "Return a legal python name for the given name for use as a unit key ." }, { "idx": "cosqa-train-16352", "doc": "python unittest how to assert 2 lists are almost equal", "code": "def expect_all(a, b):\n \"\"\"\\\n Asserts that two iterables contain the same values.\n \"\"\"\n assert all(_a == _b for _a, _b in zip_longest(a, b))", "code_tokens": "def expect_all ( a , b ) : assert all ( _a == _b for _a , _b in zip_longest ( a , b ) )", "docstring_tokens": "\\ Asserts that two iterables contain the same values .", "label": 1, "retrieval_idx": 2621, "negative": "Return list of Logger classes ." }, { "idx": "cosqa-dev-27", "doc": "how to check if 2 inputs are equal in python assert equal", "code": "def expect_all(a, b):\n \"\"\"\\\n Asserts that two iterables contain the same values.\n \"\"\"\n assert all(_a == _b for _a, _b in zip_longest(a, b))", "code_tokens": "def expect_all ( a , b ) : assert all ( _a == _b for _a , _b in zip_longest ( a , b ) )", "docstring_tokens": "\\ Asserts that two iterables contain the same values .", "label": 1, "retrieval_idx": 2621, "negative": "Creates a yaml file with the given content ." }, { "idx": "cosqa-train-9249", "doc": "python loop through proxies request", "code": "def load(self):\n \"\"\"Load proxy list from configured proxy source\"\"\"\n self._list = self._source.load()\n self._list_iter = itertools.cycle(self._list)", "code_tokens": "def load ( self ) : self . _list = self . _source . load ( ) self . _list_iter = itertools . cycle ( self . _list )", "docstring_tokens": "Load proxy list from configured proxy source", "label": 1, "retrieval_idx": 934, "negative": "Returns the greatest common divisor for a sequence of numbers . Uses a numerical tolerance so can be used on floats" }, { "idx": "cosqa-train-834", "doc": "python loess with gaussian kernel", "code": "def lognorm(x, mu, sigma=1.0):\n \"\"\" Log-normal function from scipy \"\"\"\n return stats.lognorm(sigma, scale=mu).pdf(x)", "code_tokens": "def lognorm ( x , mu , sigma = 1.0 ) : return stats . lognorm ( sigma , scale = mu ) . pdf ( x )", "docstring_tokens": "Log - normal function from scipy", "label": 1, "retrieval_idx": 741, "negative": "count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )" }, { "idx": "cosqa-train-17394", "doc": "greatest common divisor function in python", "code": "def gcd_float(numbers, tol=1e-8):\n \"\"\"\n Returns the greatest common divisor for a sequence of numbers.\n Uses a numerical tolerance, so can be used on floats\n\n Args:\n numbers: Sequence of numbers.\n tol: Numerical tolerance\n\n Returns:\n (int) Greatest common divisor of numbers.\n \"\"\"\n\n def pair_gcd_tol(a, b):\n \"\"\"Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided by it, the result comes out positive).\n \"\"\"\n while b > tol:\n a, b = b, a % b\n return a\n\n n = numbers[0]\n for i in numbers:\n n = pair_gcd_tol(n, i)\n return n", "code_tokens": "def gcd_float ( numbers , tol = 1e-8 ) : def pair_gcd_tol ( a , b ) : \"\"\"Calculate the Greatest Common Divisor of a and b.\n\n Unless b==0, the result will have the same sign as b (so that when\n b is divided by it, the result comes out positive).\n \"\"\" while b > tol : a , b = b , a % b return a n = numbers [ 0 ] for i in numbers : n = pair_gcd_tol ( n , i ) return n", "docstring_tokens": "Returns the greatest common divisor for a sequence of numbers . Uses a numerical tolerance so can be used on floats", "label": 1, "retrieval_idx": 5816, "negative": "Flush all items from cache ." }, { "idx": "cosqa-dev-530", "doc": "how to clear up memory python", "code": "def Flush(self):\n \"\"\"Flush all items from cache.\"\"\"\n while self._age:\n node = self._age.PopLeft()\n self.KillObject(node.data)\n\n self._hash = dict()", "code_tokens": "def Flush ( self ) : while self . _age : node = self . _age . PopLeft ( ) self . KillObject ( node . data ) self . _hash = dict ( )", "docstring_tokens": "Flush all items from cache .", "label": 1, "retrieval_idx": 254, "negative": "Add suffix to a full file name" }, { "idx": "cosqa-dev-591", "doc": "get eucliedan distance between two vectors python", "code": "def vector_distance(a, b):\n \"\"\"The Euclidean distance between two vectors.\"\"\"\n a = np.array(a)\n b = np.array(b)\n return np.linalg.norm(a - b)", "code_tokens": "def vector_distance ( a , b ) : a = np . array ( a ) b = np . array ( b ) return np . linalg . norm ( a - b )", "docstring_tokens": "The Euclidean distance between two vectors .", "label": 1, "retrieval_idx": 466, "negative": "Time execution of function . Returns ( res seconds ) ." }, { "idx": "cosqa-train-11239", "doc": "python interactive shell color", "code": "def auto():\n\t\"\"\"set colouring on if STDOUT is a terminal device, off otherwise\"\"\"\n\ttry:\n\t\tStyle.enabled = False\n\t\tStyle.enabled = sys.stdout.isatty()\n\texcept (AttributeError, TypeError):\n\t\tpass", "code_tokens": "def auto ( ) : try : Style . enabled = False Style . enabled = sys . stdout . isatty ( ) except ( AttributeError , TypeError ) : pass", "docstring_tokens": "set colouring on if STDOUT is a terminal device off otherwise", "label": 1, "retrieval_idx": 1007, "negative": "Given a float returns a rounded int . Should give the same result on both Py2 / 3" }, { "idx": "cosqa-train-8033", "doc": "passing a range of values python years", "code": "def from_years_range(start_year, end_year):\n \"\"\"Transform a range of years (two ints) to a DateRange object.\"\"\"\n start = datetime.date(start_year, 1 , 1)\n end = datetime.date(end_year, 12 , 31)\n return DateRange(start, end)", "code_tokens": "def from_years_range ( start_year , end_year ) : start = datetime . date ( start_year , 1 , 1 ) end = datetime . date ( end_year , 12 , 31 ) return DateRange ( start , end )", "docstring_tokens": "Transform a range of years ( two ints ) to a DateRange object .", "label": 1, "retrieval_idx": 3206, "negative": "Block until all jobs in the ThreadPool are finished . Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool!" }, { "idx": "cosqa-train-12233", "doc": "python yaml for each key value", "code": "def safe_dump(data, stream=None, **kwds):\n \"\"\"implementation of safe dumper using Ordered Dict Yaml Dumper\"\"\"\n return yaml.dump(data, stream=stream, Dumper=ODYD, **kwds)", "code_tokens": "def safe_dump ( data , stream = None , * * kwds ) : return yaml . dump ( data , stream = stream , Dumper = ODYD , * * kwds )", "docstring_tokens": "implementation of safe dumper using Ordered Dict Yaml Dumper", "label": 1, "retrieval_idx": 1351, "negative": "Add suffix to a full file name" }, { "idx": "cosqa-train-14163", "doc": "python test if value is ctypes array", "code": "def is_array(type_):\n \"\"\"returns True, if type represents C++ array type, False otherwise\"\"\"\n nake_type = remove_alias(type_)\n nake_type = remove_reference(nake_type)\n nake_type = remove_cv(nake_type)\n return isinstance(nake_type, cpptypes.array_t)", "code_tokens": "def is_array ( type_ ) : nake_type = remove_alias ( type_ ) nake_type = remove_reference ( nake_type ) nake_type = remove_cv ( nake_type ) return isinstance ( nake_type , cpptypes . array_t )", "docstring_tokens": "returns True if type represents C ++ array type False otherwise", "label": 1, "retrieval_idx": 5116, "negative": "Returns whether a path names an existing directory we can list and read files from ." }, { "idx": "cosqa-train-13261", "doc": "function return apply async python", "code": "def apply(self, func, args=(), kwds=dict()):\n \"\"\"Equivalent of the apply() builtin function. It blocks till\n the result is ready.\"\"\"\n return self.apply_async(func, args, kwds).get()", "code_tokens": "def apply ( self , func , args = ( ) , kwds = dict ( ) ) : return self . apply_async ( func , args , kwds ) . get ( )", "docstring_tokens": "Equivalent of the apply () builtin function . It blocks till the result is ready .", "label": 1, "retrieval_idx": 4964, "negative": "Return file name ( s ) from Tkinter s file open dialog ." }, { "idx": "cosqa-train-12308", "doc": "reload device program code in python", "code": "def reload(self, save_config=True):\n \"\"\"Reload the device.\n\n !!!WARNING! there is unsaved configuration!!!\n This command will reboot the system. (y/n)? [n]\n \"\"\"\n if save_config:\n self.device.send(\"copy running-config startup-config\")\n self.device(\"reload\", wait_for_string=\"This command will reboot the system\")\n self.device.ctrl.sendline(\"y\")", "code_tokens": "def reload ( self , save_config = True ) : if save_config : self . device . send ( \"copy running-config startup-config\" ) self . device ( \"reload\" , wait_for_string = \"This command will reboot the system\" ) self . device . ctrl . sendline ( \"y\" )", "docstring_tokens": "Reload the device .", "label": 1, "retrieval_idx": 4804, "negative": "Add dots ." }, { "idx": "cosqa-train-4030", "doc": "split string into n parts python", "code": "def _split_str(s, n):\n \"\"\"\n split string into list of strings by specified number.\n \"\"\"\n length = len(s)\n return [s[i:i + n] for i in range(0, length, n)]", "code_tokens": "def _split_str ( s , n ) : length = len ( s ) return [ s [ i : i + n ] for i in range ( 0 , length , n ) ]", "docstring_tokens": "split string into list of strings by specified number .", "label": 1, "retrieval_idx": 424, "negative": "True if the json_element passed is present for the task specified ." }, { "idx": "cosqa-train-10978", "doc": "python get object as dict", "code": "def conv_dict(self):\n \"\"\"dictionary of conversion\"\"\"\n return dict(integer=self.integer, real=self.real, no_type=self.no_type)", "code_tokens": "def conv_dict ( self ) : return dict ( integer = self . integer , real = self . real , no_type = self . no_type )", "docstring_tokens": "dictionary of conversion", "label": 1, "retrieval_idx": 650, "negative": "Like dict but does not hold any null values ." }, { "idx": "cosqa-train-18571", "doc": "selecting a range of 2d elements from a numpy array gives empty array in python 3", "code": "def to_0d_array(value: Any) -> np.ndarray:\n \"\"\"Given a value, wrap it in a 0-D numpy.ndarray.\n \"\"\"\n if np.isscalar(value) or (isinstance(value, np.ndarray) and\n value.ndim == 0):\n return np.array(value)\n else:\n return to_0d_object_array(value)", "code_tokens": "def to_0d_array ( value : Any ) -> np . ndarray : if np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and value . ndim == 0 ) : return np . array ( value ) else : return to_0d_object_array ( value )", "docstring_tokens": "Given a value wrap it in a 0 - D numpy . ndarray .", "label": 1, "retrieval_idx": 5815, "negative": "returns a dictionary of arg_name : default_values for the input function" }, { "idx": "cosqa-train-19958", "doc": "python read tokens from line", "code": "def get_tokens(line: str) -> Iterator[str]:\n \"\"\"\n Yields tokens from input string.\n\n :param line: Input string.\n :return: Iterator over tokens.\n \"\"\"\n for token in line.rstrip().split():\n if len(token) > 0:\n yield token", "code_tokens": "def get_tokens ( line : str ) -> Iterator [ str ] : for token in line . rstrip ( ) . split ( ) : if len ( token ) > 0 : yield token", "docstring_tokens": "Yields tokens from input string .", "label": 1, "retrieval_idx": 6106, "negative": "Logs the basic endpoint requested" }, { "idx": "cosqa-train-16924", "doc": "write data into fits file python", "code": "def write_fits(self, fitsfile):\n \"\"\"Write the ROI model to a FITS file.\"\"\"\n\n tab = self.create_table()\n hdu_data = fits.table_to_hdu(tab)\n hdus = [fits.PrimaryHDU(), hdu_data]\n fits_utils.write_hdus(hdus, fitsfile)", "code_tokens": "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 )", "docstring_tokens": "Write the ROI model to a FITS file .", "label": 1, "retrieval_idx": 1138, "negative": "decode ( bytearray raw = False ) - > value" }, { "idx": "cosqa-train-3162", "doc": "python print string with visible ansi codes", "code": "def ansi(color, text):\n \"\"\"Wrap text in an ansi escape sequence\"\"\"\n code = COLOR_CODES[color]\n return '\\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)", "code_tokens": "def ansi ( color , text ) : code = COLOR_CODES [ color ] return '\\033[1;{0}m{1}{2}' . format ( code , text , RESET_TERM )", "docstring_tokens": "Wrap text in an ansi escape sequence", "label": 1, "retrieval_idx": 2234, "negative": "Convert a date into a datetime" }, { "idx": "cosqa-train-18616", "doc": "python check if value in enum", "code": "def has_value(cls, value: int) -> bool:\n \"\"\"True if specified value exists in int enum; otherwise, False.\"\"\"\n return any(value == item.value for item in cls)", "code_tokens": "def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )", "docstring_tokens": "True if specified value exists in int enum ; otherwise False .", "label": 1, "retrieval_idx": 5812, "negative": "Block until all jobs in the ThreadPool are finished . Beware that this can make the program run into a deadlock if another thread adds new jobs to the pool!" }, { "idx": "cosqa-train-11995", "doc": "python sqlite table names in database", "code": "def get_table_names(connection):\n\t\"\"\"\n\tReturn a list of the table names in the database.\n\t\"\"\"\n\tcursor = connection.cursor()\n\tcursor.execute(\"SELECT name FROM sqlite_master WHERE type == 'table'\")\n\treturn [name for (name,) in cursor]", "code_tokens": "def get_table_names ( connection ) : cursor = connection . cursor ( ) cursor . execute ( \"SELECT name FROM sqlite_master WHERE type == 'table'\" ) return [ name for ( name , ) in cursor ]", "docstring_tokens": "Return a list of the table names in the database .", "label": 1, "retrieval_idx": 716, "negative": "Return the fully - qualified name of a function ." }, { "idx": "cosqa-train-18639", "doc": "how to remove all element from a python dictionary", "code": "def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:\n \"\"\"\n Return a new copied dictionary without the keys with ``None`` values from\n the given Mapping object.\n \"\"\"\n return {k: v for k, v in obj.items() if v is not None}", "code_tokens": "def clean_map ( obj : Mapping [ Any , Any ] ) -> Mapping [ Any , Any ] : return { k : v for k , v in obj . items ( ) if v is not None }", "docstring_tokens": "Return a new copied dictionary without the keys with None values from the given Mapping object .", "label": 1, "retrieval_idx": 5748, "negative": "Get from a list with an optional default value ." }, { "idx": "cosqa-train-11560", "doc": "python parse query string from url", "code": "def parse_query_string(query):\n \"\"\"\n parse_query_string:\n very simplistic. won't do the right thing with list values\n \"\"\"\n result = {}\n qparts = query.split('&')\n for item in qparts:\n key, value = item.split('=')\n key = key.strip()\n value = value.strip()\n result[key] = unquote_plus(value)\n return result", "code_tokens": "def parse_query_string ( query ) : result = { } qparts = query . split ( '&' ) for item in qparts : key , value = item . split ( '=' ) key = key . strip ( ) value = value . strip ( ) result [ key ] = unquote_plus ( value ) return result", "docstring_tokens": "parse_query_string : very simplistic . won t do the right thing with list values", "label": 1, "retrieval_idx": 2201, "negative": "Converts and image to matrix ( one pixel per line )" }, { "idx": "cosqa-train-5390", "doc": "python remove element set", "code": "def isolate_element(self, x):\n \"\"\"Isolates `x` from its equivalence class.\"\"\"\n members = list(self.members(x))\n self.delete_set(x)\n self.union(*(v for v in members if v != x))", "code_tokens": "def isolate_element ( self , x ) : members = list ( self . members ( x ) ) self . delete_set ( x ) self . union ( * ( v for v in members if v != x ) )", "docstring_tokens": "Isolates x from its equivalence class .", "label": 1, "retrieval_idx": 3147, "negative": "Helper parse action to convert tokens to upper case ." }, { "idx": "cosqa-train-10072", "doc": "manhattan distance in python using longitude and latitude", "code": "def _manhattan_distance(vec_a, vec_b):\n \"\"\"Return manhattan distance between two lists of numbers.\"\"\"\n if len(vec_a) != len(vec_b):\n raise ValueError('len(vec_a) must equal len(vec_b)')\n return sum(map(lambda a, b: abs(a - b), vec_a, vec_b))", "code_tokens": "def _manhattan_distance ( vec_a , vec_b ) : if len ( vec_a ) != len ( vec_b ) : raise ValueError ( 'len(vec_a) must equal len(vec_b)' ) return sum ( map ( lambda a , b : abs ( a - b ) , vec_a , vec_b ) )", "docstring_tokens": "Return manhattan distance between two lists of numbers .", "label": 1, "retrieval_idx": 1828, "negative": "Define a new macro" }, { "idx": "cosqa-train-11759", "doc": "how to read from a file to a list python", "code": "def get_list_from_file(file_name):\n \"\"\"read the lines from a file into a list\"\"\"\n with open(file_name, mode='r', encoding='utf-8') as f1:\n lst = f1.readlines()\n return lst", "code_tokens": "def get_list_from_file ( file_name ) : with open ( file_name , mode = 'r' , encoding = 'utf-8' ) as f1 : lst = f1 . readlines ( ) return lst", "docstring_tokens": "read the lines from a file into a list", "label": 1, "retrieval_idx": 3132, "negative": "Return a list of the table names in the database ." }, { "idx": "cosqa-train-8925", "doc": "dynamically update value in dictionary python", "code": "def update(self, params):\n \"\"\"Update the dev_info data from a dictionary.\n\n Only updates if it already exists in the device.\n \"\"\"\n dev_info = self.json_state.get('deviceInfo')\n dev_info.update({k: params[k] for k in params if dev_info.get(k)})", "code_tokens": "def update ( self , params ) : dev_info = self . json_state . get ( 'deviceInfo' ) dev_info . update ( { k : params [ k ] for k in params if dev_info . get ( k ) } )", "docstring_tokens": "Update the dev_info data from a dictionary .", "label": 1, "retrieval_idx": 2899, "negative": "Make a list unique retaining order of initial appearance ." }, { "idx": "cosqa-train-19838", "doc": "python replace string from right", "code": "def right_replace(string, old, new, count=1):\n \"\"\"\n Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``.\n For example::\n\n right_replace('one_two_two', 'two', 'three') -> 'one_two_three'\n \"\"\"\n if not string:\n return string\n return new.join(string.rsplit(old, count))", "code_tokens": "def right_replace ( string , old , new , count = 1 ) : if not string : return string return new . join ( string . rsplit ( old , count ) )", "docstring_tokens": "Right replaces count occurrences of old with new in string . For example ::", "label": 1, "retrieval_idx": 5625, "negative": "Helper function to read JSON file as OrderedDict" }, { "idx": "cosqa-train-11373", "doc": "how to check if a path is writeable python", "code": "def _writable_dir(path):\n \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n return os.path.isdir(path) and os.access(path, os.W_OK)", "code_tokens": "def _writable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . W_OK )", "docstring_tokens": "Whether path is a directory to which the user has write access .", "label": 1, "retrieval_idx": 651, "negative": "Executes SQL ; returns the first value of the first row or None ." }, { "idx": "cosqa-train-11142", "doc": "get attribute type in python", "code": "def get_attribute_name_id(attr):\n \"\"\"\n Return the attribute name identifier\n \"\"\"\n return attr.value.id if isinstance(attr.value, ast.Name) else None", "code_tokens": "def get_attribute_name_id ( attr ) : return attr . value . id if isinstance ( attr . value , ast . Name ) else None", "docstring_tokens": "Return the attribute name identifier", "label": 1, "retrieval_idx": 1522, "negative": "returns a dictionary of arg_name : default_values for the input function" }, { "idx": "cosqa-train-9067", "doc": "get fields of object python", "code": "def object_as_dict(obj):\n \"\"\"Turn an SQLAlchemy model into a dict of field names and values.\n\n Based on https://stackoverflow.com/a/37350445/1579058\n \"\"\"\n return {c.key: getattr(obj, c.key)\n for c in inspect(obj).mapper.column_attrs}", "code_tokens": "def object_as_dict ( obj ) : return { c . key : getattr ( obj , c . key ) for c in inspect ( obj ) . mapper . column_attrs }", "docstring_tokens": "Turn an SQLAlchemy model into a dict of field names and values .", "label": 1, "retrieval_idx": 1849, "negative": "Define a new macro" }, { "idx": "cosqa-train-17371", "doc": "how to fetch one value from one row from mysql query in python", "code": "def fetchvalue(self, sql: str, *args) -> Optional[Any]:\n \"\"\"Executes SQL; returns the first value of the first row, or None.\"\"\"\n row = self.fetchone(sql, *args)\n if row is None:\n return None\n return row[0]", "code_tokens": "def fetchvalue ( self , sql : str , * args ) -> Optional [ Any ] : row = self . fetchone ( sql , * args ) if row is None : return None return row [ 0 ]", "docstring_tokens": "Executes SQL ; returns the first value of the first row or None .", "label": 1, "retrieval_idx": 5806, "negative": "Return ctypes . Array an iterable array of int values in argb ." }, { "idx": "cosqa-train-6650", "doc": "python flask routes add", "code": "def add_url_rule(self, route, endpoint, handler):\n \"\"\"Add a new url route.\n\n Args:\n See flask.Flask.add_url_route().\n \"\"\"\n self.app.add_url_rule(route, endpoint, handler)", "code_tokens": "def add_url_rule ( self , route , endpoint , handler ) : self . app . add_url_rule ( route , endpoint , handler )", "docstring_tokens": "Add a new url route .", "label": 1, "retrieval_idx": 3536, "negative": "Go to the end of the current line and create a new line" }, { "idx": "cosqa-train-10946", "doc": "define function arg type and default values python", "code": "def get_default_args(func):\n \"\"\"\n returns a dictionary of arg_name:default_values for the input function\n \"\"\"\n args, varargs, keywords, defaults = getargspec_no_self(func)\n return dict(zip(args[-len(defaults):], defaults))", "code_tokens": "def get_default_args ( func ) : args , varargs , keywords , defaults = getargspec_no_self ( func ) return dict ( zip ( args [ - len ( defaults ) : ] , defaults ) )", "docstring_tokens": "returns a dictionary of arg_name : default_values for the input function", "label": 1, "retrieval_idx": 139, "negative": "Returns path to packaged static files" }, { "idx": "cosqa-dev-233", "doc": "python image shape detect", "code": "def get_shape(img):\n \"\"\"Return the shape of img.\n\n Paramerers\n -----------\n img:\n\n Returns\n -------\n shape: tuple\n \"\"\"\n if hasattr(img, 'shape'):\n shape = img.shape\n else:\n shape = img.get_data().shape\n return shape", "code_tokens": "def get_shape ( img ) : if hasattr ( img , 'shape' ) : shape = img . shape else : shape = img . get_data ( ) . shape return shape", "docstring_tokens": "Return the shape of img .", "label": 1, "retrieval_idx": 2021, "negative": "Scale the input array" }, { "idx": "cosqa-train-6306", "doc": "what can iterators be iterated only once in python", "code": "def _fill(self):\n \"\"\"Advance the iterator without returning the old head.\"\"\"\n try:\n self._head = self._iterable.next()\n except StopIteration:\n self._head = None", "code_tokens": "def _fill ( self ) : try : self . _head = self . _iterable . next ( ) except StopIteration : self . _head = None", "docstring_tokens": "Advance the iterator without returning the old head .", "label": 1, "retrieval_idx": 2052, "negative": "Convert comma - delimited list / string into a list of strings" }, { "idx": "cosqa-train-10207", "doc": "remove all characters in string in python", "code": "def drop_bad_characters(text):\n \"\"\"Takes a text and drops all non-printable and non-ascii characters and\n also any whitespace characters that aren't space.\n\n :arg str text: the text to fix\n\n :returns: text with all bad characters dropped\n\n \"\"\"\n # Strip all non-ascii and non-printable characters\n text = ''.join([c for c in text if c in ALLOWED_CHARS])\n return text", "code_tokens": "def drop_bad_characters ( text ) : # Strip all non-ascii and non-printable characters text = '' . join ( [ c for c in text if c in ALLOWED_CHARS ] ) return text", "docstring_tokens": "Takes a text and drops all non - printable and non - ascii characters and also any whitespace characters that aren t space .", "label": 1, "retrieval_idx": 1217, "negative": "Request that the Outstation perform a cold restart . Command syntax is : restart" }, { "idx": "cosqa-train-12644", "doc": "python circle in a square bitmap array", "code": "def getBitmap(self):\n \"\"\" Captures screen area of this region, at least the part that is on the screen\n\n Returns image as numpy array\n \"\"\"\n return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)", "code_tokens": "def getBitmap ( self ) : return PlatformManager . getBitmapFromRect ( self . x , self . y , self . w , self . h )", "docstring_tokens": "Captures screen area of this region at least the part that is on the screen", "label": 1, "retrieval_idx": 4850, "negative": "Helper function for conversion of various data types into numeric representation ." }, { "idx": "cosqa-train-12106", "doc": "location of maya python exe", "code": "def setup_environment():\n \"\"\"Set up neccessary environment variables\n\n This appends all path of sys.path to the python path\n so mayapy will find all installed modules.\n We have to make sure, that we use maya libs instead of\n libs of the virtual env. So we insert all the libs for mayapy\n first.\n\n :returns: None\n :rtype: None\n :raises: None\n \"\"\"\n osinter = ostool.get_interface()\n pypath = osinter.get_maya_envpath()\n for p in sys.path:\n pypath = os.pathsep.join((pypath, p))\n os.environ['PYTHONPATH'] = pypath", "code_tokens": "def setup_environment ( ) : osinter = ostool . get_interface ( ) pypath = osinter . get_maya_envpath ( ) for p in sys . path : pypath = os . pathsep . join ( ( pypath , p ) ) os . environ [ 'PYTHONPATH' ] = pypath", "docstring_tokens": "Set up neccessary environment variables", "label": 1, "retrieval_idx": 4771, "negative": "Add suffix to a full file name" }, { "idx": "cosqa-train-19190", "doc": "how to make letters uppercase in python skipping spaces", "code": "def uppercase_chars(string: any) -> str:\n \"\"\"Return all (and only) the uppercase chars in the given string.\"\"\"\n return ''.join([c if c.isupper() else '' for c in str(string)])", "code_tokens": "def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )", "docstring_tokens": "Return all ( and only ) the uppercase chars in the given string .", "label": 1, "retrieval_idx": 5661, "negative": "Determines the number of bytes required to store a NumPy array with the specified shape and datatype ." }, { "idx": "cosqa-train-18016", "doc": "python delete element from set", "code": "def remove_once(gset, elem):\n \"\"\"Remove the element from a set, lists or dict.\n \n >>> L = [\"Lucy\"]; S = set([\"Sky\"]); D = { \"Diamonds\": True };\n >>> remove_once(L, \"Lucy\"); remove_once(S, \"Sky\"); remove_once(D, \"Diamonds\");\n >>> print L, S, D\n [] set([]) {}\n\n Returns the element if it was removed. Raises one of the exceptions in \n :obj:`RemoveError` otherwise.\n \"\"\"\n remove = getattr(gset, 'remove', None)\n if remove is not None: remove(elem)\n else: del gset[elem]\n return elem", "code_tokens": "def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem", "docstring_tokens": "Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}", "label": 1, "retrieval_idx": 5741, "negative": "Forward mouse cursor position events to the example" }, { "idx": "cosqa-train-13067", "doc": "python get current git branch", "code": "def get_last_commit(git_path=None):\n \"\"\"\n Get the HEAD commit SHA1 of repository in current dir.\n \"\"\"\n if git_path is None: git_path = GIT_PATH\n line = get_last_commit_line(git_path)\n revision_id = line.split()[1]\n return revision_id", "code_tokens": "def get_last_commit ( git_path = None ) : if git_path is None : git_path = GIT_PATH line = get_last_commit_line ( git_path ) revision_id = line . split ( ) [ 1 ] return revision_id", "docstring_tokens": "Get the HEAD commit SHA1 of repository in current dir .", "label": 1, "retrieval_idx": 421, "negative": "Print a colored string to the target handle ." }, { "idx": "cosqa-train-3274", "doc": "how to make a restart button using python", "code": "def do_restart(self, line):\n \"\"\"Request that the Outstation perform a cold restart. Command syntax is: restart\"\"\"\n self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)", "code_tokens": "def do_restart ( self , line ) : self . application . master . Restart ( opendnp3 . RestartType . COLD , restart_callback )", "docstring_tokens": "Request that the Outstation perform a cold restart . Command syntax is : restart", "label": 1, "retrieval_idx": 2293, "negative": "Generate seed for random number generator" }, { "idx": "cosqa-train-14708", "doc": "tracing python code execution", "code": "def __run(self):\n \"\"\"Hacked run function, which installs the trace.\"\"\"\n sys.settrace(self.globaltrace)\n self.__run_backup()\n self.run = self.__run_backup", "code_tokens": "def __run ( self ) : sys . settrace ( self . globaltrace ) self . __run_backup ( ) self . run = self . __run_backup", "docstring_tokens": "Hacked run function which installs the trace .", "label": 1, "retrieval_idx": 2799, "negative": "Return the SHA1 hash of the given a file - like object as file . This will seek the file back to 0 when it s finished ." }, { "idx": "cosqa-train-8874", "doc": "delete pyc files from python script", "code": "def clean(dry_run='n'):\n \"\"\"Wipes compiled and cached python files. To simulate: pynt clean[dry_run=y]\"\"\"\n file_patterns = ['*.pyc', '*.pyo', '*~']\n dir_patterns = ['__pycache__']\n recursive_pattern_delete(project_paths.root, file_patterns, dir_patterns, dry_run=bool(dry_run.lower() == 'y'))", "code_tokens": "def clean ( dry_run = 'n' ) : file_patterns = [ '*.pyc' , '*.pyo' , '*~' ] dir_patterns = [ '__pycache__' ] recursive_pattern_delete ( project_paths . root , file_patterns , dir_patterns , dry_run = bool ( dry_run . lower ( ) == 'y' ) )", "docstring_tokens": "Wipes compiled and cached python files . To simulate : pynt clean [ dry_run = y ]", "label": 1, "retrieval_idx": 4126, "negative": "Scale the input array" }, { "idx": "cosqa-train-10370", "doc": "sleep holding up python", "code": "def test3():\n \"\"\"Test the multiprocess\n \"\"\"\n import time\n \n p = MVisionProcess()\n p.start()\n time.sleep(5)\n p.stop()", "code_tokens": "def test3 ( ) : import time p = MVisionProcess ( ) p . start ( ) time . sleep ( 5 ) p . stop ( )", "docstring_tokens": "Test the multiprocess", "label": 1, "retrieval_idx": 2206, "negative": "Open and load JSON from file ." }, { "idx": "cosqa-train-8344", "doc": "traversal in tree in python", "code": "def walk_tree(root):\n \"\"\"Pre-order depth-first\"\"\"\n yield root\n\n for child in root.children:\n for el in walk_tree(child):\n yield el", "code_tokens": "def walk_tree ( root ) : yield root for child in root . children : for el in walk_tree ( child ) : yield el", "docstring_tokens": "Pre - order depth - first", "label": 1, "retrieval_idx": 1282, "negative": "Converts a datetime to a millisecond accuracy timestamp" }, { "idx": "cosqa-train-19036", "doc": "timing a function call python", "code": "def timeit(func, *args, **kwargs):\n \"\"\"\n Time execution of function. Returns (res, seconds).\n\n >>> res, timing = timeit(time.sleep, 1)\n \"\"\"\n start_time = time.time()\n res = func(*args, **kwargs)\n timing = time.time() - start_time\n return res, timing", "code_tokens": "def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing", "docstring_tokens": "Time execution of function . Returns ( res seconds ) .", "label": 1, "retrieval_idx": 5785, "negative": "Wrap an AST Call node to lambda expression node . call : ast . Call node" }, { "idx": "cosqa-train-9090", "doc": "python how to stop playsound", "code": "def stop(self):\n \"\"\"Stops playback\"\"\"\n if self.isPlaying is True:\n self._execute(\"stop\")\n self._changePlayingState(False)", "code_tokens": "def stop ( self ) : if self . isPlaying is True : self . _execute ( \"stop\" ) self . _changePlayingState ( False )", "docstring_tokens": "Stops playback", "label": 1, "retrieval_idx": 4166, "negative": "Wrap text in an ansi escape sequence" }, { "idx": "cosqa-train-18929", "doc": "python change dictioinary values in place", "code": "def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, change\n (in place) ``d[key]`` to ``value``.\n \"\"\"\n for d in dict_list:\n d[key] = value", "code_tokens": "def dictlist_replace ( dict_list : Iterable [ Dict ] , key : str , value : Any ) -> None : for d in dict_list : d [ key ] = value", "docstring_tokens": "Process an iterable of dictionaries . For each dictionary d change ( in place ) d [ key ] to value .", "label": 1, "retrieval_idx": 6132, "negative": "Pop the heap value from the heap ." }, { "idx": "cosqa-train-10729", "doc": "can i pass instance method as variable python", "code": "def do(self):\n \"\"\"\n Set a restore point (copy the object), then call the method.\n :return: obj.do_method(*args)\n \"\"\"\n self.restore_point = self.obj.copy()\n return self.do_method(self.obj, *self.args)", "code_tokens": "def do ( self ) : self . restore_point = self . obj . copy ( ) return self . do_method ( self . obj , * self . args )", "docstring_tokens": "Set a restore point ( copy the object ) then call the method . : return : obj . do_method ( * args )", "label": 1, "retrieval_idx": 4536, "negative": "Internal function to read an XML file" }, { "idx": "cosqa-train-12261", "doc": "pickle python read entiere file", "code": "def read_raw(data_path):\n \"\"\"\n Parameters\n ----------\n data_path : str\n \"\"\"\n with open(data_path, 'rb') as f:\n data = pickle.load(f)\n return data", "code_tokens": "def read_raw ( data_path ) : with open ( data_path , 'rb' ) as f : data = pickle . load ( f ) return data", "docstring_tokens": "Parameters ---------- data_path : str", "label": 1, "retrieval_idx": 4715, "negative": "Fetch the data field if it does not exist ." }, { "idx": "cosqa-train-1879", "doc": "should there be equal no of columns to concanate two df python", "code": "def cross_join(df1, df2):\n \"\"\"\n Return a dataframe that is a cross between dataframes\n df1 and df2\n\n ref: https://github.com/pydata/pandas/issues/5401\n \"\"\"\n if len(df1) == 0:\n return df2\n\n if len(df2) == 0:\n return df1\n\n # Add as lists so that the new index keeps the items in\n # the order that they are added together\n all_columns = pd.Index(list(df1.columns) + list(df2.columns))\n df1['key'] = 1\n df2['key'] = 1\n return pd.merge(df1, df2, on='key').loc[:, all_columns]", "code_tokens": "def cross_join ( df1 , df2 ) : if len ( df1 ) == 0 : return df2 if len ( df2 ) == 0 : return df1 # Add as lists so that the new index keeps the items in # the order that they are added together all_columns = pd . Index ( list ( df1 . columns ) + list ( df2 . columns ) ) df1 [ 'key' ] = 1 df2 [ 'key' ] = 1 return pd . merge ( df1 , df2 , on = 'key' ) . loc [ : , all_columns ]", "docstring_tokens": "Return a dataframe that is a cross between dataframes df1 and df2", "label": 1, "retrieval_idx": 793, "negative": "Get random binary tree node ." }, { "idx": "cosqa-train-10841", "doc": "python flatten deep nested list", "code": "def flatten(nested):\n \"\"\" Return a flatten version of the nested argument \"\"\"\n flat_return = list()\n\n def __inner_flat(nested,flat):\n for i in nested:\n __inner_flat(i, flat) if isinstance(i, list) else flat.append(i)\n return flat\n\n __inner_flat(nested,flat_return)\n\n return flat_return", "code_tokens": "def flatten ( nested ) : flat_return = list ( ) def __inner_flat ( nested , flat ) : for i in nested : __inner_flat ( i , flat ) if isinstance ( i , list ) else flat . append ( i ) return flat __inner_flat ( nested , flat_return ) return flat_return", "docstring_tokens": "Return a flatten version of the nested argument", "label": 1, "retrieval_idx": 1816, "negative": "HTTP DELETE operation to API endpoint ." }, { "idx": "cosqa-train-11837", "doc": "how to show a variable amount of precision in python string format", "code": "def indented_show(text, howmany=1):\n \"\"\"Print a formatted indented text.\n \"\"\"\n print(StrTemplate.pad_indent(text=text, howmany=howmany))", "code_tokens": "def indented_show ( text , howmany = 1 ) : print ( StrTemplate . pad_indent ( text = text , howmany = howmany ) )", "docstring_tokens": "Print a formatted indented text .", "label": 1, "retrieval_idx": 1446, "negative": "Strip out namespace data from an ElementTree ." }, { "idx": "cosqa-train-14528", "doc": "python array get element by index with default", "code": "def list_get(l, idx, default=None):\n \"\"\"\n Get from a list with an optional default value.\n \"\"\"\n try:\n if l[idx]:\n return l[idx]\n else:\n return default\n except IndexError:\n return default", "code_tokens": "def list_get ( l , idx , default = None ) : try : if l [ idx ] : return l [ idx ] else : return default except IndexError : return default", "docstring_tokens": "Get from a list with an optional default value .", "label": 1, "retrieval_idx": 719, "negative": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ..." }, { "idx": "cosqa-train-19843", "doc": "check if string is int in python", "code": "def _isint(string):\n \"\"\"\n >>> _isint(\"123\")\n True\n >>> _isint(\"123.45\")\n False\n \"\"\"\n return type(string) is int or \\\n (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n _isconvertible(int, string)", "code_tokens": "def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )", "docstring_tokens": ">>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False", "label": 1, "retrieval_idx": 5776, "negative": "Set a restore point ( copy the object ) then call the method . : return : obj . do_method ( * args )" }, { "idx": "cosqa-train-5020", "doc": "how to change numpy array to list in python", "code": "def A(*a):\n \"\"\"convert iterable object into numpy array\"\"\"\n return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a]", "code_tokens": "def A ( * a ) : return np . array ( a [ 0 ] ) if len ( a ) == 1 else [ np . array ( o ) for o in a ]", "docstring_tokens": "convert iterable object into numpy array", "label": 1, "retrieval_idx": 856, "negative": "Takes JSON formatted data converting it into native Python objects" }, { "idx": "cosqa-train-19098", "doc": "read a file into a set python", "code": "def read_set_from_file(filename: str) -> Set[str]:\n \"\"\"\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n \"\"\"\n collection = set()\n with open(filename, 'r') as file_:\n for line in file_:\n collection.add(line.rstrip())\n return collection", "code_tokens": "def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection", "docstring_tokens": "Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .", "label": 1, "retrieval_idx": 5611, "negative": "Retrun True if x is a valid YYYYMMDD date ; otherwise return False ." }, { "idx": "cosqa-train-13927", "doc": "python round float to int", "code": "def intround(value):\n \"\"\"Given a float returns a rounded int. Should give the same result on\n both Py2/3\n \"\"\"\n\n return int(decimal.Decimal.from_float(\n value).to_integral_value(decimal.ROUND_HALF_EVEN))", "code_tokens": "def intround ( value ) : return int ( decimal . Decimal . from_float ( value ) . to_integral_value ( decimal . ROUND_HALF_EVEN ) )", "docstring_tokens": "Given a float returns a rounded int . Should give the same result on both Py2 / 3", "label": 1, "retrieval_idx": 323, "negative": "Logs out the current session by removing it from the cache . This is expected to only occur when a session has" }, { "idx": "cosqa-train-5607", "doc": "how to write a parser on python", "code": "def __init__(self):\n \"\"\"__init__: Performs basic initialisations\"\"\"\n # Root parser\n self.parser = argparse.ArgumentParser()\n # Subparsers\n self.subparsers = self.parser.add_subparsers()\n # Parser dictionary, to avoir overwriting existing parsers\n self.parsers = {}", "code_tokens": "def __init__ ( self ) : # Root parser self . parser = argparse . ArgumentParser ( ) # Subparsers self . subparsers = self . parser . add_subparsers ( ) # Parser dictionary, to avoir overwriting existing parsers self . parsers = { }", "docstring_tokens": "__init__ : Performs basic initialisations", "label": 1, "retrieval_idx": 3225, "negative": "A non - negative integer ." }, { "idx": "cosqa-train-15068", "doc": "python dict with keys no value", "code": "def nonull_dict(self):\n \"\"\"Like dict, but does not hold any null values.\n\n :return:\n\n \"\"\"\n return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}", "code_tokens": "def nonull_dict ( self ) : return { k : v for k , v in six . iteritems ( self . dict ) if v and k != '_codes' }", "docstring_tokens": "Like dict but does not hold any null values .", "label": 1, "retrieval_idx": 193, "negative": "Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket" }, { "idx": "cosqa-train-11777", "doc": "how to remove blank lines from a text file in python", "code": "def get_stripped_file_lines(filename):\n \"\"\"\n Return lines of a file with whitespace removed\n \"\"\"\n try:\n lines = open(filename).readlines()\n except FileNotFoundError:\n fatal(\"Could not open file: {!r}\".format(filename))\n\n return [line.strip() for line in lines]", "code_tokens": "def get_stripped_file_lines ( filename ) : try : lines = open ( filename ) . readlines ( ) except FileNotFoundError : fatal ( \"Could not open file: {!r}\" . format ( filename ) ) return [ line . strip ( ) for line in lines ]", "docstring_tokens": "Return lines of a file with whitespace removed", "label": 1, "retrieval_idx": 3099, "negative": "Parameters ---------- data_path : str" }, { "idx": "cosqa-train-7409", "doc": "how to hash a binary file in python", "code": "def generate_hash(filepath):\n \"\"\"Public function that reads a local file and generates a SHA256 hash digest for it\"\"\"\n fr = FileReader(filepath)\n data = fr.read_bin()\n return _calculate_sha256(data)", "code_tokens": "def generate_hash ( filepath ) : fr = FileReader ( filepath ) data = fr . read_bin ( ) return _calculate_sha256 ( data )", "docstring_tokens": "Public function that reads a local file and generates a SHA256 hash digest for it", "label": 1, "retrieval_idx": 3336, "negative": "returns a dictionary of arg_name : default_values for the input function" }, { "idx": "cosqa-train-6732", "doc": "python get function keyword names", "code": "def parse_func_kwarg_keys(func, with_vals=False):\n \"\"\" hacky inference of kwargs keys\n\n SeeAlso:\n argparse_funckw\n recursive_parse_kwargs\n parse_kwarg_keys\n parse_func_kwarg_keys\n get_func_kwargs\n\n \"\"\"\n sourcecode = get_func_sourcecode(func, strip_docstr=True,\n strip_comments=True)\n kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)\n #ut.get_func_kwargs TODO\n return kwkeys", "code_tokens": "def parse_func_kwarg_keys ( func , with_vals = False ) : sourcecode = get_func_sourcecode ( func , strip_docstr = True , strip_comments = True ) kwkeys = parse_kwarg_keys ( sourcecode , with_vals = with_vals ) #ut.get_func_kwargs TODO return kwkeys", "docstring_tokens": "hacky inference of kwargs keys", "label": 1, "retrieval_idx": 3562, "negative": "Public function that reads a local file and generates a SHA256 hash digest for it" }, { "idx": "cosqa-train-12054", "doc": "iterate through words in text file python", "code": "def extract_words(lines):\n \"\"\"\n Extract from the given iterable of lines the list of words.\n\n :param lines: an iterable of lines;\n :return: a generator of words of lines.\n \"\"\"\n for line in lines:\n for word in re.findall(r\"\\w+\", line):\n yield word", "code_tokens": "def extract_words ( lines ) : for line in lines : for word in re . findall ( r\"\\w+\" , line ) : yield word", "docstring_tokens": "Extract from the given iterable of lines the list of words .", "label": 1, "retrieval_idx": 2261, "negative": "Only return cursor instance if configured for multiselect" }, { "idx": "cosqa-train-18846", "doc": "python make a put request to restful endpoint", "code": "def put(self, endpoint: str, **kwargs) -> dict:\n \"\"\"HTTP PUT operation to API endpoint.\"\"\"\n\n return self._request('PUT', endpoint, **kwargs)", "code_tokens": "def put ( self , endpoint : str , * * kwargs ) -> dict : return self . _request ( 'PUT' , endpoint , * * kwargs )", "docstring_tokens": "HTTP PUT operation to API endpoint .", "label": 1, "retrieval_idx": 6123, "negative": "Scroll both categories Canvas and scrolling container" }, { "idx": "cosqa-train-13151", "doc": "python get the id of the current thread", "code": "def threadid(self):\n \"\"\"\n Current thread ident. If current thread is main thread then it returns ``None``.\n\n :type: int or None\n \"\"\"\n current = self.thread.ident\n main = get_main_thread()\n if main is None:\n return current\n else:\n return current if current != main.ident else None", "code_tokens": "def threadid ( self ) : current = self . thread . ident main = get_main_thread ( ) if main is None : return current else : return current if current != main . ident else None", "docstring_tokens": "Current thread ident . If current thread is main thread then it returns None .", "label": 1, "retrieval_idx": 2525, "negative": "Return true if the string is a mathematical symbol ." }, { "idx": "cosqa-train-4543", "doc": "python function returning a list of all entities is called", "code": "def filtany(entities, **kw):\n \"\"\"Filter a set of entities based on method return. Use keyword arguments.\n \n Example:\n filtmeth(entities, id='123')\n filtmeth(entities, name='bart')\n\n Multiple filters are 'OR'.\n \"\"\"\n ret = set()\n for k,v in kw.items():\n for entity in entities:\n if getattr(entity, k)() == v:\n ret.add(entity)\n return ret", "code_tokens": "def filtany ( entities , * * kw ) : ret = set ( ) for k , v in kw . items ( ) : for entity in entities : if getattr ( entity , k ) ( ) == v : ret . add ( entity ) return ret", "docstring_tokens": "Filter a set of entities based on method return . Use keyword arguments . Example : filtmeth ( entities id = 123 ) filtmeth ( entities name = bart )", "label": 1, "retrieval_idx": 2850, "negative": "Convert this confusion matrix into a 2x2 plain list of values ." }, { "idx": "cosqa-train-19579", "doc": "how to flat a list of list python", "code": "def flatten_list(x: List[Any]) -> List[Any]:\n \"\"\"\n Converts a list of lists into a flat list.\n \n Args:\n x: list of lists \n\n Returns:\n flat list\n \n As per\n http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python\n\n \"\"\" # noqa\n return [item for sublist in x for item in sublist]", "code_tokens": "def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]", "docstring_tokens": "Converts a list of lists into a flat list . Args : x : list of lists", "label": 1, "retrieval_idx": 5658, "negative": "Load JSON file" }, { "idx": "cosqa-train-19307", "doc": "python read yaml to numpy", "code": "def numpy_to_yaml(representer: Representer, data: np.ndarray) -> Sequence[Any]:\n \"\"\" Write a numpy array to YAML.\n\n It registers the array under the tag ``!numpy_array``.\n\n Use with:\n\n .. code-block:: python\n\n >>> yaml = ruamel.yaml.YAML()\n >>> yaml.representer.add_representer(np.ndarray, yaml.numpy_to_yaml)\n\n Note:\n We cannot use ``yaml.register_class`` because it won't register the proper type.\n (It would register the type of the class, rather than of `numpy.ndarray`). Instead,\n we use the above approach to register this method explicitly with the representer.\n \"\"\"\n return representer.represent_sequence(\n \"!numpy_array\",\n data.tolist()\n )", "code_tokens": "def numpy_to_yaml ( representer : Representer , data : np . ndarray ) -> Sequence [ Any ] : return representer . represent_sequence ( \"!numpy_array\" , data . tolist ( ) )", "docstring_tokens": "Write a numpy array to YAML .", "label": 1, "retrieval_idx": 6117, "negative": "Parses hostname from URL . : param url : URL : return : hostname" }, { "idx": "cosqa-train-10997", "doc": "discord python get user from id string", "code": "def get_user_by_id(self, id):\n \"\"\"Retrieve a User object by ID.\"\"\"\n return self.db_adapter.get_object(self.UserClass, id=id)", "code_tokens": "def get_user_by_id ( self , id ) : return self . db_adapter . get_object ( self . UserClass , id = id )", "docstring_tokens": "Retrieve a User object by ID .", "label": 1, "retrieval_idx": 620, "negative": "Parameters ---------- data_path : str" }, { "idx": "cosqa-train-18792", "doc": "list of arbitrary objects to counts in python", "code": "def count(args):\n \"\"\" count occurences in a list of lists\n >>> count([['a','b'],['a']])\n defaultdict(int, {'a' : 2, 'b' : 1})\n \"\"\"\n counts = defaultdict(int)\n for arg in args:\n for item in arg:\n counts[item] = counts[item] + 1\n return counts", "code_tokens": "def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts", "docstring_tokens": "count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )", "label": 1, "retrieval_idx": 5768, "negative": "Adds points and converts to topojson string ." }, { "idx": "cosqa-train-11636", "doc": "how to know queue size in python", "code": "def qsize(self):\n \"\"\"Return the approximate size of the queue (not reliable!).\"\"\"\n self.mutex.acquire()\n n = self._qsize()\n self.mutex.release()\n return n", "code_tokens": "def qsize ( self ) : self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n", "docstring_tokens": "Return the approximate size of the queue ( not reliable! ) .", "label": 1, "retrieval_idx": 425, "negative": "Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process" }, { "idx": "cosqa-train-12000", "doc": "impute missing values in python", "code": "def impute_data(self,x):\n \"\"\"Imputes data set containing Nan values\"\"\"\n imp = Imputer(missing_values='NaN', strategy='mean', axis=0)\n return imp.fit_transform(x)", "code_tokens": "def impute_data ( self , x ) : imp = Imputer ( missing_values = 'NaN' , strategy = 'mean' , axis = 0 ) return imp . fit_transform ( x )", "docstring_tokens": "Imputes data set containing Nan values", "label": 1, "retrieval_idx": 3840, "negative": "r Clean up whitespace in column names . See better version at pugnlp . clean_columns" }, { "idx": "cosqa-dev-78", "doc": "python dict rank by value", "code": "def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):\n \"\"\" Reverse sorts a #dict by a given key, optionally returning it as a\n #tuple. By default, the @dict is sorted by it's value.\n\n @dict: the #dict you wish to sorts\n @key: the #sorted key to use\n @as_tuple: returns result as a #tuple ((k, v),...)\n\n -> :class:OrderedDict or #tuple\n \"\"\"\n sorted_list = sorted(dict.items(), key=key, reverse=True)\n return OrderedDict(sorted_list) if not as_tuple else tuple(sorted_list)", "code_tokens": "def revrank_dict ( dict , key = lambda t : t [ 1 ] , as_tuple = False ) : sorted_list = sorted ( dict . items ( ) , key = key , reverse = True ) return OrderedDict ( sorted_list ) if not as_tuple else tuple ( sorted_list )", "docstring_tokens": "Reverse sorts a #dict by a given key optionally returning it as a #tuple . By default the @dict is sorted by it s value .", "label": 1, "retrieval_idx": 5999, "negative": "Determines if a system process identifer exists in process table ." }, { "idx": "cosqa-train-13276", "doc": "generate short unique id python", "code": "def generate_unique_host_id():\n \"\"\"Generate a unique ID, that is somewhat guaranteed to be unique among all\n instances running at the same time.\"\"\"\n host = \".\".join(reversed(socket.gethostname().split(\".\")))\n pid = os.getpid()\n return \"%s.%d\" % (host, pid)", "code_tokens": "def generate_unique_host_id ( ) : host = \".\" . join ( reversed ( socket . gethostname ( ) . split ( \".\" ) ) ) pid = os . getpid ( ) return \"%s.%d\" % ( host , pid )", "docstring_tokens": "Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time .", "label": 1, "retrieval_idx": 335, "negative": "Checks if an item is iterable ( list tuple generator ) but not string" }, { "idx": "cosqa-train-11501", "doc": "python numpy inverse of the matrix", "code": "def MatrixInverse(a, adj):\n \"\"\"\n Matrix inversion op.\n \"\"\"\n return np.linalg.inv(a if not adj else _adjoint(a)),", "code_tokens": "def MatrixInverse ( a , adj ) : return np . linalg . inv ( a if not adj else _adjoint ( a ) ) ,", "docstring_tokens": "Matrix inversion op .", "label": 1, "retrieval_idx": 2512, "negative": "Check if cnr or cns files are empty ( only have a header )" }, { "idx": "cosqa-train-11153", "doc": "python how to mix backslash and forward slashes in path", "code": "def norm_slash(name):\n \"\"\"Normalize path slashes.\"\"\"\n\n if isinstance(name, str):\n return name.replace('/', \"\\\\\") if not is_case_sensitive() else name\n else:\n return name.replace(b'/', b\"\\\\\") if not is_case_sensitive() else name", "code_tokens": "def norm_slash ( name ) : if isinstance ( name , str ) : return name . replace ( '/' , \"\\\\\" ) if not is_case_sensitive ( ) else name else : return name . replace ( b'/' , b\"\\\\\" ) if not is_case_sensitive ( ) else name", "docstring_tokens": "Normalize path slashes .", "label": 1, "retrieval_idx": 1288, "negative": "Return list of Logger classes ." }, { "idx": "cosqa-train-14436", "doc": "reduce functon not defined in python", "code": "def compose(func_list):\n \"\"\"\n composion of preprocessing functions\n \"\"\"\n\n def f(G, bim):\n for func in func_list:\n G, bim = func(G, bim)\n return G, bim\n\n return f", "code_tokens": "def compose ( func_list ) : def f ( G , bim ) : for func in func_list : G , bim = func ( G , bim ) return G , bim return f", "docstring_tokens": "composion of preprocessing functions", "label": 1, "retrieval_idx": 3964, "negative": "Softsign op ." }, { "idx": "cosqa-train-19789", "doc": "python detect key press linux", "code": "def _kbhit_unix() -> bool:\n \"\"\"\n Under UNIX: is a keystroke available?\n \"\"\"\n dr, dw, de = select.select([sys.stdin], [], [], 0)\n return dr != []", "code_tokens": "def _kbhit_unix ( ) -> bool : dr , dw , de = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return dr != [ ]", "docstring_tokens": "Under UNIX : is a keystroke available?", "label": 1, "retrieval_idx": 5666, "negative": "Build a C ++ binary executable" }, { "idx": "cosqa-train-17572", "doc": "how to generate random binary tree in python", "code": "def getRandomBinaryTreeLeafNode(binaryTree):\n \"\"\"Get random binary tree node.\n \"\"\"\n if binaryTree.internal == True:\n if random.random() > 0.5:\n return getRandomBinaryTreeLeafNode(binaryTree.left)\n else:\n return getRandomBinaryTreeLeafNode(binaryTree.right)\n else:\n return binaryTree", "code_tokens": "def getRandomBinaryTreeLeafNode ( binaryTree ) : if binaryTree . internal == True : if random . random ( ) > 0.5 : return getRandomBinaryTreeLeafNode ( binaryTree . left ) else : return getRandomBinaryTreeLeafNode ( binaryTree . right ) else : return binaryTree", "docstring_tokens": "Get random binary tree node .", "label": 1, "retrieval_idx": 5871, "negative": "Returns a vector of spherical bessel functions yn : x : The argument . N : values of n will run from 0 to N - 1 ." }, { "idx": "cosqa-train-2445", "doc": "python get epoch milis from datetime", "code": "def _dt_to_epoch(dt):\n \"\"\"Convert datetime to epoch seconds.\"\"\"\n try:\n epoch = dt.timestamp()\n except AttributeError: # py2\n epoch = (dt - datetime(1970, 1, 1)).total_seconds()\n return epoch", "code_tokens": "def _dt_to_epoch ( dt ) : try : epoch = dt . timestamp ( ) except AttributeError : # py2 epoch = ( dt - datetime ( 1970 , 1 , 1 ) ) . total_seconds ( ) return epoch", "docstring_tokens": "Convert datetime to epoch seconds .", "label": 1, "retrieval_idx": 459, "negative": "Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays ." }, { "idx": "cosqa-train-15289", "doc": "python get environ user windows", "code": "def get_user_name():\n \"\"\"Get user name provide by operating system\n \"\"\"\n\n if sys.platform == 'win32':\n #user = os.getenv('USERPROFILE')\n user = os.getenv('USERNAME')\n else:\n user = os.getenv('LOGNAME')\n\n return user", "code_tokens": "def get_user_name ( ) : if sys . platform == 'win32' : #user = os.getenv('USERPROFILE') user = os . getenv ( 'USERNAME' ) else : user = os . getenv ( 'LOGNAME' ) return user", "docstring_tokens": "Get user name provide by operating system", "label": 1, "retrieval_idx": 965, "negative": "Run the unit tests ." }, { "idx": "cosqa-train-9986", "doc": "iterator is past the end python", "code": "def __next__(self):\n \"\"\"Pop the head off the iterator and return it.\"\"\"\n res = self._head\n self._fill()\n if res is None:\n raise StopIteration()\n return res", "code_tokens": "def __next__ ( self ) : res = self . _head self . _fill ( ) if res is None : raise StopIteration ( ) return res", "docstring_tokens": "Pop the head off the iterator and return it .", "label": 1, "retrieval_idx": 659, "negative": "Build the lexer ." }, { "idx": "cosqa-train-9114", "doc": "python if file not exist then creat", "code": "def check_create_folder(filename):\n \"\"\"Check if the folder exisits. If not, create the folder\"\"\"\n os.makedirs(os.path.dirname(filename), exist_ok=True)", "code_tokens": "def check_create_folder ( filename ) : os . makedirs ( os . path . dirname ( filename ) , exist_ok = True )", "docstring_tokens": "Check if the folder exisits . If not create the folder", "label": 1, "retrieval_idx": 1598, "negative": "Args : points : ( nx4 ) x2 Returns : nx4 boxes ( x1y1x2y2 )" }, { "idx": "cosqa-train-18440", "doc": "python howe to tell if path passed in is absolute or relative", "code": "def is_relative_url(url):\n \"\"\" simple method to determine if a url is relative or absolute \"\"\"\n if url.startswith(\"#\"):\n return None\n if url.find(\"://\") > 0 or url.startswith(\"//\"):\n # either 'http(s)://...' or '//cdn...' and therefore absolute\n return False\n return True", "code_tokens": "def is_relative_url ( url ) : if url . startswith ( \"#\" ) : return None if url . find ( \"://\" ) > 0 or url . startswith ( \"//\" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True", "docstring_tokens": "simple method to determine if a url is relative or absolute", "label": 1, "retrieval_idx": 5758, "negative": "Removes dict keys which have have self as value ." }, { "idx": "cosqa-train-16521", "doc": "maker a string lowercase pythong", "code": "def to_snake_case(text):\n \"\"\"Convert to snake case.\n\n :param str text:\n :rtype: str\n :return:\n \"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', text)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "code_tokens": "def to_snake_case ( text ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\\1_\\2' , text ) return re . sub ( '([a-z0-9])([A-Z])' , r'\\1_\\2' , s1 ) . lower ( )", "docstring_tokens": "Convert to snake case .", "label": 1, "retrieval_idx": 1763, "negative": "" }, { "idx": "cosqa-train-9880", "doc": "python sys stdout write new line", "code": "def println(msg):\n \"\"\"\n Convenience function to print messages on a single line in the terminal\n \"\"\"\n sys.stdout.write(msg)\n sys.stdout.flush()\n sys.stdout.write('\\x08' * len(msg))\n sys.stdout.flush()", "code_tokens": "def println ( msg ) : sys . stdout . write ( msg ) sys . stdout . flush ( ) sys . stdout . write ( '\\x08' * len ( msg ) ) sys . stdout . flush ( )", "docstring_tokens": "Convenience function to print messages on a single line in the terminal", "label": 1, "retrieval_idx": 3858, "negative": "Request that the Outstation perform a cold restart . Command syntax is : restart" }, { "idx": "cosqa-train-11091", "doc": "python how to create a iterable", "code": "def force_iterable(f):\n \"\"\"Will make any functions return an iterable objects by wrapping its result in a list.\"\"\"\n def wrapper(*args, **kwargs):\n r = f(*args, **kwargs)\n if hasattr(r, '__iter__'):\n return r\n else:\n return [r]\n return wrapper", "code_tokens": "def force_iterable ( f ) : def wrapper ( * args , * * kwargs ) : r = f ( * args , * * kwargs ) if hasattr ( r , '__iter__' ) : return r else : return [ r ] return wrapper", "docstring_tokens": "Will make any functions return an iterable objects by wrapping its result in a list .", "label": 1, "retrieval_idx": 570, "negative": "Given a QuerySet and the name of field containing datetimes return the latest ( most recent ) date ." }, { "idx": "cosqa-train-9907", "doc": "how to use python function in tensorflow", "code": "def _float_feature(value):\n \"\"\"Wrapper for inserting float features into Example proto.\"\"\"\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))", "code_tokens": "def _float_feature ( value ) : if not isinstance ( value , list ) : value = [ value ] return tf . train . Feature ( float_list = tf . train . FloatList ( value = value ) )", "docstring_tokens": "Wrapper for inserting float features into Example proto .", "label": 1, "retrieval_idx": 4349, "negative": "Return the duplicates in a list ." }, { "idx": "cosqa-train-11127", "doc": "python how to get range of array with positive values numpy", "code": "def _interval_to_bound_points(array):\n \"\"\"\n Helper function which returns an array\n with the Intervals' boundaries.\n \"\"\"\n\n array_boundaries = np.array([x.left for x in array])\n array_boundaries = np.concatenate(\n (array_boundaries, np.array([array[-1].right])))\n\n return array_boundaries", "code_tokens": "def _interval_to_bound_points ( array ) : array_boundaries = np . array ( [ x . left for x in array ] ) array_boundaries = np . concatenate ( ( array_boundaries , np . array ( [ array [ - 1 ] . right ] ) ) ) return array_boundaries", "docstring_tokens": "Helper function which returns an array with the Intervals boundaries .", "label": 1, "retrieval_idx": 140, "negative": "Marker for a token" }, { "idx": "cosqa-train-10271", "doc": "python 3 a build string from iterable", "code": "def commajoin_as_strings(iterable):\n \"\"\" Join the given iterable with ',' \"\"\"\n return _(u',').join((six.text_type(i) for i in iterable))", "code_tokens": "def commajoin_as_strings ( iterable ) : return _ ( u',' ) . join ( ( six . text_type ( i ) for i in iterable ) )", "docstring_tokens": "Join the given iterable with", "label": 1, "retrieval_idx": 160, "negative": "Flush all items from cache ." }, { "idx": "cosqa-train-12615", "doc": "unchecking a radio button python", "code": "def checkbox_uncheck(self, force_check=False):\n \"\"\"\n Wrapper to uncheck a checkbox\n \"\"\"\n if self.get_attribute('checked'):\n self.click(force_click=force_check)", "code_tokens": "def checkbox_uncheck ( self , force_check = False ) : if self . get_attribute ( 'checked' ) : self . click ( force_click = force_check )", "docstring_tokens": "Wrapper to uncheck a checkbox", "label": 1, "retrieval_idx": 1582, "negative": "Delete all the files and subdirectories in a directory ." }, { "idx": "cosqa-train-12906", "doc": "python expected type sized", "code": "def _requiredSize(shape, dtype):\n\t\"\"\"\n\tDetermines the number of bytes required to store a NumPy array with\n\tthe specified shape and datatype.\n\t\"\"\"\n\treturn math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)", "code_tokens": "def _requiredSize ( shape , dtype ) : return math . floor ( np . prod ( np . asarray ( shape , dtype = np . uint64 ) ) * np . dtype ( dtype ) . itemsize )", "docstring_tokens": "Determines the number of bytes required to store a NumPy array with the specified shape and datatype .", "label": 1, "retrieval_idx": 1319, "negative": "Get a property by name" }, { "idx": "cosqa-train-18559", "doc": "python load csv to numpy array", "code": "def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array\n \"\"\"Convert a CSV object to a numpy array.\n\n Args:\n string_like (str): CSV string.\n dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the\n contents of each column, individually. This argument can only be used to\n 'upcast' the array. For downcasting, use the .astype(t) method.\n Returns:\n (np.array): numpy array\n \"\"\"\n stream = StringIO(string_like)\n return np.genfromtxt(stream, dtype=dtype, delimiter=',')", "code_tokens": "def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )", "docstring_tokens": "Convert a CSV object to a numpy array .", "label": 1, "retrieval_idx": 5746, "negative": "Returns sequence of integer ids given a sequence of string ids ." }, { "idx": "cosqa-dev-141", "doc": "python remove element from list time complexity", "code": "def remove_elements(target, indices):\n \"\"\"Remove multiple elements from a list and return result.\n This implementation is faster than the alternative below.\n Also note the creation of a new list to avoid altering the\n original. We don't have any current use for the original\n intact list, but may in the future...\"\"\"\n\n copied = list(target)\n\n for index in reversed(indices):\n del copied[index]\n return copied", "code_tokens": "def remove_elements ( target , indices ) : copied = list ( target ) for index in reversed ( indices ) : del copied [ index ] return copied", "docstring_tokens": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ...", "label": 1, "retrieval_idx": 837, "negative": "Imputes data set containing Nan values" }, { "idx": "cosqa-train-9520", "doc": "python property by string name", "code": "def get_propety_by_name(pif, name):\n \"\"\"Get a property by name\"\"\"\n warn(\"This method has been deprecated in favor of get_property_by_name\")\n return next((x for x in pif.properties if x.name == name), None)", "code_tokens": "def get_propety_by_name ( pif , name ) : warn ( \"This method has been deprecated in favor of get_property_by_name\" ) return next ( ( x for x in pif . properties if x . name == name ) , None )", "docstring_tokens": "Get a property by name", "label": 1, "retrieval_idx": 2898, "negative": "Public function that reads a local file and generates a SHA256 hash digest for it" }, { "idx": "cosqa-train-7816", "doc": "index of an entry in a list python", "code": "def is_in(self, search_list, pair):\n \"\"\"\n If pair is in search_list, return the index. Otherwise return -1\n \"\"\"\n index = -1\n for nr, i in enumerate(search_list):\n if(np.all(i == pair)):\n return nr\n return index", "code_tokens": "def is_in ( self , search_list , pair ) : index = - 1 for nr , i in enumerate ( search_list ) : if ( np . all ( i == pair ) ) : return nr return index", "docstring_tokens": "If pair is in search_list return the index . Otherwise return - 1", "label": 1, "retrieval_idx": 2444, "negative": "Like pretty but print to stdout ." }, { "idx": "cosqa-train-4764", "doc": "python how to determine if an iterable is iterable", "code": "def _is_iterable(item):\n \"\"\" Checks if an item is iterable (list, tuple, generator), but not string \"\"\"\n return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)", "code_tokens": "def _is_iterable ( item ) : return isinstance ( item , collections . Iterable ) and not isinstance ( item , six . string_types )", "docstring_tokens": "Checks if an item is iterable ( list tuple generator ) but not string", "label": 1, "retrieval_idx": 2522, "negative": "Round a number to a precision" }, { "idx": "cosqa-train-18858", "doc": "python how to create date from string", "code": "def get_from_gnucash26_date(date_str: str) -> date:\n \"\"\" Creates a datetime from GnuCash 2.6 date string \"\"\"\n date_format = \"%Y%m%d\"\n result = datetime.strptime(date_str, date_format).date()\n return result", "code_tokens": "def get_from_gnucash26_date ( date_str : str ) -> date : date_format = \"%Y%m%d\" result = datetime . strptime ( date_str , date_format ) . date ( ) return result", "docstring_tokens": "Creates a datetime from GnuCash 2 . 6 date string", "label": 1, "retrieval_idx": 5766, "negative": "Check if git command is available ." }, { "idx": "cosqa-train-11312", "doc": "how to append a line in a file in the middle of file in python", "code": "def prepend_line(filepath, line):\n \"\"\"Rewrite a file adding a line to its beginning.\n \"\"\"\n with open(filepath) as f:\n lines = f.readlines()\n\n lines.insert(0, line)\n\n with open(filepath, 'w') as f:\n f.writelines(lines)", "code_tokens": "def prepend_line ( filepath , line ) : with open ( filepath ) as f : lines = f . readlines ( ) lines . insert ( 0 , line ) with open ( filepath , 'w' ) as f : f . writelines ( lines )", "docstring_tokens": "Rewrite a file adding a line to its beginning .", "label": 1, "retrieval_idx": 629, "negative": "Python 3 input () / Python 2 raw_input ()" }, { "idx": "cosqa-train-11876", "doc": "how to split a string by every character in python", "code": "def _split(string, splitters):\n \"\"\"Splits a string into parts at multiple characters\"\"\"\n part = ''\n for character in string:\n if character in splitters:\n yield part\n part = ''\n else:\n part += character\n yield part", "code_tokens": "def _split ( string , splitters ) : part = '' for character in string : if character in splitters : yield part part = '' else : part += character yield part", "docstring_tokens": "Splits a string into parts at multiple characters", "label": 1, "retrieval_idx": 1545, "negative": "For Python3 compatibility of generator ." }, { "idx": "cosqa-train-19520", "doc": "python get index of element each time it appears in list", "code": "def index(self, item):\n \"\"\" Not recommended for use on large lists due to time\n complexity, but it works\n\n -> #int list index of @item\n \"\"\"\n for i, x in enumerate(self.iter()):\n if x == item:\n return i\n return None", "code_tokens": "def index ( self , item ) : for i , x in enumerate ( self . iter ( ) ) : if x == item : return i return None", "docstring_tokens": "Not recommended for use on large lists due to time complexity but it works", "label": 1, "retrieval_idx": 6214, "negative": "Joins a voice channel" }, { "idx": "cosqa-train-4792", "doc": "python how to make dot character", "code": "def _dotify(cls, data):\n \"\"\"Add dots.\"\"\"\n return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)", "code_tokens": "def _dotify ( cls , data ) : return '' . join ( char if char in cls . PRINTABLE_DATA else '.' for char in data )", "docstring_tokens": "Add dots .", "label": 1, "retrieval_idx": 2350, "negative": "Wipes compiled and cached python files . To simulate : pynt clean [ dry_run = y ]" }, { "idx": "cosqa-train-15375", "doc": "python heap top element", "code": "def pop(h):\n \"\"\"Pop the heap value from the heap.\"\"\"\n n = h.size() - 1\n h.swap(0, n)\n down(h, 0, n)\n return h.pop()", "code_tokens": "def pop ( h ) : n = h . size ( ) - 1 h . swap ( 0 , n ) down ( h , 0 , n ) return h . pop ( )", "docstring_tokens": "Pop the heap value from the heap .", "label": 1, "retrieval_idx": 400, "negative": "Hides the main window of the terminal and sets the visible flag to False ." }, { "idx": "cosqa-train-5644", "doc": "in python, how to print strings in different colours", "code": "def cprint(string, fg=None, bg=None, end='\\n', target=sys.stdout):\n \"\"\"Print a colored string to the target handle.\n\n fg and bg specify foreground- and background colors, respectively. The\n remaining keyword arguments are the same as for Python's built-in print\n function. Colors are returned to their defaults before the function\n returns.\n\n \"\"\"\n _color_manager.set_color(fg, bg)\n target.write(string + end)\n target.flush() # Needed for Python 3.x\n _color_manager.set_defaults()", "code_tokens": "def cprint ( string , fg = None , bg = None , end = '\\n' , target = sys . stdout ) : _color_manager . set_color ( fg , bg ) target . write ( string + end ) target . flush ( ) # Needed for Python 3.x _color_manager . set_defaults ( )", "docstring_tokens": "Print a colored string to the target handle .", "label": 1, "retrieval_idx": 1026, "negative": "Convert a CSV object to a numpy array ." }, { "idx": "cosqa-train-10096", "doc": "python yield unsupported operand type(s)", "code": "def visit_BinOp(self, node):\n \"\"\" Return type depend from both operand of the binary operation. \"\"\"\n args = [self.visit(arg) for arg in (node.left, node.right)]\n return list({frozenset.union(*x) for x in itertools.product(*args)})", "code_tokens": "def visit_BinOp ( self , node ) : args = [ self . visit ( arg ) for arg in ( node . left , node . right ) ] return list ( { frozenset . union ( * x ) for x in itertools . product ( * args ) } )", "docstring_tokens": "Return type depend from both operand of the binary operation .", "label": 1, "retrieval_idx": 4402, "negative": "Warn if nans exist in a numpy array ." }, { "idx": "cosqa-train-7703", "doc": "how to sort files by filename python", "code": "def sort_filenames(filenames):\n \"\"\"\n sort a list of files by filename only, ignoring the directory names\n \"\"\"\n basenames = [os.path.basename(x) for x in filenames]\n indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])]\n return [filenames[x] for x in indexes]", "code_tokens": "def sort_filenames ( filenames ) : basenames = [ os . path . basename ( x ) for x in filenames ] indexes = [ i [ 0 ] for i in sorted ( enumerate ( basenames ) , key = lambda x : x [ 1 ] ) ] return [ filenames [ x ] for x in indexes ]", "docstring_tokens": "sort a list of files by filename only ignoring the directory names", "label": 1, "retrieval_idx": 707, "negative": "Set value of the checkbox ." }, { "idx": "cosqa-train-7165", "doc": "how to change the axis range in a plot in python for subplots", "code": "def set_xlimits(self, row, column, min=None, max=None):\n \"\"\"Set x-axis limits of a subplot.\n\n :param row,column: specify the subplot.\n :param min: minimal axis value\n :param max: maximum axis value\n\n \"\"\"\n subplot = self.get_subplot_at(row, column)\n subplot.set_xlimits(min, max)", "code_tokens": "def set_xlimits ( self , row , column , min = None , max = None ) : subplot = self . get_subplot_at ( row , column ) subplot . set_xlimits ( min , max )", "docstring_tokens": "Set x - axis limits of a subplot .", "label": 1, "retrieval_idx": 3455, "negative": "Like map but also chains the results ." }, { "idx": "cosqa-train-5794", "doc": "python view vector to asimuth elevation", "code": "def world_to_view(v):\n \"\"\"world coords to view coords; v an eu.Vector2, returns (float, float)\"\"\"\n return v.x * config.scale_x, v.y * config.scale_y", "code_tokens": "def world_to_view ( v ) : return v . x * config . scale_x , v . y * config . scale_y", "docstring_tokens": "world coords to view coords ; v an eu . Vector2 returns ( float float )", "label": 1, "retrieval_idx": 3293, "negative": "Returns the index of the earliest occurence of an item from a list in a string" }, { "idx": "cosqa-train-7664", "doc": "python sort data by variable", "code": "def sort_data(x, y):\n \"\"\"Sort the data.\"\"\"\n xy = sorted(zip(x, y))\n x, y = zip(*xy)\n return x, y", "code_tokens": "def sort_data ( x , y ) : xy = sorted ( zip ( x , y ) ) x , y = zip ( * xy ) return x , y", "docstring_tokens": "Sort the data .", "label": 1, "retrieval_idx": 3198, "negative": "Scale the input array" }, { "idx": "cosqa-train-10854", "doc": "compute the middle index in list python", "code": "def bisect_index(a, x):\n \"\"\" Find the leftmost index of an element in a list using binary search.\n\n Parameters\n ----------\n a: list\n A sorted list.\n x: arbitrary\n The element.\n\n Returns\n -------\n int\n The index.\n\n \"\"\"\n i = bisect.bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n raise ValueError", "code_tokens": "def bisect_index ( a , x ) : i = bisect . bisect_left ( a , x ) if i != len ( a ) and a [ i ] == x : return i raise ValueError", "docstring_tokens": "Find the leftmost index of an element in a list using binary search .", "label": 1, "retrieval_idx": 1588, "negative": "sort a list of files by filename only ignoring the directory names" }, { "idx": "cosqa-train-6992", "doc": "python josn dump to file", "code": "def save_notebook(work_notebook, write_file):\n \"\"\"Saves the Jupyter work_notebook to write_file\"\"\"\n with open(write_file, 'w') as out_nb:\n json.dump(work_notebook, out_nb, indent=2)", "code_tokens": "def save_notebook ( work_notebook , write_file ) : with open ( write_file , 'w' ) as out_nb : json . dump ( work_notebook , out_nb , indent = 2 )", "docstring_tokens": "Saves the Jupyter work_notebook to write_file", "label": 1, "retrieval_idx": 2462, "negative": "Computes all the integer factors of the number n" }, { "idx": "cosqa-train-13856", "doc": "python remove condition apply to dict", "code": "def _remove_dict_keys_with_value(dict_, val):\n \"\"\"Removes `dict` keys which have have `self` as value.\"\"\"\n return {k: v for k, v in dict_.items() if v is not val}", "code_tokens": "def _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val }", "docstring_tokens": "Removes dict keys which have have self as value .", "label": 1, "retrieval_idx": 185, "negative": "Synthesize white noise" }, { "idx": "cosqa-train-11770", "doc": "python remove directory tree if no files", "code": "def clean_out_dir(directory):\n \"\"\"\n Delete all the files and subdirectories in a directory.\n \"\"\"\n if not isinstance(directory, path):\n directory = path(directory)\n for file_path in directory.files():\n file_path.remove()\n for dir_path in directory.dirs():\n dir_path.rmtree()", "code_tokens": "def clean_out_dir ( directory ) : if not isinstance ( directory , path ) : directory = path ( directory ) for file_path in directory . files ( ) : file_path . remove ( ) for dir_path in directory . dirs ( ) : dir_path . rmtree ( )", "docstring_tokens": "Delete all the files and subdirectories in a directory .", "label": 1, "retrieval_idx": 1906, "negative": "Determine whether a system service is available" }, { "idx": "cosqa-train-13922", "doc": "how to pop a node off a stack python", "code": "def push(h, x):\n \"\"\"Push a new value into heap.\"\"\"\n h.push(x)\n up(h, h.size()-1)", "code_tokens": "def push ( h , x ) : h . push ( x ) up ( h , h . size ( ) - 1 )", "docstring_tokens": "Push a new value into heap .", "label": 1, "retrieval_idx": 47, "negative": "Turn an SQLAlchemy model into a dict of field names and values ." }, { "idx": "cosqa-train-15821", "doc": "python open file with exclusive access permissions", "code": "def chmod_add_excute(filename):\n \"\"\"\n Adds execute permission to file.\n :param filename:\n :return:\n \"\"\"\n st = os.stat(filename)\n os.chmod(filename, st.st_mode | stat.S_IEXEC)", "code_tokens": "def chmod_add_excute ( filename ) : st = os . stat ( filename ) os . chmod ( filename , st . st_mode | stat . S_IEXEC )", "docstring_tokens": "Adds execute permission to file . : param filename : : return :", "label": 1, "retrieval_idx": 1152, "negative": "Generate a unique ID that is somewhat guaranteed to be unique among all instances running at the same time ." }, { "idx": "cosqa-train-11046", "doc": "python gevent combine multiprocessing", "code": "def fetch_event(urls):\n \"\"\"\n This parallel fetcher uses gevent one uses gevent\n \"\"\"\n rs = (grequests.get(u) for u in urls)\n return [content.json() for content in grequests.map(rs)]", "code_tokens": "def fetch_event ( urls ) : rs = ( grequests . get ( u ) for u in urls ) return [ content . json ( ) for content in grequests . map ( rs ) ]", "docstring_tokens": "This parallel fetcher uses gevent one uses gevent", "label": 1, "retrieval_idx": 478, "negative": "Convert a Stripe API timestamp response ( unix epoch ) to a native datetime ." }, { "idx": "cosqa-train-6681", "doc": "create copy that doesn't alter original python", "code": "def copy(obj):\n def copy(self):\n \"\"\"\n Copy self to a new object.\n \"\"\"\n from copy import deepcopy\n\n return deepcopy(self)\n obj.copy = copy\n return obj", "code_tokens": "def copy ( obj ) : def copy ( self ) : \"\"\"\n Copy self to a new object.\n \"\"\" from copy import deepcopy return deepcopy ( self ) obj . copy = copy return obj", "docstring_tokens": "", "label": 1, "retrieval_idx": 1395, "negative": "Print all rows in this result query ." }, { "idx": "cosqa-train-16570", "doc": "remove trailing whitespace in python", "code": "def clean(s):\n \"\"\"Removes trailing whitespace on each line.\"\"\"\n lines = [l.rstrip() for l in s.split('\\n')]\n return '\\n'.join(lines)", "code_tokens": "def clean ( s ) : lines = [ l . rstrip ( ) for l in s . split ( '\\n' ) ] return '\\n' . join ( lines )", "docstring_tokens": "Removes trailing whitespace on each line .", "label": 1, "retrieval_idx": 2581, "negative": "Query the configured LDAP server ." }, { "idx": "cosqa-train-6463", "doc": "python default menuitem select", "code": "def get_python(self):\n \"\"\"Only return cursor instance if configured for multiselect\"\"\"\n if self.multiselect:\n return super(MultiSelectField, self).get_python()\n\n return self._get()", "code_tokens": "def get_python ( self ) : if self . multiselect : return super ( MultiSelectField , self ) . get_python ( ) return self . _get ( )", "docstring_tokens": "Only return cursor instance if configured for multiselect", "label": 1, "retrieval_idx": 3498, "negative": "Convert a CSV object to a numpy array ." }, { "idx": "cosqa-dev-408", "doc": "get sort indexes in a list python", "code": "def _index_ordering(redshift_list):\n \"\"\"\n\n :param redshift_list: list of redshifts\n :return: indexes in acending order to be evaluated (from z=0 to z=z_source)\n \"\"\"\n redshift_list = np.array(redshift_list)\n sort_index = np.argsort(redshift_list)\n return sort_index", "code_tokens": "def _index_ordering ( redshift_list ) : redshift_list = np . array ( redshift_list ) sort_index = np . argsort ( redshift_list ) return sort_index", "docstring_tokens": "", "label": 1, "retrieval_idx": 2034, "negative": "Simple directory walker" }, { "idx": "cosqa-train-14103", "doc": "how to start a new line in python gui", "code": "def go_to_new_line(self):\n \"\"\"Go to the end of the current line and create a new line\"\"\"\n self.stdkey_end(False, False)\n self.insert_text(self.get_line_separator())", "code_tokens": "def go_to_new_line ( self ) : self . stdkey_end ( False , False ) self . insert_text ( self . get_line_separator ( ) )", "docstring_tokens": "Go to the end of the current line and create a new line", "label": 1, "retrieval_idx": 428, "negative": "Retrun True if x is a valid YYYYMMDD date ; otherwise return False ." }, { "idx": "cosqa-train-15982", "doc": "how to get tuple of colors in image python", "code": "def rgba_bytes_tuple(self, x):\n \"\"\"Provides the color corresponding to value `x` in the\n form of a tuple (R,G,B,A) with int values between 0 and 255.\n \"\"\"\n return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))", "code_tokens": "def rgba_bytes_tuple ( self , x ) : return tuple ( int ( u * 255.9999 ) for u in self . rgba_floats_tuple ( x ) )", "docstring_tokens": "Provides the color corresponding to value x in the form of a tuple ( R G B A ) with int values between 0 and 255 .", "label": 1, "retrieval_idx": 1551, "negative": "Convenience function to print messages on a single line in the terminal" }, { "idx": "cosqa-train-12120", "doc": "make datetime aware python", "code": "def date_to_datetime(x):\n \"\"\"Convert a date into a datetime\"\"\"\n if not isinstance(x, datetime) and isinstance(x, date):\n return datetime.combine(x, time())\n return x", "code_tokens": "def date_to_datetime ( x ) : if not isinstance ( x , datetime ) and isinstance ( x , date ) : return datetime . combine ( x , time ( ) ) return x", "docstring_tokens": "Convert a date into a datetime", "label": 1, "retrieval_idx": 1753, "negative": "Under UNIX : is a keystroke available?" }, { "idx": "cosqa-train-8617", "doc": "python dict drop empty", "code": "def purge_dict(idict):\n \"\"\"Remove null items from a dictionary \"\"\"\n odict = {}\n for key, val in idict.items():\n if is_null(val):\n continue\n odict[key] = val\n return odict", "code_tokens": "def purge_dict ( idict ) : odict = { } for key , val in idict . items ( ) : if is_null ( val ) : continue odict [ key ] = val return odict", "docstring_tokens": "Remove null items from a dictionary", "label": 1, "retrieval_idx": 1017, "negative": "Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process" }, { "idx": "cosqa-train-7344", "doc": "python pretty print without sort", "code": "def pprint(obj, verbose=False, max_width=79, newline='\\n'):\n \"\"\"\n Like `pretty` but print to stdout.\n \"\"\"\n printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline)\n printer.pretty(obj)\n printer.flush()\n sys.stdout.write(newline)\n sys.stdout.flush()", "code_tokens": "def pprint ( obj , verbose = False , max_width = 79 , newline = '\\n' ) : printer = RepresentationPrinter ( sys . stdout , verbose , max_width , newline ) printer . pretty ( obj ) printer . flush ( ) sys . stdout . write ( newline ) sys . stdout . flush ( )", "docstring_tokens": "Like pretty but print to stdout .", "label": 1, "retrieval_idx": 2225, "negative": "world coords to view coords ; v an eu . Vector2 returns ( float float )" }, { "idx": "cosqa-train-12579", "doc": "python check if interactive", "code": "def determine_interactive(self):\n\t\t\"\"\"Determine whether we're in an interactive shell.\n\t\tSets interactivity off if appropriate.\n\t\tcf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process\n\t\t\"\"\"\n\t\ttry:\n\t\t\tif not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):\n\t\t\t\tself.interactive = 0\n\t\t\t\treturn False\n\t\texcept Exception:\n\t\t\tself.interactive = 0\n\t\t\treturn False\n\t\tif self.interactive == 0:\n\t\t\treturn False\n\t\treturn True", "code_tokens": "def determine_interactive ( self ) : try : if not sys . stdout . isatty ( ) or os . getpgrp ( ) != os . tcgetpgrp ( sys . stdout . fileno ( ) ) : self . interactive = 0 return False except Exception : self . interactive = 0 return False if self . interactive == 0 : return False return True", "docstring_tokens": "Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process", "label": 1, "retrieval_idx": 2779, "negative": "Removes trailing whitespace on each line ." }, { "idx": "cosqa-train-13747", "doc": "python pid determine existence", "code": "def pid_exists(pid):\n \"\"\" Determines if a system process identifer exists in process table.\n \"\"\"\n try:\n os.kill(pid, 0)\n except OSError as exc:\n return exc.errno == errno.EPERM\n else:\n return True", "code_tokens": "def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True", "docstring_tokens": "Determines if a system process identifer exists in process table .", "label": 1, "retrieval_idx": 528, "negative": "Labels plots and saves file" }, { "idx": "cosqa-train-9532", "doc": "python pymongo insert without duplicatte", "code": "def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs):\n \"\"\"\n Inserts a single document into a mongo collection\n https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one\n \"\"\"\n collection = self.get_collection(mongo_collection, mongo_db=mongo_db)\n\n return collection.insert_one(doc, **kwargs)", "code_tokens": "def insert_one ( self , mongo_collection , doc , mongo_db = None , * * kwargs ) : collection = self . get_collection ( mongo_collection , mongo_db = mongo_db ) return collection . insert_one ( doc , * * kwargs )", "docstring_tokens": "Inserts a single document into a mongo collection https : // api . mongodb . com / python / current / api / pymongo / collection . html#pymongo . collection . Collection . insert_one", "label": 1, "retrieval_idx": 4267, "negative": "Forward mouse cursor position events to the example" }, { "idx": "cosqa-train-13962", "doc": "how to read json files with multiple object python", "code": "def _read_json_file(self, json_file):\n \"\"\" Helper function to read JSON file as OrderedDict \"\"\"\n\n self.log.debug(\"Reading '%s' JSON file...\" % json_file)\n\n with open(json_file, 'r') as f:\n return json.load(f, object_pairs_hook=OrderedDict)", "code_tokens": "def _read_json_file ( self , json_file ) : self . log . debug ( \"Reading '%s' JSON file...\" % json_file ) with open ( json_file , 'r' ) as f : return json . load ( f , object_pairs_hook = OrderedDict )", "docstring_tokens": "Helper function to read JSON file as OrderedDict", "label": 1, "retrieval_idx": 3131, "negative": "Print all rows in this result query ." }, { "idx": "cosqa-train-6510", "doc": "python discord leave voice channel", "code": "async def join(self, ctx, *, channel: discord.VoiceChannel):\n \"\"\"Joins a voice channel\"\"\"\n\n if ctx.voice_client is not None:\n return await ctx.voice_client.move_to(channel)\n\n await channel.connect()", "code_tokens": "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 ( )", "docstring_tokens": "Joins a voice channel", "label": 1, "retrieval_idx": 1923, "negative": "If item is not in lst add item to list at its sorted position" }, { "idx": "cosqa-train-9993", "doc": "python unittest make tests discoverable", "code": "def test():\n \"\"\"Run the unit tests.\"\"\"\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)", "code_tokens": "def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests )", "docstring_tokens": "Run the unit tests .", "label": 1, "retrieval_idx": 199, "negative": "Return a list of indexes of substr . If substr not found list is empty ." }, { "idx": "cosqa-train-7967", "doc": "multiline text send message python", "code": "async def _send_plain_text(self, request: Request, stack: Stack):\n \"\"\"\n Sends plain text using `_send_text()`.\n \"\"\"\n\n await self._send_text(request, stack, None)", "code_tokens": "async def _send_plain_text ( self , request : Request , stack : Stack ) : await self . _send_text ( request , stack , None )", "docstring_tokens": "Sends plain text using _send_text () .", "label": 1, "retrieval_idx": 1510, "negative": "Converts list to string with comma separated values . For string is no - op ." }, { "idx": "cosqa-train-6837", "doc": "extract integers from string in python", "code": "def get_numbers(s):\n \"\"\"Extracts all integers from a string an return them in a list\"\"\"\n\n result = map(int, re.findall(r'[0-9]+', unicode(s)))\n return result + [1] * (2 - len(result))", "code_tokens": "def get_numbers ( s ) : result = map ( int , re . findall ( r'[0-9]+' , unicode ( s ) ) ) return result + [ 1 ] * ( 2 - len ( result ) )", "docstring_tokens": "Extracts all integers from a string an return them in a list", "label": 1, "retrieval_idx": 2828, "negative": "Return a list of the table names in the database ." }, { "idx": "cosqa-train-14143", "doc": "python take a string after the title", "code": "def _format_title_string(self, title_string):\n \"\"\" format mpv's title \"\"\"\n return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))", "code_tokens": "def _format_title_string ( self , title_string ) : return self . _title_string_format_text_tag ( title_string . replace ( self . icy_tokkens [ 0 ] , self . icy_title_prefix ) )", "docstring_tokens": "format mpv s title", "label": 1, "retrieval_idx": 4355, "negative": "" }, { "idx": "cosqa-dev-130", "doc": "how to randomly select rows in ndarray in python", "code": "def downsample(array, k):\n \"\"\"Choose k random elements of array.\"\"\"\n length = array.shape[0]\n indices = random.sample(xrange(length), k)\n return array[indices]", "code_tokens": "def downsample ( array , k ) : length = array . shape [ 0 ] indices = random . sample ( xrange ( length ) , k ) return array [ indices ]", "docstring_tokens": "Choose k random elements of array .", "label": 1, "retrieval_idx": 794, "negative": "r Clean up whitespace in column names . See better version at pugnlp . clean_columns" }, { "idx": "cosqa-train-13902", "doc": "how to open a file with a path in python", "code": "def get_file_string(filepath):\n \"\"\"Get string from file.\"\"\"\n with open(os.path.abspath(filepath)) as f:\n return f.read()", "code_tokens": "def get_file_string ( filepath ) : with open ( os . path . abspath ( filepath ) ) as f : return f . read ( )", "docstring_tokens": "Get string from file .", "label": 1, "retrieval_idx": 1051, "negative": "Write the ROI model to a FITS file ." }, { "idx": "cosqa-dev-123", "doc": "python count distance between two vectors", "code": "def distance(vec1, vec2):\n \"\"\"Calculate the distance between two Vectors\"\"\"\n if isinstance(vec1, Vector2) \\\n and isinstance(vec2, Vector2):\n dist_vec = vec2 - vec1\n return dist_vec.length()\n else:\n raise TypeError(\"vec1 and vec2 must be Vector2's\")", "code_tokens": "def distance ( vec1 , vec2 ) : if isinstance ( vec1 , Vector2 ) and isinstance ( vec2 , Vector2 ) : dist_vec = vec2 - vec1 return dist_vec . length ( ) else : raise TypeError ( \"vec1 and vec2 must be Vector2's\" )", "docstring_tokens": "Calculate the distance between two Vectors", "label": 1, "retrieval_idx": 2719, "negative": "Convenience function to print messages on a single line in the terminal" }, { "idx": "cosqa-train-10937", "doc": "python get dimensions of list", "code": "def get_dimension_array(array):\n \"\"\"\n Get dimension of an array getting the number of rows and the max num of\n columns.\n \"\"\"\n if all(isinstance(el, list) for el in array):\n result = [len(array), len(max([x for x in array], key=len,))]\n\n # elif array and isinstance(array, list):\n else:\n result = [len(array), 1]\n\n return result", "code_tokens": "def get_dimension_array ( array ) : if all ( isinstance ( el , list ) for el in array ) : result = [ len ( array ) , len ( max ( [ x for x in array ] , key = len , ) ) ] # elif array and isinstance(array, list): else : result = [ len ( array ) , 1 ] return result", "docstring_tokens": "Get dimension of an array getting the number of rows and the max num of columns .", "label": 1, "retrieval_idx": 2080, "negative": "Wrap an AST Call node to lambda expression node . call : ast . Call node" }, { "idx": "cosqa-train-6627", "doc": "python filter lowpass minmum cutoff frequency", "code": "def fft_bandpassfilter(data, fs, lowcut, highcut):\n \"\"\"\n http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801\n \"\"\"\n fft = np.fft.fft(data)\n # n = len(data)\n # timestep = 1.0 / fs\n # freq = np.fft.fftfreq(n, d=timestep)\n bp = fft.copy()\n\n # Zero out fft coefficients\n # bp[10:-10] = 0\n\n # Normalise\n # bp *= real(fft.dot(fft))/real(bp.dot(bp))\n\n bp *= fft.dot(fft) / bp.dot(bp)\n\n # must multipy by 2 to get the correct amplitude\n ibp = 12 * np.fft.ifft(bp)\n return ibp", "code_tokens": "def fft_bandpassfilter ( data , fs , lowcut , highcut ) : fft = np . fft . fft ( data ) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft . copy ( ) # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft . dot ( fft ) / bp . dot ( bp ) # must multipy by 2 to get the correct amplitude ibp = 12 * np . fft . ifft ( bp ) return ibp", "docstring_tokens": "http : // www . swharden . com / blog / 2009 - 01 - 21 - signal - filtering - with - python / #comment - 16801", "label": 1, "retrieval_idx": 1552, "negative": "Like dict but does not hold any null values ." }, { "idx": "cosqa-train-12362", "doc": "python 3, seperate a string into a list at comma", "code": "def comma_delimited_to_list(list_param):\n \"\"\"Convert comma-delimited list / string into a list of strings\n\n :param list_param: Comma-delimited string\n :type list_param: str | unicode\n :return: A list of strings\n :rtype: list\n \"\"\"\n if isinstance(list_param, list):\n return list_param\n if isinstance(list_param, str):\n return list_param.split(',')\n else:\n return []", "code_tokens": "def comma_delimited_to_list ( list_param ) : if isinstance ( list_param , list ) : return list_param if isinstance ( list_param , str ) : return list_param . split ( ',' ) else : return [ ]", "docstring_tokens": "Convert comma - delimited list / string into a list of strings", "label": 1, "retrieval_idx": 3278, "negative": "takes flags returns indexes of True values" }, { "idx": "cosqa-train-19381", "doc": "how to delete an element in a python dictionary", "code": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, delete\n ``d[key]`` if it exists.\n \"\"\"\n for d in dict_list:\n d.pop(key, None)", "code_tokens": "def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )", "docstring_tokens": "Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .", "label": 1, "retrieval_idx": 5594, "negative": "" }, { "idx": "cosqa-train-9187", "doc": "how know if the box was selected in checkbox in python", "code": "def set_value(self, value):\n \"\"\"Set value of the checkbox.\n\n Parameters\n ----------\n value : bool\n value for the checkbox\n\n \"\"\"\n if value:\n self.setChecked(Qt.Checked)\n else:\n self.setChecked(Qt.Unchecked)", "code_tokens": "def set_value ( self , value ) : if value : self . setChecked ( Qt . Checked ) else : self . setChecked ( Qt . Unchecked )", "docstring_tokens": "Set value of the checkbox .", "label": 1, "retrieval_idx": 1655, "negative": "Reload the device ." }, { "idx": "cosqa-train-10404", "doc": "standard scalar function in python", "code": "def Softsign(a):\n \"\"\"\n Softsign op.\n \"\"\"\n return np.divide(a, np.add(np.abs(a), 1)),", "code_tokens": "def Softsign ( a ) : return np . divide ( a , np . add ( np . abs ( a ) , 1 ) ) ,", "docstring_tokens": "Softsign op .", "label": 1, "retrieval_idx": 2107, "negative": "Remove comments and empty lines" }, { "idx": "cosqa-train-9537", "doc": "python random gaussian distribution noise", "code": "def rlognormal(mu, tau, size=None):\n \"\"\"\n Return random lognormal variates.\n \"\"\"\n\n return np.random.lognormal(mu, np.sqrt(1. / tau), size)", "code_tokens": "def rlognormal ( mu , tau , size = None ) : return np . random . lognormal ( mu , np . sqrt ( 1. / tau ) , size )", "docstring_tokens": "Return random lognormal variates .", "label": 1, "retrieval_idx": 551, "negative": "Returns whether a path names an existing executable file ." }, { "idx": "cosqa-train-12390", "doc": "return the number of numeric attributes in python", "code": "def __len__(self):\n\t\t\"\"\"Get a list of the public data attributes.\"\"\"\n\t\treturn len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])", "code_tokens": "def __len__ ( self ) : return len ( [ i for i in ( set ( dir ( self ) ) - self . _STANDARD_ATTRS ) if i [ 0 ] != '_' ] )", "docstring_tokens": "Get a list of the public data attributes .", "label": 1, "retrieval_idx": 4818, "negative": "Print emphasized good the given txt message" }, { "idx": "cosqa-train-7322", "doc": "python pil camera capture", "code": "def read(self):\n \"\"\"https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image\"\"\"\n stream = BytesIO()\n self.cam.capture(stream, format='png')\n # \"Rewind\" the stream to the beginning so we can read its content\n stream.seek(0)\n return Image.open(stream)", "code_tokens": "def read ( self ) : stream = BytesIO ( ) self . cam . capture ( stream , format = 'png' ) # \"Rewind\" the stream to the beginning so we can read its content stream . seek ( 0 ) return Image . open ( stream )", "docstring_tokens": "https : // picamera . readthedocs . io / en / release - 1 . 13 / recipes1 . html#capturing - to - a - pil - image", "label": 1, "retrieval_idx": 3731, "negative": "Scroll both categories Canvas and scrolling container" }, { "idx": "cosqa-train-12959", "doc": "python flask create cookie expiration", "code": "def logout(cache):\n \"\"\"\n Logs out the current session by removing it from the cache. This is\n expected to only occur when a session has\n \"\"\"\n cache.set(flask.session['auth0_key'], None)\n flask.session.clear()\n return True", "code_tokens": "def logout ( cache ) : cache . set ( flask . session [ 'auth0_key' ] , None ) flask . session . clear ( ) return True", "docstring_tokens": "Logs out the current session by removing it from the cache . This is expected to only occur when a session has", "label": 1, "retrieval_idx": 1809, "negative": "Return scaled image size in ( width height ) format . The scaling preserves the aspect ratio . If PIL is not found returns None ." }, { "idx": "cosqa-train-11983", "doc": "python sqlalchemy model *", "code": "def save(self):\n \"\"\"Saves the updated model to the current entity db.\n \"\"\"\n self.session.add(self)\n self.session.flush()\n return self", "code_tokens": "def save ( self ) : self . session . add ( self ) self . session . flush ( ) return self", "docstring_tokens": "Saves the updated model to the current entity db .", "label": 1, "retrieval_idx": 3229, "negative": "Add subparser" }, { "idx": "cosqa-train-636", "doc": "python how to move to next command in for loop", "code": "def do_next(self, args):\n \"\"\"Step over the next statement\n \"\"\"\n self._do_print_from_last_cmd = True\n self._interp.step_over()\n return True", "code_tokens": "def do_next ( self , args ) : self . _do_print_from_last_cmd = True self . _interp . step_over ( ) return True", "docstring_tokens": "Step over the next statement", "label": 1, "retrieval_idx": 36, "negative": "Hacked run function which installs the trace ." }, { "idx": "cosqa-train-10526", "doc": "python check if object is a char", "code": "def is_string(obj):\n \"\"\"Is this a string.\n\n :param object obj:\n :rtype: bool\n \"\"\"\n if PYTHON3:\n str_type = (bytes, str)\n else:\n str_type = (bytes, str, unicode)\n return isinstance(obj, str_type)", "code_tokens": "def is_string ( obj ) : if PYTHON3 : str_type = ( bytes , str ) else : str_type = ( bytes , str , unicode ) return isinstance ( obj , str_type )", "docstring_tokens": "Is this a string .", "label": 1, "retrieval_idx": 1789, "negative": "Checks if the given type is a builtin one ." }, { "idx": "cosqa-train-7078", "doc": "how to achieve logarithmic complexity in python", "code": "def log_loss(preds, labels):\n \"\"\"Logarithmic loss with non-necessarily-binary labels.\"\"\"\n log_likelihood = np.sum(labels * np.log(preds)) / len(preds)\n return -log_likelihood", "code_tokens": "def log_loss ( preds , labels ) : log_likelihood = np . sum ( labels * np . log ( preds ) ) / len ( preds ) return - log_likelihood", "docstring_tokens": "Logarithmic loss with non - necessarily - binary labels .", "label": 1, "retrieval_idx": 1366, "negative": "Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) ." }, { "idx": "cosqa-train-4971", "doc": "python listbox scrollbar not tk", "code": "def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs):\n \"\"\"\n Create a Listbox with a vertical scrollbar.\n\n :param master: master widget\n :type master: widget\n :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`)\n :type compound: str\n :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar`\n :type autohidescrollbar: bool\n :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer\n \"\"\"\n ttk.Frame.__init__(self, master)\n self.columnconfigure(1, weight=1)\n self.rowconfigure(0, weight=1)\n self.listbox = tk.Listbox(self, **kwargs)\n if autohidescrollbar:\n self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n else:\n self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview)\n self.config_listbox(yscrollcommand=self.scrollbar.set)\n if compound is not tk.LEFT and compound is not tk.RIGHT:\n raise ValueError(\"Invalid compound value passed: {0}\".format(compound))\n self.__compound = compound\n self._grid_widgets()", "code_tokens": "def __init__ ( self , master = None , compound = tk . RIGHT , autohidescrollbar = True , * * kwargs ) : ttk . Frame . __init__ ( self , master ) self . columnconfigure ( 1 , weight = 1 ) self . rowconfigure ( 0 , weight = 1 ) self . listbox = tk . Listbox ( self , * * kwargs ) if autohidescrollbar : self . scrollbar = AutoHideScrollbar ( self , orient = tk . VERTICAL , command = self . listbox . yview ) else : self . scrollbar = ttk . Scrollbar ( self , orient = tk . VERTICAL , command = self . listbox . yview ) self . config_listbox ( yscrollcommand = self . scrollbar . set ) if compound is not tk . LEFT and compound is not tk . RIGHT : raise ValueError ( \"Invalid compound value passed: {0}\" . format ( compound ) ) self . __compound = compound self . _grid_widgets ( )", "docstring_tokens": "Create a Listbox with a vertical scrollbar .", "label": 1, "retrieval_idx": 2585, "negative": "Use the S3 SWAG backend ." }, { "idx": "cosqa-train-18815", "doc": "identify the most common number in an array python", "code": "def most_significant_bit(lst: np.ndarray) -> int:\n \"\"\"\n A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,\n i.e. the first position where a 1 appears, reading left to right.\n\n :param lst: a 1d array of 0s and 1s with at least one 1\n :return: the first position in lst that a 1 appears\n \"\"\"\n return np.argwhere(np.asarray(lst) == 1)[0][0]", "code_tokens": "def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]", "docstring_tokens": "A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .", "label": 1, "retrieval_idx": 5604, "negative": "function : to be called with each stream element as its only argument" }, { "idx": "cosqa-train-8090", "doc": "pull multiple values to make table python", "code": "def _tab(content):\n \"\"\"\n Helper funcation that converts text-based get response\n to tab separated values for additional manipulation.\n \"\"\"\n response = _data_frame(content).to_csv(index=False,sep='\\t')\n return response", "code_tokens": "def _tab ( content ) : response = _data_frame ( content ) . to_csv ( index = False , sep = '\\t' ) return response", "docstring_tokens": "Helper funcation that converts text - based get response to tab separated values for additional manipulation .", "label": 1, "retrieval_idx": 3949, "negative": "writes the line and count newlines after the line" }, { "idx": "cosqa-train-10324", "doc": "python adjust data to normal distribution", "code": "def normalize(data):\n \"\"\"Normalize the data to be in the [0, 1] range.\n\n :param data:\n :return: normalized data\n \"\"\"\n out_data = data.copy()\n\n for i, sample in enumerate(out_data):\n out_data[i] /= sum(out_data[i])\n\n return out_data", "code_tokens": "def normalize ( data ) : out_data = data . copy ( ) for i , sample in enumerate ( out_data ) : out_data [ i ] /= sum ( out_data [ i ] ) return out_data", "docstring_tokens": "Normalize the data to be in the [ 0 1 ] range .", "label": 1, "retrieval_idx": 4155, "negative": "Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate" }, { "idx": "cosqa-train-17806", "doc": "python check if float has no floating points", "code": "def is_finite(value: Any) -> bool:\n \"\"\"Return true if a value is a finite number.\"\"\"\n return isinstance(value, int) or (isinstance(value, float) and isfinite(value))", "code_tokens": "def is_finite ( value : Any ) -> bool : return isinstance ( value , int ) or ( isinstance ( value , float ) and isfinite ( value ) )", "docstring_tokens": "Return true if a value is a finite number .", "label": 1, "retrieval_idx": 5686, "negative": "A non - negative integer ." }, { "idx": "cosqa-train-18378", "doc": "string remove the last blank python", "code": "def remove_blank_lines(string):\n \"\"\" Removes all blank lines in @string\n\n -> #str without blank lines\n \"\"\"\n return \"\\n\".join(line\n for line in string.split(\"\\n\")\n if len(line.strip()))", "code_tokens": "def remove_blank_lines ( string ) : return \"\\n\" . join ( line for line in string . split ( \"\\n\" ) if len ( line . strip ( ) ) )", "docstring_tokens": "Removes all blank lines in @string", "label": 1, "retrieval_idx": 5725, "negative": "Print emphasized good the given txt message" }, { "idx": "cosqa-train-15422", "doc": "python how to display object attributes", "code": "def _repr(obj):\n \"\"\"Show the received object as precise as possible.\"\"\"\n vals = \", \".join(\"{}={!r}\".format(\n name, getattr(obj, name)) for name in obj._attribs)\n if vals:\n t = \"{}(name={}, {})\".format(obj.__class__.__name__, obj.name, vals)\n else:\n t = \"{}(name={})\".format(obj.__class__.__name__, obj.name)\n return t", "code_tokens": "def _repr ( obj ) : vals = \", \" . join ( \"{}={!r}\" . format ( name , getattr ( obj , name ) ) for name in obj . _attribs ) if vals : t = \"{}(name={}, {})\" . format ( obj . __class__ . __name__ , obj . name , vals ) else : t = \"{}(name={})\" . format ( obj . __class__ . __name__ , obj . name ) return t", "docstring_tokens": "Show the received object as precise as possible .", "label": 1, "retrieval_idx": 1533, "negative": "Display productpage with normal user and test user buttons" }, { "idx": "cosqa-train-19985", "doc": "determine if a list of numbers contains duplicates python", "code": "def find_duplicates(l: list) -> set:\n \"\"\"\n Return the duplicates in a list.\n\n The function relies on\n https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .\n Parameters\n ----------\n l : list\n Name\n\n Returns\n -------\n set\n Duplicated values\n\n >>> find_duplicates([1,2,3])\n set()\n >>> find_duplicates([1,2,1])\n {1}\n \"\"\"\n return set([x for x in l if l.count(x) > 1])", "code_tokens": "def find_duplicates ( l : list ) -> set : return set ( [ x for x in l if l . count ( x ) > 1 ] )", "docstring_tokens": "Return the duplicates in a list .", "label": 1, "retrieval_idx": 5743, "negative": "Return a new copied dictionary without the keys with None values from the given Mapping object ." }, { "idx": "cosqa-train-12927", "doc": "python figure add title label size", "code": "def label_saves(name):\n \"\"\"Labels plots and saves file\"\"\"\n plt.legend(loc=0)\n plt.ylim([0, 1.025])\n plt.xlabel('$U/D$', fontsize=20)\n plt.ylabel('$Z$', fontsize=20)\n plt.savefig(name, dpi=300, format='png',\n transparent=False, bbox_inches='tight', pad_inches=0.05)", "code_tokens": "def label_saves ( name ) : plt . legend ( loc = 0 ) plt . ylim ( [ 0 , 1.025 ] ) plt . xlabel ( '$U/D$' , fontsize = 20 ) plt . ylabel ( '$Z$' , fontsize = 20 ) plt . savefig ( name , dpi = 300 , format = 'png' , transparent = False , bbox_inches = 'tight' , pad_inches = 0.05 )", "docstring_tokens": "Labels plots and saves file", "label": 1, "retrieval_idx": 4900, "negative": "Callback to go to the next tab . Called by the accel key ." }, { "idx": "cosqa-train-19204", "doc": "python networkx longest path directed acyclic graph", "code": "def dag_longest_path(graph, source, target):\n \"\"\"\n Finds the longest path in a dag between two nodes\n \"\"\"\n if source == target:\n return [source]\n allpaths = nx.all_simple_paths(graph, source, target)\n longest_path = []\n for l in allpaths:\n if len(l) > len(longest_path):\n longest_path = l\n return longest_path", "code_tokens": "def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path", "docstring_tokens": "Finds the longest path in a dag between two nodes", "label": 1, "retrieval_idx": 5910, "negative": "Returns the last location of the minimal value of x . The position is calculated relatively to the length of x ." }, { "idx": "cosqa-train-14117", "doc": "how to take list as input in python seperated with spaces", "code": "def itemlist(item, sep, suppress_trailing=True):\n \"\"\"Create a list of items seperated by seps.\"\"\"\n return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))", "code_tokens": "def itemlist ( item , sep , suppress_trailing = True ) : return condense ( item + ZeroOrMore ( addspace ( sep + item ) ) + Optional ( sep . suppress ( ) if suppress_trailing else sep ) )", "docstring_tokens": "Create a list of items seperated by seps .", "label": 1, "retrieval_idx": 5110, "negative": "Convert human readable string to datetime . datetime ." }, { "idx": "cosqa-train-12036", "doc": "is a list in python an array", "code": "def to_list(self):\n \"\"\"Convert this confusion matrix into a 2x2 plain list of values.\"\"\"\n return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],\n [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]", "code_tokens": "def to_list ( self ) : return [ [ int ( self . table . cell_values [ 0 ] [ 1 ] ) , int ( self . table . cell_values [ 0 ] [ 2 ] ) ] , [ int ( self . table . cell_values [ 1 ] [ 1 ] ) , int ( self . table . cell_values [ 1 ] [ 2 ] ) ] ]", "docstring_tokens": "Convert this confusion matrix into a 2x2 plain list of values .", "label": 1, "retrieval_idx": 2686, "negative": "Isolates x from its equivalence class ." }, { "idx": "cosqa-train-10603", "doc": "python cosine similarity of two vectors", "code": "def cross_v2(vec1, vec2):\n \"\"\"Return the crossproduct of the two vectors as a Vec2.\n Cross product doesn't really make sense in 2D, but return the Z component\n of the 3d result.\n \"\"\"\n\n return vec1.y * vec2.x - vec1.x * vec2.y", "code_tokens": "def cross_v2 ( vec1 , vec2 ) : return vec1 . y * vec2 . x - vec1 . x * vec2 . y", "docstring_tokens": "Return the crossproduct of the two vectors as a Vec2 . Cross product doesn t really make sense in 2D but return the Z component of the 3d result .", "label": 1, "retrieval_idx": 4513, "negative": "__init__ : Performs basic initialisations" }, { "idx": "cosqa-train-13884", "doc": "how to model a sphere python", "code": "def Fsphere(q, R):\n \"\"\"Scattering form-factor amplitude of a sphere normalized to F(q=0)=V\n\n Inputs:\n -------\n ``q``: independent variable\n ``R``: sphere radius\n\n Formula:\n --------\n ``4*pi/q^3 * (sin(qR) - qR*cos(qR))``\n \"\"\"\n return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))", "code_tokens": "def Fsphere ( q , R ) : return 4 * np . pi / q ** 3 * ( np . sin ( q * R ) - q * R * np . cos ( q * R ) )", "docstring_tokens": "Scattering form - factor amplitude of a sphere normalized to F ( q = 0 ) = V", "label": 1, "retrieval_idx": 1008, "negative": "decode ( bytearray raw = False ) - > value" }, { "idx": "cosqa-train-13567", "doc": "how to check paths in python", "code": "def is_readable_dir(path):\n \"\"\"Returns whether a path names an existing directory we can list and read files from.\"\"\"\n return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)", "code_tokens": "def is_readable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . R_OK ) and os . access ( path , os . X_OK )", "docstring_tokens": "Returns whether a path names an existing directory we can list and read files from .", "label": 1, "retrieval_idx": 1644, "negative": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ..." }, { "idx": "cosqa-train-9910", "doc": "python test truth value of list", "code": "def assert_exactly_one_true(bool_list):\n \"\"\"This method asserts that only one value of the provided list is True.\n\n :param bool_list: List of booleans to check\n :return: True if only one value is True, False otherwise\n \"\"\"\n assert isinstance(bool_list, list)\n counter = 0\n for item in bool_list:\n if item:\n counter += 1\n return counter == 1", "code_tokens": "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", "docstring_tokens": "This method asserts that only one value of the provided list is True .", "label": 1, "retrieval_idx": 69, "negative": "Check if arg is a valid file that already exists on the file system ." }, { "idx": "cosqa-train-3556", "doc": "python string value of enum", "code": "def EnumValueName(self, enum, value):\n \"\"\"Returns the string name of an enum value.\n\n This is just a small helper method to simplify a common operation.\n\n Args:\n enum: string name of the Enum.\n value: int, value of the enum.\n\n Returns:\n string name of the enum value.\n\n Raises:\n KeyError if either the Enum doesn't exist or the value is not a valid\n value for the enum.\n \"\"\"\n return self.enum_types_by_name[enum].values_by_number[value].name", "code_tokens": "def EnumValueName ( self , enum , value ) : return self . enum_types_by_name [ enum ] . values_by_number [ value ] . name", "docstring_tokens": "Returns the string name of an enum value .", "label": 1, "retrieval_idx": 471, "negative": "Imputes data set containing Nan values" }, { "idx": "cosqa-train-6407", "doc": "python create null pointer with ctypes", "code": "def POINTER(obj):\n \"\"\"\n Create ctypes pointer to object.\n\n Notes\n -----\n This function converts None to a real NULL pointer because of bug\n in how ctypes handles None on 64-bit platforms.\n\n \"\"\"\n\n p = ctypes.POINTER(obj)\n if not isinstance(p.from_param, classmethod):\n def from_param(cls, x):\n if x is None:\n return cls()\n else:\n return x\n p.from_param = classmethod(from_param)\n\n return p", "code_tokens": "def POINTER ( obj ) : p = ctypes . POINTER ( obj ) if not isinstance ( p . from_param , classmethod ) : def from_param ( cls , x ) : if x is None : return cls ( ) else : return x p . from_param = classmethod ( from_param ) return p", "docstring_tokens": "Create ctypes pointer to object .", "label": 1, "retrieval_idx": 1683, "negative": "Parses hostname from URL . : param url : URL : return : hostname" }, { "idx": "cosqa-train-11407", "doc": "python md5 hash string", "code": "def md5_string(s):\n \"\"\"\n Shortcut to create md5 hash\n :param s:\n :return:\n \"\"\"\n m = hashlib.md5()\n m.update(s)\n return str(m.hexdigest())", "code_tokens": "def md5_string ( s ) : m = hashlib . md5 ( ) m . update ( s ) return str ( m . hexdigest ( ) )", "docstring_tokens": "Shortcut to create md5 hash : param s : : return :", "label": 1, "retrieval_idx": 1193, "negative": "Checks if the given type is a builtin one ." }, { "idx": "cosqa-train-11151", "doc": "python how to match dictionarys", "code": "def intersect(d1, d2):\n \"\"\"Intersect dictionaries d1 and d2 by key *and* value.\"\"\"\n return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])", "code_tokens": "def intersect ( d1 , d2 ) : return dict ( ( k , d1 [ k ] ) for k in d1 if k in d2 and d1 [ k ] == d2 [ k ] )", "docstring_tokens": "Intersect dictionaries d1 and d2 by key * and * value .", "label": 1, "retrieval_idx": 556, "negative": "Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate" }, { "idx": "cosqa-train-10325", "doc": "select elements from a list, then delete these elements in the original list python", "code": "def remove_elements(target, indices):\n \"\"\"Remove multiple elements from a list and return result.\n This implementation is faster than the alternative below.\n Also note the creation of a new list to avoid altering the\n original. We don't have any current use for the original\n intact list, but may in the future...\"\"\"\n\n copied = list(target)\n\n for index in reversed(indices):\n del copied[index]\n return copied", "code_tokens": "def remove_elements ( target , indices ) : copied = list ( target ) for index in reversed ( indices ) : del copied [ index ] return copied", "docstring_tokens": "Remove multiple elements from a list and return result . This implementation is faster than the alternative below . Also note the creation of a new list to avoid altering the original . We don t have any current use for the original intact list but may in the future ...", "label": 1, "retrieval_idx": 837, "negative": "Load JSON file" }, { "idx": "cosqa-train-8092", "doc": "pybool to c++ python 3", "code": "def convertToBool():\n \"\"\" Convert a byte value to boolean (0 or 1) if\n the global flag strictBool is True\n \"\"\"\n if not OPTIONS.strictBool.value:\n return []\n\n REQUIRES.add('strictbool.asm')\n\n result = []\n result.append('pop af')\n result.append('call __NORMALIZE_BOOLEAN')\n result.append('push af')\n\n return result", "code_tokens": "def convertToBool ( ) : if not OPTIONS . strictBool . value : return [ ] REQUIRES . add ( 'strictbool.asm' ) result = [ ] result . append ( 'pop af' ) result . append ( 'call __NORMALIZE_BOOLEAN' ) result . append ( 'push af' ) return result", "docstring_tokens": "Convert a byte value to boolean ( 0 or 1 ) if the global flag strictBool is True", "label": 1, "retrieval_idx": 257, "negative": "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 )" }, { "idx": "cosqa-train-11296", "doc": "how to add a ? in python url", "code": "def append_query_parameter(url, parameters, ignore_if_exists=True):\n \"\"\" quick and dirty appending of query parameters to a url \"\"\"\n if ignore_if_exists:\n for key in parameters.keys():\n if key + \"=\" in url:\n del parameters[key]\n parameters_str = \"&\".join(k + \"=\" + v for k, v in parameters.items())\n append_token = \"&\" if \"?\" in url else \"?\"\n return url + append_token + parameters_str", "code_tokens": "def append_query_parameter ( url , parameters , ignore_if_exists = True ) : if ignore_if_exists : for key in parameters . keys ( ) : if key + \"=\" in url : del parameters [ key ] parameters_str = \"&\" . join ( k + \"=\" + v for k , v in parameters . items ( ) ) append_token = \"&\" if \"?\" in url else \"?\" return url + append_token + parameters_str", "docstring_tokens": "quick and dirty appending of query parameters to a url", "label": 1, "retrieval_idx": 4628, "negative": "Time execution of function . Returns ( res seconds ) ." }, { "idx": "cosqa-train-13226", "doc": "python how to check whether the process with pid exist", "code": "def pid_exists(pid):\n \"\"\" Determines if a system process identifer exists in process table.\n \"\"\"\n try:\n os.kill(pid, 0)\n except OSError as exc:\n return exc.errno == errno.EPERM\n else:\n return True", "code_tokens": "def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True", "docstring_tokens": "Determines if a system process identifer exists in process table .", "label": 1, "retrieval_idx": 528, "negative": "Return the fully - qualified name of a function ." }, { "idx": "cosqa-train-11339", "doc": "how to cehck if somethign is a constant python", "code": "def is_static(*p):\n \"\"\" A static value (does not change at runtime)\n which is known at compile time\n \"\"\"\n return all(is_CONST(x) or\n is_number(x) or\n is_const(x)\n for x in p)", "code_tokens": "def is_static ( * p ) : return all ( is_CONST ( x ) or is_number ( x ) or is_const ( x ) for x in p )", "docstring_tokens": "A static value ( does not change at runtime ) which is known at compile time", "label": 1, "retrieval_idx": 1184, "negative": "Query the configured LDAP server ." }, { "idx": "cosqa-train-8363", "doc": "python check if variable exists in locals", "code": "def getvariable(name):\n \"\"\"Get the value of a local variable somewhere in the call stack.\"\"\"\n import inspect\n fr = inspect.currentframe()\n try:\n while fr:\n fr = fr.f_back\n vars = fr.f_locals\n if name in vars:\n return vars[name]\n except:\n pass\n return None", "code_tokens": "def getvariable ( name ) : import inspect fr = inspect . currentframe ( ) try : while fr : fr = fr . f_back vars = fr . f_locals if name in vars : return vars [ name ] except : pass return None", "docstring_tokens": "Get the value of a local variable somewhere in the call stack .", "label": 1, "retrieval_idx": 1793, "negative": "Convert axis coordinate to bin index ." }, { "idx": "cosqa-train-18344", "doc": "python filter a dictionary by value", "code": "def _(f, x):\n \"\"\"\n filter for dict, note `f` should have signature: `f::key->value->bool`\n \"\"\"\n return {k: v for k, v in x.items() if f(k, v)}", "code_tokens": "def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }", "docstring_tokens": "filter for dict note f should have signature : f :: key - > value - > bool", "label": 1, "retrieval_idx": 5644, "negative": "Converts list to string with comma separated values . For string is no - op ." }, { "idx": "cosqa-train-17007", "doc": "read json file and turn into dictionary using python", "code": "def from_file(file_path) -> dict:\n \"\"\" Load JSON file \"\"\"\n with io.open(file_path, 'r', encoding='utf-8') as json_stream:\n return Json.parse(json_stream, True)", "code_tokens": "def from_file ( file_path ) -> dict : with io . open ( file_path , 'r' , encoding = 'utf-8' ) as json_stream : return Json . parse ( json_stream , True )", "docstring_tokens": "Load JSON file", "label": 1, "retrieval_idx": 5563, "negative": "Raise the open file handles permitted by the Dusty daemon process and its child processes . The number we choose here needs to be within the OS X default kernel hard limit which is 10240 ." }, { "idx": "cosqa-train-10471", "doc": "python change the shape of list", "code": "def shape_list(l,shape,dtype):\n \"\"\" Shape a list of lists into the appropriate shape and data type \"\"\"\n return np.array(l, dtype=dtype).reshape(shape)", "code_tokens": "def shape_list ( l , shape , dtype ) : return np . array ( l , dtype = dtype ) . reshape ( shape )", "docstring_tokens": "Shape a list of lists into the appropriate shape and data type", "label": 1, "retrieval_idx": 2814, "negative": "Checks if an item is iterable ( list tuple generator ) but not string" }, { "idx": "cosqa-train-17916", "doc": "how to get the datatypes in python", "code": "def dtypes(self):\n \"\"\"Returns all column names and their data types as a list.\n\n >>> df.dtypes\n [('age', 'int'), ('name', 'string')]\n \"\"\"\n return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]", "code_tokens": "def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]", "docstring_tokens": "Returns all column names and their data types as a list .", "label": 1, "retrieval_idx": 5803, "negative": "Cleanup the output directory" }, { "idx": "cosqa-train-12023", "doc": "initializing an empty string with a size python", "code": "def random_str(size=10):\n \"\"\"\n create random string of selected size\n\n :param size: int, length of the string\n :return: the string\n \"\"\"\n return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))", "code_tokens": "def random_str ( size = 10 ) : return '' . join ( random . choice ( string . ascii_lowercase ) for _ in range ( size ) )", "docstring_tokens": "create random string of selected size", "label": 1, "retrieval_idx": 276, "negative": "Iterates through each image in the given directory . ( not recursive ) : param dir_path : Directory path where images files are present : return : Iterator to iterate through image files" }, { "idx": "cosqa-train-17405", "doc": "cast str as int in python", "code": "def try_cast_int(s):\n \"\"\"(str) -> int\n All the digits in a given string are concatenated and converted into a single number.\n \"\"\"\n try:\n temp = re.findall('\\d', str(s))\n temp = ''.join(temp)\n return int(temp)\n except:\n return s", "code_tokens": "def try_cast_int ( s ) : try : temp = re . findall ( '\\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s", "docstring_tokens": "( str ) - > int All the digits in a given string are concatenated and converted into a single number .", "label": 1, "retrieval_idx": 5603, "negative": "Add a section a subsection and some text to the document ." }, { "idx": "cosqa-train-5849", "doc": "python, sql table column details", "code": "def column_names(self, table):\n \"\"\"An iterable of column names, for a particular table or\n view.\"\"\"\n\n table_info = self.execute(\n u'PRAGMA table_info(%s)' % quote(table))\n return (column['name'] for column in table_info)", "code_tokens": "def column_names ( self , table ) : table_info = self . execute ( u'PRAGMA table_info(%s)' % quote ( table ) ) return ( column [ 'name' ] for column in table_info )", "docstring_tokens": "An iterable of column names for a particular table or view .", "label": 1, "retrieval_idx": 2535, "negative": "Get from a list with an optional default value ." }, { "idx": "cosqa-dev-560", "doc": "python pathlib to traverse directories", "code": "def get_files(dir_name):\n \"\"\"Simple directory walker\"\"\"\n return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]", "code_tokens": "def get_files ( dir_name ) : return [ ( os . path . join ( '.' , d ) , [ os . path . join ( d , f ) for f in files ] ) for d , _ , files in os . walk ( dir_name ) ]", "docstring_tokens": "Simple directory walker", "label": 1, "retrieval_idx": 2992, "negative": "Get dimension of an array getting the number of rows and the max num of columns ." }, { "idx": "cosqa-train-14803", "doc": "python create list of columns with their dtype", "code": "def _get_str_columns(sf):\n \"\"\"\n Returns a list of names of columns that are string type.\n \"\"\"\n return [name for name in sf.column_names() if sf[name].dtype == str]", "code_tokens": "def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]", "docstring_tokens": "Returns a list of names of columns that are string type .", "label": 1, "retrieval_idx": 1858, "negative": "Strip the whitespace from all column names in the given DataFrame and return the result ." }, { "idx": "cosqa-train-9967", "doc": "python turn all nested object to dict", "code": "def as_dict(self):\n \"\"\"Return all child objects in nested dict.\"\"\"\n dicts = [x.as_dict for x in self.children]\n return {'{0} {1}'.format(self.name, self.value): dicts}", "code_tokens": "def as_dict ( self ) : dicts = [ x . as_dict for x in self . children ] return { '{0} {1}' . format ( self . name , self . value ) : dicts }", "docstring_tokens": "Return all child objects in nested dict .", "label": 1, "retrieval_idx": 3775, "negative": "Use the S3 SWAG backend ." }, { "idx": "cosqa-train-11699", "doc": "python read dicom images", "code": "def numpy(self):\n \"\"\" Grabs image data and converts it to a numpy array \"\"\"\n # load GDCM's image reading functionality\n image_reader = gdcm.ImageReader()\n image_reader.SetFileName(self.fname)\n if not image_reader.Read():\n raise IOError(\"Could not read DICOM image\")\n pixel_array = self._gdcm_to_numpy(image_reader.GetImage())\n return pixel_array", "code_tokens": "def numpy ( self ) : # load GDCM's image reading functionality image_reader = gdcm . ImageReader ( ) image_reader . SetFileName ( self . fname ) if not image_reader . Read ( ) : raise IOError ( \"Could not read DICOM image\" ) pixel_array = self . _gdcm_to_numpy ( image_reader . GetImage ( ) ) return pixel_array", "docstring_tokens": "Grabs image data and converts it to a numpy array", "label": 1, "retrieval_idx": 1089, "negative": "Show the y - axis tick labels for a subplot ." }, { "idx": "cosqa-train-9285", "doc": "python making string lower case", "code": "def to_camel(s):\n \"\"\"\n :param string s: under_scored string to be CamelCased\n :return: CamelCase version of input\n :rtype: str\n \"\"\"\n # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups\n return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)", "code_tokens": "def to_camel ( s ) : # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re . sub ( r'_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , '_' + s )", "docstring_tokens": ": param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str", "label": 1, "retrieval_idx": 3683, "negative": "Return whether two objects are equal via recursion using : func : numpy . array_equal for comparing numpy arays ." }, { "idx": "cosqa-train-9519", "doc": "how to implement a macro in python", "code": "def define_macro(self, name, themacro):\n \"\"\"Define a new macro\n\n Parameters\n ----------\n name : str\n The name of the macro.\n themacro : str or Macro\n The action to do upon invoking the macro. If a string, a new\n Macro object is created by passing the string to it.\n \"\"\"\n\n from IPython.core import macro\n\n if isinstance(themacro, basestring):\n themacro = macro.Macro(themacro)\n if not isinstance(themacro, macro.Macro):\n raise ValueError('A macro must be a string or a Macro instance.')\n self.user_ns[name] = themacro", "code_tokens": "def define_macro ( self , name , themacro ) : from IPython . core import macro if isinstance ( themacro , basestring ) : themacro = macro . Macro ( themacro ) if not isinstance ( themacro , macro . Macro ) : raise ValueError ( 'A macro must be a string or a Macro instance.' ) self . user_ns [ name ] = themacro", "docstring_tokens": "Define a new macro", "label": 1, "retrieval_idx": 4263, "negative": "Use the S3 SWAG backend ." }, { "idx": "cosqa-train-14131", "doc": "python subprocess close stdin", "code": "def _finish(self):\n \"\"\"\n Closes and waits for subprocess to exit.\n \"\"\"\n if self._process.returncode is None:\n self._process.stdin.flush()\n self._process.stdin.close()\n self._process.wait()\n self.closed = True", "code_tokens": "def _finish ( self ) : if self . _process . returncode is None : self . _process . stdin . flush ( ) self . _process . stdin . close ( ) self . _process . wait ( ) self . closed = True", "docstring_tokens": "Closes and waits for subprocess to exit .", "label": 1, "retrieval_idx": 3531, "negative": "Saves a value to session ." }, { "idx": "cosqa-train-16776", "doc": "sum within a comprehension python", "code": "def _accumulate(sequence, func):\n \"\"\"\n Python2 accumulate implementation taken from\n https://docs.python.org/3/library/itertools.html#itertools.accumulate\n \"\"\"\n iterator = iter(sequence)\n total = next(iterator)\n yield total\n for element in iterator:\n total = func(total, element)\n yield total", "code_tokens": "def _accumulate ( sequence , func ) : iterator = iter ( sequence ) total = next ( iterator ) yield total for element in iterator : total = func ( total , element ) yield total", "docstring_tokens": "Python2 accumulate implementation taken from https : // docs . python . org / 3 / library / itertools . html#itertools . accumulate", "label": 1, "retrieval_idx": 325, "negative": "Return true if a value is a finite number ." }, { "idx": "cosqa-train-12089", "doc": "python timedelta without microseconds", "code": "def timedelta_seconds(timedelta):\n \"\"\"Returns the total timedelta duration in seconds.\"\"\"\n return (timedelta.total_seconds() if hasattr(timedelta, \"total_seconds\")\n else timedelta.days * 24 * 3600 + timedelta.seconds +\n timedelta.microseconds / 1000000.)", "code_tokens": "def timedelta_seconds ( timedelta ) : return ( timedelta . total_seconds ( ) if hasattr ( timedelta , \"total_seconds\" ) else timedelta . days * 24 * 3600 + timedelta . seconds + timedelta . microseconds / 1000000. )", "docstring_tokens": "Returns the total timedelta duration in seconds .", "label": 1, "retrieval_idx": 4766, "negative": "Hacked run function which installs the trace ." }, { "idx": "cosqa-train-16968", "doc": "change python object to string", "code": "def string(value) -> str:\n \"\"\" string dict/object/value to JSON \"\"\"\n return system_json.dumps(Json(value).safe_object(), ensure_ascii=False)", "code_tokens": "def string ( value ) -> str : return system_json . dumps ( Json ( value ) . safe_object ( ) , ensure_ascii = False )", "docstring_tokens": "string dict / object / value to JSON", "label": 1, "retrieval_idx": 5541, "negative": "Request that the Outstation perform a cold restart . Command syntax is : restart" }, { "idx": "cosqa-train-4701", "doc": "eit request header in python flask", "code": "def get_trace_id_from_flask():\n \"\"\"Get trace_id from flask request headers.\n\n :rtype: str\n :returns: TraceID in HTTP request headers.\n \"\"\"\n if flask is None or not flask.request:\n return None\n\n header = flask.request.headers.get(_FLASK_TRACE_HEADER)\n\n if header is None:\n return None\n\n trace_id = header.split(\"/\", 1)[0]\n\n return trace_id", "code_tokens": "def get_trace_id_from_flask ( ) : if flask is None or not flask . request : return None header = flask . request . headers . get ( _FLASK_TRACE_HEADER ) if header is None : return None trace_id = header . split ( \"/\" , 1 ) [ 0 ] return trace_id", "docstring_tokens": "Get trace_id from flask request headers .", "label": 1, "retrieval_idx": 1456, "negative": "Fill NaNs with the previous value the next value or if all are NaN then 1 . 0" }, { "idx": "cosqa-dev-423", "doc": "python lower all elements in list", "code": "def gen_lower(x: Iterable[str]) -> Generator[str, None, None]:\n \"\"\"\n Args:\n x: iterable of strings\n\n Yields:\n each string in lower case\n \"\"\"\n for string in x:\n yield string.lower()", "code_tokens": "def gen_lower ( x : Iterable [ str ] ) -> Generator [ str , None , None ] : for string in x : yield string . lower ( )", "docstring_tokens": "Args : x : iterable of strings", "label": 1, "retrieval_idx": 5592, "negative": "WeChat access token" }, { "idx": "cosqa-train-14769", "doc": "using sort to move element in to new position in list python", "code": "def insort_no_dup(lst, item):\n \"\"\"\n If item is not in lst, add item to list at its sorted position\n \"\"\"\n import bisect\n ix = bisect.bisect_left(lst, item)\n if lst[ix] != item: \n lst[ix:ix] = [item]", "code_tokens": "def insort_no_dup ( lst , item ) : import bisect ix = bisect . bisect_left ( lst , item ) if lst [ ix ] != item : lst [ ix : ix ] = [ item ]", "docstring_tokens": "If item is not in lst add item to list at its sorted position", "label": 1, "retrieval_idx": 3348, "negative": "Stops playback" }, { "idx": "cosqa-train-19246", "doc": "remove special characters from column names in python", "code": "def normalize_column_names(df):\n r\"\"\" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`\n\n >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])\n >>> normalize_column_names(df)\n ['hello_world', 'not_here']\n \"\"\"\n columns = df.columns if hasattr(df, 'columns') else df\n columns = [c.lower().replace(' ', '_') for c in columns]\n return columns", "code_tokens": "def normalize_column_names ( df ) : columns = df . columns if hasattr ( df , 'columns' ) else df columns = [ c . lower ( ) . replace ( ' ' , '_' ) for c in columns ] return columns", "docstring_tokens": "r Clean up whitespace in column names . See better version at pugnlp . clean_columns", "label": 1, "retrieval_idx": 6049, "negative": "Under UNIX : is a keystroke available?" }, { "idx": "cosqa-dev-345", "doc": "calculate the average of a given list in python", "code": "def mean(inlist):\n \"\"\"\nReturns the arithematic mean of the values in the passed list.\nAssumes a '1D' list, but will function on the 1st dim of an array(!).\n\nUsage: lmean(inlist)\n\"\"\"\n sum = 0\n for item in inlist:\n sum = sum + item\n return sum / float(len(inlist))", "code_tokens": "def mean ( inlist ) : sum = 0 for item in inlist : sum = sum + item return sum / float ( len ( inlist ) )", "docstring_tokens": "Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) .", "label": 1, "retrieval_idx": 1278, "negative": "Convert a date into a datetime" }, { "idx": "cosqa-train-10217", "doc": "past python git clone", "code": "def mkhead(repo, path):\n \"\"\":return: New branch/head instance\"\"\"\n return git.Head(repo, git.Head.to_full_path(path))", "code_tokens": "def mkhead ( repo , path ) : return git . Head ( repo , git . Head . to_full_path ( path ) )", "docstring_tokens": ": return : New branch / head instance", "label": 1, "retrieval_idx": 4425, "negative": "Converts list to string with comma separated values . For string is no - op ." }, { "idx": "cosqa-train-7023", "doc": "python lambda function with 3 params", "code": "def make_lambda(call):\n \"\"\"Wrap an AST Call node to lambda expression node.\n call: ast.Call node\n \"\"\"\n empty_args = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])\n return ast.Lambda(args=empty_args, body=call)", "code_tokens": "def make_lambda ( call ) : empty_args = ast . arguments ( args = [ ] , vararg = None , kwarg = None , defaults = [ ] ) return ast . Lambda ( args = empty_args , body = call )", "docstring_tokens": "Wrap an AST Call node to lambda expression node . call : ast . Call node", "label": 1, "retrieval_idx": 2067, "negative": "Print fatal errors that occurred during validation runs ." }, { "idx": "cosqa-train-12911", "doc": "check for punctuation python", "code": "def is_punctuation(text):\n \"\"\"Check if given string is a punctuation\"\"\"\n return not (text.lower() in config.AVRO_VOWELS or\n text.lower() in config.AVRO_CONSONANTS)", "code_tokens": "def is_punctuation ( text ) : return not ( text . lower ( ) in config . AVRO_VOWELS or text . lower ( ) in config . AVRO_CONSONANTS )", "docstring_tokens": "Check if given string is a punctuation", "label": 1, "retrieval_idx": 3520, "negative": "Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing" }, { "idx": "cosqa-train-4157", "doc": "unsupported media type json python", "code": "def parse(self, data, mimetype):\n \"\"\"\n Parses a byte array containing a JSON document and returns a Python object.\n :param data: The byte array containing a JSON document.\n :param MimeType mimetype: The mimetype chose to parse the data.\n :return: A Python object.\n \"\"\"\n encoding = mimetype.params.get('charset') or 'utf-8'\n\n return json.loads(data.decode(encoding))", "code_tokens": "def parse ( self , data , mimetype ) : encoding = mimetype . params . get ( 'charset' ) or 'utf-8' return json . loads ( data . decode ( encoding ) )", "docstring_tokens": "Parses a byte array containing a JSON document and returns a Python object . : param data : The byte array containing a JSON document . : param MimeType mimetype : The mimetype chose to parse the data . : return : A Python object .", "label": 1, "retrieval_idx": 2695, "negative": "Get user name provide by operating system" }, { "idx": "cosqa-train-19905", "doc": "python separate string to list", "code": "def _str_to_list(value, separator):\n \"\"\"Convert a string to a list with sanitization.\"\"\"\n value_list = [item.strip() for item in value.split(separator)]\n value_list_sanitized = builtins.list(filter(None, value_list))\n if len(value_list_sanitized) > 0:\n return value_list_sanitized\n else:\n raise ValueError('Invalid list variable.')", "code_tokens": "def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )", "docstring_tokens": "Convert a string to a list with sanitization .", "label": 1, "retrieval_idx": 5723, "negative": "Logs out the current session by removing it from the cache . This is expected to only occur when a session has" }, { "idx": "cosqa-train-18773", "doc": "python remove phrase from list of strings", "code": "def remove_empty_text(utterances: List[Utterance]) -> List[Utterance]:\n \"\"\"Remove empty utterances from a list of utterances\n Args:\n utterances: The list of utterance we are processing\n \"\"\"\n return [utter for utter in utterances if utter.text.strip() != \"\"]", "code_tokens": "def remove_empty_text ( utterances : List [ Utterance ] ) -> List [ Utterance ] : return [ utter for utter in utterances if utter . text . strip ( ) != \"\" ]", "docstring_tokens": "Remove empty utterances from a list of utterances Args : utterances : The list of utterance we are processing", "label": 1, "retrieval_idx": 5557, "negative": "Round a number to a precision" }, { "idx": "cosqa-train-4468", "doc": "python fastest way to load data", "code": "def get_data(self):\n \"\"\"\n Fetch the data field if it does not exist.\n \"\"\"\n try:\n return DocumentDataDict(self.__dict__['data'])\n except KeyError:\n self._lazy_load()\n return DocumentDataDict(self.__dict__['data'])", "code_tokens": "def get_data ( self ) : try : return DocumentDataDict ( self . __dict__ [ 'data' ] ) except KeyError : self . _lazy_load ( ) return DocumentDataDict ( self . __dict__ [ 'data' ] )", "docstring_tokens": "Fetch the data field if it does not exist .", "label": 1, "retrieval_idx": 2830, "negative": "Return flattened dictionary from MultiDict ." }, { "idx": "cosqa-train-10637", "doc": "add noise to the audio python", "code": "def synthesize(self, duration):\n \"\"\"\n Synthesize white noise\n\n Args:\n duration (numpy.timedelta64): The duration of the synthesized sound\n \"\"\"\n sr = self.samplerate.samples_per_second\n seconds = duration / Seconds(1)\n samples = np.random.uniform(low=-1., high=1., size=int(sr * seconds))\n return AudioSamples(samples, self.samplerate)", "code_tokens": "def synthesize ( self , duration ) : sr = self . samplerate . samples_per_second seconds = duration / Seconds ( 1 ) samples = np . random . uniform ( low = - 1. , high = 1. , size = int ( sr * seconds ) ) return AudioSamples ( samples , self . samplerate )", "docstring_tokens": "Synthesize white noise", "label": 1, "retrieval_idx": 694, "negative": "Returns path to packaged static files" }, { "idx": "cosqa-train-10163", "doc": "object with commas turned into list python", "code": "def seq_to_str(obj, sep=\",\"):\n \"\"\"\n Given a sequence convert it to a comma separated string.\n If, however, the argument is a single object, return its string\n representation.\n \"\"\"\n if isinstance(obj, string_classes):\n return obj\n elif isinstance(obj, (list, tuple)):\n return sep.join([str(x) for x in obj])\n else:\n return str(obj)", "code_tokens": "def seq_to_str ( obj , sep = \",\" ) : if isinstance ( obj , string_classes ) : return obj elif isinstance ( obj , ( list , tuple ) ) : return sep . join ( [ str ( x ) for x in obj ] ) else : return str ( obj )", "docstring_tokens": "Given a sequence convert it to a comma separated string . If however the argument is a single object return its string representation .", "label": 1, "retrieval_idx": 1439, "negative": "Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) ." }, { "idx": "cosqa-train-9747", "doc": "python set limits on x axis", "code": "def set_xlimits(self, min=None, max=None):\n \"\"\"Set limits for the x-axis.\n\n :param min: minimum value to be displayed. If None, it will be\n calculated.\n :param max: maximum value to be displayed. If None, it will be\n calculated.\n\n \"\"\"\n self.limits['xmin'] = min\n self.limits['xmax'] = max", "code_tokens": "def set_xlimits ( self , min = None , max = None ) : self . limits [ 'xmin' ] = min self . limits [ 'xmax' ] = max", "docstring_tokens": "Set limits for the x - axis .", "label": 1, "retrieval_idx": 3834, "negative": "Round a number to a precision" }, { "idx": "cosqa-train-7841", "doc": "is python ssl socket connection thread safe", "code": "def enable_ssl(self, *args, **kwargs):\n \"\"\"\n Transforms the regular socket.socket to an ssl.SSLSocket for secure\n connections. Any arguments are passed to ssl.wrap_socket:\n http://docs.python.org/dev/library/ssl.html#ssl.wrap_socket\n \"\"\"\n if self.handshake_sent:\n raise SSLError('can only enable SSL before handshake')\n\n self.secure = True\n self.sock = ssl.wrap_socket(self.sock, *args, **kwargs)", "code_tokens": "def enable_ssl ( self , * args , * * kwargs ) : if self . handshake_sent : raise SSLError ( 'can only enable SSL before handshake' ) self . secure = True self . sock = ssl . wrap_socket ( self . sock , * args , * * kwargs )", "docstring_tokens": "Transforms the regular socket . socket to an ssl . SSLSocket for secure connections . Any arguments are passed to ssl . wrap_socket : http : // docs . python . org / dev / library / ssl . html#ssl . wrap_socket", "label": 1, "retrieval_idx": 2787, "negative": "Get the parent directory of a filename ." }, { "idx": "cosqa-train-7998", "doc": "python3 encode decode bytes", "code": "def to_bytes(value):\n \"\"\" str to bytes (py3k) \"\"\"\n vtype = type(value)\n\n if vtype == bytes or vtype == type(None):\n return value\n\n try:\n return vtype.encode(value)\n except UnicodeEncodeError:\n pass\n return value", "code_tokens": "def to_bytes ( value ) : vtype = type ( value ) if vtype == bytes or vtype == type ( None ) : return value try : return vtype . encode ( value ) except UnicodeEncodeError : pass return value", "docstring_tokens": "str to bytes ( py3k )", "label": 1, "retrieval_idx": 1377, "negative": "Convert a string to a list with sanitization ." }, { "idx": "cosqa-train-2119", "doc": "xsd file to python object", "code": "def from_file(cls, file_path, validate=True):\n \"\"\" Creates a Python object from a XML file\n\n :param file_path: Path to the XML file\n :param validate: XML should be validated against the embedded XSD definition\n :type validate: Boolean\n :returns: the Python object\n \"\"\"\n return xmlmap.load_xmlobject_from_file(file_path, xmlclass=cls, validate=validate)", "code_tokens": "def from_file ( cls , file_path , validate = True ) : return xmlmap . load_xmlobject_from_file ( file_path , xmlclass = cls , validate = validate )", "docstring_tokens": "Creates a Python object from a XML file", "label": 1, "retrieval_idx": 1677, "negative": "WeChat access token" }, { "idx": "cosqa-train-10773", "doc": "python expand a path", "code": "def expandpath(path):\n \"\"\"\n Expand a filesystem path that may or may not contain user/env vars.\n\n :param str path: path to expand\n :return str: expanded version of input path\n \"\"\"\n return os.path.expandvars(os.path.expanduser(path)).replace(\"//\", \"/\")", "code_tokens": "def expandpath ( path ) : return os . path . expandvars ( os . path . expanduser ( path ) ) . replace ( \"//\" , \"/\" )", "docstring_tokens": "Expand a filesystem path that may or may not contain user / env vars .", "label": 1, "retrieval_idx": 3524, "negative": "Return random lognormal variates ." }, { "idx": "cosqa-train-12970", "doc": "python flask template table example", "code": "def index():\n \"\"\" Display productpage with normal user and test user buttons\"\"\"\n global productpage\n\n table = json2html.convert(json = json.dumps(productpage),\n table_attributes=\"class=\\\"table table-condensed table-bordered table-hover\\\"\")\n\n return render_template('index.html', serviceTable=table)", "code_tokens": "def index ( ) : global productpage table = json2html . convert ( json = json . dumps ( productpage ) , table_attributes = \"class=\\\"table table-condensed table-bordered table-hover\\\"\" ) return render_template ( 'index.html' , serviceTable = table )", "docstring_tokens": "Display productpage with normal user and test user buttons", "label": 1, "retrieval_idx": 4050, "negative": "Return flattened dictionary from MultiDict ." }, { "idx": "cosqa-train-2983", "doc": "how to check if object defined python", "code": "def is_defined(self, objtxt, force_import=False):\n \"\"\"Return True if object is defined\"\"\"\n return self.interpreter.is_defined(objtxt, force_import)", "code_tokens": "def is_defined ( self , objtxt , force_import = False ) : return self . interpreter . is_defined ( objtxt , force_import )", "docstring_tokens": "Return True if object is defined", "label": 1, "retrieval_idx": 202, "negative": "Take a dataframe and string - i - fy a column of values . Turn nan / None into and all other values into strings ." }, { "idx": "cosqa-train-14540", "doc": "s3 sync between bucket python", "code": "def s3(ctx, bucket_name, data_file, region):\n \"\"\"Use the S3 SWAG backend.\"\"\"\n if not ctx.data_file:\n ctx.data_file = data_file\n\n if not ctx.bucket_name:\n ctx.bucket_name = bucket_name\n\n if not ctx.region:\n ctx.region = region\n\n ctx.type = 's3'", "code_tokens": "def s3 ( ctx , bucket_name , data_file , region ) : if not ctx . data_file : ctx . data_file = data_file if not ctx . bucket_name : ctx . bucket_name = bucket_name if not ctx . region : ctx . region = region ctx . type = 's3'", "docstring_tokens": "Use the S3 SWAG backend .", "label": 1, "retrieval_idx": 1312, "negative": "hacky inference of kwargs keys" }, { "idx": "cosqa-train-6525", "doc": "change the position of 3d coordinate in python", "code": "def list(self):\n \"\"\"position in 3d space\"\"\"\n return [self._pos3d.x, self._pos3d.y, self._pos3d.z]", "code_tokens": "def list ( self ) : return [ self . _pos3d . x , self . _pos3d . y , self . _pos3d . z ]", "docstring_tokens": "position in 3d space", "label": 1, "retrieval_idx": 1270, "negative": "Deserialize s ( a str ) to a Python object ." }, { "idx": "cosqa-train-11131", "doc": "python how to get the number of cores in a computer", "code": "def _num_cpus_darwin():\n \"\"\"Return the number of active CPUs on a Darwin system.\"\"\"\n p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)\n return p.stdout.read()", "code_tokens": "def _num_cpus_darwin ( ) : p = subprocess . Popen ( [ 'sysctl' , '-n' , 'hw.ncpu' ] , stdout = subprocess . PIPE ) return p . stdout . read ( )", "docstring_tokens": "Return the number of active CPUs on a Darwin system .", "label": 1, "retrieval_idx": 956, "negative": "Convert a ctypes float pointer array to a numpy array ." }, { "idx": "cosqa-train-4829", "doc": "python how to use pdb set trace", "code": "def set_trace():\n \"\"\"Start a Pdb instance at the calling frame, with stdout routed to sys.__stdout__.\"\"\"\n # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py\n pdb.Pdb(stdout=sys.__stdout__).set_trace(sys._getframe().f_back)", "code_tokens": "def set_trace ( ) : # https://github.com/nose-devs/nose/blob/master/nose/tools/nontrivial.py pdb . Pdb ( stdout = sys . __stdout__ ) . set_trace ( sys . _getframe ( ) . f_back )", "docstring_tokens": "Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ .", "label": 1, "retrieval_idx": 900, "negative": "Initiates a graceful stop of the processes" }, { "idx": "cosqa-train-10710", "doc": "python dictionary url encode", "code": "def get_dict_to_encoded_url(data):\n \"\"\"\n Converts a dict to an encoded URL.\n Example: given data = {'a': 1, 'b': 2}, it returns 'a=1&b=2'\n \"\"\"\n unicode_data = dict([(k, smart_str(v)) for k, v in data.items()])\n encoded = urllib.urlencode(unicode_data)\n return encoded", "code_tokens": "def get_dict_to_encoded_url ( data ) : unicode_data = dict ( [ ( k , smart_str ( v ) ) for k , v in data . items ( ) ] ) encoded = urllib . urlencode ( unicode_data ) return encoded", "docstring_tokens": "Converts a dict to an encoded URL . Example : given data = { a : 1 b : 2 } it returns a = 1&b = 2", "label": 1, "retrieval_idx": 2486, "negative": "The Euclidean distance between two vectors ." }, { "idx": "cosqa-train-18842", "doc": "how to check whether a string is int in python", "code": "def _isint(string):\n \"\"\"\n >>> _isint(\"123\")\n True\n >>> _isint(\"123.45\")\n False\n \"\"\"\n return type(string) is int or \\\n (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \\\n _isconvertible(int, string)", "code_tokens": "def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )", "docstring_tokens": ">>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False", "label": 1, "retrieval_idx": 5776, "negative": "Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ ." }, { "idx": "cosqa-train-16717", "doc": "python 3 change permission of file chmod", "code": "def add_exec_permission_to(target_file):\n \"\"\"Add executable permissions to the file\n\n :param target_file: the target file whose permission to be changed\n \"\"\"\n mode = os.stat(target_file).st_mode\n os.chmod(target_file, mode | stat.S_IXUSR)", "code_tokens": "def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )", "docstring_tokens": "Add executable permissions to the file", "label": 1, "retrieval_idx": 2659, "negative": "Create all your database objects ( SQLAlchemy specific ) ." }, { "idx": "cosqa-train-8829", "doc": "python gaussian filter array", "code": "def smooth_gaussian(image, sigma=1):\n \"\"\"Returns Gaussian smoothed image.\n\n :param image: numpy array or :class:`jicimagelib.image.Image`\n :param sigma: standard deviation\n :returns: :class:`jicimagelib.image.Image`\n \"\"\"\n return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode=\"nearest\")", "code_tokens": "def smooth_gaussian ( image , sigma = 1 ) : return scipy . ndimage . filters . gaussian_filter ( image , sigma = sigma , mode = \"nearest\" )", "docstring_tokens": "Returns Gaussian smoothed image .", "label": 1, "retrieval_idx": 374, "negative": "Removes dict keys which have have self as value ." }, { "idx": "cosqa-train-17526", "doc": "how to cut off a calculated number to two decimals in python", "code": "def truncate(value: Decimal, n_digits: int) -> Decimal:\n \"\"\"Truncates a value to a number of decimals places\"\"\"\n return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)", "code_tokens": "def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )", "docstring_tokens": "Truncates a value to a number of decimals places", "label": 1, "retrieval_idx": 5704, "negative": "Return list of the key property names for a class" }, { "idx": "cosqa-train-14497", "doc": "replace many value at once in python", "code": "def replace_list(items, match, replacement):\n \"\"\"Replaces occurrences of a match string in a given list of strings and returns\n a list of new strings. The match string can be a regex expression.\n\n Args:\n items (list): the list of strings to modify.\n match (str): the search expression.\n replacement (str): the string to replace with.\n \"\"\"\n return [replace(item, match, replacement) for item in items]", "code_tokens": "def replace_list ( items , match , replacement ) : return [ replace ( item , match , replacement ) for item in items ]", "docstring_tokens": "Replaces occurrences of a match string in a given list of strings and returns a list of new strings . The match string can be a regex expression .", "label": 1, "retrieval_idx": 3362, "negative": "Truncates a value to a number of decimals places" }, { "idx": "cosqa-train-15806", "doc": "python numpy conver to float64", "code": "def as_float_array(a):\n \"\"\"View the quaternion array as an array of floats\n\n This function is fast (of order 1 microsecond) because no data is\n copied; the returned quantity is just a \"view\" of the original.\n\n The output view has one more dimension (of size 4) than the input\n array, but is otherwise the same shape.\n\n \"\"\"\n return np.asarray(a, dtype=np.quaternion).view((np.double, 4))", "code_tokens": "def as_float_array ( a ) : return np . asarray ( a , dtype = np . quaternion ) . view ( ( np . double , 4 ) )", "docstring_tokens": "View the quaternion array as an array of floats", "label": 1, "retrieval_idx": 854, "negative": "read the lines from a file into a list" }, { "idx": "cosqa-train-11161", "doc": "python how to rank a list object", "code": "def ranks(self, key, value):\n \"\"\"Populate the ``ranks`` key.\"\"\"\n return [normalize_rank(el) for el in force_list(value.get('a'))]", "code_tokens": "def ranks ( self , key , value ) : return [ normalize_rank ( el ) for el in force_list ( value . get ( 'a' ) ) ]", "docstring_tokens": "Populate the ranks key .", "label": 1, "retrieval_idx": 4604, "negative": "Return a list of indexes of substr . If substr not found list is empty ." }, { "idx": "cosqa-train-7195", "doc": "how to check if file doesn't exist in python", "code": "def is_valid_file(parser, arg):\n \"\"\"Check if arg is a valid file that already exists on the file system.\"\"\"\n arg = os.path.abspath(arg)\n if not os.path.exists(arg):\n parser.error(\"The file %s does not exist!\" % arg)\n else:\n return arg", "code_tokens": "def is_valid_file ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . exists ( arg ) : parser . error ( \"The file %s does not exist!\" % arg ) else : return arg", "docstring_tokens": "Check if arg is a valid file that already exists on the file system .", "label": 1, "retrieval_idx": 2931, "negative": "Removes stopwords contained in a list of words ." }, { "idx": "cosqa-train-7384", "doc": "how to get the parent directory in python", "code": "def get_parent_dir(name):\n \"\"\"Get the parent directory of a filename.\"\"\"\n parent_dir = os.path.dirname(os.path.dirname(name))\n if parent_dir:\n return parent_dir\n return os.path.abspath('.')", "code_tokens": "def get_parent_dir ( name ) : parent_dir = os . path . dirname ( os . path . dirname ( name ) ) if parent_dir : return parent_dir return os . path . abspath ( '.' )", "docstring_tokens": "Get the parent directory of a filename .", "label": 1, "retrieval_idx": 415, "negative": "Similar to print but prints to stderr ." }, { "idx": "cosqa-train-8125", "doc": "resize an image python pil", "code": "def resize(self, size):\n \"\"\"Return a new Image instance with the given size.\"\"\"\n return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))", "code_tokens": "def resize ( self , size ) : return Image ( self . pil_image . resize ( size , PIL . Image . ANTIALIAS ) )", "docstring_tokens": "Return a new Image instance with the given size .", "label": 1, "retrieval_idx": 2018, "negative": "replace nan in a by val and returns the replaced array and the nan position" }, { "idx": "cosqa-train-8244", "doc": "python boxplot data frame", "code": "def compute_boxplot(self, series):\n \"\"\"\n Compute boxplot for given pandas Series.\n \"\"\"\n from matplotlib.cbook import boxplot_stats\n series = series[series.notnull()]\n if len(series.values) == 0:\n return {}\n elif not is_numeric_dtype(series):\n return self.non_numeric_stats(series)\n stats = boxplot_stats(list(series.values))[0]\n stats['count'] = len(series.values)\n stats['fliers'] = \"|\".join(map(str, stats['fliers']))\n return stats", "code_tokens": "def compute_boxplot ( self , series ) : from matplotlib . cbook import boxplot_stats series = series [ series . notnull ( ) ] if len ( series . values ) == 0 : return { } elif not is_numeric_dtype ( series ) : return self . non_numeric_stats ( series ) stats = boxplot_stats ( list ( series . values ) ) [ 0 ] stats [ 'count' ] = len ( series . values ) stats [ 'fliers' ] = \"|\" . join ( map ( str , stats [ 'fliers' ] ) ) return stats", "docstring_tokens": "Compute boxplot for given pandas Series .", "label": 1, "retrieval_idx": 2783, "negative": "given a DataFrame where records are stored row - wise rearrange it such that records are stored column - wise ." }, { "idx": "cosqa-train-11056", "doc": "python glpk read from lp file", "code": "def glpk_read_cplex(path):\n \"\"\"Reads cplex file and returns glpk problem.\n\n Returns\n -------\n glp_prob\n A glpk problems (same type as returned by glp_create_prob)\n \"\"\"\n from swiglpk import glp_create_prob, glp_read_lp\n\n problem = glp_create_prob()\n glp_read_lp(problem, None, path)\n return problem", "code_tokens": "def glpk_read_cplex ( path ) : from swiglpk import glp_create_prob , glp_read_lp problem = glp_create_prob ( ) glp_read_lp ( problem , None , path ) return problem", "docstring_tokens": "Reads cplex file and returns glpk problem .", "label": 1, "retrieval_idx": 4588, "negative": "Like dict but does not hold any null values ." }, { "idx": "cosqa-train-12080", "doc": "python threadpool close join", "code": "def join(self):\n\t\t\"\"\"Note that the Executor must be close()'d elsewhere,\n\t\tor join() will never return.\n\t\t\"\"\"\n\t\tself.inputfeeder_thread.join()\n\t\tself.pool.join()\n\t\tself.resulttracker_thread.join()\n\t\tself.failuretracker_thread.join()", "code_tokens": "def join ( self ) : self . inputfeeder_thread . join ( ) self . pool . join ( ) self . resulttracker_thread . join ( ) self . failuretracker_thread . join ( )", "docstring_tokens": "Note that the Executor must be close () d elsewhere or join () will never return .", "label": 1, "retrieval_idx": 1252, "negative": "Return a list of indexes of substr . If substr not found list is empty ." }, { "idx": "cosqa-train-11940", "doc": "python sklearn onehotencoder string values", "code": "def one_hot2string(arr, vocab):\n \"\"\"Convert a one-hot encoded array back to string\n \"\"\"\n tokens = one_hot2token(arr)\n indexToLetter = _get_index_dict(vocab)\n\n return [''.join([indexToLetter[x] for x in row]) for row in tokens]", "code_tokens": "def one_hot2string ( arr , vocab ) : tokens = one_hot2token ( arr ) indexToLetter = _get_index_dict ( vocab ) return [ '' . join ( [ indexToLetter [ x ] for x in row ] ) for row in tokens ]", "docstring_tokens": "Convert a one - hot encoded array back to string", "label": 1, "retrieval_idx": 1405, "negative": "Performs drag a element to another elmenet ." }, { "idx": "cosqa-train-19085", "doc": "python change to bytes", "code": "def to_bytes(data: Any) -> bytearray:\n \"\"\"\n Convert anything to a ``bytearray``.\n \n See\n \n - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3\n - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1\n \"\"\" # noqa\n if isinstance(data, int):\n return bytearray([data])\n return bytearray(data, encoding='latin-1')", "code_tokens": "def to_bytes ( data : Any ) -> bytearray : # noqa if isinstance ( data , int ) : return bytearray ( [ data ] ) return bytearray ( data , encoding = 'latin-1' )", "docstring_tokens": "Convert anything to a bytearray . See - http : // stackoverflow . com / questions / 7585435 / best - way - to - convert - string - to - bytes - in - python - 3 - http : // stackoverflow . com / questions / 10459067 / how - to - convert - my - bytearrayb - x9e - x18k - x9a - to - something - like - this - x9e - x1", "label": 1, "retrieval_idx": 5708, "negative": "Create ctypes pointer to object ." }, { "idx": "cosqa-train-7005", "doc": "python json loads try", "code": "def json(body, charset='utf-8', **kwargs):\n \"\"\"Takes JSON formatted data, converting it into native Python objects\"\"\"\n return json_converter.loads(text(body, charset=charset))", "code_tokens": "def json ( body , charset = 'utf-8' , * * kwargs ) : return json_converter . loads ( text ( body , charset = charset ) )", "docstring_tokens": "Takes JSON formatted data converting it into native Python objects", "label": 1, "retrieval_idx": 2057, "negative": "Check if cnr or cns files are empty ( only have a header )" }, { "idx": "cosqa-train-6677", "doc": "create an empty column in data frame python", "code": "def add_blank_row(self, label):\n \"\"\"\n Add a blank row with only an index value to self.df.\n This is done inplace.\n \"\"\"\n col_labels = self.df.columns\n blank_item = pd.Series({}, index=col_labels, name=label)\n # use .loc to add in place (append won't do that)\n self.df.loc[blank_item.name] = blank_item\n return self.df", "code_tokens": "def add_blank_row ( self , label ) : col_labels = self . df . columns blank_item = pd . Series ( { } , index = col_labels , name = label ) # use .loc to add in place (append won't do that) self . df . loc [ blank_item . name ] = blank_item return self . df", "docstring_tokens": "Add a blank row with only an index value to self . df . This is done inplace .", "label": 1, "retrieval_idx": 27, "negative": "Get dimension of an array getting the number of rows and the max num of columns ." }, { "idx": "cosqa-train-5971", "doc": "remove whitespace at end of line in python", "code": "def clean(s):\n \"\"\"Removes trailing whitespace on each line.\"\"\"\n lines = [l.rstrip() for l in s.split('\\n')]\n return '\\n'.join(lines)", "code_tokens": "def clean ( s ) : lines = [ l . rstrip ( ) for l in s . split ( '\\n' ) ] return '\\n' . join ( lines )", "docstring_tokens": "Removes trailing whitespace on each line .", "label": 1, "retrieval_idx": 2581, "negative": "__init__ : Performs basic initialisations" }, { "idx": "cosqa-train-12933", "doc": "python file opening modes", "code": "def open_file(file, mode):\n\t\"\"\"Open a file.\n\n\t:arg file: file-like or path-like object.\n\t:arg str mode: ``mode`` argument for :func:`open`.\n\t\"\"\"\n\tif hasattr(file, \"read\"):\n\t\treturn file\n\tif hasattr(file, \"open\"):\n\t\treturn file.open(mode)\n\treturn open(file, mode)", "code_tokens": "def open_file ( file , mode ) : if hasattr ( file , \"read\" ) : return file if hasattr ( file , \"open\" ) : return file . open ( mode ) return open ( file , mode )", "docstring_tokens": "Open a file .", "label": 1, "retrieval_idx": 1796, "negative": "HTTP DELETE operation to API endpoint ." }, { "idx": "cosqa-train-8432", "doc": "python code input prompt for questions", "code": "def string_input(prompt=''):\n \"\"\"Python 3 input()/Python 2 raw_input()\"\"\"\n v = sys.version[0]\n if v == '3':\n return input(prompt)\n else:\n return raw_input(prompt)", "code_tokens": "def string_input ( prompt = '' ) : v = sys . version [ 0 ] if v == '3' : return input ( prompt ) else : return raw_input ( prompt )", "docstring_tokens": "Python 3 input () / Python 2 raw_input ()", "label": 1, "retrieval_idx": 63, "negative": "Raise the open file handles permitted by the Dusty daemon process and its child processes . The number we choose here needs to be within the OS X default kernel hard limit which is 10240 ." }, { "idx": "cosqa-train-9433", "doc": "python parse a log file that is logging", "code": "def parse(self):\n \"\"\"\n Parse file specified by constructor.\n \"\"\"\n f = open(self.parse_log_path, \"r\")\n self.parse2(f)\n f.close()", "code_tokens": "def parse ( self ) : f = open ( self . parse_log_path , \"r\" ) self . parse2 ( f ) f . close ( )", "docstring_tokens": "Parse file specified by constructor .", "label": 1, "retrieval_idx": 1429, "negative": "Remove non - alphanumerical characters from metric word . And trim excessive underscores ." }, { "idx": "cosqa-train-19595", "doc": "remove an entry from a dict python", "code": "def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:\n \"\"\"\n Process an iterable of dictionaries. For each dictionary ``d``, delete\n ``d[key]`` if it exists.\n \"\"\"\n for d in dict_list:\n d.pop(key, None)", "code_tokens": "def dictlist_wipe_key ( dict_list : Iterable [ Dict ] , key : str ) -> None : for d in dict_list : d . pop ( key , None )", "docstring_tokens": "Process an iterable of dictionaries . For each dictionary d delete d [ key ] if it exists .", "label": 1, "retrieval_idx": 5594, "negative": "This parallel fetcher uses gevent one uses gevent" }, { "idx": "cosqa-train-7984", "doc": "new line statemnt pythong write", "code": "def write_line(self, line, count=1):\n \"\"\"writes the line and count newlines after the line\"\"\"\n self.write(line)\n self.write_newlines(count)", "code_tokens": "def write_line ( self , line , count = 1 ) : self . write ( line ) self . write_newlines ( count )", "docstring_tokens": "writes the line and count newlines after the line", "label": 1, "retrieval_idx": 2415, "negative": ">>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False" }, { "idx": "cosqa-train-5792", "doc": "python view as series column format string", "code": "def format(x, format):\n \"\"\"Uses http://www.cplusplus.com/reference/string/to_string/ for formatting\"\"\"\n # don't change the dtype, otherwise for each block the dtype may be different (string length)\n sl = vaex.strings.format(x, format)\n return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)", "code_tokens": "def format ( x , format ) : # don't change the dtype, otherwise for each block the dtype may be different (string length) sl = vaex . strings . format ( x , format ) return column . ColumnStringArrow ( sl . bytes , sl . indices , sl . length , sl . offset , string_sequence = sl )", "docstring_tokens": "Uses http : // www . cplusplus . com / reference / string / to_string / for formatting", "label": 1, "retrieval_idx": 3291, "negative": "Return a dataframe that is a cross between dataframes df1 and df2" }, { "idx": "cosqa-train-7598", "doc": "python select not null column values", "code": "def selectnotnone(table, field, complement=False):\n \"\"\"Select rows where the given field is not `None`.\"\"\"\n\n return select(table, field, lambda v: v is not None,\n complement=complement)", "code_tokens": "def selectnotnone ( table , field , complement = False ) : return select ( table , field , lambda v : v is not None , complement = complement )", "docstring_tokens": "Select rows where the given field is not None .", "label": 1, "retrieval_idx": 1092, "negative": "Wrapper for inserting float features into Example proto ." }, { "idx": "cosqa-train-11238", "doc": "how do functions in python know the parametr type", "code": "def is_symbol(string):\n \"\"\"\n Return true if the string is a mathematical symbol.\n \"\"\"\n return (\n is_int(string) or is_float(string) or\n is_constant(string) or is_unary(string) or\n is_binary(string) or\n (string == '(') or (string == ')')\n )", "code_tokens": "def is_symbol ( string ) : return ( is_int ( string ) or is_float ( string ) or is_constant ( string ) or is_unary ( string ) or is_binary ( string ) or ( string == '(' ) or ( string == ')' ) )", "docstring_tokens": "Return true if the string is a mathematical symbol .", "label": 1, "retrieval_idx": 4548, "negative": "Start a Pdb instance at the calling frame with stdout routed to sys . __stdout__ ." }, { "idx": "cosqa-train-13050", "doc": "cursor positioning python windows", "code": "def ensure_hbounds(self):\n \"\"\"Ensure the cursor is within horizontal screen bounds.\"\"\"\n self.cursor.x = min(max(0, self.cursor.x), self.columns - 1)", "code_tokens": "def ensure_hbounds ( self ) : self . cursor . x = min ( max ( 0 , self . cursor . x ) , self . columns - 1 )", "docstring_tokens": "Ensure the cursor is within horizontal screen bounds .", "label": 1, "retrieval_idx": 365, "negative": "Returns the total timedelta duration in seconds ." }, { "idx": "cosqa-train-11103", "doc": "python how to equally space points in an ellipse", "code": "def create_ellipse(width,height,angle):\n \"\"\"Create parametric ellipse from 200 points.\"\"\"\n angle = angle / 180.0 * np.pi\n thetas = np.linspace(0,2*np.pi,200)\n a = width / 2.0\n b = height / 2.0\n\n x = a*np.cos(thetas)*np.cos(angle) - b*np.sin(thetas)*np.sin(angle)\n y = a*np.cos(thetas)*np.sin(angle) + b*np.sin(thetas)*np.cos(angle)\n z = np.zeros(thetas.shape)\n return np.vstack((x,y,z)).T", "code_tokens": "def create_ellipse ( width , height , angle ) : angle = angle / 180.0 * np . pi thetas = np . linspace ( 0 , 2 * np . pi , 200 ) a = width / 2.0 b = height / 2.0 x = a * np . cos ( thetas ) * np . cos ( angle ) - b * np . sin ( thetas ) * np . sin ( angle ) y = a * np . cos ( thetas ) * np . sin ( angle ) + b * np . sin ( thetas ) * np . cos ( angle ) z = np . zeros ( thetas . shape ) return np . vstack ( ( x , y , z ) ) . T", "docstring_tokens": "Create parametric ellipse from 200 points .", "label": 1, "retrieval_idx": 1016, "negative": "helper function for quick base conversions from strings to integers" }, { "idx": "cosqa-train-9780", "doc": "how to see how similar two images are in python", "code": "def _sim_fill(r1, r2, imsize):\n \"\"\"\n calculate the fill similarity over the image\n \"\"\"\n bbsize = (\n (max(r1[\"max_x\"], r2[\"max_x\"]) - min(r1[\"min_x\"], r2[\"min_x\"]))\n * (max(r1[\"max_y\"], r2[\"max_y\"]) - min(r1[\"min_y\"], r2[\"min_y\"]))\n )\n return 1.0 - (bbsize - r1[\"size\"] - r2[\"size\"]) / imsize", "code_tokens": "def _sim_fill ( r1 , r2 , imsize ) : bbsize = ( ( max ( r1 [ \"max_x\" ] , r2 [ \"max_x\" ] ) - min ( r1 [ \"min_x\" ] , r2 [ \"min_x\" ] ) ) * ( max ( r1 [ \"max_y\" ] , r2 [ \"max_y\" ] ) - min ( r1 [ \"min_y\" ] , r2 [ \"min_y\" ] ) ) ) return 1.0 - ( bbsize - r1 [ \"size\" ] - r2 [ \"size\" ] ) / imsize", "docstring_tokens": "calculate the fill similarity over the image", "label": 1, "retrieval_idx": 1294, "negative": "Calculate the distance between two Vectors" }, { "idx": "cosqa-train-9562", "doc": "how to make a input to have no spaces in python\\", "code": "def pass_from_pipe(cls):\n \"\"\"Return password from pipe if not on TTY, else False.\n \"\"\"\n is_pipe = not sys.stdin.isatty()\n return is_pipe and cls.strip_last_newline(sys.stdin.read())", "code_tokens": "def pass_from_pipe ( cls ) : is_pipe = not sys . stdin . isatty ( ) return is_pipe and cls . strip_last_newline ( sys . stdin . read ( ) )", "docstring_tokens": "Return password from pipe if not on TTY else False .", "label": 1, "retrieval_idx": 3248, "negative": "Stops iterating before yielding the specified idx ." }, { "idx": "cosqa-train-14356", "doc": "next line to read in python", "code": "def __next__(self):\n \"\"\"\n\n :return: a pair (1-based line number in the input, row)\n \"\"\"\n # Retrieve the row, thereby incrementing the line number:\n row = super(UnicodeReaderWithLineNumber, self).__next__()\n return self.lineno + 1, row", "code_tokens": "def __next__ ( self ) : # Retrieve the row, thereby incrementing the line number: row = super ( UnicodeReaderWithLineNumber , self ) . __next__ ( ) return self . lineno + 1 , row", "docstring_tokens": "", "label": 1, "retrieval_idx": 1590, "negative": "Logs the basic endpoint requested" }, { "idx": "cosqa-train-14340", "doc": "move an item in list to front python", "code": "def list_move_to_front(l,value='other'):\n \"\"\"if the value is in the list, move it to the front and return it.\"\"\"\n l=list(l)\n if value in l:\n l.remove(value)\n l.insert(0,value)\n return l", "code_tokens": "def list_move_to_front ( l , value = 'other' ) : l = list ( l ) if value in l : l . remove ( value ) l . insert ( 0 , value ) return l", "docstring_tokens": "if the value is in the list move it to the front and return it .", "label": 1, "retrieval_idx": 1236, "negative": "Set up neccessary environment variables" }, { "idx": "cosqa-train-10077", "doc": "python wrap (s,w) print", "code": "def _wrap(text, columns=80):\n \"\"\"\n Own \"dumb\" reimplementation of textwrap.wrap().\n\n This is because calling .wrap() on bigger strings can take a LOT of\n processor power. And I mean like 8 seconds of 3GHz CPU just to wrap 20kB of\n text without spaces.\n\n Args:\n text (str): Text to wrap.\n columns (int): Wrap after `columns` characters.\n\n Returns:\n str: Wrapped text.\n \"\"\"\n out = []\n for cnt, char in enumerate(text):\n out.append(char)\n\n if (cnt + 1) % columns == 0:\n out.append(\"\\n\")\n\n return \"\".join(out)", "code_tokens": "def _wrap ( text , columns = 80 ) : out = [ ] for cnt , char in enumerate ( text ) : out . append ( char ) if ( cnt + 1 ) % columns == 0 : out . append ( \"\\n\" ) return \"\" . join ( out )", "docstring_tokens": "Own dumb reimplementation of textwrap . wrap () .", "label": 1, "retrieval_idx": 4399, "negative": "Logarithmic loss with non - necessarily - binary labels ." }, { "idx": "cosqa-train-18137", "doc": "how to check if missing values are blanks or nan or none in python", "code": "def warn_if_nans_exist(X):\n \"\"\"Warn if nans exist in a numpy array.\"\"\"\n null_count = count_rows_with_nans(X)\n total = len(X)\n percent = 100 * null_count / total\n\n if null_count > 0:\n warning_message = \\\n 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \\\n 'complete rows will be plotted.'.format(null_count, total, percent)\n warnings.warn(warning_message, DataWarning)", "code_tokens": "def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning )", "docstring_tokens": "Warn if nans exist in a numpy array .", "label": 1, "retrieval_idx": 5888, "negative": "WeChat access token" }, { "idx": "cosqa-train-12117", "doc": "python to get the indices of bin edges", "code": "def val_to_bin(edges, x):\n \"\"\"Convert axis coordinate to bin index.\"\"\"\n ibin = np.digitize(np.array(x, ndmin=1), edges) - 1\n return ibin", "code_tokens": "def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin", "docstring_tokens": "Convert axis coordinate to bin index .", "label": 1, "retrieval_idx": 521, "negative": "Deserialize s ( a str ) to a Python object ." }, { "idx": "cosqa-train-10587", "doc": "python comma separated value", "code": "def list_to_csv(value):\n \"\"\"\n Converts list to string with comma separated values. For string is no-op.\n \"\"\"\n if isinstance(value, (list, tuple, set)):\n value = \",\".join(value)\n return value", "code_tokens": "def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = \",\" . join ( value ) return value", "docstring_tokens": "Converts list to string with comma separated values . For string is no - op .", "label": 1, "retrieval_idx": 77, "negative": "Captures screen area of this region at least the part that is on the screen" }, { "idx": "cosqa-train-13897", "doc": "python requests disable ssl certificate verification", "code": "def disable_insecure_request_warning():\n \"\"\"Suppress warning about untrusted SSL certificate.\"\"\"\n import requests\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)", "code_tokens": "def disable_insecure_request_warning ( ) : import requests from requests . packages . urllib3 . exceptions import InsecureRequestWarning requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning )", "docstring_tokens": "Suppress warning about untrusted SSL certificate .", "label": 1, "retrieval_idx": 2308, "negative": "Internal method to directly add a _NamespaceInfo object to this set . No sanity checks are done ( e . g . checking for prefix conflicts ) so be sure to do it yourself before calling this ." }, { "idx": "cosqa-train-7918", "doc": "python var and distribution of probability", "code": "def pdf(x, mu, std):\n \"\"\"Probability density function (normal distribution)\"\"\"\n return (1.0 / (std * sqrt(2 * pi))) * np.exp(-(x - mu) ** 2 / (2 * std ** 2))", "code_tokens": "def pdf ( x , mu , std ) : return ( 1.0 / ( std * sqrt ( 2 * pi ) ) ) * np . exp ( - ( x - mu ) ** 2 / ( 2 * std ** 2 ) )", "docstring_tokens": "Probability density function ( normal distribution )", "label": 1, "retrieval_idx": 96, "negative": "Retrieve a User object by ID ." }, { "idx": "cosqa-dev-269", "doc": "how to determine it's a orthogonal matrix using python", "code": "def is_orthogonal(\n matrix: np.ndarray,\n *,\n rtol: float = 1e-5,\n atol: float = 1e-8) -> bool:\n \"\"\"Determines if a matrix is approximately orthogonal.\n\n A matrix is orthogonal if it's square and real and its transpose is its\n inverse.\n\n Args:\n matrix: The matrix to check.\n rtol: The per-matrix-entry relative tolerance on equality.\n atol: The per-matrix-entry absolute tolerance on equality.\n\n Returns:\n Whether the matrix is orthogonal within the given tolerance.\n \"\"\"\n return (matrix.shape[0] == matrix.shape[1] and\n np.all(np.imag(matrix) == 0) and\n np.allclose(matrix.dot(matrix.T), np.eye(matrix.shape[0]),\n rtol=rtol,\n atol=atol))", "code_tokens": "def is_orthogonal ( matrix : np . ndarray , * , rtol : float = 1e-5 , atol : float = 1e-8 ) -> bool : return ( matrix . shape [ 0 ] == matrix . shape [ 1 ] and np . all ( np . imag ( matrix ) == 0 ) and np . allclose ( matrix . dot ( matrix . T ) , np . eye ( matrix . shape [ 0 ] ) , rtol = rtol , atol = atol ) )", "docstring_tokens": "Determines if a matrix is approximately orthogonal .", "label": 1, "retrieval_idx": 5774, "negative": "Performs drag a element to another elmenet ." }, { "idx": "cosqa-train-10422", "doc": "strip html tags in python", "code": "def do_striptags(value):\n \"\"\"Strip SGML/XML tags and replace adjacent whitespace by one space.\n \"\"\"\n if hasattr(value, '__html__'):\n value = value.__html__()\n return Markup(unicode(value)).striptags()", "code_tokens": "def do_striptags ( value ) : if hasattr ( value , '__html__' ) : value = value . __html__ ( ) return Markup ( unicode ( value ) ) . striptags ( )", "docstring_tokens": "Strip SGML / XML tags and replace adjacent whitespace by one space .", "label": 1, "retrieval_idx": 3792, "negative": "Open a file ." }, { "idx": "cosqa-train-12879", "doc": "center align python text", "code": "def center_text(text, width=80):\n \"\"\"Center all lines of the text.\n\n It is assumed that all lines width is smaller then B{width}, because the\n line width will not be checked.\n\n Args:\n text (str): Text to wrap.\n width (int): Maximum number of characters per line.\n\n Returns:\n str: Centered text.\n \"\"\"\n centered = []\n for line in text.splitlines():\n centered.append(line.center(width))\n return \"\\n\".join(centered)", "code_tokens": "def center_text ( text , width = 80 ) : centered = [ ] for line in text . splitlines ( ) : centered . append ( line . center ( width ) ) return \"\\n\" . join ( centered )", "docstring_tokens": "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 .", "label": 1, "retrieval_idx": 156, "negative": "Delete all the files and subdirectories in a directory ." }, { "idx": "cosqa-train-2468", "doc": "python get list of keys on an object", "code": "def get_keys_from_class(cc):\n \"\"\"Return list of the key property names for a class \"\"\"\n return [prop.name for prop in cc.properties.values() \\\n if 'key' in prop.qualifiers]", "code_tokens": "def get_keys_from_class ( cc ) : return [ prop . name for prop in cc . properties . values ( ) if 'key' in prop . qualifiers ]", "docstring_tokens": "Return list of the key property names for a class", "label": 1, "retrieval_idx": 387, "negative": "Helper parse action to convert tokens to upper case ." }, { "idx": "cosqa-train-9972", "doc": "is there any python function to check for nan valu", "code": "def reduce_fn(x):\n \"\"\"\n Aggregation function to get the first non-zero value.\n \"\"\"\n values = x.values if pd and isinstance(x, pd.Series) else x\n for v in values:\n if not is_nan(v):\n return v\n return np.NaN", "code_tokens": "def reduce_fn ( x ) : values = x . values if pd and isinstance ( x , pd . Series ) else x for v in values : if not is_nan ( v ) : return v return np . NaN", "docstring_tokens": "Aggregation function to get the first non - zero value .", "label": 1, "retrieval_idx": 621, "negative": "Return password from pipe if not on TTY else False ." }, { "idx": "cosqa-train-13065", "doc": "python get cookie for request", "code": "def parse_cookies(self, req, name, field):\n \"\"\"Pull the value from the cookiejar.\"\"\"\n return core.get_value(req.COOKIES, name, field)", "code_tokens": "def parse_cookies ( self , req , name , field ) : return core . get_value ( req . COOKIES , name , field )", "docstring_tokens": "Pull the value from the cookiejar .", "label": 1, "retrieval_idx": 3111, "negative": "Truncates a value to a number of decimals places" }, { "idx": "cosqa-train-13388", "doc": "python is list no na", "code": "def is_listish(obj):\n \"\"\"Check if something quacks like a list.\"\"\"\n if isinstance(obj, (list, tuple, set)):\n return True\n return is_sequence(obj)", "code_tokens": "def is_listish ( obj ) : if isinstance ( obj , ( list , tuple , set ) ) : return True return is_sequence ( obj )", "docstring_tokens": "Check if something quacks like a list .", "label": 1, "retrieval_idx": 755, "negative": "Generate unique document id for ElasticSearch ." }, { "idx": "cosqa-train-15046", "doc": "python determine if a file is image", "code": "def is_image(filename):\n \"\"\"Determine if given filename is an image.\"\"\"\n # note: isfile() also accepts symlinks\n return os.path.isfile(filename) and filename.lower().endswith(ImageExts)", "code_tokens": "def is_image ( filename ) : # note: isfile() also accepts symlinks return os . path . isfile ( filename ) and filename . lower ( ) . endswith ( ImageExts )", "docstring_tokens": "Determine if given filename is an image .", "label": 1, "retrieval_idx": 1636, "negative": "Return a list of the table names in the database ." }, { "idx": "cosqa-train-11796", "doc": "python reorganise a data frame", "code": "def _preprocess(df):\n \"\"\"\n given a DataFrame where records are stored row-wise, rearrange it\n such that records are stored column-wise.\n \"\"\"\n\n df = df.stack()\n\n df.index.rename([\"id\", \"time\"], inplace=True) # .reset_index()\n df.name = \"value\"\n df = df.reset_index()\n\n return df", "code_tokens": "def _preprocess ( df ) : df = df . stack ( ) df . index . rename ( [ \"id\" , \"time\" ] , inplace = True ) # .reset_index() df . name = \"value\" df = df . reset_index ( ) return df", "docstring_tokens": "given a DataFrame where records are stored row - wise rearrange it such that records are stored column - wise .", "label": 1, "retrieval_idx": 4720, "negative": "Stops iterating before yielding the specified idx ." }, { "idx": "cosqa-train-12282", "doc": "read first line in txt file in python", "code": "def getfirstline(file, default):\n \"\"\"\n Returns the first line of a file.\n \"\"\"\n with open(file, 'rb') as fh:\n content = fh.readlines()\n if len(content) == 1:\n return content[0].decode('utf-8').strip('\\n')\n\n return default", "code_tokens": "def getfirstline ( file , default ) : with open ( file , 'rb' ) as fh : content = fh . readlines ( ) if len ( content ) == 1 : return content [ 0 ] . decode ( 'utf-8' ) . strip ( '\\n' ) return default", "docstring_tokens": "Returns the first line of a file .", "label": 1, "retrieval_idx": 971, "negative": ": type aws_access_key_id : string : param aws_access_key_id : Your AWS Access Key ID" }, { "idx": "cosqa-train-16638", "doc": "pass defined parser object to subparser python", "code": "def sub(name, func,**kwarg):\n \"\"\" Add subparser\n\n \"\"\"\n sp = subparsers.add_parser(name, **kwarg)\n sp.set_defaults(func=func)\n sp.arg = sp.add_argument\n return sp", "code_tokens": "def sub ( name , func , * * kwarg ) : sp = subparsers . add_parser ( name , * * kwarg ) sp . set_defaults ( func = func ) sp . arg = sp . add_argument return sp", "docstring_tokens": "Add subparser", "label": 1, "retrieval_idx": 2600, "negative": "Inserts a single document into a mongo collection https : // api . mongodb . com / python / current / api / pymongo / collection . html#pymongo . collection . Collection . insert_one" }, { "idx": "cosqa-train-7552", "doc": "how to print generic error in python", "code": "def print_err(*args, end='\\n'):\n \"\"\"Similar to print, but prints to stderr.\n \"\"\"\n print(*args, end=end, file=sys.stderr)\n sys.stderr.flush()", "code_tokens": "def print_err ( * args , end = '\\n' ) : print ( * args , end = end , file = sys . stderr ) sys . stderr . flush ( )", "docstring_tokens": "Similar to print but prints to stderr .", "label": 1, "retrieval_idx": 3811, "negative": "takes flags returns indexes of True values" }, { "idx": "cosqa-train-14625", "doc": "python change the name of a key", "code": "def unit_key_from_name(name):\n \"\"\"Return a legal python name for the given name for use as a unit key.\"\"\"\n result = name\n\n for old, new in six.iteritems(UNIT_KEY_REPLACEMENTS):\n result = result.replace(old, new)\n\n # Collapse redundant underscores and convert to uppercase.\n result = re.sub(r'_+', '_', result.upper())\n\n return result", "code_tokens": "def unit_key_from_name ( name ) : result = name for old , new in six . iteritems ( UNIT_KEY_REPLACEMENTS ) : result = result . replace ( old , new ) # Collapse redundant underscores and convert to uppercase. result = re . sub ( r'_+' , '_' , result . upper ( ) ) return result", "docstring_tokens": "Return a legal python name for the given name for use as a unit key .", "label": 1, "retrieval_idx": 1602, "negative": "Pop the head off the iterator and return it ." }, { "idx": "cosqa-train-12190", "doc": "moving mouse python click", "code": "def mouse_move_event(self, event):\n \"\"\"\n Forward mouse cursor position events to the example\n \"\"\"\n self.example.mouse_position_event(event.x(), event.y())", "code_tokens": "def mouse_move_event ( self , event ) : self . example . mouse_position_event ( event . x ( ) , event . y ( ) )", "docstring_tokens": "Forward mouse cursor position events to the example", "label": 1, "retrieval_idx": 984, "negative": "Calculates factorial iteratively . If mod is not None then return ( n! % mod ) Time Complexity - O ( n )" }, { "idx": "cosqa-train-14209", "doc": "python to determine if services are running", "code": "def service_available(service_name):\n \"\"\"Determine whether a system service is available\"\"\"\n try:\n subprocess.check_output(\n ['service', service_name, 'status'],\n stderr=subprocess.STDOUT).decode('UTF-8')\n except subprocess.CalledProcessError as e:\n return b'unrecognized service' not in e.output\n else:\n return True", "code_tokens": "def service_available ( service_name ) : try : subprocess . check_output ( [ 'service' , service_name , 'status' ] , stderr = subprocess . STDOUT ) . decode ( 'UTF-8' ) except subprocess . CalledProcessError as e : return b'unrecognized service' not in e . output else : return True", "docstring_tokens": "Determine whether a system service is available", "label": 1, "retrieval_idx": 235, "negative": "If pair is in search_list return the index . Otherwise return - 1" }, { "idx": "cosqa-train-18231", "doc": "python set contains multiple items", "code": "def issuperset(self, items):\n \"\"\"Return whether this collection contains all items.\n\n >>> Unique(['spam', 'eggs']).issuperset(['spam', 'spam', 'spam'])\n True\n \"\"\"\n return all(_compat.map(self._seen.__contains__, items))", "code_tokens": "def issuperset ( self , items ) : return all ( _compat . map ( self . _seen . __contains__ , items ) )", "docstring_tokens": "Return whether this collection contains all items .", "label": 1, "retrieval_idx": 6019, "negative": "Logs the basic endpoint requested" }, { "idx": "cosqa-train-17616", "doc": "python protobyf parse from byte", "code": "def decode(self, bytes, raw=False):\n \"\"\"decode(bytearray, raw=False) -> value\n\n Decodes the given bytearray according to this PrimitiveType\n definition.\n\n NOTE: The parameter ``raw`` is present to adhere to the\n ``decode()`` inteface, but has no effect for PrimitiveType\n definitions.\n \"\"\"\n return struct.unpack(self.format, buffer(bytes))[0]", "code_tokens": "def decode ( self , bytes , raw = False ) : return struct . unpack ( self . format , buffer ( bytes ) ) [ 0 ]", "docstring_tokens": "decode ( bytearray raw = False ) - > value", "label": 1, "retrieval_idx": 5882, "negative": "HTTP DELETE operation to API endpoint ." }, { "idx": "cosqa-train-2007", "doc": "python check if a directory is writable", "code": "def _writable_dir(path):\n \"\"\"Whether `path` is a directory, to which the user has write access.\"\"\"\n return os.path.isdir(path) and os.access(path, os.W_OK)", "code_tokens": "def _writable_dir ( path ) : return os . path . isdir ( path ) and os . access ( path , os . W_OK )", "docstring_tokens": "Whether path is a directory to which the user has write access .", "label": 1, "retrieval_idx": 651, "negative": "Convert datetime to epoch seconds ." }, { "idx": "cosqa-train-16594", "doc": "object as list python", "code": "def as_list(self):\n \"\"\"Return all child objects in nested lists of strings.\"\"\"\n return [self.name, self.value, [x.as_list for x in self.children]]", "code_tokens": "def as_list ( self ) : return [ self . name , self . value , [ x . as_list for x in self . children ] ]", "docstring_tokens": "Return all child objects in nested lists of strings .", "label": 1, "retrieval_idx": 633, "negative": "Are two indexes equal? Checks by comparing str () versions of them . ( AM UNSURE IF THIS IS ENOUGH . )" }, { "idx": "cosqa-dev-486", "doc": "replace function nan python", "code": "def _replace_nan(a, val):\n \"\"\"\n replace nan in a by val, and returns the replaced array and the nan\n position\n \"\"\"\n mask = isnull(a)\n return where_method(val, mask, a), mask", "code_tokens": "def _replace_nan ( a , val ) : mask = isnull ( a ) return where_method ( val , mask , a ) , mask", "docstring_tokens": "replace nan in a by val and returns the replaced array and the nan position", "label": 1, "retrieval_idx": 1025, "negative": "Wrapper for inserting float features into Example proto ." }, { "idx": "cosqa-train-19425", "doc": "python hash table check if key exist", "code": "def check_key(self, key: str) -> bool:\n \"\"\"\n Checks if key exists in datastore. True if yes, False if no.\n\n :param: SHA512 hash key\n\n :return: whether or key not exists in datastore\n \"\"\"\n keys = self.get_keys()\n return key in keys", "code_tokens": "def check_key ( self , key : str ) -> bool : keys = self . get_keys ( ) return key in keys", "docstring_tokens": "Checks if key exists in datastore . True if yes False if no .", "label": 1, "retrieval_idx": 5872, "negative": "Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) ." }, { "idx": "cosqa-train-14671", "doc": "take all points in box python", "code": "def point8_to_box(points):\n \"\"\"\n Args:\n points: (nx4)x2\n Returns:\n nx4 boxes (x1y1x2y2)\n \"\"\"\n p = points.reshape((-1, 4, 2))\n minxy = p.min(axis=1) # nx2\n maxxy = p.max(axis=1) # nx2\n return np.concatenate((minxy, maxxy), axis=1)", "code_tokens": "def point8_to_box ( points ) : p = points . reshape ( ( - 1 , 4 , 2 ) ) minxy = p . min ( axis = 1 ) # nx2 maxxy = p . max ( axis = 1 ) # nx2 return np . concatenate ( ( minxy , maxxy ) , axis = 1 )", "docstring_tokens": "Args : points : ( nx4 ) x2 Returns : nx4 boxes ( x1y1x2y2 )", "label": 1, "retrieval_idx": 5215, "negative": "Return a cleaned string with token sorted ." }, { "idx": "cosqa-train-14950", "doc": "python create enum by name", "code": "def get_enum_from_name(self, enum_name):\n \"\"\"\n Return an enum from a name\n Args:\n enum_name (str): name of the enum\n Returns:\n Enum\n \"\"\"\n return next((e for e in self.enums if e.name == enum_name), None)", "code_tokens": "def get_enum_from_name ( self , enum_name ) : return next ( ( e for e in self . enums if e . name == enum_name ) , None )", "docstring_tokens": "Return an enum from a name Args : enum_name ( str ) : name of the enum Returns : Enum", "label": 1, "retrieval_idx": 4091, "negative": "Log - normal function from scipy" }, { "idx": "cosqa-train-11399", "doc": "python matplotlib use arrow markers", "code": "def add_arrow(self, x1, y1, x2, y2, **kws):\n \"\"\"add arrow to plot\"\"\"\n self.panel.add_arrow(x1, y1, x2, y2, **kws)", "code_tokens": "def add_arrow ( self , x1 , y1 , x2 , y2 , * * kws ) : self . panel . add_arrow ( x1 , y1 , x2 , y2 , * * kws )", "docstring_tokens": "add arrow to plot", "label": 1, "retrieval_idx": 3302, "negative": "Delete all the files and subdirectories in a directory ." }, { "idx": "cosqa-train-8819", "doc": "python function default args", "code": "def get_default_args(func):\n \"\"\"\n returns a dictionary of arg_name:default_values for the input function\n \"\"\"\n args, varargs, keywords, defaults = getargspec_no_self(func)\n return dict(zip(args[-len(defaults):], defaults))", "code_tokens": "def get_default_args ( func ) : args , varargs , keywords , defaults = getargspec_no_self ( func ) return dict ( zip ( args [ - len ( defaults ) : ] , defaults ) )", "docstring_tokens": "returns a dictionary of arg_name : default_values for the input function", "label": 1, "retrieval_idx": 139, "negative": "Logs out the current session by removing it from the cache . This is expected to only occur when a session has" }, { "idx": "cosqa-train-19364", "doc": "python how to select first 100 rows", "code": "def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \\\n -> Generator[Any, None, None]:\n \"\"\"\n Generate the first value in each row.\n\n Args:\n cursor: the cursor\n arraysize: split fetches into chunks of this many records\n\n Yields:\n the first value of each row\n \"\"\"\n return (row[0] for row in genrows(cursor, arraysize))", "code_tokens": "def genfirstvalues ( cursor : Cursor , arraysize : int = 1000 ) -> Generator [ Any , None , None ] : return ( row [ 0 ] for row in genrows ( cursor , arraysize ) )", "docstring_tokens": "Generate the first value in each row .", "label": 1, "retrieval_idx": 5650, "negative": "When the with statement ends ." }, { "idx": "cosqa-train-17740", "doc": "removing columnsns in data frame python", "code": "def clean_column_names(df: DataFrame) -> DataFrame:\n \"\"\"\n Strip the whitespace from all column names in the given DataFrame\n and return the result.\n \"\"\"\n f = df.copy()\n f.columns = [col.strip() for col in f.columns]\n return f", "code_tokens": "def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f", "docstring_tokens": "Strip the whitespace from all column names in the given DataFrame and return the result .", "label": 1, "retrieval_idx": 5616, "negative": "Delete all the files and subdirectories in a directory ." }, { "idx": "cosqa-train-19654", "doc": "python array to torch tensor", "code": "def astensor(array: TensorLike) -> BKTensor:\n \"\"\"Covert numpy array to tensorflow tensor\"\"\"\n tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)\n return tensor", "code_tokens": "def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor", "docstring_tokens": "Covert numpy array to tensorflow tensor", "label": 1, "retrieval_idx": 5649, "negative": "create random string of selected size" }, { "idx": "cosqa-dev-116", "doc": "how to turn a list into a csv python", "code": "def list_to_csv(value):\n \"\"\"\n Converts list to string with comma separated values. For string is no-op.\n \"\"\"\n if isinstance(value, (list, tuple, set)):\n value = \",\".join(value)\n return value", "code_tokens": "def list_to_csv ( value ) : if isinstance ( value , ( list , tuple , set ) ) : value = \",\" . join ( value ) return value", "docstring_tokens": "Converts list to string with comma separated values . For string is no - op .", "label": 1, "retrieval_idx": 77, "negative": "Set limits for the x - axis ." }, { "idx": "cosqa-train-13423", "doc": "how do i unzip file in python", "code": "def _unzip_handle(handle):\n \"\"\"Transparently unzip the file handle\"\"\"\n if isinstance(handle, basestring):\n handle = _gzip_open_filename(handle)\n else:\n handle = _gzip_open_handle(handle)\n return handle", "code_tokens": "def _unzip_handle ( handle ) : if isinstance ( handle , basestring ) : handle = _gzip_open_filename ( handle ) else : handle = _gzip_open_handle ( handle ) return handle", "docstring_tokens": "Transparently unzip the file handle", "label": 1, "retrieval_idx": 1220, "negative": "Calculates the average value of a list of numbers Returns a float" } ]