[ { "idx": "cosqa-dev-0", "doc": "python check relation is symmetric", "code": "def is_edge_consistent(graph, u, v):\n \"\"\"Check if all edges between two nodes have the same relation.\n\n :param pybel.BELGraph graph: A BEL Graph\n :param tuple u: The source BEL node\n :param tuple v: The target BEL node\n :return: If all edges from the source to target node have the same relation\n :rtype: bool\n \"\"\"\n if not graph.has_edge(u, v):\n raise ValueError('{} does not contain an edge ({}, {})'.format(graph, u, v))\n\n return 0 == len(set(d[RELATION] for d in graph.edge[u][v].values()))", "code_tokens": "def is_edge_consistent ( graph , u , v ) : if not graph . has_edge ( u , v ) : raise ValueError ( '{} does not contain an edge ({}, {})' . format ( graph , u , v ) ) return 0 == len ( set ( d [ RELATION ] for d in graph . edge [ u ] [ v ] . values ( ) ) )", "docstring_tokens": "Check if all edges between two nodes have the same relation .", "label": 0 }, { "idx": "cosqa-dev-1", "doc": "python split strings into list of lines", "code": "def split_multiline(value):\n \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n return [element for element in (line.strip() for line in value.split('\\n'))\n if element]", "code_tokens": "def split_multiline ( value ) : return [ element for element in ( line . strip ( ) for line in value . split ( '\\n' ) ) if element ]", "docstring_tokens": "Split a multiline string into a list excluding blank lines .", "label": 1 }, { "idx": "cosqa-dev-2", "doc": "python notify all other threads to stop", "code": "def wait_until_exit(self):\n \"\"\" Wait until all the threads are finished.\n\n \"\"\"\n [t.join() for t in self.threads]\n\n self.threads = list()", "code_tokens": "def wait_until_exit ( self ) : [ t . join ( ) for t in self . threads ] self . threads = list ( )", "docstring_tokens": "Wait until all the threads are finished .", "label": 0 }, { "idx": "cosqa-dev-3", "doc": "loading a series of images in python and resizing them", "code": "def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]:\n \"\"\"\n Load and pre-process the images specified with absolute paths.\n\n :param image_paths: List of images specified with paths.\n :param image_size: Tuple to resize the image to (Channels, Height, Width)\n :return: A list of loaded images (numpy arrays).\n \"\"\"\n image_size = image_size[1:] # we do not need the number of channels\n images = []\n for image_path in image_paths:\n images.append(load_preprocess_image(image_path, image_size))\n return images", "code_tokens": "def load_preprocess_images ( image_paths : List [ str ] , image_size : tuple ) -> List [ np . ndarray ] : image_size = image_size [ 1 : ] # we do not need the number of channels images = [ ] for image_path in image_paths : images . append ( load_preprocess_image ( image_path , image_size ) ) return images", "docstring_tokens": "Load and pre - process the images specified with absolute paths .", "label": 1 }, { "idx": "cosqa-dev-4", "doc": "python use numpy array as list in code", "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": 0 }, { "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 }, { "idx": "cosqa-dev-6", "doc": "add color to print python", "code": "def write_color(string, name, style='normal', when='auto'):\n \"\"\" Write the given colored string to standard out. \"\"\"\n write(color(string, name, style, when))", "code_tokens": "def write_color ( string , name , style = 'normal' , when = 'auto' ) : write ( color ( string , name , style , when ) )", "docstring_tokens": "Write the given colored string to standard out .", "label": 1 }, { "idx": "cosqa-dev-7", "doc": "python detect if cpython or pypu", "code": "def supports_py3(project_name):\n \"\"\"Check with PyPI if a project supports Python 3.\"\"\"\n log = logging.getLogger(\"ciu\")\n log.info(\"Checking {} ...\".format(project_name))\n request = requests.get(\"https://pypi.org/pypi/{}/json\".format(project_name))\n if request.status_code >= 400:\n log = logging.getLogger(\"ciu\")\n log.warning(\"problem fetching {}, assuming ported ({})\".format(\n project_name, request.status_code))\n return True\n response = request.json()\n return any(c.startswith(\"Programming Language :: Python :: 3\")\n for c in response[\"info\"][\"classifiers\"])", "code_tokens": "def supports_py3 ( project_name ) : log = logging . getLogger ( \"ciu\" ) log . info ( \"Checking {} ...\" . format ( project_name ) ) request = requests . get ( \"https://pypi.org/pypi/{}/json\" . format ( project_name ) ) if request . status_code >= 400 : log = logging . getLogger ( \"ciu\" ) log . warning ( \"problem fetching {}, assuming ported ({})\" . format ( project_name , request . status_code ) ) return True response = request . json ( ) return any ( c . startswith ( \"Programming Language :: Python :: 3\" ) for c in response [ \"info\" ] [ \"classifiers\" ] )", "docstring_tokens": "Check with PyPI if a project supports Python 3 .", "label": 0 }, { "idx": "cosqa-dev-8", "doc": "python create c dll with ctypes", "code": "def load(self, name):\n \"\"\"Loads and returns foreign library.\"\"\"\n name = ctypes.util.find_library(name)\n return ctypes.cdll.LoadLibrary(name)", "code_tokens": "def load ( self , name ) : name = ctypes . util . find_library ( name ) return ctypes . cdll . LoadLibrary ( name )", "docstring_tokens": "Loads and returns foreign library .", "label": 0 }, { "idx": "cosqa-dev-9", "doc": "python limit number to two decimals", "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 }, { "idx": "cosqa-dev-10", "doc": "get the last record in sql python", "code": "def get_last_id(self, cur, table='reaction'):\n \"\"\"\n Get the id of the last written row in table\n\n Parameters\n ----------\n cur: database connection().cursor() object\n table: str\n 'reaction', 'publication', 'publication_system', 'reaction_system'\n\n Returns: id\n \"\"\"\n cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n .format(table))\n result = cur.fetchone()\n if result is not None:\n id = result[0]\n else:\n id = 0\n return id", "code_tokens": "def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( \"SELECT seq FROM sqlite_sequence WHERE name='{0}'\" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id", "docstring_tokens": "Get the id of the last written row in table", "label": 1 }, { "idx": "cosqa-dev-11", "doc": "python update docstring while inheretance", "code": "def inheritdoc(method):\n \"\"\"Set __doc__ of *method* to __doc__ of *method* in its parent class.\n\n Since this is used on :class:`.StringMixIn`, the \"parent class\" used is\n ``str``. This function can be used as a decorator.\n \"\"\"\n method.__doc__ = getattr(str, method.__name__).__doc__\n return method", "code_tokens": "def inheritdoc ( method ) : method . __doc__ = getattr ( str , method . __name__ ) . __doc__ return method", "docstring_tokens": "Set __doc__ of * method * to __doc__ of * method * in its parent class .", "label": 1 }, { "idx": "cosqa-dev-12", "doc": "setdefault dictionary function python", "code": "def setDictDefaults (d, defaults):\n \"\"\"Sets all defaults for the given dictionary to those contained in a\n second defaults dictionary. This convenience method calls:\n\n d.setdefault(key, value)\n\n for each key and value in the given defaults dictionary.\n \"\"\"\n for key, val in defaults.items():\n d.setdefault(key, val)\n\n return d", "code_tokens": "def setDictDefaults ( d , defaults ) : for key , val in defaults . items ( ) : d . setdefault ( key , val ) return d", "docstring_tokens": "Sets all defaults for the given dictionary to those contained in a second defaults dictionary . This convenience method calls :", "label": 1 }, { "idx": "cosqa-dev-13", "doc": "python how to limit the rate of http request", "code": "def _ratelimited_get(self, *args, **kwargs):\n \"\"\"Perform get request, handling rate limiting.\"\"\"\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n # It's possible that Space-Track will return HTTP status 500 with a\n # query rate limit violation. This can happen if a script is cancelled\n # before it has finished sleeping to satisfy the rate limit and it is\n # started again.\n #\n # Let's catch this specific instance and retry once if it happens.\n if resp.status_code == 500:\n # Let's only retry if the error page tells us it's a rate limit\n # violation.\n if 'violated your query rate limit' in resp.text:\n # Mimic the RateLimiter callback behaviour.\n until = time.time() + self._ratelimiter.period\n t = threading.Thread(target=self._ratelimit_callback, args=(until,))\n t.daemon = True\n t.start()\n time.sleep(self._ratelimiter.period)\n\n # Now retry\n with self._ratelimiter:\n resp = self.session.get(*args, **kwargs)\n\n return resp", "code_tokens": "def _ratelimited_get ( self , * args , * * kwargs ) : with self . _ratelimiter : resp = self . session . get ( * args , * * kwargs ) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished sleeping to satisfy the rate limit and it is # started again. # # Let's catch this specific instance and retry once if it happens. if resp . status_code == 500 : # Let's only retry if the error page tells us it's a rate limit # violation. if 'violated your query rate limit' in resp . text : # Mimic the RateLimiter callback behaviour. until = time . time ( ) + self . _ratelimiter . period t = threading . Thread ( target = self . _ratelimit_callback , args = ( until , ) ) t . daemon = True t . start ( ) time . sleep ( self . _ratelimiter . period ) # Now retry with self . _ratelimiter : resp = self . session . get ( * args , * * kwargs ) return resp", "docstring_tokens": "Perform get request handling rate limiting .", "label": 1 }, { "idx": "cosqa-dev-14", "doc": "python unittest not discovered", "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": 0 }, { "idx": "cosqa-dev-15", "doc": "custom distance matrix python", "code": "def get_distance_matrix(x):\n \"\"\"Get distance matrix given a matrix. Used in testing.\"\"\"\n square = nd.sum(x ** 2.0, axis=1, keepdims=True)\n distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose()))\n return nd.sqrt(distance_square)", "code_tokens": "def get_distance_matrix ( x ) : square = nd . sum ( x ** 2.0 , axis = 1 , keepdims = True ) distance_square = square + square . transpose ( ) - ( 2.0 * nd . dot ( x , x . transpose ( ) ) ) return nd . sqrt ( distance_square )", "docstring_tokens": "Get distance matrix given a matrix . Used in testing .", "label": 1 }, { "idx": "cosqa-dev-16", "doc": "python cast derived to base", "code": "def _opt_call_from_base_type(self, value):\n \"\"\"Call _from_base_type() if necessary.\n\n If the value is a _BaseValue instance, unwrap it and call all\n _from_base_type() methods. Otherwise, return the value\n unchanged.\n \"\"\"\n if isinstance(value, _BaseValue):\n value = self._call_from_base_type(value.b_val)\n return value", "code_tokens": "def _opt_call_from_base_type ( self , value ) : if isinstance ( value , _BaseValue ) : value = self . _call_from_base_type ( value . b_val ) return value", "docstring_tokens": "Call _from_base_type () if necessary .", "label": 0 }, { "idx": "cosqa-dev-17", "doc": "how to test null in python assert", "code": "def assert_is_not(expected, actual, message=None, extra=None):\n \"\"\"Raises an AssertionError if expected is actual.\"\"\"\n assert expected is not actual, _assert_fail_message(\n message, expected, actual, \"is\", extra\n )", "code_tokens": "def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , \"is\" , extra )", "docstring_tokens": "Raises an AssertionError if expected is actual .", "label": 0 }, { "idx": "cosqa-dev-18", "doc": "python get top max values from dictionary", "code": "def get_keys_of_max_n(dict_obj, n):\n \"\"\"Returns the keys that maps to the top n max values in the given dict.\n\n Example:\n --------\n >>> dict_obj = {'a':2, 'b':1, 'c':5}\n >>> get_keys_of_max_n(dict_obj, 2)\n ['a', 'c']\n \"\"\"\n return sorted([\n item[0]\n for item in sorted(\n dict_obj.items(), key=lambda item: item[1], reverse=True\n )[:n]\n ])", "code_tokens": "def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )", "docstring_tokens": "Returns the keys that maps to the top n max values in the given dict .", "label": 1 }, { "idx": "cosqa-dev-19", "doc": "python remove comments in string from /* */", "code": "def CleanseComments(line):\n \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n Args:\n line: A line of C++ source.\n\n Returns:\n The line with single-line comments removed.\n \"\"\"\n commentpos = line.find('//')\n if commentpos != -1 and not IsCppString(line[:commentpos]):\n line = line[:commentpos].rstrip()\n # get rid of /* ... */\n return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "code_tokens": "def CleanseComments ( line ) : commentpos = line . find ( '//' ) if commentpos != - 1 and not IsCppString ( line [ : commentpos ] ) : line = line [ : commentpos ] . rstrip ( ) # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS . sub ( '' , line )", "docstring_tokens": "Removes // - comments and single - line C - style / * * / comments .", "label": 1 }, { "idx": "cosqa-dev-20", "doc": "how to put an exit button in python", "code": "def exit(self):\n \"\"\"Handle interactive exit.\n\n This method calls the ask_exit callback.\"\"\"\n if self.confirm_exit:\n if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):\n self.ask_exit()\n else:\n self.ask_exit()", "code_tokens": "def exit ( self ) : if self . confirm_exit : if self . ask_yes_no ( 'Do you really want to exit ([y]/n)?' , 'y' ) : self . ask_exit ( ) else : self . ask_exit ( )", "docstring_tokens": "Handle interactive exit .", "label": 0 }, { "idx": "cosqa-dev-21", "doc": "how to run 2to3 on python", "code": "def command_py2to3(args):\n \"\"\"\n Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.\n \"\"\"\n from lib2to3.main import main\n sys.exit(main(\"lib2to3.fixes\", args=args.sources))", "code_tokens": "def command_py2to3 ( args ) : from lib2to3 . main import main sys . exit ( main ( \"lib2to3.fixes\" , args = args . sources ) )", "docstring_tokens": "Apply 2to3 tool ( Python2 to Python3 conversion tool ) to Python sources .", "label": 1 }, { "idx": "cosqa-dev-22", "doc": "wrap a function python explicit keyword", "code": "def map_wrap(f):\n \"\"\"Wrap standard function to easily pass into 'map' processing.\n \"\"\"\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n return wrapper", "code_tokens": "def map_wrap ( f ) : @ functools . wraps ( f ) def wrapper ( * args , * * kwargs ) : return f ( * args , * * kwargs ) return wrapper", "docstring_tokens": "Wrap standard function to easily pass into map processing .", "label": 0 }, { "idx": "cosqa-dev-23", "doc": "argparse run function python", "code": "def cli_run():\n \"\"\"docstring for argparse\"\"\"\n parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')\n parser.add_argument('query', help=\"What's the problem ?\", type=str, nargs='+')\n parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')\n args = parser.parse_args()\n main(args)", "code_tokens": "def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = \"What's the problem ?\" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )", "docstring_tokens": "docstring for argparse", "label": 1 }, { "idx": "cosqa-dev-24", "doc": "python array to numpy scalar", "code": "def is_scalar(value):\n \"\"\"Test if the given value is a scalar.\n\n This function also works with memory mapped array values, in contrast to the numpy is_scalar method.\n\n Args:\n value: the value to test for being a scalar value\n\n Returns:\n boolean: if the given value is a scalar or not\n \"\"\"\n return np.isscalar(value) or (isinstance(value, np.ndarray) and (len(np.squeeze(value).shape) == 0))", "code_tokens": "def is_scalar ( value ) : return np . isscalar ( value ) or ( isinstance ( value , np . ndarray ) and ( len ( np . squeeze ( value ) . shape ) == 0 ) )", "docstring_tokens": "Test if the given value is a scalar .", "label": 0 }, { "idx": "cosqa-dev-25", "doc": "python include file from a super directory", "code": "def setup_path():\n \"\"\"Sets up the python include paths to include src\"\"\"\n import os.path; import sys\n\n if sys.argv[0]:\n top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n sys.path = [os.path.join(top_dir, \"src\")] + sys.path\n pass\n return", "code_tokens": "def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , \"src\" ) ] + sys . path pass return", "docstring_tokens": "Sets up the python include paths to include src", "label": 1 }, { "idx": "cosqa-dev-26", "doc": "how to get a list of prime numbers in python", "code": "def getPrimeFactors(n):\n \"\"\"\n Get all the prime factor of given integer\n @param n integer\n @return list [1, ..., n]\n \"\"\"\n lo = [1]\n n2 = n // 2\n k = 2\n for k in range(2, n2 + 1):\n if (n // k)*k == n:\n lo.append(k)\n return lo + [n, ]", "code_tokens": "def getPrimeFactors ( n ) : lo = [ 1 ] n2 = n // 2 k = 2 for k in range ( 2 , n2 + 1 ) : if ( n // k ) * k == n : lo . append ( k ) return lo + [ n , ]", "docstring_tokens": "Get all the prime factor of given integer", "label": 0 }, { "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 }, { "idx": "cosqa-dev-28", "doc": "python int to bin", "code": "def intToBin(i):\n \"\"\" Integer to two bytes \"\"\"\n # devide in two parts (bytes)\n i1 = i % 256\n i2 = int(i / 256)\n # make string (little endian)\n return chr(i1) + chr(i2)", "code_tokens": "def intToBin ( i ) : # devide in two parts (bytes) i1 = i % 256 i2 = int ( i / 256 ) # make string (little endian) return chr ( i1 ) + chr ( i2 )", "docstring_tokens": "Integer to two bytes", "label": 1 }, { "idx": "cosqa-dev-29", "doc": "python extract text from all child nodes", "code": "def _extract_node_text(node):\n \"\"\"Extract text from a given lxml node.\"\"\"\n\n texts = map(\n six.text_type.strip, map(six.text_type, map(unescape, node.xpath(\".//text()\")))\n )\n return \" \".join(text for text in texts if text)", "code_tokens": "def _extract_node_text ( node ) : texts = map ( six . text_type . strip , map ( six . text_type , map ( unescape , node . xpath ( \".//text()\" ) ) ) ) return \" \" . join ( text for text in texts if text )", "docstring_tokens": "Extract text from a given lxml node .", "label": 1 }, { "idx": "cosqa-dev-30", "doc": "check if a is df or not python", "code": "def is_float_array(l):\n r\"\"\"Checks if l is a numpy array of floats (any dimension\n\n \"\"\"\n if isinstance(l, np.ndarray):\n if l.dtype.kind == 'f':\n return True\n return False", "code_tokens": "def is_float_array ( l ) : if isinstance ( l , np . ndarray ) : if l . dtype . kind == 'f' : return True return False", "docstring_tokens": "r Checks if l is a numpy array of floats ( any dimension", "label": 0 }, { "idx": "cosqa-dev-31", "doc": "object of type bytes is not json serializable python", "code": "def loadb(b):\n \"\"\"Deserialize ``b`` (instance of ``bytes``) to a Python object.\"\"\"\n assert isinstance(b, (bytes, bytearray))\n return std_json.loads(b.decode('utf-8'))", "code_tokens": "def loadb ( b ) : assert isinstance ( b , ( bytes , bytearray ) ) return std_json . loads ( b . decode ( 'utf-8' ) )", "docstring_tokens": "Deserialize b ( instance of bytes ) to a Python object .", "label": 0 }, { "idx": "cosqa-dev-32", "doc": "how to check memory usage in python", "code": "def psutil_phymem_usage():\n \"\"\"\n Return physical memory usage (float)\n Requires the cross-platform psutil (>=v0.3) library\n (https://github.com/giampaolo/psutil)\n \"\"\"\n import psutil\n # This is needed to avoid a deprecation warning error with\n # newer psutil versions\n try:\n percent = psutil.virtual_memory().percent\n except:\n percent = psutil.phymem_usage().percent\n return percent", "code_tokens": "def psutil_phymem_usage ( ) : import psutil # This is needed to avoid a deprecation warning error with\n # newer psutil versions\n try : percent = psutil . virtual_memory ( ) . percent except : percent = psutil . phymem_usage ( ) . percent return percent", "docstring_tokens": "Return physical memory usage ( float ) Requires the cross - platform psutil ( > = v0 . 3 ) library ( https : // github . com / giampaolo / psutil )", "label": 1 }, { "idx": "cosqa-dev-33", "doc": "python see if file contains a line", "code": "def is_line_in_file(filename: str, line: str) -> bool:\n \"\"\"\n Detects whether a line is present within a file.\n\n Args:\n filename: file to check\n line: line to search for (as an exact match)\n \"\"\"\n assert \"\\n\" not in line\n with open(filename, \"r\") as file:\n for fileline in file:\n if fileline == line:\n return True\n return False", "code_tokens": "def is_line_in_file ( filename : str , line : str ) -> bool : assert \"\\n\" not in line with open ( filename , \"r\" ) as file : for fileline in file : if fileline == line : return True return False", "docstring_tokens": "Detects whether a line is present within a file .", "label": 1 }, { "idx": "cosqa-dev-34", "doc": "how to plot the distribution in python", "code": "def plot(self):\n \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "code_tokens": "def plot ( self ) : plt . plot ( self . bin_edges , self . hist , self . bin_edges , self . best_pdf )", "docstring_tokens": "Plot the empirical histogram versus best - fit distribution s PDF .", "label": 0 }, { "idx": "cosqa-dev-35", "doc": "format function to make table python", "code": "def adapter(data, headers, **kwargs):\n \"\"\"Wrap vertical table in a function for TabularOutputFormatter.\"\"\"\n keys = ('sep_title', 'sep_character', 'sep_length')\n return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))", "code_tokens": "def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )", "docstring_tokens": "Wrap vertical table in a function for TabularOutputFormatter .", "label": 0 }, { "idx": "cosqa-dev-36", "doc": "python get current language", "code": "def get_language(self):\n \"\"\"\n Get the language parameter from the current request.\n \"\"\"\n return get_language_parameter(self.request, self.query_language_key, default=self.get_default_language(object=object))", "code_tokens": "def get_language ( self ) : return get_language_parameter ( self . request , self . query_language_key , default = self . get_default_language ( object = object ) )", "docstring_tokens": "Get the language parameter from the current request .", "label": 1 }, { "idx": "cosqa-dev-37", "doc": "random number normal distribution in python", "code": "def rnormal(mu, tau, size=None):\n \"\"\"\n Random normal variates.\n \"\"\"\n return np.random.normal(mu, 1. / np.sqrt(tau), size)", "code_tokens": "def rnormal ( mu , tau , size = None ) : return np . random . normal ( mu , 1. / np . sqrt ( tau ) , size )", "docstring_tokens": "Random normal variates .", "label": 1 }, { "idx": "cosqa-dev-38", "doc": "python logging stop wrapping text at characters", "code": "def write(self, text):\n \"\"\"Write text. An additional attribute terminator with a value of\n None is added to the logging record to indicate that StreamHandler\n should not add a newline.\"\"\"\n self.logger.log(self.loglevel, text, extra={'terminator': None})", "code_tokens": "def write ( self , text ) : self . logger . log ( self . loglevel , text , extra = { 'terminator' : None } )", "docstring_tokens": "Write text . An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler should not add a newline .", "label": 0 }, { "idx": "cosqa-dev-39", "doc": "how to get the index of something in a list python", "code": "def sorted_index(values, x):\n \"\"\"\n For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n :param values: list\n :param x: item\n :return: integer index\n \"\"\"\n i = bisect_left(values, x)\n j = bisect_right(values, x)\n return values[i:j].index(x) + i", "code_tokens": "def sorted_index ( values , x ) : i = bisect_left ( values , x ) j = bisect_right ( values , x ) return values [ i : j ] . index ( x ) + i", "docstring_tokens": "For list values returns the index location of element x . If x does not exist will raise an error .", "label": 0 }, { "idx": "cosqa-dev-40", "doc": "list spefic file extension python", "code": "def _get_compiled_ext():\n \"\"\"Official way to get the extension of compiled files (.pyc or .pyo)\"\"\"\n for ext, mode, typ in imp.get_suffixes():\n if typ == imp.PY_COMPILED:\n return ext", "code_tokens": "def _get_compiled_ext ( ) : for ext , mode , typ in imp . get_suffixes ( ) : if typ == imp . PY_COMPILED : return ext", "docstring_tokens": "Official way to get the extension of compiled files ( . pyc or . pyo )", "label": 0 }, { "idx": "cosqa-dev-41", "doc": "how to flatten a list using python", "code": "def flatten_list(l: List[list]) -> list:\n \"\"\" takes a list of lists, l and returns a flat list\n \"\"\"\n return [v for inner_l in l for v in inner_l]", "code_tokens": "def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]", "docstring_tokens": "takes a list of lists l and returns a flat list", "label": 1 }, { "idx": "cosqa-dev-42", "doc": "how to reset multi index python", "code": "def cmd_reindex():\n \"\"\"Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.\n\n The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until\n the rename succeeds.\n \"\"\"\n db = connect(args.database)\n for idx in args.indexes:\n pg_reindex(db, idx)", "code_tokens": "def cmd_reindex ( ) : db = connect ( args . database ) for idx in args . indexes : pg_reindex ( db , idx )", "docstring_tokens": "Uses CREATE INDEX CONCURRENTLY to create a duplicate index then tries to swap the new index for the original .", "label": 0 }, { "idx": "cosqa-dev-43", "doc": "delete value from heap python", "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 }, { "idx": "cosqa-dev-44", "doc": "python tkinter choose folder button", "code": "def on_source_directory_chooser_clicked(self):\n \"\"\"Autoconnect slot activated when tbSourceDir is clicked.\"\"\"\n\n title = self.tr('Set the source directory for script and scenario')\n self.choose_directory(self.source_directory, title)", "code_tokens": "def on_source_directory_chooser_clicked ( self ) : title = self . tr ( 'Set the source directory for script and scenario' ) self . choose_directory ( self . source_directory , title )", "docstring_tokens": "Autoconnect slot activated when tbSourceDir is clicked .", "label": 0 }, { "idx": "cosqa-dev-45", "doc": "save and load keras model python", "code": "def save_keras_definition(keras_model, path):\n \"\"\"\n Save a Keras model definition to JSON with given path\n \"\"\"\n model_json = keras_model.to_json()\n with open(path, \"w\") as json_file:\n json_file.write(model_json)", "code_tokens": "def save_keras_definition ( keras_model , path ) : model_json = keras_model . to_json ( ) with open ( path , \"w\" ) as json_file : json_file . write ( model_json )", "docstring_tokens": "Save a Keras model definition to JSON with given path", "label": 0 }, { "idx": "cosqa-dev-46", "doc": "python3 how to know a sring is bytes", "code": "def bytes_to_str(s, encoding='utf-8'):\n \"\"\"Returns a str if a bytes object is given.\"\"\"\n if six.PY3 and isinstance(s, bytes):\n return s.decode(encoding)\n return s", "code_tokens": "def bytes_to_str ( s , encoding = 'utf-8' ) : if six . PY3 and isinstance ( s , bytes ) : return s . decode ( encoding ) return s", "docstring_tokens": "Returns a str if a bytes object is given .", "label": 0 }, { "idx": "cosqa-dev-47", "doc": "set xticks for every axes python", "code": "def set_xticks_for_all(self, row_column_list=None, ticks=None):\n \"\"\"Manually specify the x-axis tick values.\n\n :param row_column_list: a list containing (row, column) tuples to\n specify the subplots, or None to indicate *all* subplots.\n :type row_column_list: list or None\n :param ticks: list of tick values.\n\n \"\"\"\n if row_column_list is None:\n self.ticks['x'] = ticks\n else:\n for row, column in row_column_list:\n self.set_xticks(row, column, ticks)", "code_tokens": "def set_xticks_for_all ( self , row_column_list = None , ticks = None ) : if row_column_list is None : self . ticks [ 'x' ] = ticks else : for row , column in row_column_list : self . set_xticks ( row , column , ticks )", "docstring_tokens": "Manually specify the x - axis tick values .", "label": 1 }, { "idx": "cosqa-dev-48", "doc": "python pass object to format", "code": "def __str__(self):\n \"\"\"Returns a pretty-printed string for this object.\"\"\"\n return 'Output name: \"%s\" watts: %d type: \"%s\" id: %d' % (\n self._name, self._watts, self._output_type, self._integration_id)", "code_tokens": "def __str__ ( self ) : return 'Output name: \"%s\" watts: %d type: \"%s\" id: %d' % ( self . _name , self . _watts , self . _output_type , self . _integration_id )", "docstring_tokens": "Returns a pretty - printed string for this object .", "label": 0 }, { "idx": "cosqa-dev-49", "doc": "how to make a drop down menu on python", "code": "def separator(self, menu=None):\n \"\"\"Add a separator\"\"\"\n self.gui.get_menu(menu or self.menu).addSeparator()", "code_tokens": "def separator ( self , menu = None ) : self . gui . get_menu ( menu or self . menu ) . addSeparator ( )", "docstring_tokens": "Add a separator", "label": 0 }, { "idx": "cosqa-dev-50", "doc": "python numpy apply function to vector", "code": "def unit_vector(x):\n \"\"\"Return a unit vector in the same direction as x.\"\"\"\n y = np.array(x, dtype='float')\n return y/norm(y)", "code_tokens": "def unit_vector ( x ) : y = np . array ( x , dtype = 'float' ) return y / norm ( y )", "docstring_tokens": "Return a unit vector in the same direction as x .", "label": 0 }, { "idx": "cosqa-dev-51", "doc": "python finding last occurance of string", "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 }, { "idx": "cosqa-dev-52", "doc": "calculate manhattan distance from minkowski and pearson python", "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 }, { "idx": "cosqa-dev-53", "doc": "python parse date on a data frame", "code": "def _parse(self, date_str, format='%Y-%m-%d'):\n \"\"\"\n helper function for parsing FRED date string into datetime\n \"\"\"\n rv = pd.to_datetime(date_str, format=format)\n if hasattr(rv, 'to_pydatetime'):\n rv = rv.to_pydatetime()\n return rv", "code_tokens": "def _parse ( self , date_str , format = '%Y-%m-%d' ) : rv = pd . to_datetime ( date_str , format = format ) if hasattr ( rv , 'to_pydatetime' ) : rv = rv . to_pydatetime ( ) return rv", "docstring_tokens": "helper function for parsing FRED date string into datetime", "label": 0 }, { "idx": "cosqa-dev-54", "doc": "python remove legend once plotted", "code": "def remove_legend(ax=None):\n \"\"\"Remove legend for axes or gca.\n\n See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html\n \"\"\"\n from pylab import gca, draw\n if ax is None:\n ax = gca()\n ax.legend_ = None\n draw()", "code_tokens": "def remove_legend ( ax = None ) : from pylab import gca , draw if ax is None : ax = gca ( ) ax . legend_ = None draw ( )", "docstring_tokens": "Remove legend for axes or gca .", "label": 1 }, { "idx": "cosqa-dev-55", "doc": "average length of a words in a set python", "code": "def get_average_length_of_string(strings):\n \"\"\"Computes average length of words\n\n :param strings: list of words\n :return: Average length of word on list\n \"\"\"\n if not strings:\n return 0\n\n return sum(len(word) for word in strings) / len(strings)", "code_tokens": "def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings )", "docstring_tokens": "Computes average length of words", "label": 1 }, { "idx": "cosqa-dev-56", "doc": "python set check is consists an element", "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 }, { "idx": "cosqa-dev-57", "doc": "python distort image like fisheye", "code": "def post_process(self):\n \"\"\" Apply last 2D transforms\"\"\"\n self.image.putdata(self.pixels)\n self.image = self.image.transpose(Image.ROTATE_90)", "code_tokens": "def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )", "docstring_tokens": "Apply last 2D transforms", "label": 0 }, { "idx": "cosqa-dev-58", "doc": "how to add a string to a filename in 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 }, { "idx": "cosqa-dev-59", "doc": "push item to top of stack python", "code": "def _heappush_max(heap, item):\n \"\"\" why is this not in heapq \"\"\"\n heap.append(item)\n heapq._siftdown_max(heap, 0, len(heap) - 1)", "code_tokens": "def _heappush_max ( heap , item ) : heap . append ( item ) heapq . _siftdown_max ( heap , 0 , len ( heap ) - 1 )", "docstring_tokens": "why is this not in heapq", "label": 0 }, { "idx": "cosqa-dev-60", "doc": "how to multiply unknown by matrix in python", "code": "def __rmatmul__(self, other):\n \"\"\"\n Matrix multiplication using binary `@` operator in Python>=3.5.\n \"\"\"\n return self.T.dot(np.transpose(other)).T", "code_tokens": "def __rmatmul__ ( self , other ) : return self . T . dot ( np . transpose ( other ) ) . T", "docstring_tokens": "Matrix multiplication using binary", "label": 0 }, { "idx": "cosqa-dev-61", "doc": "how to send a string in output stream python", "code": "def _send_cmd(self, cmd):\n \"\"\"Write command to remote process\n \"\"\"\n self._process.stdin.write(\"{}\\n\".format(cmd).encode(\"utf-8\"))\n self._process.stdin.flush()", "code_tokens": "def _send_cmd ( self , cmd ) : self . _process . stdin . write ( \"{}\\n\" . format ( cmd ) . encode ( \"utf-8\" ) ) self . _process . stdin . flush ( )", "docstring_tokens": "Write command to remote process", "label": 0 }, { "idx": "cosqa-dev-62", "doc": "how to check a variable is float in python", "code": "def parse_reading(val: str) -> Optional[float]:\n \"\"\" Convert reading value to float (if possible) \"\"\"\n try:\n return float(val)\n except ValueError:\n logging.warning('Reading of \"%s\" is not a number', val)\n return None", "code_tokens": "def parse_reading ( val : str ) -> Optional [ float ] : try : return float ( val ) except ValueError : logging . warning ( 'Reading of \"%s\" is not a number' , val ) return None", "docstring_tokens": "Convert reading value to float ( if possible )", "label": 0 }, { "idx": "cosqa-dev-63", "doc": "how to iterate through hash functions python", "code": "def omnihash(obj):\n \"\"\" recursively hash unhashable objects \"\"\"\n if isinstance(obj, set):\n return hash(frozenset(omnihash(e) for e in obj))\n elif isinstance(obj, (tuple, list)):\n return hash(tuple(omnihash(e) for e in obj))\n elif isinstance(obj, dict):\n return hash(frozenset((k, omnihash(v)) for k, v in obj.items()))\n else:\n return hash(obj)", "code_tokens": "def omnihash ( obj ) : if isinstance ( obj , set ) : return hash ( frozenset ( omnihash ( e ) for e in obj ) ) elif isinstance ( obj , ( tuple , list ) ) : return hash ( tuple ( omnihash ( e ) for e in obj ) ) elif isinstance ( obj , dict ) : return hash ( frozenset ( ( k , omnihash ( v ) ) for k , v in obj . items ( ) ) ) else : return hash ( obj )", "docstring_tokens": "recursively hash unhashable objects", "label": 0 }, { "idx": "cosqa-dev-64", "doc": "python return first 2 dimensions of 3 dimensional array", "code": "def quaternion_imag(quaternion):\n \"\"\"Return imaginary part of quaternion.\n\n >>> quaternion_imag([3, 0, 1, 2])\n array([0., 1., 2.])\n\n \"\"\"\n return np.array(quaternion[1:4], dtype=np.float64, copy=True)", "code_tokens": "def quaternion_imag ( quaternion ) : return np . array ( quaternion [ 1 : 4 ] , dtype = np . float64 , copy = True )", "docstring_tokens": "Return imaginary part of quaternion .", "label": 0 }, { "idx": "cosqa-dev-65", "doc": "make jinja2 fast python", "code": "def clear_caches():\n \"\"\"Jinja2 keeps internal caches for environments and lexers. These are\n used so that Jinja2 doesn't have to recreate environments and lexers all\n the time. Normally you don't have to care about that but if you are\n measuring memory consumption you may want to clean the caches.\n \"\"\"\n from jinja2.environment import _spontaneous_environments\n from jinja2.lexer import _lexer_cache\n _spontaneous_environments.clear()\n _lexer_cache.clear()", "code_tokens": "def clear_caches ( ) : from jinja2 . environment import _spontaneous_environments from jinja2 . lexer import _lexer_cache _spontaneous_environments . clear ( ) _lexer_cache . clear ( )", "docstring_tokens": "Jinja2 keeps internal caches for environments and lexers . These are used so that Jinja2 doesn t have to recreate environments and lexers all the time . Normally you don t have to care about that but if you are measuring memory consumption you may want to clean the caches .", "label": 0 }, { "idx": "cosqa-dev-66", "doc": "python create object without class", "code": "def create_object(cls, members):\n \"\"\"Promise an object of class `cls` with content `members`.\"\"\"\n obj = cls.__new__(cls)\n obj.__dict__ = members\n return obj", "code_tokens": "def create_object ( cls , members ) : obj = cls . __new__ ( cls ) obj . __dict__ = members return obj", "docstring_tokens": "Promise an object of class cls with content members .", "label": 1 }, { "idx": "cosqa-dev-67", "doc": "remove node from bst python", "code": "def remove_from_lib(self, name):\n \"\"\" Remove an object from the bin folder. \"\"\"\n self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "code_tokens": "def remove_from_lib ( self , name ) : self . __remove_path ( os . path . join ( self . root_dir , \"lib\" , name ) )", "docstring_tokens": "Remove an object from the bin folder .", "label": 0 }, { "idx": "cosqa-dev-68", "doc": "python show traceback nice", "code": "def format_exc(*exc_info):\n \"\"\"Show exception with traceback.\"\"\"\n typ, exc, tb = exc_info or sys.exc_info()\n error = traceback.format_exception(typ, exc, tb)\n return \"\".join(error)", "code_tokens": "def format_exc ( * exc_info ) : typ , exc , tb = exc_info or sys . exc_info ( ) error = traceback . format_exception ( typ , exc , tb ) return \"\" . join ( error )", "docstring_tokens": "Show exception with traceback .", "label": 0 }, { "idx": "cosqa-dev-69", "doc": "sqlite python fetch as dict", "code": "def sqliteRowsToDicts(sqliteRows):\n \"\"\"\n Unpacks sqlite rows as returned by fetchall\n into an array of simple dicts.\n\n :param sqliteRows: array of rows returned from fetchall DB call\n :return: array of dicts, keyed by the column names.\n \"\"\"\n return map(lambda r: dict(zip(r.keys(), r)), sqliteRows)", "code_tokens": "def sqliteRowsToDicts ( sqliteRows ) : return map ( lambda r : dict ( zip ( r . keys ( ) , r ) ) , sqliteRows )", "docstring_tokens": "Unpacks sqlite rows as returned by fetchall into an array of simple dicts .", "label": 1 }, { "idx": "cosqa-dev-70", "doc": "python object remove attribute", "code": "def delete(self):\n \"\"\"Remove this object.\"\"\"\n self._client.remove_object(self._instance, self._bucket, self.name)", "code_tokens": "def delete ( self ) : self . _client . remove_object ( self . _instance , self . _bucket , self . name )", "docstring_tokens": "Remove this object .", "label": 0 }, { "idx": "cosqa-dev-71", "doc": "python gtk get toplevel widget", "code": "def get_builder_toplevel(self, builder):\n \"\"\"Get the toplevel widget from a gtk.Builder file.\n\n The main view implementation first searches for the widget named as\n self.toplevel_name (which defaults to \"main\". If this is missing, or not\n a gtk.Window, the first toplevel window found in the gtk.Builder is\n used.\n \"\"\"\n toplevel = builder.get_object(self.toplevel_name)\n if not gobject.type_is_a(toplevel, gtk.Window):\n toplevel = None\n if toplevel is None:\n toplevel = get_first_builder_window(builder)\n return toplevel", "code_tokens": "def get_builder_toplevel ( self , builder ) : toplevel = builder . get_object ( self . toplevel_name ) if not gobject . type_is_a ( toplevel , gtk . Window ) : toplevel = None if toplevel is None : toplevel = get_first_builder_window ( builder ) return toplevel", "docstring_tokens": "Get the toplevel widget from a gtk . Builder file .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-73", "doc": "python int ip to string", "code": "def _get_binary_from_ipv4(self, ip_addr):\n \"\"\"Converts IPv4 address to binary form.\"\"\"\n\n return struct.unpack(\"!L\", socket.inet_pton(socket.AF_INET,\n ip_addr))[0]", "code_tokens": "def _get_binary_from_ipv4 ( self , ip_addr ) : return struct . unpack ( \"!L\" , socket . inet_pton ( socket . AF_INET , ip_addr ) ) [ 0 ]", "docstring_tokens": "Converts IPv4 address to binary form .", "label": 0 }, { "idx": "cosqa-dev-74", "doc": "python returning a pdf", "code": "def _pdf_at_peak(self):\n \"\"\"Pdf evaluated at the peak.\"\"\"\n return (self.peak - self.low) / (self.high - self.low)", "code_tokens": "def _pdf_at_peak ( self ) : return ( self . peak - self . low ) / ( self . high - self . low )", "docstring_tokens": "Pdf evaluated at the peak .", "label": 0 }, { "idx": "cosqa-dev-75", "doc": "temporary cache files in python", "code": "def is_cached(file_name):\n\t\"\"\"\n\tCheck if a given file is available in the cache or not\n\t\"\"\"\n\n\tgml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)\n\n\treturn isfile(gml_file_path)", "code_tokens": "def is_cached ( file_name ) : gml_file_path = join ( join ( expanduser ( '~' ) , OCTOGRID_DIRECTORY ) , file_name ) return isfile ( gml_file_path )", "docstring_tokens": "Check if a given file is available in the cache or not", "label": 0 }, { "idx": "cosqa-dev-76", "doc": "function in python to strip spaces", "code": "def strip_spaces(s):\n \"\"\" Strip excess spaces from a string \"\"\"\n return u\" \".join([c for c in s.split(u' ') if c])", "code_tokens": "def strip_spaces ( s ) : return u\" \" . join ( [ c for c in s . split ( u' ' ) if c ] )", "docstring_tokens": "Strip excess spaces from a string", "label": 1 }, { "idx": "cosqa-dev-77", "doc": "return columns of type python", "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": 0 }, { "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 }, { "idx": "cosqa-dev-79", "doc": "python json back to type", "code": "def _default(self, obj):\n \"\"\" return a serialized version of obj or raise a TypeError\n\n :param obj:\n :return: Serialized version of obj\n \"\"\"\n return obj.__dict__ if isinstance(obj, JsonObj) else json.JSONDecoder().decode(obj)", "code_tokens": "def _default ( self , obj ) : return obj . __dict__ if isinstance ( obj , JsonObj ) else json . JSONDecoder ( ) . decode ( obj )", "docstring_tokens": "return a serialized version of obj or raise a TypeError", "label": 0 }, { "idx": "cosqa-dev-80", "doc": "python random normal specify range", "code": "def runiform(lower, upper, size=None):\n \"\"\"\n Random uniform variates.\n \"\"\"\n return np.random.uniform(lower, upper, size)", "code_tokens": "def runiform ( lower , upper , size = None ) : return np . random . uniform ( lower , upper , size )", "docstring_tokens": "Random uniform variates .", "label": 1 }, { "idx": "cosqa-dev-81", "doc": "wxpython add horizontal line", "code": "def get_hline():\n \"\"\" gets a horiztonal line \"\"\"\n return Window(\n width=LayoutDimension.exact(1),\n height=LayoutDimension.exact(1),\n content=FillControl('-', token=Token.Line))", "code_tokens": "def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) )", "docstring_tokens": "gets a horiztonal line", "label": 1 }, { "idx": "cosqa-dev-82", "doc": "how to return a list of files sorted by file creation time python", "code": "def sort_by_modified(files_or_folders: list) -> list:\n \"\"\"\n Sort files or folders by modified time\n\n Args:\n files_or_folders: list of files or folders\n\n Returns:\n list\n \"\"\"\n return sorted(files_or_folders, key=os.path.getmtime, reverse=True)", "code_tokens": "def sort_by_modified ( files_or_folders : list ) -> list : return sorted ( files_or_folders , key = os . path . getmtime , reverse = True )", "docstring_tokens": "Sort files or folders by modified time", "label": 1 }, { "idx": "cosqa-dev-83", "doc": "python parsing a string into datetime", "code": "def parse_datetime(dt_str):\n \"\"\"Parse datetime.\"\"\"\n date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n dt_str = dt_str.replace(\"Z\", \" +0000\")\n return datetime.datetime.strptime(dt_str, date_format)", "code_tokens": "def parse_datetime ( dt_str ) : date_format = \"%Y-%m-%dT%H:%M:%S %z\" dt_str = dt_str . replace ( \"Z\" , \" +0000\" ) return datetime . datetime . strptime ( dt_str , date_format )", "docstring_tokens": "Parse datetime .", "label": 1 }, { "idx": "cosqa-dev-84", "doc": "python interpolate datetime index", "code": "def spline_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis):\n \"\"\"A datetime-version that takes datetime object list as x_axis\n \"\"\"\n numeric_datetime_axis = [\n totimestamp(a_datetime) for a_datetime in datetime_axis\n ]\n\n numeric_datetime_new_axis = [\n totimestamp(a_datetime) for a_datetime in datetime_new_axis\n ]\n\n return spline_interpolate(\n numeric_datetime_axis, y_axis, numeric_datetime_new_axis)", "code_tokens": "def spline_interpolate_by_datetime ( datetime_axis , y_axis , datetime_new_axis ) : numeric_datetime_axis = [ totimestamp ( a_datetime ) for a_datetime in datetime_axis ] numeric_datetime_new_axis = [ totimestamp ( a_datetime ) for a_datetime in datetime_new_axis ] return spline_interpolate ( numeric_datetime_axis , y_axis , numeric_datetime_new_axis )", "docstring_tokens": "A datetime - version that takes datetime object list as x_axis", "label": 0 }, { "idx": "cosqa-dev-85", "doc": "python array save and load", "code": "def _openResources(self):\n \"\"\" Uses numpy.load to open the underlying file\n \"\"\"\n arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)\n check_is_an_array(arr)\n self._array = arr", "code_tokens": "def _openResources ( self ) : arr = np . load ( self . _fileName , allow_pickle = ALLOW_PICKLE ) check_is_an_array ( arr ) self . _array = arr", "docstring_tokens": "Uses numpy . load to open the underlying file", "label": 0 }, { "idx": "cosqa-dev-86", "doc": "python linear interpolate value on line segment", "code": "def _linear_interpolation(x, X, Y):\n \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n \"\"\"\n return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])", "code_tokens": "def _linear_interpolation ( x , X , Y ) : return ( Y [ 1 ] * ( x - X [ 0 ] ) + Y [ 0 ] * ( X [ 1 ] - x ) ) / ( X [ 1 ] - X [ 0 ] )", "docstring_tokens": "Given two data points [ X Y ] linearly interpolate those at x .", "label": 1 }, { "idx": "cosqa-dev-87", "doc": "python returning a wrapped function", "code": "def map_wrap(f):\n \"\"\"Wrap standard function to easily pass into 'map' processing.\n \"\"\"\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n return f(*args, **kwargs)\n return wrapper", "code_tokens": "def map_wrap ( f ) : @ functools . wraps ( f ) def wrapper ( * args , * * kwargs ) : return f ( * args , * * kwargs ) return wrapper", "docstring_tokens": "Wrap standard function to easily pass into map processing .", "label": 0 }, { "idx": "cosqa-dev-88", "doc": "python tkinter does trace call in another trace", "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": 0 }, { "idx": "cosqa-dev-89", "doc": "check is two paths are equivalent python", "code": "def samefile(a: str, b: str) -> bool:\n \"\"\"Check if two pathes represent the same file.\"\"\"\n try:\n return os.path.samefile(a, b)\n except OSError:\n return os.path.normpath(a) == os.path.normpath(b)", "code_tokens": "def samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )", "docstring_tokens": "Check if two pathes represent the same file .", "label": 1 }, { "idx": "cosqa-dev-90", "doc": "python get file basename without extension", "code": "def remove_ext(fname):\n \"\"\"Removes the extension from a filename\n \"\"\"\n bn = os.path.basename(fname)\n return os.path.splitext(bn)[0]", "code_tokens": "def remove_ext ( fname ) : bn = os . path . basename ( fname ) return os . path . splitext ( bn ) [ 0 ]", "docstring_tokens": "Removes the extension from a filename", "label": 1 }, { "idx": "cosqa-dev-91", "doc": "python set to value of dictionary if exists else defaul", "code": "def setdefaults(dct, defaults):\n \"\"\"Given a target dct and a dict of {key:default value} pairs,\n calls setdefault for all of those pairs.\"\"\"\n for key in defaults:\n dct.setdefault(key, defaults[key])\n\n return dct", "code_tokens": "def setdefaults ( dct , defaults ) : for key in defaults : dct . setdefault ( key , defaults [ key ] ) return dct", "docstring_tokens": "Given a target dct and a dict of { key : default value } pairs calls setdefault for all of those pairs .", "label": 1 }, { "idx": "cosqa-dev-92", "doc": "make a 2d array into 1d python", "code": "def _convert_to_array(array_like, dtype):\n \"\"\"\n Convert Matrix attributes which are array-like or buffer to array.\n \"\"\"\n if isinstance(array_like, bytes):\n return np.frombuffer(array_like, dtype=dtype)\n return np.asarray(array_like, dtype=dtype)", "code_tokens": "def _convert_to_array ( array_like , dtype ) : if isinstance ( array_like , bytes ) : return np . frombuffer ( array_like , dtype = dtype ) return np . asarray ( array_like , dtype = dtype )", "docstring_tokens": "Convert Matrix attributes which are array - like or buffer to array .", "label": 0 }, { "idx": "cosqa-dev-93", "doc": "python create range in steps", "code": "def _xxrange(self, start, end, step_count):\n \"\"\"Generate n values between start and end.\"\"\"\n _step = (end - start) / float(step_count)\n return (start + (i * _step) for i in xrange(int(step_count)))", "code_tokens": "def _xxrange ( self , start , end , step_count ) : _step = ( end - start ) / float ( step_count ) return ( start + ( i * _step ) for i in xrange ( int ( step_count ) ) )", "docstring_tokens": "Generate n values between start and end .", "label": 1 }, { "idx": "cosqa-dev-94", "doc": "python code to grab first and last index", "code": "def _rindex(mylist: Sequence[T], x: T) -> int:\n \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n return len(mylist) - mylist[::-1].index(x) - 1", "code_tokens": "def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1", "docstring_tokens": "Index of the last occurrence of x in the sequence .", "label": 0 }, { "idx": "cosqa-dev-95", "doc": "aws lambda request url python", "code": "def get_api_url(self, lambda_name, stage_name):\n \"\"\"\n Given a lambda_name and stage_name, return a valid API URL.\n \"\"\"\n api_id = self.get_api_id(lambda_name)\n if api_id:\n return \"https://{}.execute-api.{}.amazonaws.com/{}\".format(api_id, self.boto_session.region_name, stage_name)\n else:\n return None", "code_tokens": "def get_api_url ( self , lambda_name , stage_name ) : api_id = self . get_api_id ( lambda_name ) if api_id : return \"https://{}.execute-api.{}.amazonaws.com/{}\" . format ( api_id , self . boto_session . region_name , stage_name ) else : return None", "docstring_tokens": "Given a lambda_name and stage_name return a valid API URL .", "label": 0 }, { "idx": "cosqa-dev-96", "doc": "python regex remove c comments", "code": "def CleanseComments(line):\n \"\"\"Removes //-comments and single-line C-style /* */ comments.\n\n Args:\n line: A line of C++ source.\n\n Returns:\n The line with single-line comments removed.\n \"\"\"\n commentpos = line.find('//')\n if commentpos != -1 and not IsCppString(line[:commentpos]):\n line = line[:commentpos].rstrip()\n # get rid of /* ... */\n return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)", "code_tokens": "def CleanseComments ( line ) : commentpos = line . find ( '//' ) if commentpos != - 1 and not IsCppString ( line [ : commentpos ] ) : line = line [ : commentpos ] . rstrip ( ) # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS . sub ( '' , line )", "docstring_tokens": "Removes // - comments and single - line C - style / * * / comments .", "label": 1 }, { "idx": "cosqa-dev-97", "doc": "how to get block device information python linux", "code": "async def sysinfo(dev: Device):\n \"\"\"Print out system information (version, MAC addrs).\"\"\"\n click.echo(await dev.get_system_info())\n click.echo(await dev.get_interface_information())", "code_tokens": "async def sysinfo ( dev : Device ) : click . echo ( await dev . get_system_info ( ) ) click . echo ( await dev . get_interface_information ( ) )", "docstring_tokens": "Print out system information ( version MAC addrs ) .", "label": 0 }, { "idx": "cosqa-dev-98", "doc": "python re remove python block comments", "code": "def split_comment(cls, code):\n \"\"\" Removes comments (#...) from python code. \"\"\"\n if '#' not in code: return code\n #: Remove comments only (leave quoted strings as they are)\n subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0)\n return re.sub(cls.re_pytokens, subf, code)", "code_tokens": "def split_comment ( cls , code ) : if '#' not in code : return code #: Remove comments only (leave quoted strings as they are) subf = lambda m : '' if m . group ( 0 ) [ 0 ] == '#' else m . group ( 0 ) return re . sub ( cls . re_pytokens , subf , code )", "docstring_tokens": "Removes comments ( # ... ) from python code .", "label": 1 }, { "idx": "cosqa-dev-99", "doc": "python sort an object by a value", "code": "def csort(objs, key):\n \"\"\"Order-preserving sorting function.\"\"\"\n idxs = dict((obj, i) for (i, obj) in enumerate(objs))\n return sorted(objs, key=lambda obj: (key(obj), idxs[obj]))", "code_tokens": "def csort ( objs , key ) : idxs = dict ( ( obj , i ) for ( i , obj ) in enumerate ( objs ) ) return sorted ( objs , key = lambda obj : ( key ( obj ) , idxs [ obj ] ) )", "docstring_tokens": "Order - preserving sorting function .", "label": 1 }, { "idx": "cosqa-dev-100", "doc": "how to reset an object in python", "code": "def reset(self):\n \"\"\"Reset the instance\n\n - reset rows and header\n \"\"\"\n\n self._hline_string = None\n self._row_size = None\n self._header = []\n self._rows = []", "code_tokens": "def reset ( self ) : self . _hline_string = None self . _row_size = None self . _header = [ ] self . _rows = [ ]", "docstring_tokens": "Reset the instance", "label": 1 }, { "idx": "cosqa-dev-101", "doc": "python index object has no attribute remove", "code": "def _remove_from_index(index, obj):\n \"\"\"Removes object ``obj`` from the ``index``.\"\"\"\n try:\n index.value_map[indexed_value(index, obj)].remove(obj.id)\n except KeyError:\n pass", "code_tokens": "def _remove_from_index ( index , obj ) : try : index . value_map [ indexed_value ( index , obj ) ] . remove ( obj . id ) except KeyError : pass", "docstring_tokens": "Removes object obj from the index .", "label": 0 }, { "idx": "cosqa-dev-102", "doc": "python get cpu specifications", "code": "def get_system_cpu_times():\n \"\"\"Return system CPU times as a namedtuple.\"\"\"\n user, nice, system, idle = _psutil_osx.get_system_cpu_times()\n return _cputimes_ntuple(user, nice, system, idle)", "code_tokens": "def get_system_cpu_times ( ) : user , nice , system , idle = _psutil_osx . get_system_cpu_times ( ) return _cputimes_ntuple ( user , nice , system , idle )", "docstring_tokens": "Return system CPU times as a namedtuple .", "label": 1 }, { "idx": "cosqa-dev-103", "doc": "python output graph without graphviz", "code": "def cli(yamlfile, directory, out, classname, format):\n \"\"\" Generate graphviz representations of the biolink model \"\"\"\n DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)", "code_tokens": "def cli ( yamlfile , directory , out , classname , format ) : DotGenerator ( yamlfile , format ) . serialize ( classname = classname , dirname = directory , filename = out )", "docstring_tokens": "Generate graphviz representations of the biolink model", "label": 0 }, { "idx": "cosqa-dev-104", "doc": "how to make a single line comment in python", "code": "def comment (self, s, **args):\n \"\"\"Write DOT comment.\"\"\"\n self.write(u\"// \")\n self.writeln(s=s, **args)", "code_tokens": "def comment ( self , s , * * args ) : self . write ( u\"// \" ) self . writeln ( s = s , * * args )", "docstring_tokens": "Write DOT comment .", "label": 1 }, { "idx": "cosqa-dev-105", "doc": "heapify not working python", "code": "def _heappush_max(heap, item):\n \"\"\" why is this not in heapq \"\"\"\n heap.append(item)\n heapq._siftdown_max(heap, 0, len(heap) - 1)", "code_tokens": "def _heappush_max ( heap , item ) : heap . append ( item ) heapq . _siftdown_max ( heap , 0 , len ( heap ) - 1 )", "docstring_tokens": "why is this not in heapq", "label": 0 }, { "idx": "cosqa-dev-106", "doc": "get index of an item in list python", "code": "def sorted_index(values, x):\n \"\"\"\n For list, values, returns the index location of element x. If x does not exist will raise an error.\n\n :param values: list\n :param x: item\n :return: integer index\n \"\"\"\n i = bisect_left(values, x)\n j = bisect_right(values, x)\n return values[i:j].index(x) + i", "code_tokens": "def sorted_index ( values , x ) : i = bisect_left ( values , x ) j = bisect_right ( values , x ) return values [ i : j ] . index ( x ) + i", "docstring_tokens": "For list values returns the index location of element x . If x does not exist will raise an error .", "label": 1 }, { "idx": "cosqa-dev-107", "doc": "how to clear shell screen in python", "code": "def clear():\n \"\"\"Clears the console.\"\"\"\n if sys.platform.startswith(\"win\"):\n call(\"cls\", shell=True)\n else:\n call(\"clear\", shell=True)", "code_tokens": "def clear ( ) : if sys . platform . startswith ( \"win\" ) : call ( \"cls\" , shell = True ) else : call ( \"clear\" , shell = True )", "docstring_tokens": "Clears the console .", "label": 1 }, { "idx": "cosqa-dev-108", "doc": "python django models booleanfield default", "code": "def parse_value(self, value):\n \"\"\"Cast value to `bool`.\"\"\"\n parsed = super(BoolField, self).parse_value(value)\n return bool(parsed) if parsed is not None else None", "code_tokens": "def parse_value ( self , value ) : parsed = super ( BoolField , self ) . parse_value ( value ) return bool ( parsed ) if parsed is not None else None", "docstring_tokens": "Cast value to bool .", "label": 0 }, { "idx": "cosqa-dev-109", "doc": "keep track of position read file python", "code": "def get_known_read_position(fp, buffered=True):\n \"\"\" \n Return a position in a file which is known to be read & handled.\n It assumes a buffered file and streaming processing. \n \"\"\"\n buffer_size = io.DEFAULT_BUFFER_SIZE if buffered else 0\n return max(fp.tell() - buffer_size, 0)", "code_tokens": "def get_known_read_position ( fp , buffered = True ) : buffer_size = io . DEFAULT_BUFFER_SIZE if buffered else 0 return max ( fp . tell ( ) - buffer_size , 0 )", "docstring_tokens": "Return a position in a file which is known to be read & handled . It assumes a buffered file and streaming processing .", "label": 0 }, { "idx": "cosqa-dev-110", "doc": "python set type to string", "code": "def check_str(obj):\n \"\"\" Returns a string for various input types \"\"\"\n if isinstance(obj, str):\n return obj\n if isinstance(obj, float):\n return str(int(obj))\n else:\n return str(obj)", "code_tokens": "def check_str ( obj ) : if isinstance ( obj , str ) : return obj if isinstance ( obj , float ) : return str ( int ( obj ) ) else : return str ( obj )", "docstring_tokens": "Returns a string for various input types", "label": 1 }, { "idx": "cosqa-dev-111", "doc": "python resize image exif keep", "code": "def crop_box(im, box=False, **kwargs):\n \"\"\"Uses box coordinates to crop an image without resizing it first.\"\"\"\n if box:\n im = im.crop(box)\n return im", "code_tokens": "def crop_box ( im , box = False , * * kwargs ) : if box : im = im . crop ( box ) return im", "docstring_tokens": "Uses box coordinates to crop an image without resizing it first .", "label": 0 }, { "idx": "cosqa-dev-112", "doc": "product of numbers in a list python", "code": "def _cumprod(l):\n \"\"\"Cumulative product of a list.\n\n Args:\n l: a list of integers\n Returns:\n a list with one more element (starting with 1)\n \"\"\"\n ret = [1]\n for item in l:\n ret.append(ret[-1] * item)\n return ret", "code_tokens": "def _cumprod ( l ) : ret = [ 1 ] for item in l : ret . append ( ret [ - 1 ] * item ) return ret", "docstring_tokens": "Cumulative product of a list .", "label": 1 }, { "idx": "cosqa-dev-113", "doc": "how to check if data type is string in python", "code": "def _isstring(dtype):\n \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n if the dtype is string or unicode.\n \"\"\"\n return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "code_tokens": "def _isstring ( dtype ) : return dtype . type == numpy . unicode_ or dtype . type == numpy . string_", "docstring_tokens": "Given a numpy dtype determines whether it is a string . Returns True if the dtype is string or unicode .", "label": 0 }, { "idx": "cosqa-dev-114", "doc": "how to check empty file 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": 0 }, { "idx": "cosqa-dev-115", "doc": "python 3 get the first sunday of the month", "code": "def first_sunday(self, year, month):\n \"\"\"Get the first sunday of a month.\"\"\"\n date = datetime(year, month, 1, 0)\n days_until_sunday = 6 - date.weekday()\n\n return date + timedelta(days=days_until_sunday)", "code_tokens": "def first_sunday ( self , year , month ) : date = datetime ( year , month , 1 , 0 ) days_until_sunday = 6 - date . weekday ( ) return date + timedelta ( days = days_until_sunday )", "docstring_tokens": "Get the first sunday of a month .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-117", "doc": "python creating a dictionary from reading a csv file with dictreader", "code": "def csv_to_dicts(file, header=None):\n \"\"\"Reads a csv and returns a List of Dicts with keys given by header row.\"\"\"\n with open(file) as csvfile:\n return [row for row in csv.DictReader(csvfile, fieldnames=header)]", "code_tokens": "def csv_to_dicts ( file , header = None ) : with open ( file ) as csvfile : return [ row for row in csv . DictReader ( csvfile , fieldnames = header ) ]", "docstring_tokens": "Reads a csv and returns a List of Dicts with keys given by header row .", "label": 1 }, { "idx": "cosqa-dev-118", "doc": "last week in each month python", "code": "def get_period_last_3_months() -> str:\n \"\"\" Returns the last week as a period string \"\"\"\n today = Datum()\n today.today()\n\n # start_date = today - timedelta(weeks=13)\n start_date = today.clone()\n start_date.subtract_months(3)\n\n period = get_period(start_date.date, today.date)\n return period", "code_tokens": "def get_period_last_3_months ( ) -> str : today = Datum ( ) today . today ( ) # start_date = today - timedelta(weeks=13) start_date = today . clone ( ) start_date . subtract_months ( 3 ) period = get_period ( start_date . date , today . date ) return period", "docstring_tokens": "Returns the last week as a period string", "label": 0 }, { "idx": "cosqa-dev-119", "doc": "truncate to two decimals 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": 0 }, { "idx": "cosqa-dev-120", "doc": "python set text size", "code": "def set_font_size(self, size):\n \"\"\"Convenience method for just changing font size.\"\"\"\n if self.font.font_size == size:\n pass\n else:\n self.font._set_size(size)", "code_tokens": "def set_font_size ( self , size ) : if self . font . font_size == size : pass else : self . font . _set_size ( size )", "docstring_tokens": "Convenience method for just changing font size .", "label": 1 }, { "idx": "cosqa-dev-121", "doc": "python script chmod +x", "code": "def chmod_plus_w(path):\n \"\"\"Equivalent of unix `chmod +w path`\"\"\"\n path_mode = os.stat(path).st_mode\n path_mode &= int('777', 8)\n path_mode |= stat.S_IWRITE\n os.chmod(path, path_mode)", "code_tokens": "def chmod_plus_w ( path ) : path_mode = os . stat ( path ) . st_mode path_mode &= int ( '777' , 8 ) path_mode |= stat . S_IWRITE os . chmod ( path , path_mode )", "docstring_tokens": "Equivalent of unix chmod + w path", "label": 0 }, { "idx": "cosqa-dev-122", "doc": "how to randomize a datetime python", "code": "def _rnd_datetime(self, start, end):\n \"\"\"Internal random datetime generator.\n \"\"\"\n return self.from_utctimestamp(\n random.randint(\n int(self.to_utctimestamp(start)),\n int(self.to_utctimestamp(end)),\n )\n )", "code_tokens": "def _rnd_datetime ( self , start , end ) : return self . from_utctimestamp ( random . randint ( int ( self . to_utctimestamp ( start ) ) , int ( self . to_utctimestamp ( end ) ) , ) )", "docstring_tokens": "Internal random datetime generator .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-124", "doc": "how to get the computer info of a remote computer on python", "code": "def get():\n \"\"\" Get local facts about this machine.\n\n Returns:\n json-compatible dict with all facts of this host\n \"\"\"\n result = runCommand('facter --json', raise_error_on_fail=True)\n json_facts = result[1]\n facts = json.loads(json_facts)\n return facts", "code_tokens": "def get ( ) : result = runCommand ( 'facter --json' , raise_error_on_fail = True ) json_facts = result [ 1 ] facts = json . loads ( json_facts ) return facts", "docstring_tokens": "Get local facts about this machine .", "label": 0 }, { "idx": "cosqa-dev-125", "doc": "term frequency implementation in python", "code": "def _relative_frequency(self, word):\n\t\t\"\"\"Computes the log relative frequency for a word form\"\"\"\n\n\t\tcount = self.type_counts.get(word, 0)\n\t\treturn math.log(count/len(self.type_counts)) if count > 0 else 0", "code_tokens": "def _relative_frequency ( self , word ) : count = self . type_counts . get ( word , 0 ) return math . log ( count / len ( self . type_counts ) ) if count > 0 else 0", "docstring_tokens": "Computes the log relative frequency for a word form", "label": 0 }, { "idx": "cosqa-dev-126", "doc": "inverse a dictionary python", "code": "def invertDictMapping(d):\n \"\"\" Invert mapping of dictionary (i.e. map values to list of keys) \"\"\"\n inv_map = {}\n for k, v in d.items():\n inv_map[v] = inv_map.get(v, [])\n inv_map[v].append(k)\n return inv_map", "code_tokens": "def invertDictMapping ( d ) : inv_map = { } for k , v in d . items ( ) : inv_map [ v ] = inv_map . get ( v , [ ] ) inv_map [ v ] . append ( k ) return inv_map", "docstring_tokens": "Invert mapping of dictionary ( i . e . map values to list of keys )", "label": 1 }, { "idx": "cosqa-dev-127", "doc": "get factors of a number python", "code": "def _factor_generator(n):\n \"\"\"\n From a given natural integer, returns the prime factors and their multiplicity\n :param n: Natural integer\n :return:\n \"\"\"\n p = prime_factors(n)\n factors = {}\n for p1 in p:\n try:\n factors[p1] += 1\n except KeyError:\n factors[p1] = 1\n return factors", "code_tokens": "def _factor_generator ( n ) : p = prime_factors ( n ) factors = { } for p1 in p : try : factors [ p1 ] += 1 except KeyError : factors [ p1 ] = 1 return factors", "docstring_tokens": "From a given natural integer returns the prime factors and their multiplicity : param n : Natural integer : return :", "label": 1 }, { "idx": "cosqa-dev-128", "doc": "how to restart a python program after it fininshed", "code": "def restart_program():\n \"\"\"\n DOES NOT WORK WELL WITH MOPIDY\n Hack from\n https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program\n to support updating the settings, since mopidy is not able to do that yet\n Restarts the current program\n Note: this function does not return. Any cleanup action (like\n saving data) must be done before calling this function\n \"\"\"\n\n python = sys.executable\n os.execl(python, python, * sys.argv)", "code_tokens": "def restart_program ( ) : python = sys . executable os . execl ( python , python , * sys . argv )", "docstring_tokens": "DOES NOT WORK WELL WITH MOPIDY Hack from https : // www . daniweb . com / software - development / python / code / 260268 / restart - your - python - program to support updating the settings since mopidy is not able to do that yet Restarts the current program Note : this function does not return . Any cleanup action ( like saving data ) must be done before calling this function", "label": 1 }, { "idx": "cosqa-dev-129", "doc": "python xml test for empty tag", "code": "def is_empty(self):\n \"\"\"Returns True if the root node contains no child elements, no text,\n and no attributes other than **type**. Returns False if any are present.\"\"\"\n non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type']\n return len(self.node) == 0 and len(non_type_attributes) == 0 \\\n and not self.node.text and not self.node.tail", "code_tokens": "def is_empty ( self ) : non_type_attributes = [ attr for attr in self . node . attrib . keys ( ) if attr != 'type' ] return len ( self . node ) == 0 and len ( non_type_attributes ) == 0 and not self . node . text and not self . node . tail", "docstring_tokens": "Returns True if the root node contains no child elements no text and no attributes other than ** type ** . Returns False if any are present .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-131", "doc": "how to expand pythons", "code": "def _expand(self, str, local_vars={}):\n \"\"\"Expand $vars in a string.\"\"\"\n return ninja_syntax.expand(str, self.vars, local_vars)", "code_tokens": "def _expand ( self , str , local_vars = { } ) : return ninja_syntax . expand ( str , self . vars , local_vars )", "docstring_tokens": "Expand $vars in a string .", "label": 0 }, { "idx": "cosqa-dev-132", "doc": "automaticly back to the previous page in python", "code": "def accel_prev(self, *args):\n \"\"\"Callback to go to the previous tab. Called by the accel key.\n \"\"\"\n if self.get_notebook().get_current_page() == 0:\n self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)\n else:\n self.get_notebook().prev_page()\n return True", "code_tokens": "def accel_prev ( self , * args ) : if self . get_notebook ( ) . get_current_page ( ) == 0 : self . get_notebook ( ) . set_current_page ( self . get_notebook ( ) . get_n_pages ( ) - 1 ) else : self . get_notebook ( ) . prev_page ( ) return True", "docstring_tokens": "Callback to go to the previous tab . Called by the accel key .", "label": 0 }, { "idx": "cosqa-dev-133", "doc": "no address associated with hostname smtp python", "code": "def get_server(address=None):\n \"\"\"Return an SMTP servername guess from outgoing email address.\"\"\"\n if address:\n domain = address.split(\"@\")[1]\n try:\n return SMTP_SERVERS[domain]\n except KeyError:\n return (\"smtp.\" + domain, 465)\n return (None, None)", "code_tokens": "def get_server ( address = None ) : if address : domain = address . split ( \"@\" ) [ 1 ] try : return SMTP_SERVERS [ domain ] except KeyError : return ( \"smtp.\" + domain , 465 ) return ( None , None )", "docstring_tokens": "Return an SMTP servername guess from outgoing email address .", "label": 0 }, { "idx": "cosqa-dev-134", "doc": "write comparisons for custom object python", "code": "def equal(obj1, obj2):\n \"\"\"Calculate equality between two (Comparable) objects.\"\"\"\n Comparable.log(obj1, obj2, '==')\n equality = obj1.equality(obj2)\n Comparable.log(obj1, obj2, '==', result=equality)\n return equality", "code_tokens": "def equal ( obj1 , obj2 ) : Comparable . log ( obj1 , obj2 , '==' ) equality = obj1 . equality ( obj2 ) Comparable . log ( obj1 , obj2 , '==' , result = equality ) return equality", "docstring_tokens": "Calculate equality between two ( Comparable ) objects .", "label": 1 }, { "idx": "cosqa-dev-135", "doc": "mongodb objectid to python int", "code": "def find_one_by_id(self, _id):\n \"\"\"\n Find a single document by id\n\n :param str _id: BSON string repreentation of the Id\n :return: a signle object\n :rtype: dict\n\n \"\"\"\n document = (yield self.collection.find_one({\"_id\": ObjectId(_id)}))\n raise Return(self._obj_cursor_to_dictionary(document))", "code_tokens": "def find_one_by_id ( self , _id ) : document = ( yield self . collection . find_one ( { \"_id\" : ObjectId ( _id ) } ) ) raise Return ( self . _obj_cursor_to_dictionary ( document ) )", "docstring_tokens": "Find a single document by id", "label": 0 }, { "idx": "cosqa-dev-136", "doc": "how to hamming distance in python without functions", "code": "def levenshtein_distance_metric(a, b):\n \"\"\" 1 - farthest apart (same number of words, all diff). 0 - same\"\"\"\n return (levenshtein_distance(a, b) / (2.0 * max(len(a), len(b), 1)))", "code_tokens": "def levenshtein_distance_metric ( a , b ) : return ( levenshtein_distance ( a , b ) / ( 2.0 * max ( len ( a ) , len ( b ) , 1 ) ) )", "docstring_tokens": "1 - farthest apart ( same number of words all diff ) . 0 - same", "label": 0 }, { "idx": "cosqa-dev-137", "doc": "python save a dictionary to csv file", "code": "def save_dict_to_file(filename, dictionary):\n \"\"\"Saves dictionary as CSV file.\"\"\"\n with open(filename, 'w') as f:\n writer = csv.writer(f)\n for k, v in iteritems(dictionary):\n writer.writerow([str(k), str(v)])", "code_tokens": "def save_dict_to_file ( filename , dictionary ) : with open ( filename , 'w' ) as f : writer = csv . writer ( f ) for k , v in iteritems ( dictionary ) : writer . writerow ( [ str ( k ) , str ( v ) ] )", "docstring_tokens": "Saves dictionary as CSV file .", "label": 1 }, { "idx": "cosqa-dev-138", "doc": "how to write a repr function in python for a board", "code": "def script_repr(val,imports,prefix,settings):\n \"\"\"\n Variant of repr() designed for generating a runnable script.\n\n Instances of types that require special handling can use the\n script_repr_reg dictionary. Using the type as a key, add a\n function that returns a suitable representation of instances of\n that type, and adds the required import statement.\n\n The repr of a parameter can be suppressed by returning None from\n the appropriate hook in script_repr_reg.\n \"\"\"\n return pprint(val,imports,prefix,settings,unknown_value=None,\n qualify=True,separator=\"\\n\")", "code_tokens": "def script_repr ( val , imports , prefix , settings ) : return pprint ( val , imports , prefix , settings , unknown_value = None , qualify = True , separator = \"\\n\" )", "docstring_tokens": "Variant of repr () designed for generating a runnable script .", "label": 0 }, { "idx": "cosqa-dev-139", "doc": "python enum get by index", "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": 0 }, { "idx": "cosqa-dev-140", "doc": "python 3 map to list code", "code": "def mmap(func, iterable):\n \"\"\"Wrapper to make map() behave the same on Py2 and Py3.\"\"\"\n\n if sys.version_info[0] > 2:\n return [i for i in map(func, iterable)]\n else:\n return map(func, iterable)", "code_tokens": "def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )", "docstring_tokens": "Wrapper to make map () behave the same on Py2 and Py3 .", "label": 0 }, { "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 }, { "idx": "cosqa-dev-142", "doc": "python iteration progress bar", "code": "def __call__(self, _):\n \"\"\"Update the progressbar.\"\"\"\n if self.iter % self.step == 0:\n self.pbar.update(self.step)\n\n self.iter += 1", "code_tokens": "def __call__ ( self , _ ) : if self . iter % self . step == 0 : self . pbar . update ( self . step ) self . iter += 1", "docstring_tokens": "Update the progressbar .", "label": 0 }, { "idx": "cosqa-dev-143", "doc": "remove whitespaces from string python", "code": "def text_cleanup(data, key, last_type):\n \"\"\" I strip extra whitespace off multi-line strings if they are ready to be stripped!\"\"\"\n if key in data and last_type == STRING_TYPE:\n data[key] = data[key].strip()\n return data", "code_tokens": "def text_cleanup ( data , key , last_type ) : if key in data and last_type == STRING_TYPE : data [ key ] = data [ key ] . strip ( ) return data", "docstring_tokens": "I strip extra whitespace off multi - line strings if they are ready to be stripped!", "label": 1 }, { "idx": "cosqa-dev-144", "doc": "python export graphviz generate graph", "code": "def cli(yamlfile, directory, out, classname, format):\n \"\"\" Generate graphviz representations of the biolink model \"\"\"\n DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)", "code_tokens": "def cli ( yamlfile , directory , out , classname , format ) : DotGenerator ( yamlfile , format ) . serialize ( classname = classname , dirname = directory , filename = out )", "docstring_tokens": "Generate graphviz representations of the biolink model", "label": 0 }, { "idx": "cosqa-dev-145", "doc": "python del vars defined", "code": "def clear_global(self):\n \"\"\"Clear only any cached global data.\n\n \"\"\"\n vname = self.varname\n logger.debug(f'global clearning {vname}')\n if vname in globals():\n logger.debug('removing global instance var: {}'.format(vname))\n del globals()[vname]", "code_tokens": "def clear_global ( self ) : vname = self . varname logger . debug ( f'global clearning {vname}' ) if vname in globals ( ) : logger . debug ( 'removing global instance var: {}' . format ( vname ) ) del globals ( ) [ vname ]", "docstring_tokens": "Clear only any cached global data .", "label": 1 }, { "idx": "cosqa-dev-146", "doc": "python get first date in a month", "code": "def monthly(date=datetime.date.today()):\n \"\"\"\n Take a date object and return the first day of the month.\n \"\"\"\n return datetime.date(date.year, date.month, 1)", "code_tokens": "def monthly ( date = datetime . date . today ( ) ) : return datetime . date ( date . year , date . month , 1 )", "docstring_tokens": "Take a date object and return the first day of the month .", "label": 1 }, { "idx": "cosqa-dev-147", "doc": "using def in python to show document string", "code": "def debug_src(src, pm=False, globs=None):\n \"\"\"Debug a single doctest docstring, in argument `src`'\"\"\"\n testsrc = script_from_examples(src)\n debug_script(testsrc, pm, globs)", "code_tokens": "def debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )", "docstring_tokens": "Debug a single doctest docstring in argument src", "label": 0 }, { "idx": "cosqa-dev-148", "doc": "pop a dict out of the list python", "code": "def multi_pop(d, *args):\n \"\"\" pops multiple keys off a dict like object \"\"\"\n retval = {}\n for key in args:\n if key in d:\n retval[key] = d.pop(key)\n return retval", "code_tokens": "def multi_pop ( d , * args ) : retval = { } for key in args : if key in d : retval [ key ] = d . pop ( key ) return retval", "docstring_tokens": "pops multiple keys off a dict like object", "label": 0 }, { "idx": "cosqa-dev-149", "doc": "how to exepct error in python", "code": "def clean_error(err):\n \"\"\"\n Take stderr bytes returned from MicroPython and attempt to create a\n non-verbose error message.\n \"\"\"\n if err:\n decoded = err.decode('utf-8')\n try:\n return decoded.split('\\r\\n')[-2]\n except Exception:\n return decoded\n return 'There was an error.'", "code_tokens": "def clean_error ( err ) : if err : decoded = err . decode ( 'utf-8' ) try : return decoded . split ( '\\r\\n' ) [ - 2 ] except Exception : return decoded return 'There was an error.'", "docstring_tokens": "Take stderr bytes returned from MicroPython and attempt to create a non - verbose error message .", "label": 0 }, { "idx": "cosqa-dev-150", "doc": "get the first day of the month in python", "code": "def get_month_start(day=None):\n \"\"\"Returns the first day of the given month.\"\"\"\n day = add_timezone(day or datetime.date.today())\n return day.replace(day=1)", "code_tokens": "def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 )", "docstring_tokens": "Returns the first day of the given month .", "label": 1 }, { "idx": "cosqa-dev-151", "doc": "python flask deployment static path", "code": "def staticdir():\n \"\"\"Return the location of the static data directory.\"\"\"\n root = os.path.abspath(os.path.dirname(__file__))\n return os.path.join(root, \"static\")", "code_tokens": "def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , \"static\" )", "docstring_tokens": "Return the location of the static data directory .", "label": 1 }, { "idx": "cosqa-dev-152", "doc": "python argparse add subparser", "code": "def set_subparsers_args(self, *args, **kwargs):\n \"\"\"\n Sets args and kwargs that are passed when creating a subparsers group\n in an argparse.ArgumentParser i.e. when calling\n argparser.ArgumentParser.add_subparsers\n \"\"\"\n self.subparsers_args = args\n self.subparsers_kwargs = kwargs", "code_tokens": "def set_subparsers_args ( self , * args , * * kwargs ) : self . subparsers_args = args self . subparsers_kwargs = kwargs", "docstring_tokens": "Sets args and kwargs that are passed when creating a subparsers group in an argparse . ArgumentParser i . e . when calling argparser . ArgumentParser . add_subparsers", "label": 0 }, { "idx": "cosqa-dev-153", "doc": "killl all threads python", "code": "def terminate(self):\n \"\"\"Terminate all workers and threads.\"\"\"\n for t in self._threads:\n t.quit()\n self._thread = []\n self._workers = []", "code_tokens": "def terminate ( self ) : for t in self . _threads : t . quit ( ) self . _thread = [ ] self . _workers = [ ]", "docstring_tokens": "Terminate all workers and threads .", "label": 1 }, { "idx": "cosqa-dev-154", "doc": "make all caps lowercase python", "code": "def convert_camel_case_to_snake_case(name):\n \"\"\"Convert CamelCase to snake_case.\"\"\"\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()", "code_tokens": "def convert_camel_case_to_snake_case ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\\1_\\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\\1_\\2' , s1 ) . lower ( )", "docstring_tokens": "Convert CamelCase to snake_case .", "label": 0 }, { "idx": "cosqa-dev-155", "doc": "python unsupported operand types for instance", "code": "def __init__(self,operand,operator,**args):\n \"\"\"\n Accepts a NumberGenerator operand, an operator, and\n optional arguments to be provided to the operator when calling\n it on the operand.\n \"\"\"\n # Note that it's currently not possible to set\n # parameters in the superclass when creating an instance,\n # because **args is used by this class itself.\n super(UnaryOperator,self).__init__()\n\n self.operand=operand\n self.operator=operator\n self.args=args", "code_tokens": "def __init__ ( self , operand , operator , * * args ) : # Note that it's currently not possible to set # parameters in the superclass when creating an instance, # because **args is used by this class itself. super ( UnaryOperator , self ) . __init__ ( ) self . operand = operand self . operator = operator self . args = args", "docstring_tokens": "Accepts a NumberGenerator operand an operator and optional arguments to be provided to the operator when calling it on the operand .", "label": 0 }, { "idx": "cosqa-dev-156", "doc": "python remove object from dist", "code": "def remove_from_lib(self, name):\n \"\"\" Remove an object from the bin folder. \"\"\"\n self.__remove_path(os.path.join(self.root_dir, \"lib\", name))", "code_tokens": "def remove_from_lib ( self , name ) : self . __remove_path ( os . path . join ( self . root_dir , \"lib\" , name ) )", "docstring_tokens": "Remove an object from the bin folder .", "label": 1 }, { "idx": "cosqa-dev-157", "doc": "python how to tell if string or array", "code": "def _isstring(dtype):\n \"\"\"Given a numpy dtype, determines whether it is a string. Returns True\n if the dtype is string or unicode.\n \"\"\"\n return dtype.type == numpy.unicode_ or dtype.type == numpy.string_", "code_tokens": "def _isstring ( dtype ) : return dtype . type == numpy . unicode_ or dtype . type == numpy . string_", "docstring_tokens": "Given a numpy dtype determines whether it is a string . Returns True if the dtype is string or unicode .", "label": 0 }, { "idx": "cosqa-dev-158", "doc": "how to get traceback error info python", "code": "def get_last_or_frame_exception():\n \"\"\"Intended to be used going into post mortem routines. If\n sys.last_traceback is set, we will return that and assume that\n this is what post-mortem will want. If sys.last_traceback has not\n been set, then perhaps we *about* to raise an error and are\n fielding an exception. So assume that sys.exc_info()[2]\n is where we want to look.\"\"\"\n\n try:\n if inspect.istraceback(sys.last_traceback):\n # We do have a traceback so prefer that.\n return sys.last_type, sys.last_value, sys.last_traceback\n except AttributeError:\n pass\n return sys.exc_info()", "code_tokens": "def get_last_or_frame_exception ( ) : try : if inspect . istraceback ( sys . last_traceback ) : # We do have a traceback so prefer that. return sys . last_type , sys . last_value , sys . last_traceback except AttributeError : pass return sys . exc_info ( )", "docstring_tokens": "Intended to be used going into post mortem routines . If sys . last_traceback is set we will return that and assume that this is what post - mortem will want . If sys . last_traceback has not been set then perhaps we * about * to raise an error and are fielding an exception . So assume that sys . exc_info () [ 2 ] is where we want to look .", "label": 0 }, { "idx": "cosqa-dev-159", "doc": "python if type is str", "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 }, { "idx": "cosqa-dev-160", "doc": "finding the minimum value in a part of a list python", "code": "def find_le(a, x):\n \"\"\"Find rightmost value less than or equal to x.\"\"\"\n i = bs.bisect_right(a, x)\n if i: return i - 1\n raise ValueError", "code_tokens": "def find_le ( a , x ) : i = bs . bisect_right ( a , x ) if i : return i - 1 raise ValueError", "docstring_tokens": "Find rightmost value less than or equal to x .", "label": 0 }, { "idx": "cosqa-dev-161", "doc": "python check for deprecated usage", "code": "def warn_deprecated(message, stacklevel=2): # pragma: no cover\n \"\"\"Warn deprecated.\"\"\"\n\n warnings.warn(\n message,\n category=DeprecationWarning,\n stacklevel=stacklevel\n )", "code_tokens": "def warn_deprecated ( message , stacklevel = 2 ) : # pragma: no cover warnings . warn ( message , category = DeprecationWarning , stacklevel = stacklevel )", "docstring_tokens": "Warn deprecated .", "label": 0 }, { "idx": "cosqa-dev-162", "doc": "how to show certain plots in python", "code": "def show(self, title=''):\n \"\"\"\n Display Bloch sphere and corresponding data sets.\n \"\"\"\n self.render(title=title)\n if self.fig:\n plt.show(self.fig)", "code_tokens": "def show ( self , title = '' ) : self . render ( title = title ) if self . fig : plt . show ( self . fig )", "docstring_tokens": "Display Bloch sphere and corresponding data sets .", "label": 0 }, { "idx": "cosqa-dev-163", "doc": "python array with column names", "code": "def from_array(cls, arr):\n \"\"\"Convert a structured NumPy array into a Table.\"\"\"\n return cls().with_columns([(f, arr[f]) for f in arr.dtype.names])", "code_tokens": "def from_array ( cls , arr ) : return cls ( ) . with_columns ( [ ( f , arr [ f ] ) for f in arr . dtype . names ] )", "docstring_tokens": "Convert a structured NumPy array into a Table .", "label": 0 }, { "idx": "cosqa-dev-164", "doc": "list in python are dynamic arrays", "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": 0 }, { "idx": "cosqa-dev-165", "doc": "python check file is excuatable or not", "code": "def is_file_exists_error(e):\n \"\"\"\n Returns whether the exception *e* was raised due to an already existing file or directory.\n \"\"\"\n if six.PY3:\n return isinstance(e, FileExistsError) # noqa: F821\n else:\n return isinstance(e, OSError) and e.errno == 17", "code_tokens": "def is_file_exists_error ( e ) : if six . PY3 : return isinstance ( e , FileExistsError ) # noqa: F821 else : return isinstance ( e , OSError ) and e . errno == 17", "docstring_tokens": "Returns whether the exception * e * was raised due to an already existing file or directory .", "label": 0 }, { "idx": "cosqa-dev-166", "doc": "replacing two characters with replace in 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 }, { "idx": "cosqa-dev-167", "doc": "python webdriver kill the command shell", "code": "def kill(self):\n \"\"\"Kill the browser.\n\n This is useful when the browser is stuck.\n \"\"\"\n if self.process:\n self.process.kill()\n self.process.wait()", "code_tokens": "def kill ( self ) : if self . process : self . process . kill ( ) self . process . wait ( )", "docstring_tokens": "Kill the browser .", "label": 0 }, { "idx": "cosqa-dev-168", "doc": "get the structure of a table from conn python", "code": "def get_table_list(dbconn):\n \"\"\"\n Get a list of tables that exist in dbconn\n :param dbconn: database connection\n :return: List of table names\n \"\"\"\n cur = dbconn.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n try:\n return [item[0] for item in cur.fetchall()]\n except IndexError:\n return get_table_list(dbconn)", "code_tokens": "def get_table_list ( dbconn ) : cur = dbconn . cursor ( ) cur . execute ( \"SELECT name FROM sqlite_master WHERE type='table';\" ) try : return [ item [ 0 ] for item in cur . fetchall ( ) ] except IndexError : return get_table_list ( dbconn )", "docstring_tokens": "Get a list of tables that exist in dbconn : param dbconn : database connection : return : List of table names", "label": 0 }, { "idx": "cosqa-dev-169", "doc": "python if type array", "code": "def is_iterable(value):\n \"\"\"must be an iterable (list, array, tuple)\"\"\"\n return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value", "code_tokens": "def is_iterable ( value ) : return isinstance ( value , np . ndarray ) or isinstance ( value , list ) or isinstance ( value , tuple ) , value", "docstring_tokens": "must be an iterable ( list array tuple )", "label": 1 }, { "idx": "cosqa-dev-170", "doc": "how to read contents from a file in python", "code": "def read_text_from_file(path: str) -> str:\n \"\"\" Reads text file contents \"\"\"\n with open(path) as text_file:\n content = text_file.read()\n\n return content", "code_tokens": "def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content", "docstring_tokens": "Reads text file contents", "label": 1 }, { "idx": "cosqa-dev-171", "doc": "python see if a string has punctuation", "code": "def is_delimiter(line):\n \"\"\" True if a line consists only of a single punctuation character.\"\"\"\n return bool(line) and line[0] in punctuation and line[0]*len(line) == line", "code_tokens": "def is_delimiter ( line ) : return bool ( line ) and line [ 0 ] in punctuation and line [ 0 ] * len ( line ) == line", "docstring_tokens": "True if a line consists only of a single punctuation character .", "label": 1 }, { "idx": "cosqa-dev-172", "doc": "how to make a str an int in python", "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 }, { "idx": "cosqa-dev-173", "doc": "change type for each value in list python", "code": "def flatten(l, types=(list, float)):\n \"\"\"\n Flat nested list of lists into a single list.\n \"\"\"\n l = [item if isinstance(item, types) else [item] for item in l]\n return [item for sublist in l for item in sublist]", "code_tokens": "def flatten ( l , types = ( list , float ) ) : l = [ item if isinstance ( item , types ) else [ item ] for item in l ] return [ item for sublist in l for item in sublist ]", "docstring_tokens": "Flat nested list of lists into a single list .", "label": 0 }, { "idx": "cosqa-dev-174", "doc": "crop black out of image python", "code": "def _trim(image):\n \"\"\"Trim a PIL image and remove white space.\"\"\"\n background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))\n diff = PIL.ImageChops.difference(image, background)\n diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n if bbox:\n image = image.crop(bbox)\n return image", "code_tokens": "def _trim ( image ) : background = PIL . Image . new ( image . mode , image . size , image . getpixel ( ( 0 , 0 ) ) ) diff = PIL . ImageChops . difference ( image , background ) diff = PIL . ImageChops . add ( diff , diff , 2.0 , - 100 ) bbox = diff . getbbox ( ) if bbox : image = image . crop ( bbox ) return image", "docstring_tokens": "Trim a PIL image and remove white space .", "label": 0 }, { "idx": "cosqa-dev-175", "doc": "get cell background color python sheets api", "code": "def _get_background_color(self):\n \"\"\"Returns background color rgb tuple of right line\"\"\"\n\n color = self.cell_attributes[self.key][\"bgcolor\"]\n return tuple(c / 255.0 for c in color_pack2rgb(color))", "code_tokens": "def _get_background_color ( self ) : color = self . cell_attributes [ self . key ] [ \"bgcolor\" ] return tuple ( c / 255.0 for c in color_pack2rgb ( color ) )", "docstring_tokens": "Returns background color rgb tuple of right line", "label": 1 }, { "idx": "cosqa-dev-176", "doc": "python3 see if object is string", "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 }, { "idx": "cosqa-dev-177", "doc": "python check if all elements in a list are equal", "code": "def _check_elements_equal(lst):\n \"\"\"\n Returns true if all of the elements in the list are equal.\n \"\"\"\n assert isinstance(lst, list), \"Input value must be a list.\"\n return not lst or lst.count(lst[0]) == len(lst)", "code_tokens": "def _check_elements_equal ( lst ) : assert isinstance ( lst , list ) , \"Input value must be a list.\" return not lst or lst . count ( lst [ 0 ] ) == len ( lst )", "docstring_tokens": "Returns true if all of the elements in the list are equal .", "label": 1 }, { "idx": "cosqa-dev-178", "doc": "python round to three significant digits", "code": "def round_sig(x, sig):\n \"\"\"Round the number to the specified number of significant figures\"\"\"\n return round(x, sig - int(floor(log10(abs(x)))) - 1)", "code_tokens": "def round_sig ( x , sig ) : return round ( x , sig - int ( floor ( log10 ( abs ( x ) ) ) ) - 1 )", "docstring_tokens": "Round the number to the specified number of significant figures", "label": 1 }, { "idx": "cosqa-dev-179", "doc": "convet tensor to arrray in python", "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": 0 }, { "idx": "cosqa-dev-180", "doc": "extract word document custom properties with python", "code": "def contains_extractor(document):\n \"\"\"A basic document feature extractor that returns a dict of words that the\n document contains.\"\"\"\n tokens = _get_document_tokens(document)\n features = dict((u'contains({0})'.format(w), True) for w in tokens)\n return features", "code_tokens": "def contains_extractor ( document ) : tokens = _get_document_tokens ( document ) features = dict ( ( u'contains({0})' . format ( w ) , True ) for w in tokens ) return features", "docstring_tokens": "A basic document feature extractor that returns a dict of words that the document contains .", "label": 0 }, { "idx": "cosqa-dev-181", "doc": "how to normalize an array in python with maximum value", "code": "def min_max_normalize(img):\n \"\"\"Centre and normalize a given array.\n\n Parameters:\n ----------\n img: np.ndarray\n\n \"\"\"\n\n min_img = img.min()\n max_img = img.max()\n\n return (img - min_img) / (max_img - min_img)", "code_tokens": "def min_max_normalize ( img ) : min_img = img . min ( ) max_img = img . max ( ) return ( img - min_img ) / ( max_img - min_img )", "docstring_tokens": "Centre and normalize a given array .", "label": 1 }, { "idx": "cosqa-dev-182", "doc": "how to fill na with values in a 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": 0 }, { "idx": "cosqa-dev-183", "doc": "compute l2 norm in python", "code": "def l2_norm(params):\n \"\"\"Computes l2 norm of params by flattening them into a vector.\"\"\"\n flattened, _ = flatten(params)\n return np.dot(flattened, flattened)", "code_tokens": "def l2_norm ( params ) : flattened , _ = flatten ( params ) return np . dot ( flattened , flattened )", "docstring_tokens": "Computes l2 norm of params by flattening them into a vector .", "label": 1 }, { "idx": "cosqa-dev-184", "doc": "signleton db2 conneciton python", "code": "def main(ctx, connection):\n \"\"\"Command line interface for PyBEL.\"\"\"\n ctx.obj = Manager(connection=connection)\n ctx.obj.bind()", "code_tokens": "def main ( ctx , connection ) : ctx . obj = Manager ( connection = connection ) ctx . obj . bind ( )", "docstring_tokens": "Command line interface for PyBEL .", "label": 0 }, { "idx": "cosqa-dev-185", "doc": "how to check if something is on range or not in python", "code": "def isin(value, values):\n \"\"\" Check that value is in values \"\"\"\n for i, v in enumerate(value):\n if v not in np.array(values)[:, i]:\n return False\n return True", "code_tokens": "def isin ( value , values ) : for i , v in enumerate ( value ) : if v not in np . array ( values ) [ : , i ] : return False return True", "docstring_tokens": "Check that value is in values", "label": 0 }, { "idx": "cosqa-dev-186", "doc": "how to convertthe date format in python", "code": "def solr_to_date(d):\n \"\"\" converts YYYY-MM-DDT00:00:00Z to DD-MM-YYYY \"\"\"\n return \"{day}:{m}:{y}\".format(y=d[:4], m=d[5:7], day=d[8:10]) if d else d", "code_tokens": "def solr_to_date ( d ) : return \"{day}:{m}:{y}\" . format ( y = d [ : 4 ] , m = d [ 5 : 7 ] , day = d [ 8 : 10 ] ) if d else d", "docstring_tokens": "converts YYYY - MM - DDT00 : 00 : 00Z to DD - MM - YYYY", "label": 0 }, { "idx": "cosqa-dev-187", "doc": "how to get the accuracy of a model in python", "code": "def cat_acc(y_true, y_pred):\n \"\"\"Categorical accuracy\n \"\"\"\n return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))", "code_tokens": "def cat_acc ( y_true , y_pred ) : return np . mean ( y_true . argmax ( axis = 1 ) == y_pred . argmax ( axis = 1 ) )", "docstring_tokens": "Categorical accuracy", "label": 1 }, { "idx": "cosqa-dev-188", "doc": "number of rows in python data frame", "code": "def count_(self):\n \"\"\"\n Returns the number of rows of the main dataframe\n \"\"\"\n try:\n num = len(self.df.index)\n except Exception as e:\n self.err(e, \"Can not count data\")\n return\n return num", "code_tokens": "def count_ ( self ) : try : num = len ( self . df . index ) except Exception as e : self . err ( e , \"Can not count data\" ) return return num", "docstring_tokens": "Returns the number of rows of the main dataframe", "label": 1 }, { "idx": "cosqa-dev-189", "doc": "setting python path for shared objects", "code": "def libpath(self):\n \"\"\"Returns the full path to the shared *wrapper* library created for the\n module.\n \"\"\"\n from os import path\n return path.join(self.dirpath, self.libname)", "code_tokens": "def libpath ( self ) : from os import path return path . join ( self . dirpath , self . libname )", "docstring_tokens": "Returns the full path to the shared * wrapper * library created for the module .", "label": 0 }, { "idx": "cosqa-dev-190", "doc": "python get text screen column width", "code": "def _visual_width(line):\n \"\"\"Get the the number of columns required to display a string\"\"\"\n\n return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, \"\", line))", "code_tokens": "def _visual_width ( line ) : return len ( re . sub ( colorama . ansitowin32 . AnsiToWin32 . ANSI_CSI_RE , \"\" , line ) )", "docstring_tokens": "Get the the number of columns required to display a string", "label": 0 }, { "idx": "cosqa-dev-191", "doc": "opengl with python 2d", "code": "def create_opengl_object(gl_gen_function, n=1):\n \"\"\"Returns int pointing to an OpenGL texture\"\"\"\n handle = gl.GLuint(1)\n gl_gen_function(n, byref(handle)) # Create n Empty Objects\n if n > 1:\n return [handle.value + el for el in range(n)] # Return list of handle values\n else:\n return handle.value", "code_tokens": "def create_opengl_object ( gl_gen_function , n = 1 ) : handle = gl . GLuint ( 1 ) gl_gen_function ( n , byref ( handle ) ) # Create n Empty Objects if n > 1 : return [ handle . value + el for el in range ( n ) ] # Return list of handle values else : return handle . value", "docstring_tokens": "Returns int pointing to an OpenGL texture", "label": 0 }, { "idx": "cosqa-dev-192", "doc": "how to read a csv file an make it a matrix python", "code": "def load_data(filename):\n \"\"\"\n :rtype : numpy matrix\n \"\"\"\n data = pandas.read_csv(filename, header=None, delimiter='\\t', skiprows=9)\n return data.as_matrix()", "code_tokens": "def load_data ( filename ) : data = pandas . read_csv ( filename , header = None , delimiter = '\\t' , skiprows = 9 ) return data . as_matrix ( )", "docstring_tokens": ": rtype : numpy matrix", "label": 1 }, { "idx": "cosqa-dev-193", "doc": "python new lines in doc string", "code": "def process_docstring(app, what, name, obj, options, lines):\n \"\"\"React to a docstring event and append contracts to it.\"\"\"\n # pylint: disable=unused-argument\n # pylint: disable=too-many-arguments\n lines.extend(_format_contracts(what=what, obj=obj))", "code_tokens": "def process_docstring ( app , what , name , obj , options , lines ) : # pylint: disable=unused-argument # pylint: disable=too-many-arguments lines . extend ( _format_contracts ( what = what , obj = obj ) )", "docstring_tokens": "React to a docstring event and append contracts to it .", "label": 0 }, { "idx": "cosqa-dev-194", "doc": "how to center text on print in python", "code": "def info(txt):\n \"\"\"Print, emphasized 'neutral', the given 'txt' message\"\"\"\n\n print(\"%s# %s%s%s\" % (PR_EMPH_CC, get_time_stamp(), txt, PR_NC))\n sys.stdout.flush()", "code_tokens": "def info ( txt ) : print ( \"%s# %s%s%s\" % ( PR_EMPH_CC , get_time_stamp ( ) , txt , PR_NC ) ) sys . stdout . flush ( )", "docstring_tokens": "Print emphasized neutral the given txt message", "label": 0 }, { "idx": "cosqa-dev-195", "doc": "pad with 0s python", "code": "def zero_pad(m, n=1):\n \"\"\"Pad a matrix with zeros, on all sides.\"\"\"\n return np.pad(m, (n, n), mode='constant', constant_values=[0])", "code_tokens": "def zero_pad ( m , n = 1 ) : return np . pad ( m , ( n , n ) , mode = 'constant' , constant_values = [ 0 ] )", "docstring_tokens": "Pad a matrix with zeros on all sides .", "label": 1 }, { "idx": "cosqa-dev-196", "doc": "python flask redirect to inde", "code": "def logout():\n \"\"\" Log out the active user\n \"\"\"\n flogin.logout_user()\n next = flask.request.args.get('next')\n return flask.redirect(next or flask.url_for(\"user\"))", "code_tokens": "def logout ( ) : flogin . logout_user ( ) next = flask . request . args . get ( 'next' ) return flask . redirect ( next or flask . url_for ( \"user\" ) )", "docstring_tokens": "Log out the active user", "label": 0 }, { "idx": "cosqa-dev-197", "doc": "how to return the key with the largest value in python", "code": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n \"\"\"\n Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n :param buckets: List of buckets.\n :return: The largest bucket in the list.\n \"\"\"\n return max(buckets)", "code_tokens": "def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )", "docstring_tokens": "Returns the default bucket from a list of buckets i . e . the largest bucket .", "label": 0 }, { "idx": "cosqa-dev-198", "doc": "set python request headers", "code": "def with_headers(self, headers):\n \"\"\"Sets multiple headers on the request and returns the request itself.\n\n Keyword arguments:\n headers -- a dict-like object which contains the headers to set.\n \"\"\"\n for key, value in headers.items():\n self.with_header(key, value)\n return self", "code_tokens": "def with_headers ( self , headers ) : for key , value in headers . items ( ) : self . with_header ( key , value ) return self", "docstring_tokens": "Sets multiple headers on the request and returns the request itself .", "label": 1 }, { "idx": "cosqa-dev-199", "doc": "function for raise to in python", "code": "def raise_os_error(_errno, path=None):\n \"\"\"\n Helper for raising the correct exception under Python 3 while still\n being able to raise the same common exception class in Python 2.7.\n \"\"\"\n\n msg = \"%s: '%s'\" % (strerror(_errno), path) if path else strerror(_errno)\n raise OSError(_errno, msg)", "code_tokens": "def raise_os_error ( _errno , path = None ) : msg = \"%s: '%s'\" % ( strerror ( _errno ) , path ) if path else strerror ( _errno ) raise OSError ( _errno , msg )", "docstring_tokens": "Helper for raising the correct exception under Python 3 while still being able to raise the same common exception class in Python 2 . 7 .", "label": 0 }, { "idx": "cosqa-dev-200", "doc": "python check value allow enum", "code": "def check(self, var):\n \"\"\"Check whether the provided value is a valid enum constant.\"\"\"\n if not isinstance(var, _str_type): return False\n return _enum_mangle(var) in self._consts", "code_tokens": "def check ( self , var ) : if not isinstance ( var , _str_type ) : return False return _enum_mangle ( var ) in self . _consts", "docstring_tokens": "Check whether the provided value is a valid enum constant .", "label": 1 }, { "idx": "cosqa-dev-201", "doc": "python matplotlib legend within in the grid", "code": "def finish_plot():\n \"\"\"Helper for plotting.\"\"\"\n plt.legend()\n plt.grid(color='0.7')\n plt.xlabel('x')\n plt.ylabel('y')\n plt.show()", "code_tokens": "def finish_plot ( ) : plt . legend ( ) plt . grid ( color = '0.7' ) plt . xlabel ( 'x' ) plt . ylabel ( 'y' ) plt . show ( )", "docstring_tokens": "Helper for plotting .", "label": 0 }, { "idx": "cosqa-dev-202", "doc": "how to generate a unique random number in python", "code": "def _get_random_id():\n \"\"\" Get a random (i.e., unique) string identifier\"\"\"\n symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits\n return ''.join(random.choice(symbols) for _ in range(15))", "code_tokens": "def _get_random_id ( ) : symbols = string . ascii_uppercase + string . ascii_lowercase + string . digits return '' . join ( random . choice ( symbols ) for _ in range ( 15 ) )", "docstring_tokens": "Get a random ( i . e . unique ) string identifier", "label": 0 }, { "idx": "cosqa-dev-203", "doc": "python code to plot a fourier waveform", "code": "def translate_fourier(image, dx):\n \"\"\" Translate an image in fourier-space with plane waves \"\"\"\n N = image.shape[0]\n\n f = 2*np.pi*np.fft.fftfreq(N)\n kx,ky,kz = np.meshgrid(*(f,)*3, indexing='ij')\n kv = np.array([kx,ky,kz]).T\n\n q = np.fft.fftn(image)*np.exp(-1.j*(kv*dx).sum(axis=-1)).T\n return np.real(np.fft.ifftn(q))", "code_tokens": "def translate_fourier ( image , dx ) : N = image . shape [ 0 ] f = 2 * np . pi * np . fft . fftfreq ( N ) kx , ky , kz = np . meshgrid ( * ( f , ) * 3 , indexing = 'ij' ) kv = np . array ( [ kx , ky , kz ] ) . T q = np . fft . fftn ( image ) * np . exp ( - 1.j * ( kv * dx ) . sum ( axis = - 1 ) ) . T return np . real ( np . fft . ifftn ( q ) )", "docstring_tokens": "Translate an image in fourier - space with plane waves", "label": 1 }, { "idx": "cosqa-dev-204", "doc": "python get prefix from string", "code": "def remove_prefix(text, prefix):\n\t\"\"\"\n\tRemove the prefix from the text if it exists.\n\n\t>>> remove_prefix('underwhelming performance', 'underwhelming ')\n\t'performance'\n\n\t>>> remove_prefix('something special', 'sample')\n\t'something special'\n\t\"\"\"\n\tnull, prefix, rest = text.rpartition(prefix)\n\treturn rest", "code_tokens": "def remove_prefix ( text , prefix ) : null , prefix , rest = text . rpartition ( prefix ) return rest", "docstring_tokens": "Remove the prefix from the text if it exists .", "label": 0 }, { "idx": "cosqa-dev-205", "doc": "how to make a list of a given size without inputs in python", "code": "def batch(items, size):\n \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n batch size.\"\"\"\n return [items[x:x + size] for x in xrange(0, len(items), size)]", "code_tokens": "def batch ( items , size ) : return [ items [ x : x + size ] for x in xrange ( 0 , len ( items ) , size ) ]", "docstring_tokens": "Batches a list into a list of lists with sub - lists sized by a specified batch size .", "label": 0 }, { "idx": "cosqa-dev-206", "doc": "python access a textfile", "code": "def read_text_from_file(path: str) -> str:\n \"\"\" Reads text file contents \"\"\"\n with open(path) as text_file:\n content = text_file.read()\n\n return content", "code_tokens": "def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content", "docstring_tokens": "Reads text file contents", "label": 1 }, { "idx": "cosqa-dev-207", "doc": "check virtualenv is loaded on python", "code": "def _pip_exists(self):\n \"\"\"Returns True if pip exists inside the virtual environment. Can be\n used as a naive way to verify that the environment is installed.\"\"\"\n return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))", "code_tokens": "def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )", "docstring_tokens": "Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .", "label": 0 }, { "idx": "cosqa-dev-208", "doc": "python get calling function frame info", "code": "def extract_module_locals(depth=0):\n \"\"\"Returns (module, locals) of the funciton `depth` frames away from the caller\"\"\"\n f = sys._getframe(depth + 1)\n global_ns = f.f_globals\n module = sys.modules[global_ns['__name__']]\n return (module, f.f_locals)", "code_tokens": "def extract_module_locals ( depth = 0 ) : f = sys . _getframe ( depth + 1 ) global_ns = f . f_globals module = sys . modules [ global_ns [ '__name__' ] ] return ( module , f . f_locals )", "docstring_tokens": "Returns ( module locals ) of the funciton depth frames away from the caller", "label": 0 }, { "idx": "cosqa-dev-209", "doc": "python cast str as bool", "code": "def FromString(self, string):\n \"\"\"Parse a bool from a string.\"\"\"\n if string.lower() in (\"false\", \"no\", \"n\"):\n return False\n\n if string.lower() in (\"true\", \"yes\", \"y\"):\n return True\n\n raise TypeValueError(\"%s is not recognized as a boolean value.\" % string)", "code_tokens": "def FromString ( self , string ) : if string . lower ( ) in ( \"false\" , \"no\" , \"n\" ) : return False if string . lower ( ) in ( \"true\" , \"yes\" , \"y\" ) : return True raise TypeValueError ( \"%s is not recognized as a boolean value.\" % string )", "docstring_tokens": "Parse a bool from a string .", "label": 1 }, { "idx": "cosqa-dev-210", "doc": "python pool join hang", "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": 0 }, { "idx": "cosqa-dev-211", "doc": "python argparse boolean type", "code": "def str2bool(value):\n \"\"\"Parse Yes/No/Default string\n https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse\"\"\"\n if value.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n if value.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n if value.lower() in ('d', 'default', ''):\n return None\n raise argparse.ArgumentTypeError('Expected: (Y)es/(T)rue/(N)o/(F)alse/(D)efault')", "code_tokens": "def str2bool ( value ) : if value . lower ( ) in ( 'yes' , 'true' , 't' , 'y' , '1' ) : return True if value . lower ( ) in ( 'no' , 'false' , 'f' , 'n' , '0' ) : return False if value . lower ( ) in ( 'd' , 'default' , '' ) : return None raise argparse . ArgumentTypeError ( 'Expected: (Y)es/(T)rue/(N)o/(F)alse/(D)efault' )", "docstring_tokens": "Parse Yes / No / Default string https : // stackoverflow . com / questions / 15008758 / parsing - boolean - values - with - argparse", "label": 0 }, { "idx": "cosqa-dev-212", "doc": "capitalize entire string pythonm", "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": 0 }, { "idx": "cosqa-dev-213", "doc": "python detect file is locked by other process", "code": "def lock_file(f, block=False):\n \"\"\"\n If block=False (the default), die hard and fast if another process has\n already grabbed the lock for this file.\n\n If block=True, wait for the lock to be released, then continue.\n \"\"\"\n try:\n flags = fcntl.LOCK_EX\n if not block:\n flags |= fcntl.LOCK_NB\n fcntl.flock(f.fileno(), flags)\n except IOError as e:\n if e.errno in (errno.EACCES, errno.EAGAIN):\n raise SystemExit(\"ERROR: %s is locked by another process.\" %\n f.name)\n raise", "code_tokens": "def lock_file ( f , block = False ) : try : flags = fcntl . LOCK_EX if not block : flags |= fcntl . LOCK_NB fcntl . flock ( f . fileno ( ) , flags ) except IOError as e : if e . errno in ( errno . EACCES , errno . EAGAIN ) : raise SystemExit ( \"ERROR: %s is locked by another process.\" % f . name ) raise", "docstring_tokens": "If block = False ( the default ) die hard and fast if another process has already grabbed the lock for this file .", "label": 0 }, { "idx": "cosqa-dev-214", "doc": "outer product of two vectors python", "code": "def dot_v3(v, w):\n \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n return sum([x * y for x, y in zip(v, w)])", "code_tokens": "def dot_v3 ( v , w ) : return sum ( [ x * y for x , y in zip ( v , w ) ] )", "docstring_tokens": "Return the dotproduct of two vectors .", "label": 0 }, { "idx": "cosqa-dev-215", "doc": "how to set a exit in python", "code": "def fail(message=None, exit_status=None):\n \"\"\"Prints the specified message and exits the program with the specified\n exit status.\n\n \"\"\"\n print('Error:', message, file=sys.stderr)\n sys.exit(exit_status or 1)", "code_tokens": "def fail ( message = None , exit_status = None ) : print ( 'Error:' , message , file = sys . stderr ) sys . exit ( exit_status or 1 )", "docstring_tokens": "Prints the specified message and exits the program with the specified exit status .", "label": 0 }, { "idx": "cosqa-dev-216", "doc": "rgba to gray python cv2", "code": "def gray2bgr(img):\n \"\"\"Convert a grayscale image to BGR image.\n\n Args:\n img (ndarray or str): The input image.\n\n Returns:\n ndarray: The converted BGR image.\n \"\"\"\n img = img[..., None] if img.ndim == 2 else img\n out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n return out_img", "code_tokens": "def gray2bgr ( img ) : img = img [ ... , None ] if img . ndim == 2 else img out_img = cv2 . cvtColor ( img , cv2 . COLOR_GRAY2BGR ) return out_img", "docstring_tokens": "Convert a grayscale image to BGR image .", "label": 0 }, { "idx": "cosqa-dev-217", "doc": "python redis rpush list", "code": "def lpush(self, key, *args):\n \"\"\"Emulate lpush.\"\"\"\n redis_list = self._get_list(key, 'LPUSH', create=True)\n\n # Creates the list at this key if it doesn't exist, and appends args to its beginning\n args_reversed = [self._encode(arg) for arg in args]\n args_reversed.reverse()\n updated_list = args_reversed + redis_list\n self.redis[self._encode(key)] = updated_list\n\n # Return the length of the list after the push operation\n return len(updated_list)", "code_tokens": "def lpush ( self , key , * args ) : redis_list = self . _get_list ( key , 'LPUSH' , create = True ) # Creates the list at this key if it doesn't exist, and appends args to its beginning args_reversed = [ self . _encode ( arg ) for arg in args ] args_reversed . reverse ( ) updated_list = args_reversed + redis_list self . redis [ self . _encode ( key ) ] = updated_list # Return the length of the list after the push operation return len ( updated_list )", "docstring_tokens": "Emulate lpush .", "label": 0 }, { "idx": "cosqa-dev-218", "doc": "how to move cursor to the next line in python", "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 }, { "idx": "cosqa-dev-219", "doc": "python script totell if a service is 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 }, { "idx": "cosqa-dev-220", "doc": "python duck typing object validate", "code": "def isnamedtuple(obj):\n \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n return isinstance(obj, tuple) \\\n and hasattr(obj, \"_fields\") \\\n and hasattr(obj, \"_asdict\") \\\n and callable(obj._asdict)", "code_tokens": "def isnamedtuple ( obj ) : return isinstance ( obj , tuple ) and hasattr ( obj , \"_fields\" ) and hasattr ( obj , \"_asdict\" ) and callable ( obj . _asdict )", "docstring_tokens": "Heuristic check if an object is a namedtuple .", "label": 0 }, { "idx": "cosqa-dev-221", "doc": "how to make max heap python", "code": "def heappop_max(heap):\n \"\"\"Maxheap version of a heappop.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup_max(heap, 0)\n return returnitem\n return lastelt", "code_tokens": "def heappop_max ( heap ) : lastelt = heap . pop ( ) # raises appropriate IndexError if heap is empty if heap : returnitem = heap [ 0 ] heap [ 0 ] = lastelt _siftup_max ( heap , 0 ) return returnitem return lastelt", "docstring_tokens": "Maxheap version of a heappop .", "label": 1 }, { "idx": "cosqa-dev-222", "doc": "python decompress image file", "code": "def decompress(f):\n \"\"\"Decompress a Plan 9 image file. Assumes f is already cued past the\n initial 'compressed\\n' string.\n \"\"\"\n\n r = meta(f.read(60))\n return r, decomprest(f, r[4])", "code_tokens": "def decompress ( f ) : r = meta ( f . read ( 60 ) ) return r , decomprest ( f , r [ 4 ] )", "docstring_tokens": "Decompress a Plan 9 image file . Assumes f is already cued past the initial compressed \\ n string .", "label": 1 }, { "idx": "cosqa-dev-223", "doc": "python celery task start another task", "code": "def schedule_task(self):\n \"\"\"\n Schedules this publish action as a Celery task.\n \"\"\"\n from .tasks import publish_task\n\n publish_task.apply_async(kwargs={'pk': self.pk}, eta=self.scheduled_time)", "code_tokens": "def schedule_task ( self ) : from . tasks import publish_task publish_task . apply_async ( kwargs = { 'pk' : self . pk } , eta = self . scheduled_time )", "docstring_tokens": "Schedules this publish action as a Celery task .", "label": 0 }, { "idx": "cosqa-dev-224", "doc": "python unit test assertequals", "code": "def step_impl06(context):\n \"\"\"Prepare test for singleton property.\n\n :param context: test context.\n \"\"\"\n store = context.SingleStore\n context.st_1 = store()\n context.st_2 = store()\n context.st_3 = store()", "code_tokens": "def step_impl06 ( context ) : store = context . SingleStore context . st_1 = store ( ) context . st_2 = store ( ) context . st_3 = store ( )", "docstring_tokens": "Prepare test for singleton property .", "label": 0 }, { "idx": "cosqa-dev-225", "doc": "python time diff ms", "code": "def timediff(time):\n \"\"\"Return the difference in seconds between now and the given time.\"\"\"\n now = datetime.datetime.utcnow()\n diff = now - time\n diff_sec = diff.total_seconds()\n return diff_sec", "code_tokens": "def timediff ( time ) : now = datetime . datetime . utcnow ( ) diff = now - time diff_sec = diff . total_seconds ( ) return diff_sec", "docstring_tokens": "Return the difference in seconds between now and the given time .", "label": 1 }, { "idx": "cosqa-dev-226", "doc": "python modify data of a column", "code": "def alter_change_column(self, table, column, field):\n \"\"\"Support change columns.\"\"\"\n return self._update_column(table, column, lambda a, b: b)", "code_tokens": "def alter_change_column ( self , table , column , field ) : return self . _update_column ( table , column , lambda a , b : b )", "docstring_tokens": "Support change columns .", "label": 1 }, { "idx": "cosqa-dev-227", "doc": "python normalize a 2d array", "code": "def denorm(self,arr):\n \"\"\"Reverse the normalization done to a batch of images.\n\n Arguments:\n arr: of shape/size (N,3,sz,sz)\n \"\"\"\n if type(arr) is not np.ndarray: arr = to_np(arr)\n if len(arr.shape)==3: arr = arr[None]\n return self.transform.denorm(np.rollaxis(arr,1,4))", "code_tokens": "def denorm ( self , arr ) : if type ( arr ) is not np . ndarray : arr = to_np ( arr ) if len ( arr . shape ) == 3 : arr = arr [ None ] return self . transform . denorm ( np . rollaxis ( arr , 1 , 4 ) )", "docstring_tokens": "Reverse the normalization done to a batch of images .", "label": 0 }, { "idx": "cosqa-dev-228", "doc": "python check whether date is valid", "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 }, { "idx": "cosqa-dev-229", "doc": "how to change column name in data frame of python+", "code": "def col_rename(df,col_name,new_col_name):\n \"\"\" Changes a column name in a DataFrame\n Parameters:\n df - DataFrame\n DataFrame to operate on\n col_name - string\n Name of column to change\n new_col_name - string\n New name of column\n \"\"\"\n col_list = list(df.columns)\n for index,value in enumerate(col_list):\n if value == col_name:\n col_list[index] = new_col_name\n break\n df.columns = col_list", "code_tokens": "def col_rename ( df , col_name , new_col_name ) : col_list = list ( df . columns ) for index , value in enumerate ( col_list ) : if value == col_name : col_list [ index ] = new_col_name break df . columns = col_list", "docstring_tokens": "Changes a column name in a DataFrame Parameters : df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column", "label": 1 }, { "idx": "cosqa-dev-230", "doc": "python stop a function calling", "code": "def stop(self) -> None:\n \"\"\"Stops the analysis as soon as possible.\"\"\"\n if self._stop and not self._posted_kork:\n self._stop()\n self._stop = None", "code_tokens": "def stop ( self ) -> None : if self . _stop and not self . _posted_kork : self . _stop ( ) self . _stop = None", "docstring_tokens": "Stops the analysis as soon as possible .", "label": 0 }, { "idx": "cosqa-dev-231", "doc": "python3 determining if program is still running", "code": "def is_alive(self):\n \"\"\"\n @rtype: bool\n @return: C{True} if the process is currently running.\n \"\"\"\n try:\n self.wait(0)\n except WindowsError:\n e = sys.exc_info()[1]\n return e.winerror == win32.WAIT_TIMEOUT\n return False", "code_tokens": "def is_alive ( self ) : try : self . wait ( 0 ) except WindowsError : e = sys . exc_info ( ) [ 1 ] return e . winerror == win32 . WAIT_TIMEOUT return False", "docstring_tokens": "", "label": 1 }, { "idx": "cosqa-dev-232", "doc": "python selcet the next n elements from iterator", "code": "def split_every(n, iterable):\n \"\"\"Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have\n less than n elements.\n\n See http://stackoverflow.com/a/22919323/503377.\"\"\"\n items = iter(iterable)\n return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))", "code_tokens": "def split_every ( n , iterable ) : items = iter ( iterable ) return itertools . takewhile ( bool , ( list ( itertools . islice ( items , n ) ) for _ in itertools . count ( ) ) )", "docstring_tokens": "Returns a generator that spits an iteratable into n - sized chunks . The last chunk may have less than n elements .", "label": 0 }, { "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 }, { "idx": "cosqa-dev-234", "doc": "how to call the text file and read it in python", "code": "def read_text_from_file(path: str) -> str:\n \"\"\" Reads text file contents \"\"\"\n with open(path) as text_file:\n content = text_file.read()\n\n return content", "code_tokens": "def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content", "docstring_tokens": "Reads text file contents", "label": 1 }, { "idx": "cosqa-dev-235", "doc": "how to define the width of a gaussian distribution in python", "code": "def gaussian_distribution(mean, stdev, num_pts=50):\n \"\"\" get an x and y numpy.ndarray that spans the +/- 4\n standard deviation range of a gaussian distribution with\n a given mean and standard deviation. useful for plotting\n\n Parameters\n ----------\n mean : float\n the mean of the distribution\n stdev : float\n the standard deviation of the distribution\n num_pts : int\n the number of points in the returned ndarrays.\n Default is 50\n\n Returns\n -------\n x : numpy.ndarray\n the x-values of the distribution\n y : numpy.ndarray\n the y-values of the distribution\n\n \"\"\"\n xstart = mean - (4.0 * stdev)\n xend = mean + (4.0 * stdev)\n x = np.linspace(xstart,xend,num_pts)\n y = (1.0/np.sqrt(2.0*np.pi*stdev*stdev)) * np.exp(-1.0 * ((x - mean)**2)/(2.0*stdev*stdev))\n return x,y", "code_tokens": "def gaussian_distribution ( mean , stdev , num_pts = 50 ) : xstart = mean - ( 4.0 * stdev ) xend = mean + ( 4.0 * stdev ) x = np . linspace ( xstart , xend , num_pts ) y = ( 1.0 / np . sqrt ( 2.0 * np . pi * stdev * stdev ) ) * np . exp ( - 1.0 * ( ( x - mean ) ** 2 ) / ( 2.0 * stdev * stdev ) ) return x , y", "docstring_tokens": "get an x and y numpy . ndarray that spans the + / - 4 standard deviation range of a gaussian distribution with a given mean and standard deviation . useful for plotting", "label": 1 }, { "idx": "cosqa-dev-236", "doc": "how to use python to check if the internet is up", "code": "def _internet_on(address):\n \"\"\"\n Check to see if the internet is on by pinging a set address.\n :param address: the IP or address to hit\n :return: a boolean - true if can be reached, false if not.\n \"\"\"\n try:\n urllib2.urlopen(address, timeout=1)\n return True\n except urllib2.URLError as err:\n return False", "code_tokens": "def _internet_on ( address ) : try : urllib2 . urlopen ( address , timeout = 1 ) return True except urllib2 . URLError as err : return False", "docstring_tokens": "Check to see if the internet is on by pinging a set address . : param address : the IP or address to hit : return : a boolean - true if can be reached false if not .", "label": 1 }, { "idx": "cosqa-dev-237", "doc": "vectorizing a function python", "code": "def apply(f, obj, *args, **kwargs):\n \"\"\"Apply a function in parallel to each element of the input\"\"\"\n return vectorize(f)(obj, *args, **kwargs)", "code_tokens": "def apply ( f , obj , * args , * * kwargs ) : return vectorize ( f ) ( obj , * args , * * kwargs )", "docstring_tokens": "Apply a function in parallel to each element of the input", "label": 1 }, { "idx": "cosqa-dev-238", "doc": "python words with highest tfidf", "code": "def top_1_tpu(inputs):\n \"\"\"find max and argmax over the last dimension.\n\n Works well on TPU\n\n Args:\n inputs: A tensor with shape [..., depth]\n\n Returns:\n values: a Tensor with shape [...]\n indices: a Tensor with shape [...]\n \"\"\"\n inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)\n mask = tf.to_int32(tf.equal(inputs_max, inputs))\n index = tf.range(tf.shape(inputs)[-1]) * mask\n return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1)", "code_tokens": "def top_1_tpu ( inputs ) : inputs_max = tf . reduce_max ( inputs , axis = - 1 , keepdims = True ) mask = tf . to_int32 ( tf . equal ( inputs_max , inputs ) ) index = tf . range ( tf . shape ( inputs ) [ - 1 ] ) * mask return tf . squeeze ( inputs_max , - 1 ) , tf . reduce_max ( index , axis = - 1 )", "docstring_tokens": "find max and argmax over the last dimension .", "label": 0 }, { "idx": "cosqa-dev-239", "doc": "how to capitalize every letter in a word in a sentence in python", "code": "def mixedcase(path):\n \"\"\"Removes underscores and capitalizes the neighbouring character\"\"\"\n words = path.split('_')\n return words[0] + ''.join(word.title() for word in words[1:])", "code_tokens": "def mixedcase ( path ) : words = path . split ( '_' ) return words [ 0 ] + '' . join ( word . title ( ) for word in words [ 1 : ] )", "docstring_tokens": "Removes underscores and capitalizes the neighbouring character", "label": 0 }, { "idx": "cosqa-dev-240", "doc": "python how to key in kwargs and key not in kwargs", "code": "def update_not_existing_kwargs(to_update, update_from):\n \"\"\"\n This function updates the keyword aguments from update_from in\n to_update, only if the keys are not set in to_update.\n\n This is used for updated kwargs from the default dicts.\n \"\"\"\n if to_update is None:\n to_update = {}\n to_update.update({k:v for k,v in update_from.items() if k not in to_update})\n return to_update", "code_tokens": "def update_not_existing_kwargs ( to_update , update_from ) : if to_update is None : to_update = { } to_update . update ( { k : v for k , v in update_from . items ( ) if k not in to_update } ) return to_update", "docstring_tokens": "This function updates the keyword aguments from update_from in to_update only if the keys are not set in to_update .", "label": 0 }, { "idx": "cosqa-dev-241", "doc": "python median value numpy", "code": "def fast_median(a):\n \"\"\"Fast median operation for masked array using 50th-percentile\n \"\"\"\n a = checkma(a)\n #return scoreatpercentile(a.compressed(), 50)\n if a.count() > 0:\n out = np.percentile(a.compressed(), 50)\n else:\n out = np.ma.masked\n return out", "code_tokens": "def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out", "docstring_tokens": "Fast median operation for masked array using 50th - percentile", "label": 1 }, { "idx": "cosqa-dev-242", "doc": "how to check whether the line is last or not in python", "code": "def cell_ends_with_code(lines):\n \"\"\"Is the last line of the cell a line with code?\"\"\"\n if not lines:\n return False\n if not lines[-1].strip():\n return False\n if lines[-1].startswith('#'):\n return False\n return True", "code_tokens": "def cell_ends_with_code ( lines ) : if not lines : return False if not lines [ - 1 ] . strip ( ) : return False if lines [ - 1 ] . startswith ( '#' ) : return False return True", "docstring_tokens": "Is the last line of the cell a line with code?", "label": 1 }, { "idx": "cosqa-dev-243", "doc": "read numpy array from csv file python", "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 }, { "idx": "cosqa-dev-244", "doc": "how to check if a previous button had been pressed python", "code": "def is_clicked(self, MouseStateType):\n \"\"\"\n Did the user depress and release the button to signify a click?\n MouseStateType is the button to query. Values found under StateTypes.py\n \"\"\"\n return self.previous_mouse_state.query_state(MouseStateType) and (\n not self.current_mouse_state.query_state(MouseStateType))", "code_tokens": "def is_clicked ( self , MouseStateType ) : return self . previous_mouse_state . query_state ( MouseStateType ) and ( not self . current_mouse_state . query_state ( MouseStateType ) )", "docstring_tokens": "Did the user depress and release the button to signify a click? MouseStateType is the button to query . Values found under StateTypes . py", "label": 1 }, { "idx": "cosqa-dev-245", "doc": "python how to compare 2 list to identify id's not in one list", "code": "def isetdiff_flags(list1, list2):\n \"\"\"\n move to util_iter\n \"\"\"\n set2 = set(list2)\n return (item not in set2 for item in list1)", "code_tokens": "def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 )", "docstring_tokens": "move to util_iter", "label": 1 }, { "idx": "cosqa-dev-246", "doc": "python add utomatically docstrings", "code": "def process_docstring(app, what, name, obj, options, lines):\n \"\"\"React to a docstring event and append contracts to it.\"\"\"\n # pylint: disable=unused-argument\n # pylint: disable=too-many-arguments\n lines.extend(_format_contracts(what=what, obj=obj))", "code_tokens": "def process_docstring ( app , what , name , obj , options , lines ) : # pylint: disable=unused-argument # pylint: disable=too-many-arguments lines . extend ( _format_contracts ( what = what , obj = obj ) )", "docstring_tokens": "React to a docstring event and append contracts to it .", "label": 0 }, { "idx": "cosqa-dev-247", "doc": "how to select the last row in python in numpy", "code": "def other_ind(self):\n \"\"\"last row or column of square A\"\"\"\n return np.full(self.n_min, self.size - 1, dtype=np.int)", "code_tokens": "def other_ind ( self ) : return np . full ( self . n_min , self . size - 1 , dtype = np . int )", "docstring_tokens": "last row or column of square A", "label": 0 }, { "idx": "cosqa-dev-248", "doc": "generates a random decimal number between 1 and 10 , python", "code": "def money(min=0, max=10):\n \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n value = random.choice(range(min * 100, max * 100))\n return \"%1.2f\" % (float(value) / 100)", "code_tokens": "def money ( min = 0 , max = 10 ) : value = random . choice ( range ( min * 100 , max * 100 ) ) return \"%1.2f\" % ( float ( value ) / 100 )", "docstring_tokens": "Return a str of decimal with two digits after a decimal mark .", "label": 1 }, { "idx": "cosqa-dev-249", "doc": "python split strings multiline", "code": "def split_multiline(value):\n \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n return [element for element in (line.strip() for line in value.split('\\n'))\n if element]", "code_tokens": "def split_multiline ( value ) : return [ element for element in ( line . strip ( ) for line in value . split ( '\\n' ) ) if element ]", "docstring_tokens": "Split a multiline string into a list excluding blank lines .", "label": 1 }, { "idx": "cosqa-dev-250", "doc": "plot histogram python as percentage", "code": "def plot(self):\n \"\"\"Plot the empirical histogram versus best-fit distribution's PDF.\"\"\"\n plt.plot(self.bin_edges, self.hist, self.bin_edges, self.best_pdf)", "code_tokens": "def plot ( self ) : plt . plot ( self . bin_edges , self . hist , self . bin_edges , self . best_pdf )", "docstring_tokens": "Plot the empirical histogram versus best - fit distribution s PDF .", "label": 1 }, { "idx": "cosqa-dev-251", "doc": "create task asyncio python", "code": "def create_task(coro, loop):\n # pragma: no cover\n \"\"\"Compatibility wrapper for the loop.create_task() call introduced in\n 3.4.2.\"\"\"\n if hasattr(loop, 'create_task'):\n return loop.create_task(coro)\n return asyncio.Task(coro, loop=loop)", "code_tokens": "def create_task ( coro , loop ) : # pragma: no cover if hasattr ( loop , 'create_task' ) : return loop . create_task ( coro ) return asyncio . Task ( coro , loop = loop )", "docstring_tokens": "Compatibility wrapper for the loop . create_task () call introduced in 3 . 4 . 2 .", "label": 1 }, { "idx": "cosqa-dev-252", "doc": "python environment location directory is not empty", "code": "def launched():\n \"\"\"Test whether the current python environment is the correct lore env.\n\n :return: :any:`True` if the environment is launched\n :rtype: bool\n \"\"\"\n if not PREFIX:\n return False\n\n return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)", "code_tokens": "def launched ( ) : if not PREFIX : return False return os . path . realpath ( sys . prefix ) == os . path . realpath ( PREFIX )", "docstring_tokens": "Test whether the current python environment is the correct lore env .", "label": 0 }, { "idx": "cosqa-dev-253", "doc": "how to take spaces out of datetime func python", "code": "def stringToDate(fmt=\"%Y-%m-%d\"):\n \"\"\"returns a function to convert a string to a datetime.date instance\n using the formatting string fmt as in time.strftime\"\"\"\n import time\n import datetime\n def conv_func(s):\n return datetime.date(*time.strptime(s,fmt)[:3])\n return conv_func", "code_tokens": "def stringToDate ( fmt = \"%Y-%m-%d\" ) : import time import datetime def conv_func ( s ) : return datetime . date ( * time . strptime ( s , fmt ) [ : 3 ] ) return conv_func", "docstring_tokens": "returns a function to convert a string to a datetime . date instance using the formatting string fmt as in time . strftime", "label": 0 }, { "idx": "cosqa-dev-254", "doc": "is a python set unordered", "code": "def unique(_list):\n \"\"\"\n Makes the list have unique items only and maintains the order\n\n list(set()) won't provide that\n\n :type _list list\n :rtype: list\n \"\"\"\n ret = []\n\n for item in _list:\n if item not in ret:\n ret.append(item)\n\n return ret", "code_tokens": "def unique ( _list ) : ret = [ ] for item in _list : if item not in ret : ret . append ( item ) return ret", "docstring_tokens": "Makes the list have unique items only and maintains the order", "label": 0 }, { "idx": "cosqa-dev-255", "doc": "how to get key with max value python", "code": "def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]:\n \"\"\"\n Returns the default bucket from a list of buckets, i.e. the largest bucket.\n\n :param buckets: List of buckets.\n :return: The largest bucket in the list.\n \"\"\"\n return max(buckets)", "code_tokens": "def get_default_bucket_key ( buckets : List [ Tuple [ int , int ] ] ) -> Tuple [ int , int ] : return max ( buckets )", "docstring_tokens": "Returns the default bucket from a list of buckets i . e . the largest bucket .", "label": 0 }, { "idx": "cosqa-dev-256", "doc": "delimeted string to tuple in python", "code": "def ver_to_tuple(value):\n \"\"\"\n Convert version like string to a tuple of integers.\n \"\"\"\n return tuple(int(_f) for _f in re.split(r'\\D+', value) if _f)", "code_tokens": "def ver_to_tuple ( value ) : return tuple ( int ( _f ) for _f in re . split ( r'\\D+' , value ) if _f )", "docstring_tokens": "Convert version like string to a tuple of integers .", "label": 0 }, { "idx": "cosqa-dev-257", "doc": "how to get the latest date in a list python djangp", "code": "def lastmod(self, author):\n \"\"\"Return the last modification of the entry.\"\"\"\n lastitems = EntryModel.objects.published().order_by('-modification_date').filter(author=author).only('modification_date')\n return lastitems[0].modification_date", "code_tokens": "def lastmod ( self , author ) : lastitems = EntryModel . objects . published ( ) . order_by ( '-modification_date' ) . filter ( author = author ) . only ( 'modification_date' ) return lastitems [ 0 ] . modification_date", "docstring_tokens": "Return the last modification of the entry .", "label": 0 }, { "idx": "cosqa-dev-258", "doc": "global usage in python pytest", "code": "def run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv. Return result code.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tresult_code = __import__('pytest').main()\n\t\t\tif result_code:\n\t\t\t\traise SystemExit(result_code)", "code_tokens": "def run_tests ( self ) : with _save_argv ( _sys . argv [ : 1 ] + self . addopts ) : result_code = __import__ ( 'pytest' ) . main ( ) if result_code : raise SystemExit ( result_code )", "docstring_tokens": "Invoke pytest replacing argv . Return result code .", "label": 0 }, { "idx": "cosqa-dev-259", "doc": "python determine one folder is a subfolder of another", "code": "def is_subdir(a, b):\n \"\"\"\n Return true if a is a subdirectory of b\n \"\"\"\n a, b = map(os.path.abspath, [a, b])\n\n return os.path.commonpath([a, b]) == b", "code_tokens": "def is_subdir ( a , b ) : a , b = map ( os . path . abspath , [ a , b ] ) return os . path . commonpath ( [ a , b ] ) == b", "docstring_tokens": "Return true if a is a subdirectory of b", "label": 1 }, { "idx": "cosqa-dev-260", "doc": "how to write a function in python in descending order", "code": "def get_order(self, codes):\n \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "code_tokens": "def get_order ( self , codes ) : return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] )", "docstring_tokens": "Return evidence codes in order shown in code2name .", "label": 0 }, { "idx": "cosqa-dev-261", "doc": "using color in python printouts", "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 }, { "idx": "cosqa-dev-262", "doc": "multiple sql query python", "code": "def store_many(self, sql, values):\n \"\"\"Abstraction over executemany method\"\"\"\n cursor = self.get_cursor()\n cursor.executemany(sql, values)\n self.conn.commit()", "code_tokens": "def store_many ( self , sql , values ) : cursor = self . get_cursor ( ) cursor . executemany ( sql , values ) self . conn . commit ( )", "docstring_tokens": "Abstraction over executemany method", "label": 0 }, { "idx": "cosqa-dev-263", "doc": "splitting messages based on number of characters in python", "code": "def split_string(text, chars_per_string):\n \"\"\"\n Splits one string into multiple strings, with a maximum amount of `chars_per_string` characters per string.\n This is very useful for splitting one giant message into multiples.\n\n :param text: The text to split\n :param chars_per_string: The number of characters per line the text is split into.\n :return: The splitted text as a list of strings.\n \"\"\"\n return [text[i:i + chars_per_string] for i in range(0, len(text), chars_per_string)]", "code_tokens": "def split_string ( text , chars_per_string ) : return [ text [ i : i + chars_per_string ] for i in range ( 0 , len ( text ) , chars_per_string ) ]", "docstring_tokens": "Splits one string into multiple strings with a maximum amount of chars_per_string characters per string . This is very useful for splitting one giant message into multiples .", "label": 0 }, { "idx": "cosqa-dev-264", "doc": "displaying different pages in python", "code": "def Output(self):\n \"\"\"Output all sections of the page.\"\"\"\n self.Open()\n self.Header()\n self.Body()\n self.Footer()", "code_tokens": "def Output ( self ) : self . Open ( ) self . Header ( ) self . Body ( ) self . Footer ( )", "docstring_tokens": "Output all sections of the page .", "label": 0 }, { "idx": "cosqa-dev-265", "doc": "jacobian and hessian in python", "code": "def inverse_jacobian(self, maps):\n \"\"\"Returns the Jacobian for transforming mass1 and mass2 to\n mchirp and eta.\n \"\"\"\n m1 = maps[parameters.mass1]\n m2 = maps[parameters.mass2]\n mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)\n eta = conversions.eta_from_mass1_mass2(m1, m2)\n return -1. * mchirp / eta**(6./5)", "code_tokens": "def inverse_jacobian ( self , maps ) : m1 = maps [ parameters . mass1 ] m2 = maps [ parameters . mass2 ] mchirp = conversions . mchirp_from_mass1_mass2 ( m1 , m2 ) eta = conversions . eta_from_mass1_mass2 ( m1 , m2 ) return - 1. * mchirp / eta ** ( 6. / 5 )", "docstring_tokens": "Returns the Jacobian for transforming mass1 and mass2 to mchirp and eta .", "label": 0 }, { "idx": "cosqa-dev-266", "doc": "how to access an ordered dictionary in python", "code": "def format_result(input):\n \"\"\"From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python\n \"\"\"\n items = list(iteritems(input))\n return OrderedDict(sorted(items, key=lambda x: x[0]))", "code_tokens": "def format_result ( input ) : items = list ( iteritems ( input ) ) return OrderedDict ( sorted ( items , key = lambda x : x [ 0 ] ) )", "docstring_tokens": "From : http : // stackoverflow . com / questions / 13062300 / convert - a - dict - to - sorted - dict - in - python", "label": 0 }, { "idx": "cosqa-dev-267", "doc": "python check string is blank", "code": "def is_valid_variable_name(string_to_check):\n \"\"\"\n Returns whether the provided name is a valid variable name in Python\n\n :param string_to_check: the string to be checked\n :return: True or False\n \"\"\"\n\n try:\n\n parse('{} = None'.format(string_to_check))\n return True\n\n except (SyntaxError, ValueError, TypeError):\n\n return False", "code_tokens": "def is_valid_variable_name ( string_to_check ) : try : parse ( '{} = None' . format ( string_to_check ) ) return True except ( SyntaxError , ValueError , TypeError ) : return False", "docstring_tokens": "Returns whether the provided name is a valid variable name in Python", "label": 0 }, { "idx": "cosqa-dev-268", "doc": "python covariance of two array", "code": "def covariance(self,pt0,pt1):\n \"\"\" get the covarince between two points implied by Vario2d\n\n Parameters\n ----------\n pt0 : (iterable of len 2)\n first point x and y\n pt1 : (iterable of len 2)\n second point x and y\n\n Returns\n -------\n cov : float\n covariance between pt0 and pt1\n\n \"\"\"\n\n x = np.array([pt0[0],pt1[0]])\n y = np.array([pt0[1],pt1[1]])\n names = [\"n1\",\"n2\"]\n return self.covariance_matrix(x,y,names=names).x[0,1]", "code_tokens": "def covariance ( self , pt0 , pt1 ) : x = np . array ( [ pt0 [ 0 ] , pt1 [ 0 ] ] ) y = np . array ( [ pt0 [ 1 ] , pt1 [ 1 ] ] ) names = [ \"n1\" , \"n2\" ] return self . covariance_matrix ( x , y , names = names ) . x [ 0 , 1 ]", "docstring_tokens": "get the covarince between two points implied by Vario2d", "label": 1 }, { "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 }, { "idx": "cosqa-dev-270", "doc": "python accpet http request mock server", "code": "def requests_post(url, data=None, json=None, **kwargs):\n \"\"\"Requests-mock requests.post wrapper.\"\"\"\n return requests_request('post', url, data=data, json=json, **kwargs)", "code_tokens": "def requests_post ( url , data = None , json = None , * * kwargs ) : return requests_request ( 'post' , url , data = data , json = json , * * kwargs )", "docstring_tokens": "Requests - mock requests . post wrapper .", "label": 0 }, { "idx": "cosqa-dev-271", "doc": "how to post a variable in the request body in python api", "code": "def set_json_item(key, value):\n \"\"\" manipulate json data on the fly\n \"\"\"\n data = get_json()\n data[key] = value\n\n request = get_request()\n request[\"BODY\"] = json.dumps(data)", "code_tokens": "def set_json_item ( key , value ) : data = get_json ( ) data [ key ] = value request = get_request ( ) request [ \"BODY\" ] = json . dumps ( data )", "docstring_tokens": "manipulate json data on the fly", "label": 0 }, { "idx": "cosqa-dev-272", "doc": "adding noise to images python", "code": "def shot_noise(x, severity=1):\n \"\"\"Shot noise corruption to images.\n\n Args:\n x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].\n severity: integer, severity of corruption.\n\n Returns:\n numpy array, image with uint8 pixels in [0,255]. Added shot noise.\n \"\"\"\n c = [60, 25, 12, 5, 3][severity - 1]\n x = np.array(x) / 255.\n x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255\n return around_and_astype(x_clip)", "code_tokens": "def shot_noise ( x , severity = 1 ) : c = [ 60 , 25 , 12 , 5 , 3 ] [ severity - 1 ] x = np . array ( x ) / 255. x_clip = np . clip ( np . random . poisson ( x * c ) / float ( c ) , 0 , 1 ) * 255 return around_and_astype ( x_clip )", "docstring_tokens": "Shot noise corruption to images .", "label": 1 }, { "idx": "cosqa-dev-273", "doc": "calculate time of a python function", "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 }, { "idx": "cosqa-dev-274", "doc": "what function covert a string to a float in python", "code": "def energy_string_to_float( string ):\n \"\"\"\n Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n Args:\n string (str): The string to convert.\n \n Return\n (float) \n \"\"\"\n energy_re = re.compile( \"(-?\\d+\\.\\d+)\" )\n return float( energy_re.match( string ).group(0) )", "code_tokens": "def energy_string_to_float ( string ) : energy_re = re . compile ( \"(-?\\d+\\.\\d+)\" ) return float ( energy_re . match ( string ) . group ( 0 ) )", "docstring_tokens": "Convert a string of a calculation energy e . g . - 1 . 2345 eV to a float .", "label": 1 }, { "idx": "cosqa-dev-275", "doc": "passing a 3d python array to c++", "code": "def cfloat64_array_to_numpy(cptr, length):\n \"\"\"Convert a ctypes double pointer array to a numpy array.\"\"\"\n if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):\n return np.fromiter(cptr, dtype=np.float64, count=length)\n else:\n raise RuntimeError('Expected double pointer')", "code_tokens": "def cfloat64_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_double ) ) : return np . fromiter ( cptr , dtype = np . float64 , count = length ) else : raise RuntimeError ( 'Expected double pointer' )", "docstring_tokens": "Convert a ctypes double pointer array to a numpy array .", "label": 0 }, { "idx": "cosqa-dev-276", "doc": "python load json arry from file", "code": "def from_file(filename):\n \"\"\"\n load an nparray object from a json filename\n\n @parameter str filename: path to the file\n \"\"\"\n f = open(filename, 'r')\n j = json.load(f)\n f.close()\n\n return from_dict(j)", "code_tokens": "def from_file ( filename ) : f = open ( filename , 'r' ) j = json . load ( f ) f . close ( ) return from_dict ( j )", "docstring_tokens": "load an nparray object from a json filename", "label": 1 }, { "idx": "cosqa-dev-277", "doc": "python join two df and dont duplicate columns", "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 }, { "idx": "cosqa-dev-278", "doc": "how to remove links with certain characters python3", "code": "def escape_link(url):\n \"\"\"Remove dangerous URL schemes like javascript: and escape afterwards.\"\"\"\n lower_url = url.lower().strip('\\x00\\x1a \\n\\r\\t')\n for scheme in _scheme_blacklist:\n if lower_url.startswith(scheme):\n return ''\n return escape(url, quote=True, smart_amp=False)", "code_tokens": "def escape_link ( url ) : lower_url = url . lower ( ) . strip ( '\\x00\\x1a \\n\\r\\t' ) for scheme in _scheme_blacklist : if lower_url . startswith ( scheme ) : return '' return escape ( url , quote = True , smart_amp = False )", "docstring_tokens": "Remove dangerous URL schemes like javascript : and escape afterwards .", "label": 1 }, { "idx": "cosqa-dev-279", "doc": "python limit time for function", "code": "def timed (log=sys.stderr, limit=2.0):\n \"\"\"Decorator to run a function with timing info.\"\"\"\n return lambda func: timeit(func, log, limit)", "code_tokens": "def timed ( log = sys . stderr , limit = 2.0 ) : return lambda func : timeit ( func , log , limit )", "docstring_tokens": "Decorator to run a function with timing info .", "label": 1 }, { "idx": "cosqa-dev-280", "doc": "python dict to yaml", "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": 0 }, { "idx": "cosqa-dev-281", "doc": "python 3 clear all variables", "code": "def _clear(self):\n \"\"\"Resets all assigned data for the current message.\"\"\"\n self._finished = False\n self._measurement = None\n self._message = None\n self._message_body = None", "code_tokens": "def _clear ( self ) : self . _finished = False self . _measurement = None self . _message = None self . _message_body = None", "docstring_tokens": "Resets all assigned data for the current message .", "label": 0 }, { "idx": "cosqa-dev-282", "doc": "how to dynamically save a file in python", "code": "def pickle_save(thing,fname):\n \"\"\"save something to a pickle file\"\"\"\n pickle.dump(thing, open(fname,\"wb\"),pickle.HIGHEST_PROTOCOL)\n return thing", "code_tokens": "def pickle_save ( thing , fname ) : pickle . dump ( thing , open ( fname , \"wb\" ) , pickle . HIGHEST_PROTOCOL ) return thing", "docstring_tokens": "save something to a pickle file", "label": 0 }, { "idx": "cosqa-dev-283", "doc": "python xor two strings of binary code", "code": "def xor(a, b):\n \"\"\"Bitwise xor on equal length bytearrays.\"\"\"\n return bytearray(i ^ j for i, j in zip(a, b))", "code_tokens": "def xor ( a , b ) : return bytearray ( i ^ j for i , j in zip ( a , b ) )", "docstring_tokens": "Bitwise xor on equal length bytearrays .", "label": 1 }, { "idx": "cosqa-dev-284", "doc": "python implement hashable object", "code": "def __hash__(self):\n \"\"\"Return ``hash(self)``.\"\"\"\n return hash((type(self), self.domain, self.range, self.partition))", "code_tokens": "def __hash__ ( self ) : return hash ( ( type ( self ) , self . domain , self . range , self . partition ) )", "docstring_tokens": "Return hash ( self ) .", "label": 0 }, { "idx": "cosqa-dev-285", "doc": "how to go to a new line on python", "code": "def erase_lines(n=1):\n \"\"\" Erases n lines from the screen and moves the cursor up to follow\n \"\"\"\n for _ in range(n):\n print(codes.cursor[\"up\"], end=\"\")\n print(codes.cursor[\"eol\"], end=\"\")", "code_tokens": "def erase_lines ( n = 1 ) : for _ in range ( n ) : print ( codes . cursor [ \"up\" ] , end = \"\" ) print ( codes . cursor [ \"eol\" ] , end = \"\" )", "docstring_tokens": "Erases n lines from the screen and moves the cursor up to follow", "label": 0 }, { "idx": "cosqa-dev-286", "doc": "concertnate strings and ints in python", "code": "def type_converter(text):\n \"\"\" I convert strings into integers, floats, and strings! \"\"\"\n if text.isdigit():\n return int(text), int\n\n try:\n return float(text), float\n except ValueError:\n return text, STRING_TYPE", "code_tokens": "def type_converter ( text ) : if text . isdigit ( ) : return int ( text ) , int try : return float ( text ) , float except ValueError : return text , STRING_TYPE", "docstring_tokens": "I convert strings into integers floats and strings!", "label": 0 }, { "idx": "cosqa-dev-287", "doc": "how to set domain in python to allow complex numbers", "code": "def _config_win32_domain(self, domain):\n \"\"\"Configure a Domain registry entry.\"\"\"\n # we call str() on domain to convert it from unicode to ascii\n self.domain = dns.name.from_text(str(domain))", "code_tokens": "def _config_win32_domain ( self , domain ) : # we call str() on domain to convert it from unicode to ascii self . domain = dns . name . from_text ( str ( domain ) )", "docstring_tokens": "Configure a Domain registry entry .", "label": 0 }, { "idx": "cosqa-dev-288", "doc": "loading yaml file in python", "code": "def load_yaml(filepath):\n \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n with open(filepath) as f:\n txt = f.read()\n return yaml.load(txt)", "code_tokens": "def load_yaml ( filepath ) : with open ( filepath ) as f : txt = f . read ( ) return yaml . load ( txt )", "docstring_tokens": "Convenience function for loading yaml - encoded data from disk .", "label": 1 }, { "idx": "cosqa-dev-289", "doc": "python lambda to return len of longest element", "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 }, { "idx": "cosqa-dev-290", "doc": "max value and min vlaue constants in python", "code": "def _digits(minval, maxval):\n \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n if minval == maxval:\n return 3\n else:\n return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "code_tokens": "def _digits ( minval , maxval ) : if minval == maxval : return 3 else : return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) )", "docstring_tokens": "Digits needed to comforatbly display values in [ minval maxval ]", "label": 0 }, { "idx": "cosqa-dev-291", "doc": "python function to remove all non english letters", "code": "def clean(self, text):\n \"\"\"Remove all unwanted characters from text.\"\"\"\n return ''.join([c for c in text if c in self.alphabet])", "code_tokens": "def clean ( self , text ) : return '' . join ( [ c for c in text if c in self . alphabet ] )", "docstring_tokens": "Remove all unwanted characters from text .", "label": 1 }, { "idx": "cosqa-dev-292", "doc": "how do i make a list a certain size in python", "code": "def batch(items, size):\n \"\"\"Batches a list into a list of lists, with sub-lists sized by a specified\n batch size.\"\"\"\n return [items[x:x + size] for x in xrange(0, len(items), size)]", "code_tokens": "def batch ( items , size ) : return [ items [ x : x + size ] for x in xrange ( 0 , len ( items ) , size ) ]", "docstring_tokens": "Batches a list into a list of lists with sub - lists sized by a specified batch size .", "label": 0 }, { "idx": "cosqa-dev-293", "doc": "how to flush text files in python", "code": "def file_writelines_flush_sync(path, lines):\n \"\"\"\n Fill file at @path with @lines then flush all buffers\n (Python and system buffers)\n \"\"\"\n fp = open(path, 'w')\n try:\n fp.writelines(lines)\n flush_sync_file_object(fp)\n finally:\n fp.close()", "code_tokens": "def file_writelines_flush_sync ( path , lines ) : fp = open ( path , 'w' ) try : fp . writelines ( lines ) flush_sync_file_object ( fp ) finally : fp . close ( )", "docstring_tokens": "Fill file at", "label": 1 }, { "idx": "cosqa-dev-294", "doc": "check if an element is present in python and webdriver", "code": "def is_element_present(driver, selector, by=By.CSS_SELECTOR):\n \"\"\"\n Returns whether the specified element selector is present on the page.\n @Params\n driver - the webdriver object (required)\n selector - the locator that is used (required)\n by - the method to search for the locator (Default: By.CSS_SELECTOR)\n @Returns\n Boolean (is element present)\n \"\"\"\n try:\n driver.find_element(by=by, value=selector)\n return True\n except Exception:\n return False", "code_tokens": "def is_element_present ( driver , selector , by = By . CSS_SELECTOR ) : try : driver . find_element ( by = by , value = selector ) return True except Exception : return False", "docstring_tokens": "Returns whether the specified element selector is present on the page .", "label": 1 }, { "idx": "cosqa-dev-295", "doc": "encode a none type python", "code": "def _encode_bool(name, value, dummy0, dummy1):\n \"\"\"Encode a python boolean (True/False).\"\"\"\n return b\"\\x08\" + name + (value and b\"\\x01\" or b\"\\x00\")", "code_tokens": "def _encode_bool ( name , value , dummy0 , dummy1 ) : return b\"\\x08\" + name + ( value and b\"\\x01\" or b\"\\x00\" )", "docstring_tokens": "Encode a python boolean ( True / False ) .", "label": 0 }, { "idx": "cosqa-dev-296", "doc": "python limit variable inputs for a function", "code": "def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:\n \"\"\"Rate limit a function.\"\"\"\n return util.rate_limited(max_per_hour, *args)", "code_tokens": "def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )", "docstring_tokens": "Rate limit a function .", "label": 0 }, { "idx": "cosqa-dev-297", "doc": "matrix to adjacency list python", "code": "def get_adjacent_matrix(self):\n \"\"\"Get adjacency matrix.\n\n Returns:\n :param adj: adjacency matrix\n :type adj: np.ndarray\n \"\"\"\n edges = self.edges\n num_edges = len(edges) + 1\n adj = np.zeros([num_edges, num_edges])\n\n for k in range(num_edges - 1):\n adj[edges[k].L, edges[k].R] = 1\n adj[edges[k].R, edges[k].L] = 1\n\n return adj", "code_tokens": "def get_adjacent_matrix ( self ) : edges = self . edges num_edges = len ( edges ) + 1 adj = np . zeros ( [ num_edges , num_edges ] ) for k in range ( num_edges - 1 ) : adj [ edges [ k ] . L , edges [ k ] . R ] = 1 adj [ edges [ k ] . R , edges [ k ] . L ] = 1 return adj", "docstring_tokens": "Get adjacency matrix .", "label": 1 }, { "idx": "cosqa-dev-298", "doc": "mongodb python query distinct", "code": "def fast_distinct(self):\n \"\"\"\n Because standard distinct used on the all fields are very slow and works only with PostgreSQL database\n this method provides alternative to the standard distinct method.\n :return: qs with unique objects\n \"\"\"\n return self.model.objects.filter(pk__in=self.values_list('pk', flat=True))", "code_tokens": "def fast_distinct ( self ) : return self . model . objects . filter ( pk__in = self . values_list ( 'pk' , flat = True ) )", "docstring_tokens": "Because standard distinct used on the all fields are very slow and works only with PostgreSQL database this method provides alternative to the standard distinct method . : return : qs with unique objects", "label": 1 }, { "idx": "cosqa-dev-299", "doc": "get xml text python", "code": "def __get_xml_text(root):\n \"\"\" Return the text for the given root node (xml.dom.minidom). \"\"\"\n txt = \"\"\n for e in root.childNodes:\n if (e.nodeType == e.TEXT_NODE):\n txt += e.data\n return txt", "code_tokens": "def __get_xml_text ( root ) : txt = \"\" for e in root . childNodes : if ( e . nodeType == e . TEXT_NODE ) : txt += e . data return txt", "docstring_tokens": "Return the text for the given root node ( xml . dom . minidom ) .", "label": 1 }, { "idx": "cosqa-dev-300", "doc": "python get rid of last element in array", "code": "def remove_last_entry(self):\n \"\"\"Remove the last NoteContainer in the Bar.\"\"\"\n self.current_beat -= 1.0 / self.bar[-1][1]\n self.bar = self.bar[:-1]\n return self.current_beat", "code_tokens": "def remove_last_entry ( self ) : self . current_beat -= 1.0 / self . bar [ - 1 ] [ 1 ] self . bar = self . bar [ : - 1 ] return self . current_beat", "docstring_tokens": "Remove the last NoteContainer in the Bar .", "label": 0 }, { "idx": "cosqa-dev-301", "doc": "how to create wrapped socket in python", "code": "def connected_socket(address, timeout=3):\n \"\"\" yields a connected socket \"\"\"\n sock = socket.create_connection(address, timeout)\n yield sock\n sock.close()", "code_tokens": "def connected_socket ( address , timeout = 3 ) : sock = socket . create_connection ( address , timeout ) yield sock sock . close ( )", "docstring_tokens": "yields a connected socket", "label": 0 }, { "idx": "cosqa-dev-302", "doc": "python sleep in a while loop", "code": "def main(idle):\n \"\"\"Any normal python logic which runs a loop. Can take arguments.\"\"\"\n while True:\n\n LOG.debug(\"Sleeping for {0} seconds.\".format(idle))\n time.sleep(idle)", "code_tokens": "def main ( idle ) : while True : LOG . debug ( \"Sleeping for {0} seconds.\" . format ( idle ) ) time . sleep ( idle )", "docstring_tokens": "Any normal python logic which runs a loop . Can take arguments .", "label": 1 }, { "idx": "cosqa-dev-303", "doc": "built in function to check a datatype is list or not in python", "code": "def is_iter_non_string(obj):\n \"\"\"test if object is a list or tuple\"\"\"\n if isinstance(obj, list) or isinstance(obj, tuple):\n return True\n return False", "code_tokens": "def is_iter_non_string ( obj ) : if isinstance ( obj , list ) or isinstance ( obj , tuple ) : return True return False", "docstring_tokens": "test if object is a list or tuple", "label": 1 }, { "idx": "cosqa-dev-304", "doc": "python see if queue is empty", "code": "def full(self):\n \"\"\"Return True if the queue is full\"\"\"\n if not self.size: return False\n return len(self.pq) == (self.size + self.removed_count)", "code_tokens": "def full ( self ) : if not self . size : return False return len ( self . pq ) == ( self . size + self . removed_count )", "docstring_tokens": "Return True if the queue is full", "label": 0 }, { "idx": "cosqa-dev-305", "doc": "python read in a text file with comments into a list", "code": "def parse_comments_for_file(filename):\n \"\"\"\n Return a list of all parsed comments in a file. Mostly for testing &\n interactive use.\n \"\"\"\n return [parse_comment(strip_stars(comment), next_line)\n for comment, next_line in get_doc_comments(read_file(filename))]", "code_tokens": "def parse_comments_for_file ( filename ) : return [ parse_comment ( strip_stars ( comment ) , next_line ) for comment , next_line in get_doc_comments ( read_file ( filename ) ) ]", "docstring_tokens": "Return a list of all parsed comments in a file . Mostly for testing & interactive use .", "label": 1 }, { "idx": "cosqa-dev-306", "doc": "python matplotlib colorbar colormap", "code": "def palettebar(height, length, colormap):\n \"\"\"Return the channels of a palettebar.\n \"\"\"\n cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))\n cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())\n + colormap.values.min())\n\n return colormap.palettize(cbar)", "code_tokens": "def palettebar ( height , length , colormap ) : cbar = np . tile ( np . arange ( length ) * 1.0 / ( length - 1 ) , ( height , 1 ) ) cbar = ( cbar * ( colormap . values . max ( ) + 1 - colormap . values . min ( ) ) + colormap . values . min ( ) ) return colormap . palettize ( cbar )", "docstring_tokens": "Return the channels of a palettebar .", "label": 0 }, { "idx": "cosqa-dev-307", "doc": "python int to base", "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": 0 }, { "idx": "cosqa-dev-308", "doc": "python optionparser print usage", "code": "def help(self, level=0):\n \"\"\"return the usage string for available options \"\"\"\n self.cmdline_parser.formatter.output_level = level\n with _patch_optparse():\n return self.cmdline_parser.format_help()", "code_tokens": "def help ( self , level = 0 ) : self . cmdline_parser . formatter . output_level = level with _patch_optparse ( ) : return self . cmdline_parser . format_help ( )", "docstring_tokens": "return the usage string for available options", "label": 0 }, { "idx": "cosqa-dev-309", "doc": "write a python function to count the number of lines in a text file", "code": "def line_count(fn):\n \"\"\" Get line count of file\n\n Args:\n fn (str): Path to file\n\n Return:\n Number of lines in file (int)\n \"\"\"\n\n with open(fn) as f:\n for i, l in enumerate(f):\n pass\n return i + 1", "code_tokens": "def line_count ( fn ) : with open ( fn ) as f : for i , l in enumerate ( f ) : pass return i + 1", "docstring_tokens": "Get line count of file", "label": 1 }, { "idx": "cosqa-dev-310", "doc": "redisclient set not working python", "code": "def __setitem__(self, field, value):\n \"\"\" :see::meth:RedisMap.__setitem__ \"\"\"\n return self._client.hset(self.key_prefix, field, self._dumps(value))", "code_tokens": "def __setitem__ ( self , field , value ) : return self . _client . hset ( self . key_prefix , field , self . _dumps ( value ) )", "docstring_tokens": ": see :: meth : RedisMap . __setitem__", "label": 0 }, { "idx": "cosqa-dev-311", "doc": "python return index of object in a list", "code": "def get_list_index(lst, index_or_name):\n \"\"\"\n Return the index of an element in the list.\n\n Args:\n lst (list): The list.\n index_or_name (int or str): The value of the reference element, or directly its numeric index.\n\n Returns:\n (int) The index of the element in the list.\n \"\"\"\n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n return lst.index(index_or_name)", "code_tokens": "def get_list_index ( lst , index_or_name ) : if isinstance ( index_or_name , six . integer_types ) : return index_or_name return lst . index ( index_or_name )", "docstring_tokens": "Return the index of an element in the list .", "label": 1 }, { "idx": "cosqa-dev-312", "doc": "change the axis subplot python", "code": "def activate_subplot(numPlot):\n \"\"\"Make subplot *numPlot* active on the canvas.\n\n Use this if a simple ``subplot(numRows, numCols, numPlot)``\n overwrites the subplot instead of activating it.\n \"\"\"\n # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html\n from pylab import gcf, axes\n numPlot -= 1 # index is 0-based, plots are 1-based\n return axes(gcf().get_axes()[numPlot])", "code_tokens": "def activate_subplot ( numPlot ) : # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html from pylab import gcf , axes numPlot -= 1 # index is 0-based, plots are 1-based return axes ( gcf ( ) . get_axes ( ) [ numPlot ] )", "docstring_tokens": "Make subplot * numPlot * active on the canvas .", "label": 0 }, { "idx": "cosqa-dev-313", "doc": "python downsample 3d array", "code": "def downsample_with_striding(array, factor):\n \"\"\"Downsample x by factor using striding.\n\n @return: The downsampled array, of the same type as x.\n \"\"\"\n return array[tuple(np.s_[::f] for f in factor)]", "code_tokens": "def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]", "docstring_tokens": "Downsample x by factor using striding .", "label": 1 }, { "idx": "cosqa-dev-314", "doc": "python check if file has been modified hash", "code": "def check_dependency(self, dependency_path):\n \"\"\"Check if mtime of dependency_path is greater than stored mtime.\"\"\"\n stored_hash = self._stamp_file_hashes.get(dependency_path)\n\n # This file was newly added, or we don't have a file\n # with stored hashes yet. Assume out of date.\n if not stored_hash:\n return False\n\n return stored_hash == _sha1_for_file(dependency_path)", "code_tokens": "def check_dependency ( self , dependency_path ) : stored_hash = self . _stamp_file_hashes . get ( dependency_path ) # This file was newly added, or we don't have a file # with stored hashes yet. Assume out of date. if not stored_hash : return False return stored_hash == _sha1_for_file ( dependency_path )", "docstring_tokens": "Check if mtime of dependency_path is greater than stored mtime .", "label": 0 }, { "idx": "cosqa-dev-315", "doc": "python image normalization lighting condition", "code": "def min_max_normalize(img):\n \"\"\"Centre and normalize a given array.\n\n Parameters:\n ----------\n img: np.ndarray\n\n \"\"\"\n\n min_img = img.min()\n max_img = img.max()\n\n return (img - min_img) / (max_img - min_img)", "code_tokens": "def min_max_normalize ( img ) : min_img = img . min ( ) max_img = img . max ( ) return ( img - min_img ) / ( max_img - min_img )", "docstring_tokens": "Centre and normalize a given array .", "label": 1 }, { "idx": "cosqa-dev-316", "doc": "check if a string start with a prefix in python", "code": "def starts_with_prefix_in_list(text, prefixes):\n \"\"\"\n Return True if the given string starts with one of the prefixes in the given list, otherwise\n return False.\n\n Arguments:\n text (str): Text to check for prefixes.\n prefixes (list): List of prefixes to check for.\n\n Returns:\n bool: True if the given text starts with any of the given prefixes, otherwise False.\n \"\"\"\n for prefix in prefixes:\n if text.startswith(prefix):\n return True\n return False", "code_tokens": "def starts_with_prefix_in_list ( text , prefixes ) : for prefix in prefixes : if text . startswith ( prefix ) : return True return False", "docstring_tokens": "Return True if the given string starts with one of the prefixes in the given list otherwise return False .", "label": 1 }, { "idx": "cosqa-dev-317", "doc": "how in python coerce data frame to dictionary", "code": "def _dict(content):\n \"\"\"\n Helper funcation that converts text-based get response\n to a python dictionary for additional manipulation.\n \"\"\"\n if _has_pandas:\n data = _data_frame(content).to_dict(orient='records')\n else:\n response = loads(content)\n key = [x for x in response.keys() if x in c.response_data][0]\n data = response[key]\n return data", "code_tokens": "def _dict ( content ) : if _has_pandas : data = _data_frame ( content ) . to_dict ( orient = 'records' ) else : response = loads ( content ) key = [ x for x in response . keys ( ) if x in c . response_data ] [ 0 ] data = response [ key ] return data", "docstring_tokens": "Helper funcation that converts text - based get response to a python dictionary for additional manipulation .", "label": 0 }, { "idx": "cosqa-dev-318", "doc": "python logging param in string", "code": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "code_tokens": "def debug ( self , text ) : self . logger . debug ( \"{}{}\" . format ( self . message_prefix , text ) )", "docstring_tokens": "Ajout d un message de log de type DEBUG", "label": 0 }, { "idx": "cosqa-dev-319", "doc": "python get boolean input from user", "code": "def boolean(value):\n \"\"\"\n Configuration-friendly boolean type converter.\n\n Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n \"\"\"\n if isinstance(value, bool):\n return value\n\n if value == \"\":\n return False\n\n return strtobool(value)", "code_tokens": "def boolean ( value ) : if isinstance ( value , bool ) : return value if value == \"\" : return False return strtobool ( value )", "docstring_tokens": "Configuration - friendly boolean type converter .", "label": 1 }, { "idx": "cosqa-dev-320", "doc": "how to turn a string into a datetime python", "code": "def parse_datetime(dt_str):\n \"\"\"Parse datetime.\"\"\"\n date_format = \"%Y-%m-%dT%H:%M:%S %z\"\n dt_str = dt_str.replace(\"Z\", \" +0000\")\n return datetime.datetime.strptime(dt_str, date_format)", "code_tokens": "def parse_datetime ( dt_str ) : date_format = \"%Y-%m-%dT%H:%M:%S %z\" dt_str = dt_str . replace ( \"Z\" , \" +0000\" ) return datetime . datetime . strptime ( dt_str , date_format )", "docstring_tokens": "Parse datetime .", "label": 1 }, { "idx": "cosqa-dev-321", "doc": "longest common substring using contains python", "code": "def long_substr(data):\n \"\"\"Return the longest common substring in a list of strings.\n \n Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python\n \"\"\"\n substr = ''\n if len(data) > 1 and len(data[0]) > 0:\n for i in range(len(data[0])):\n for j in range(len(data[0])-i+1):\n if j > len(substr) and all(data[0][i:i+j] in x for x in data):\n substr = data[0][i:i+j]\n elif len(data) == 1:\n substr = data[0]\n return substr", "code_tokens": "def long_substr ( data ) : substr = '' if len ( data ) > 1 and len ( data [ 0 ] ) > 0 : for i in range ( len ( data [ 0 ] ) ) : for j in range ( len ( data [ 0 ] ) - i + 1 ) : if j > len ( substr ) and all ( data [ 0 ] [ i : i + j ] in x for x in data ) : substr = data [ 0 ] [ i : i + j ] elif len ( data ) == 1 : substr = data [ 0 ] return substr", "docstring_tokens": "Return the longest common substring in a list of strings . Credit : http : // stackoverflow . com / questions / 2892931 / longest - common - substring - from - more - than - two - strings - python", "label": 1 }, { "idx": "cosqa-dev-322", "doc": "destroy an object at constructor python using destroy", "code": "def __del__(self):\n \"\"\"Frees all resources.\n \"\"\"\n if hasattr(self, '_Api'):\n self._Api.close()\n\n self._Logger.info('object destroyed')", "code_tokens": "def __del__ ( self ) : if hasattr ( self , '_Api' ) : self . _Api . close ( ) self . _Logger . info ( 'object destroyed' )", "docstring_tokens": "Frees all resources .", "label": 0 }, { "idx": "cosqa-dev-323", "doc": "python asyncio how to stop the loop", "code": "async def wait_and_quit(loop):\n\t\"\"\"Wait until all task are executed.\"\"\"\n\tfrom pylp.lib.tasks import running\n\tif running:\n\t\tawait asyncio.wait(map(lambda runner: runner.future, running))", "code_tokens": "async def wait_and_quit ( loop ) : from pylp . lib . tasks import running if running : await asyncio . wait ( map ( lambda runner : runner . future , running ) )", "docstring_tokens": "Wait until all task are executed .", "label": 0 }, { "idx": "cosqa-dev-324", "doc": "rabbitmq python pika confirm", "code": "def reconnect(self):\n \"\"\"Reconnect to rabbitmq server\"\"\"\n import pika\n import pika.exceptions\n\n self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n self.channel = self.connection.channel()\n try:\n self.channel.queue_declare(self.name)\n except pika.exceptions.ChannelClosed:\n self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))\n self.channel = self.connection.channel()", "code_tokens": "def reconnect ( self ) : import pika import pika . exceptions self . connection = pika . BlockingConnection ( pika . URLParameters ( self . amqp_url ) ) self . channel = self . connection . channel ( ) try : self . channel . queue_declare ( self . name ) except pika . exceptions . ChannelClosed : self . connection = pika . BlockingConnection ( pika . URLParameters ( self . amqp_url ) ) self . channel = self . connection . channel ( )", "docstring_tokens": "Reconnect to rabbitmq server", "label": 0 }, { "idx": "cosqa-dev-325", "doc": "python check if you are root", "code": "def require_root(fn):\n \"\"\"\n Decorator to make sure, that user is root.\n \"\"\"\n @wraps(fn)\n def xex(*args, **kwargs):\n assert os.geteuid() == 0, \\\n \"You have to be root to run function '%s'.\" % fn.__name__\n return fn(*args, **kwargs)\n\n return xex", "code_tokens": "def require_root ( fn ) : @ wraps ( fn ) def xex ( * args , * * kwargs ) : assert os . geteuid ( ) == 0 , \"You have to be root to run function '%s'.\" % fn . __name__ return fn ( * args , * * kwargs ) return xex", "docstring_tokens": "Decorator to make sure that user is root .", "label": 0 }, { "idx": "cosqa-dev-326", "doc": "python good hash function", "code": "def _my_hash(arg_list):\n # type: (List[Any]) -> int\n \"\"\"Simple helper hash function\"\"\"\n res = 0\n for arg in arg_list:\n res = res * 31 + hash(arg)\n return res", "code_tokens": "def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res", "docstring_tokens": "Simple helper hash function", "label": 0 }, { "idx": "cosqa-dev-327", "doc": "python check is datetime object", "code": "def is_timestamp(obj):\n \"\"\"\n Yaml either have automatically converted it to a datetime object\n or it is a string that will be validated later.\n \"\"\"\n return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)", "code_tokens": "def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj )", "docstring_tokens": "Yaml either have automatically converted it to a datetime object or it is a string that will be validated later .", "label": 1 }, { "idx": "cosqa-dev-328", "doc": "python replace between two words", "code": "def multi_replace(instr, search_list=[], repl_list=None):\n \"\"\"\n Does a string replace with a list of search and replacements\n\n TODO: rename\n \"\"\"\n repl_list = [''] * len(search_list) if repl_list is None else repl_list\n for ser, repl in zip(search_list, repl_list):\n instr = instr.replace(ser, repl)\n return instr", "code_tokens": "def multi_replace ( instr , search_list = [ ] , repl_list = None ) : repl_list = [ '' ] * len ( search_list ) if repl_list is None else repl_list for ser , repl in zip ( search_list , repl_list ) : instr = instr . replace ( ser , repl ) return instr", "docstring_tokens": "Does a string replace with a list of search and replacements", "label": 0 }, { "idx": "cosqa-dev-329", "doc": "python take absolute value of array", "code": "def fn_abs(self, value):\n \"\"\"\n Return the absolute value of a number.\n\n :param value: The number.\n :return: The absolute value of the number.\n \"\"\"\n\n if is_ndarray(value):\n return numpy.absolute(value)\n else:\n return abs(value)", "code_tokens": "def fn_abs ( self , value ) : if is_ndarray ( value ) : return numpy . absolute ( value ) else : return abs ( value )", "docstring_tokens": "Return the absolute value of a number .", "label": 1 }, { "idx": "cosqa-dev-330", "doc": "how to make a list hashable in python", "code": "def unique(iterable):\n \"\"\" Returns a list copy in which each item occurs only once (in-order).\n \"\"\"\n seen = set()\n return [x for x in iterable if x not in seen and not seen.add(x)]", "code_tokens": "def unique ( iterable ) : seen = set ( ) return [ x for x in iterable if x not in seen and not seen . add ( x ) ]", "docstring_tokens": "Returns a list copy in which each item occurs only once ( in - order ) .", "label": 0 }, { "idx": "cosqa-dev-331", "doc": "inner product of vectors 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 }, { "idx": "cosqa-dev-332", "doc": "number of unique 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 }, { "idx": "cosqa-dev-333", "doc": "match specifc string except other python", "code": "def matches(self, s):\n \"\"\"Whether the pattern matches anywhere in the string s.\"\"\"\n regex_matches = self.compiled_regex.search(s) is not None\n return not regex_matches if self.inverted else regex_matches", "code_tokens": "def matches ( self , s ) : regex_matches = self . compiled_regex . search ( s ) is not None return not regex_matches if self . inverted else regex_matches", "docstring_tokens": "Whether the pattern matches anywhere in the string s .", "label": 1 }, { "idx": "cosqa-dev-334", "doc": "python know last element in for loop", "code": "def iter_with_last(iterable):\n \"\"\"\n :return: generator of tuples (isLastFlag, item)\n \"\"\"\n # Ensure it's an iterator and get the first field\n iterable = iter(iterable)\n prev = next(iterable)\n for item in iterable:\n # Lag by one item so I know I'm not at the end\n yield False, prev\n prev = item\n # Last item\n yield True, prev", "code_tokens": "def iter_with_last ( iterable ) : # Ensure it's an iterator and get the first field iterable = iter ( iterable ) prev = next ( iterable ) for item in iterable : # Lag by one item so I know I'm not at the end yield False , prev prev = item # Last item yield True , prev", "docstring_tokens": ": return : generator of tuples ( isLastFlag item )", "label": 0 }, { "idx": "cosqa-dev-335", "doc": "python fix encoding def", "code": "def b(s):\n\t\"\"\" Encodes Unicode strings to byte strings, if necessary. \"\"\"\n\n\treturn s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())", "code_tokens": "def b ( s ) : return s if isinstance ( s , bytes ) else s . encode ( locale . getpreferredencoding ( ) )", "docstring_tokens": "Encodes Unicode strings to byte strings if necessary .", "label": 0 }, { "idx": "cosqa-dev-336", "doc": "how to check all the column names in table in python", "code": "def _columns_for_table(table_name):\n \"\"\"\n Return all of the columns registered for a given table.\n\n Parameters\n ----------\n table_name : str\n\n Returns\n -------\n columns : dict of column wrappers\n Keys will be column names.\n\n \"\"\"\n return {cname: col\n for (tname, cname), col in _COLUMNS.items()\n if tname == table_name}", "code_tokens": "def _columns_for_table ( table_name ) : return { cname : col for ( tname , cname ) , col in _COLUMNS . items ( ) if tname == table_name }", "docstring_tokens": "Return all of the columns registered for a given table .", "label": 0 }, { "idx": "cosqa-dev-337", "doc": "how to sort names in reverse alphabetical in python", "code": "def get_order(self, codes):\n \"\"\"Return evidence codes in order shown in code2name.\"\"\"\n return sorted(codes, key=lambda e: [self.ev2idx.get(e)])", "code_tokens": "def get_order ( self , codes ) : return sorted ( codes , key = lambda e : [ self . ev2idx . get ( e ) ] )", "docstring_tokens": "Return evidence codes in order shown in code2name .", "label": 0 }, { "idx": "cosqa-dev-338", "doc": "get all the variable in python local", "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 }, { "idx": "cosqa-dev-339", "doc": "python computation with the index of min", "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": 0 }, { "idx": "cosqa-dev-340", "doc": "how to make time limit in python", "code": "def timed (log=sys.stderr, limit=2.0):\n \"\"\"Decorator to run a function with timing info.\"\"\"\n return lambda func: timeit(func, log, limit)", "code_tokens": "def timed ( log = sys . stderr , limit = 2.0 ) : return lambda func : timeit ( func , log , limit )", "docstring_tokens": "Decorator to run a function with timing info .", "label": 0 }, { "idx": "cosqa-dev-341", "doc": "python flatten a dict", "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 }, { "idx": "cosqa-dev-342", "doc": "python get distance between two points in same cluster", "code": "def skip_connection_distance(a, b):\n \"\"\"The distance between two skip-connections.\"\"\"\n if a[2] != b[2]:\n return 1.0\n len_a = abs(a[1] - a[0])\n len_b = abs(b[1] - b[0])\n return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))", "code_tokens": "def skip_connection_distance ( a , b ) : if a [ 2 ] != b [ 2 ] : return 1.0 len_a = abs ( a [ 1 ] - a [ 0 ] ) len_b = abs ( b [ 1 ] - b [ 0 ] ) return ( abs ( a [ 0 ] - b [ 0 ] ) + abs ( len_a - len_b ) ) / ( max ( a [ 0 ] , b [ 0 ] ) + max ( len_a , len_b ) )", "docstring_tokens": "The distance between two skip - connections .", "label": 0 }, { "idx": "cosqa-dev-343", "doc": "how do you make a horizontal line in python", "code": "def get_hline():\n \"\"\" gets a horiztonal line \"\"\"\n return Window(\n width=LayoutDimension.exact(1),\n height=LayoutDimension.exact(1),\n content=FillControl('-', token=Token.Line))", "code_tokens": "def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) )", "docstring_tokens": "gets a horiztonal line", "label": 1 }, { "idx": "cosqa-dev-344", "doc": "python rpy2 robjects not found", "code": "def setup_detect_python2():\n \"\"\"\n Call this before using the refactoring tools to create them on demand\n if needed.\n \"\"\"\n if None in [RTs._rt_py2_detect, RTs._rtp_py2_detect]:\n RTs._rt_py2_detect = RefactoringTool(py2_detect_fixers)\n RTs._rtp_py2_detect = RefactoringTool(py2_detect_fixers,\n {'print_function': True})", "code_tokens": "def setup_detect_python2 ( ) : if None in [ RTs . _rt_py2_detect , RTs . _rtp_py2_detect ] : RTs . _rt_py2_detect = RefactoringTool ( py2_detect_fixers ) RTs . _rtp_py2_detect = RefactoringTool ( py2_detect_fixers , { 'print_function' : True } )", "docstring_tokens": "Call this before using the refactoring tools to create them on demand if needed .", "label": 0 }, { "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 }, { "idx": "cosqa-dev-346", "doc": "wxpython close panel on cancel", "code": "def on_close(self, evt):\n \"\"\"\n Pop-up menu and wx.EVT_CLOSE closing event\n \"\"\"\n self.stop() # DoseWatcher\n if evt.EventObject is not self: # Avoid deadlocks\n self.Close() # wx.Frame\n evt.Skip()", "code_tokens": "def on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )", "docstring_tokens": "Pop - up menu and wx . EVT_CLOSE closing event", "label": 0 }, { "idx": "cosqa-dev-347", "doc": "python dict remove items by keys", "code": "def filter_dict(d, keys):\n \"\"\"\n Creates a new dict from an existing dict that only has the given keys\n \"\"\"\n return {k: v for k, v in d.items() if k in keys}", "code_tokens": "def filter_dict ( d , keys ) : return { k : v for k , v in d . items ( ) if k in keys }", "docstring_tokens": "Creates a new dict from an existing dict that only has the given keys", "label": 1 }, { "idx": "cosqa-dev-348", "doc": "using python to send serial commands", "code": "def command(self, cmd, *args):\n \"\"\"\n Sends a command and an (optional) sequence of arguments through to the\n delegated serial interface. Note that the arguments are passed through\n as data.\n \"\"\"\n self._serial_interface.command(cmd)\n if len(args) > 0:\n self._serial_interface.data(list(args))", "code_tokens": "def command ( self , cmd , * args ) : self . _serial_interface . command ( cmd ) if len ( args ) > 0 : self . _serial_interface . data ( list ( args ) )", "docstring_tokens": "Sends a command and an ( optional ) sequence of arguments through to the delegated serial interface . Note that the arguments are passed through as data .", "label": 1 }, { "idx": "cosqa-dev-349", "doc": "relace multiple characters in a string with emty string python", "code": "def multiple_replace(string, replacements):\n # type: (str, Dict[str,str]) -> str\n \"\"\"Simultaneously replace multiple strigns in a string\n\n Args:\n string (str): Input string\n replacements (Dict[str,str]): Replacements dictionary\n\n Returns:\n str: String with replacements\n\n \"\"\"\n pattern = re.compile(\"|\".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)\n return pattern.sub(lambda x: replacements[x.group(0)], string)", "code_tokens": "def multiple_replace ( string , replacements ) : # type: (str, Dict[str,str]) -> str pattern = re . compile ( \"|\" . join ( [ re . escape ( k ) for k in sorted ( replacements , key = len , reverse = True ) ] ) , flags = re . DOTALL ) return pattern . sub ( lambda x : replacements [ x . group ( 0 ) ] , string )", "docstring_tokens": "Simultaneously replace multiple strigns in a string", "label": 1 }, { "idx": "cosqa-dev-350", "doc": "python have a destructor", "code": "def __del__(self):\n \"\"\"Frees all resources.\n \"\"\"\n if hasattr(self, '_Api'):\n self._Api.close()\n\n self._Logger.info('object destroyed')", "code_tokens": "def __del__ ( self ) : if hasattr ( self , '_Api' ) : self . _Api . close ( ) self . _Logger . info ( 'object destroyed' )", "docstring_tokens": "Frees all resources .", "label": 0 }, { "idx": "cosqa-dev-351", "doc": "improve python processing multicore", "code": "def getCollectDServer(queue, cfg):\n \"\"\"Get the appropriate collectd server (multi processed or not)\"\"\"\n server = CollectDServerMP if cfg.collectd_workers > 1 else CollectDServer\n return server(queue, cfg)", "code_tokens": "def getCollectDServer ( queue , cfg ) : server = CollectDServerMP if cfg . collectd_workers > 1 else CollectDServer return server ( queue , cfg )", "docstring_tokens": "Get the appropriate collectd server ( multi processed or not )", "label": 0 }, { "idx": "cosqa-dev-352", "doc": "python if text file type", "code": "def IsBinary(self, filename):\n\t\t\"\"\"Returns true if the guessed mimetyped isnt't in text group.\"\"\"\n\t\tmimetype = mimetypes.guess_type(filename)[0]\n\t\tif not mimetype:\n\t\t\treturn False # e.g. README, \"real\" binaries usually have an extension\n\t\t# special case for text files which don't start with text/\n\t\tif mimetype in TEXT_MIMETYPES:\n\t\t\treturn False\n\t\treturn not mimetype.startswith(\"text/\")", "code_tokens": "def IsBinary ( self , filename ) : mimetype = mimetypes . guess_type ( filename ) [ 0 ] if not mimetype : return False # e.g. README, \"real\" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES : return False return not mimetype . startswith ( \"text/\" )", "docstring_tokens": "Returns true if the guessed mimetyped isnt t in text group .", "label": 0 }, { "idx": "cosqa-dev-353", "doc": "python finding the lowest integer in a group of numbers", "code": "def find_le(a, x):\n \"\"\"Find rightmost value less than or equal to x.\"\"\"\n i = bs.bisect_right(a, x)\n if i: return i - 1\n raise ValueError", "code_tokens": "def find_le ( a , x ) : i = bs . bisect_right ( a , x ) if i : return i - 1 raise ValueError", "docstring_tokens": "Find rightmost value less than or equal to x .", "label": 0 }, { "idx": "cosqa-dev-354", "doc": "python 3 rounding or floats", "code": "def py3round(number):\n \"\"\"Unified rounding in all python versions.\"\"\"\n if abs(round(number) - number) == 0.5:\n return int(2.0 * round(number / 2.0))\n\n return int(round(number))", "code_tokens": "def py3round ( number ) : if abs ( round ( number ) - number ) == 0.5 : return int ( 2.0 * round ( number / 2.0 ) ) return int ( round ( number ) )", "docstring_tokens": "Unified rounding in all python versions .", "label": 1 }, { "idx": "cosqa-dev-355", "doc": "python tkinter remove checkbox", "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": 0 }, { "idx": "cosqa-dev-356", "doc": "python set of integers to set of strings", "code": "def ranges_to_set(lst):\n \"\"\"\n Convert a list of ranges to a set of numbers::\n\n >>> ranges = [(1,3), (5,6)]\n >>> sorted(list(ranges_to_set(ranges)))\n [1, 2, 3, 5, 6]\n\n \"\"\"\n return set(itertools.chain(*(range(x[0], x[1]+1) for x in lst)))", "code_tokens": "def ranges_to_set ( lst ) : return set ( itertools . chain ( * ( range ( x [ 0 ] , x [ 1 ] + 1 ) for x in lst ) ) )", "docstring_tokens": "Convert a list of ranges to a set of numbers ::", "label": 0 }, { "idx": "cosqa-dev-357", "doc": "how to zip files in python", "code": "def extract_zip(zip_path, target_folder):\n \"\"\"\n Extract the content of the zip-file at `zip_path` into `target_folder`.\n \"\"\"\n with zipfile.ZipFile(zip_path) as archive:\n archive.extractall(target_folder)", "code_tokens": "def extract_zip ( zip_path , target_folder ) : with zipfile . ZipFile ( zip_path ) as archive : archive . extractall ( target_folder )", "docstring_tokens": "Extract the content of the zip - file at zip_path into target_folder .", "label": 0 }, { "idx": "cosqa-dev-358", "doc": "python array slice dont include last element", "code": "def getbyteslice(self, start, end):\n \"\"\"Direct access to byte data.\"\"\"\n c = self._rawarray[start:end]\n return c", "code_tokens": "def getbyteslice ( self , start , end ) : c = self . _rawarray [ start : end ] return c", "docstring_tokens": "Direct access to byte data .", "label": 0 }, { "idx": "cosqa-dev-359", "doc": "python expand into kwargs", "code": "def prepare_query_params(**kwargs):\n \"\"\"\n Prepares given parameters to be used in querystring.\n \"\"\"\n return [\n (sub_key, sub_value)\n for key, value in kwargs.items()\n for sub_key, sub_value in expand(value, key)\n if sub_value is not None\n ]", "code_tokens": "def prepare_query_params ( * * kwargs ) : return [ ( sub_key , sub_value ) for key , value in kwargs . items ( ) for sub_key , sub_value in expand ( value , key ) if sub_value is not None ]", "docstring_tokens": "Prepares given parameters to be used in querystring .", "label": 0 }, { "idx": "cosqa-dev-360", "doc": "write pdf file python stack overflow", "code": "def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):\n \"\"\"\n Appends a PDF to a pyPDF writer. Legacy interface.\n \"\"\"\n append_memory_pdf_to_writer(input_pdf=input_pdf,\n writer=output_writer)", "code_tokens": "def append_pdf ( input_pdf : bytes , output_writer : PdfFileWriter ) : append_memory_pdf_to_writer ( input_pdf = input_pdf , writer = output_writer )", "docstring_tokens": "Appends a PDF to a pyPDF writer . Legacy interface .", "label": 0 }, { "idx": "cosqa-dev-361", "doc": "check python flask running on server", "code": "def is_client(self):\n \"\"\"Return True if Glances is running in client mode.\"\"\"\n return (self.args.client or self.args.browser) and not self.args.server", "code_tokens": "def is_client ( self ) : return ( self . args . client or self . args . browser ) and not self . args . server", "docstring_tokens": "Return True if Glances is running in client mode .", "label": 0 }, { "idx": "cosqa-dev-362", "doc": "how to print clear the screen in python", "code": "def clear(self):\n \"\"\"\n Clear screen and go to 0,0\n \"\"\"\n # Erase current output first.\n self.erase()\n\n # Send \"Erase Screen\" command and go to (0, 0).\n output = self.output\n\n output.erase_screen()\n output.cursor_goto(0, 0)\n output.flush()\n\n self.request_absolute_cursor_position()", "code_tokens": "def clear ( self ) : # Erase current output first. self . erase ( ) # Send \"Erase Screen\" command and go to (0, 0). output = self . output output . erase_screen ( ) output . cursor_goto ( 0 , 0 ) output . flush ( ) self . request_absolute_cursor_position ( )", "docstring_tokens": "Clear screen and go to 0 0", "label": 1 }, { "idx": "cosqa-dev-363", "doc": "get width and height of string in python", "code": "def text_width(string, font_name, font_size):\n \"\"\"Determine with width in pixels of string.\"\"\"\n return stringWidth(string, fontName=font_name, fontSize=font_size)", "code_tokens": "def text_width ( string , font_name , font_size ) : return stringWidth ( string , fontName = font_name , fontSize = font_size )", "docstring_tokens": "Determine with width in pixels of string .", "label": 1 }, { "idx": "cosqa-dev-364", "doc": "python logging to file not written", "code": "def log_no_newline(self, msg):\n \"\"\" print the message to the predefined log file without newline \"\"\"\n self.print2file(self.logfile, False, False, msg)", "code_tokens": "def log_no_newline ( self , msg ) : self . print2file ( self . logfile , False , False , msg )", "docstring_tokens": "print the message to the predefined log file without newline", "label": 0 }, { "idx": "cosqa-dev-365", "doc": "python datetime iso format string", "code": "def isoformat(dt):\n \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n if not isinstance(dt, datetime.datetime):\n raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n if dt.tzinfo is None:\n raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n return dt.isoformat().replace(\"+00:00\", \"Z\")", "code_tokens": "def isoformat ( dt ) : if not isinstance ( dt , datetime . datetime ) : raise TypeError ( \"Must provide datetime.datetime object to isoformat\" ) if dt . tzinfo is None : raise ValueError ( \"naive datetime objects are not allowed beyond the library boundaries\" ) return dt . isoformat ( ) . replace ( \"+00:00\" , \"Z\" )", "docstring_tokens": "Return an ISO - 8601 formatted string from the provided datetime object", "label": 1 }, { "idx": "cosqa-dev-366", "doc": "prevent color of white or black using python colorsys", "code": "def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout):\n \"\"\"Set foreground- and background colors and intensity.\"\"\"\n raise NotImplementedError", "code_tokens": "def set_color ( self , fg = None , bg = None , intensify = False , target = sys . stdout ) : raise NotImplementedError", "docstring_tokens": "Set foreground - and background colors and intensity .", "label": 1 }, { "idx": "cosqa-dev-367", "doc": "python signal handling kill", "code": "def set_terminate_listeners(stream):\n \"\"\"Die on SIGTERM or SIGINT\"\"\"\n\n def stop(signum, frame):\n terminate(stream.listener)\n\n # Installs signal handlers for handling SIGINT and SIGTERM\n # gracefully.\n signal.signal(signal.SIGINT, stop)\n signal.signal(signal.SIGTERM, stop)", "code_tokens": "def set_terminate_listeners ( stream ) : def stop ( signum , frame ) : terminate ( stream . listener ) # Installs signal handlers for handling SIGINT and SIGTERM # gracefully. signal . signal ( signal . SIGINT , stop ) signal . signal ( signal . SIGTERM , stop )", "docstring_tokens": "Die on SIGTERM or SIGINT", "label": 0 }, { "idx": "cosqa-dev-368", "doc": "how to calculate zscore from str list in python", "code": "def zs(inlist):\n \"\"\"\nReturns a list of z-scores, one for each score in the passed list.\n\nUsage: lzs(inlist)\n\"\"\"\n zscores = []\n for item in inlist:\n zscores.append(z(inlist, item))\n return zscores", "code_tokens": "def zs ( inlist ) : zscores = [ ] for item in inlist : zscores . append ( z ( inlist , item ) ) return zscores", "docstring_tokens": "Returns a list of z - scores one for each score in the passed list .", "label": 0 }, { "idx": "cosqa-dev-369", "doc": "pulling data out of hdf5 matlab files python", "code": "def _load_data(filepath):\n \"\"\"Loads the images and latent values into Numpy arrays.\"\"\"\n with h5py.File(filepath, \"r\") as h5dataset:\n image_array = np.array(h5dataset[\"images\"])\n # The 'label' data set in the hdf5 file actually contains the float values\n # and not the class labels.\n values_array = np.array(h5dataset[\"labels\"])\n return image_array, values_array", "code_tokens": "def _load_data ( filepath ) : with h5py . File ( filepath , \"r\" ) as h5dataset : image_array = np . array ( h5dataset [ \"images\" ] ) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np . array ( h5dataset [ \"labels\" ] ) return image_array , values_array", "docstring_tokens": "Loads the images and latent values into Numpy arrays .", "label": 0 }, { "idx": "cosqa-dev-370", "doc": "how to get the last element in linked list in python", "code": "def get_tail(self):\n \"\"\"Gets tail\n\n :return: Tail of linked list\n \"\"\"\n node = self.head\n last_node = self.head\n\n while node is not None:\n last_node = node\n node = node.next_node\n\n return last_node", "code_tokens": "def get_tail ( self ) : node = self . head last_node = self . head while node is not None : last_node = node node = node . next_node return last_node", "docstring_tokens": "Gets tail", "label": 1 }, { "idx": "cosqa-dev-371", "doc": "python make a list into dict", "code": "def list_of_lists_to_dict(l):\n \"\"\" Convert list of key,value lists to dict\n\n [['id', 1], ['id', 2], ['id', 3], ['foo': 4]]\n {'id': [1, 2, 3], 'foo': [4]}\n \"\"\"\n d = {}\n for key, val in l:\n d.setdefault(key, []).append(val)\n return d", "code_tokens": "def list_of_lists_to_dict ( l ) : d = { } for key , val in l : d . setdefault ( key , [ ] ) . append ( val ) return d", "docstring_tokens": "Convert list of key value lists to dict", "label": 1 }, { "idx": "cosqa-dev-372", "doc": "python2 get value from dict with default value", "code": "def get_value(key, obj, default=missing):\n \"\"\"Helper for pulling a keyed value off various types of objects\"\"\"\n if isinstance(key, int):\n return _get_value_for_key(key, obj, default)\n return _get_value_for_keys(key.split('.'), obj, default)", "code_tokens": "def get_value ( key , obj , default = missing ) : if isinstance ( key , int ) : return _get_value_for_key ( key , obj , default ) return _get_value_for_keys ( key . split ( '.' ) , obj , default )", "docstring_tokens": "Helper for pulling a keyed value off various types of objects", "label": 1 }, { "idx": "cosqa-dev-373", "doc": "list string python remove commas", "code": "def split_elements(value):\n \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n l = [v.strip() for v in value.split(',')]\n if len(l) == 1:\n l = value.split()\n return l", "code_tokens": "def split_elements ( value ) : l = [ v . strip ( ) for v in value . split ( ',' ) ] if len ( l ) == 1 : l = value . split ( ) return l", "docstring_tokens": "Split a string with comma or space - separated elements into a list .", "label": 1 }, { "idx": "cosqa-dev-374", "doc": "how hard to port python to android", "code": "def pause():\n\t\"\"\"Tell iTunes to pause\"\"\"\n\n\tif not settings.platformCompatible():\n\t\treturn False\n\n\t(output, error) = subprocess.Popen([\"osascript\", \"-e\", PAUSE], stdout=subprocess.PIPE).communicate()", "code_tokens": "def pause ( ) : if not settings . platformCompatible ( ) : return False ( output , error ) = subprocess . Popen ( [ \"osascript\" , \"-e\" , PAUSE ] , stdout = subprocess . PIPE ) . communicate ( )", "docstring_tokens": "Tell iTunes to pause", "label": 0 }, { "idx": "cosqa-dev-375", "doc": "python remaining blanks spaces from list", "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": 0 }, { "idx": "cosqa-dev-376", "doc": "remove columns from pd 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": 0 }, { "idx": "cosqa-dev-377", "doc": "python magic determine file mime", "code": "def from_file(filename, mime=False):\n \"\"\" Opens file, attempts to identify content based\n off magic number and will return the file extension.\n If mime is True it will return the mime type instead.\n\n :param filename: path to file\n :param mime: Return mime, not extension\n :return: guessed extension or mime\n \"\"\"\n\n head, foot = _file_details(filename)\n return _magic(head, foot, mime, ext_from_filename(filename))", "code_tokens": "def from_file ( filename , mime = False ) : head , foot = _file_details ( filename ) return _magic ( head , foot , mime , ext_from_filename ( filename ) )", "docstring_tokens": "Opens file attempts to identify content based off magic number and will return the file extension . If mime is True it will return the mime type instead .", "label": 1 }, { "idx": "cosqa-dev-378", "doc": "python how to know data type", "code": "def maybe_infer_dtype_type(element):\n \"\"\"Try to infer an object's dtype, for use in arithmetic ops\n\n Uses `element.dtype` if that's available.\n Objects implementing the iterator protocol are cast to a NumPy array,\n and from there the array's type is used.\n\n Parameters\n ----------\n element : object\n Possibly has a `.dtype` attribute, and possibly the iterator\n protocol.\n\n Returns\n -------\n tipo : type\n\n Examples\n --------\n >>> from collections import namedtuple\n >>> Foo = namedtuple(\"Foo\", \"dtype\")\n >>> maybe_infer_dtype_type(Foo(np.dtype(\"i8\")))\n numpy.int64\n \"\"\"\n tipo = None\n if hasattr(element, 'dtype'):\n tipo = element.dtype\n elif is_list_like(element):\n element = np.asarray(element)\n tipo = element.dtype\n return tipo", "code_tokens": "def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo", "docstring_tokens": "Try to infer an object s dtype for use in arithmetic ops", "label": 1 }, { "idx": "cosqa-dev-379", "doc": "generate random 17 character id python", "code": "def random_id(length):\n \"\"\"Generates a random ID of given length\"\"\"\n\n def char():\n \"\"\"Generate single random char\"\"\"\n\n return random.choice(string.ascii_letters + string.digits)\n\n return \"\".join(char() for _ in range(length))", "code_tokens": "def random_id ( length ) : def char ( ) : \"\"\"Generate single random char\"\"\" return random . choice ( string . ascii_letters + string . digits ) return \"\" . join ( char ( ) for _ in range ( length ) )", "docstring_tokens": "Generates a random ID of given length", "label": 0 }, { "idx": "cosqa-dev-380", "doc": "python tkinter set default combobox value", "code": "def select_default(self):\n \"\"\"\n Resets the combo box to the original \"selected\" value from the\n constructor (or the first value if no selected value was specified).\n \"\"\"\n if self._default is None:\n if not self._set_option_by_index(0):\n utils.error_format(self.description + \"\\n\" +\n \"Unable to select default option as the Combo is empty\")\n\n else:\n if not self._set_option(self._default):\n utils.error_format( self.description + \"\\n\" +\n \"Unable to select default option as it doesnt exist in the Combo\")", "code_tokens": "def select_default ( self ) : if self . _default is None : if not self . _set_option_by_index ( 0 ) : utils . error_format ( self . description + \"\\n\" + \"Unable to select default option as the Combo is empty\" ) else : if not self . _set_option ( self . _default ) : utils . error_format ( self . description + \"\\n\" + \"Unable to select default option as it doesnt exist in the Combo\" )", "docstring_tokens": "Resets the combo box to the original selected value from the constructor ( or the first value if no selected value was specified ) .", "label": 1 }, { "idx": "cosqa-dev-381", "doc": "python + how to count the number of lines in a file", "code": "def line_count(fn):\n \"\"\" Get line count of file\n\n Args:\n fn (str): Path to file\n\n Return:\n Number of lines in file (int)\n \"\"\"\n\n with open(fn) as f:\n for i, l in enumerate(f):\n pass\n return i + 1", "code_tokens": "def line_count ( fn ) : with open ( fn ) as f : for i , l in enumerate ( f ) : pass return i + 1", "docstring_tokens": "Get line count of file", "label": 1 }, { "idx": "cosqa-dev-382", "doc": "python get type of values in a columns", "code": "def _get_column_types(self, data):\n \"\"\"Get a list of the data types for each column in *data*.\"\"\"\n columns = list(zip_longest(*data))\n return [self._get_column_type(column) for column in columns]", "code_tokens": "def _get_column_types ( self , data ) : columns = list ( zip_longest ( * data ) ) return [ self . _get_column_type ( column ) for column in columns ]", "docstring_tokens": "Get a list of the data types for each column in * data * .", "label": 1 }, { "idx": "cosqa-dev-383", "doc": "python change encoding stdout", "code": "def stdout_encode(u, default='utf-8'):\n \"\"\" Encodes a given string with the proper standard out encoding\n If sys.stdout.encoding isn't specified, it this defaults to @default\n\n @default: default encoding\n\n -> #str with standard out encoding\n \"\"\"\n # from http://stackoverflow.com/questions/3627793/best-output-type-and-\n # encoding-practices-for-repr-functions\n encoding = sys.stdout.encoding or default\n return u.encode(encoding, \"replace\").decode(encoding, \"replace\")", "code_tokens": "def stdout_encode ( u , default = 'utf-8' ) : # from http://stackoverflow.com/questions/3627793/best-output-type-and- # encoding-practices-for-repr-functions encoding = sys . stdout . encoding or default return u . encode ( encoding , \"replace\" ) . decode ( encoding , \"replace\" )", "docstring_tokens": "Encodes a given string with the proper standard out encoding If sys . stdout . encoding isn t specified it this defaults to @default", "label": 1 }, { "idx": "cosqa-dev-384", "doc": "python format datetime as iso string", "code": "def isoformat(dt):\n \"\"\"Return an ISO-8601 formatted string from the provided datetime object\"\"\"\n if not isinstance(dt, datetime.datetime):\n raise TypeError(\"Must provide datetime.datetime object to isoformat\")\n\n if dt.tzinfo is None:\n raise ValueError(\"naive datetime objects are not allowed beyond the library boundaries\")\n\n return dt.isoformat().replace(\"+00:00\", \"Z\")", "code_tokens": "def isoformat ( dt ) : if not isinstance ( dt , datetime . datetime ) : raise TypeError ( \"Must provide datetime.datetime object to isoformat\" ) if dt . tzinfo is None : raise ValueError ( \"naive datetime objects are not allowed beyond the library boundaries\" ) return dt . isoformat ( ) . replace ( \"+00:00\" , \"Z\" )", "docstring_tokens": "Return an ISO - 8601 formatted string from the provided datetime object", "label": 1 }, { "idx": "cosqa-dev-385", "doc": "yaml read file python", "code": "def getYamlDocument(filePath):\n \"\"\"\n Return a yaml file's contents as a dictionary\n \"\"\"\n with open(filePath) as stream:\n doc = yaml.load(stream)\n return doc", "code_tokens": "def getYamlDocument ( filePath ) : with open ( filePath ) as stream : doc = yaml . load ( stream ) return doc", "docstring_tokens": "Return a yaml file s contents as a dictionary", "label": 1 }, { "idx": "cosqa-dev-386", "doc": "python 2 make timezone aware", "code": "def make_aware(dt):\n \"\"\"Appends tzinfo and assumes UTC, if datetime object has no tzinfo already.\"\"\"\n return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)", "code_tokens": "def make_aware ( dt ) : return dt if dt . tzinfo else dt . replace ( tzinfo = timezone . utc )", "docstring_tokens": "Appends tzinfo and assumes UTC if datetime object has no tzinfo already .", "label": 1 }, { "idx": "cosqa-dev-387", "doc": "python check string %s", "code": "def check(text):\n \"\"\"Check the text.\"\"\"\n err = \"misc.currency\"\n msg = u\"Incorrect use of symbols in {}.\"\n\n symbols = [\n \"\\$[\\d]* ?(?:dollars|usd|us dollars)\"\n ]\n\n return existence_check(text, symbols, err, msg)", "code_tokens": "def check ( text ) : err = \"misc.currency\" msg = u\"Incorrect use of symbols in {}.\" symbols = [ \"\\$[\\d]* ?(?:dollars|usd|us dollars)\" ] return existence_check ( text , symbols , err , msg )", "docstring_tokens": "Check the text .", "label": 1 }, { "idx": "cosqa-dev-388", "doc": "python last modified datetime", "code": "def last_modified_date(filename):\n \"\"\"Last modified timestamp as a UTC datetime\"\"\"\n mtime = os.path.getmtime(filename)\n dt = datetime.datetime.utcfromtimestamp(mtime)\n return dt.replace(tzinfo=pytz.utc)", "code_tokens": "def last_modified_date ( filename ) : mtime = os . path . getmtime ( filename ) dt = datetime . datetime . utcfromtimestamp ( mtime ) return dt . replace ( tzinfo = pytz . utc )", "docstring_tokens": "Last modified timestamp as a UTC datetime", "label": 1 }, { "idx": "cosqa-dev-389", "doc": "wcompare two lisrs and return common elements in python", "code": "def get_common_elements(list1, list2):\n \"\"\"find the common elements in two lists. used to support auto align\n might be faster with sets\n\n Parameters\n ----------\n list1 : list\n a list of objects\n list2 : list\n a list of objects\n\n Returns\n -------\n list : list\n list of common objects shared by list1 and list2\n \n \"\"\"\n #result = []\n #for item in list1:\n # if item in list2:\n # result.append(item)\n #Return list(set(list1).intersection(set(list2)))\n set2 = set(list2)\n result = [item for item in list1 if item in set2]\n return result", "code_tokens": "def get_common_elements ( list1 , list2 ) : #result = [] #for item in list1: # if item in list2: # result.append(item) #Return list(set(list1).intersection(set(list2))) set2 = set ( list2 ) result = [ item for item in list1 if item in set2 ] return result", "docstring_tokens": "find the common elements in two lists . used to support auto align might be faster with sets", "label": 1 }, { "idx": "cosqa-dev-390", "doc": "does with close a file upon exiting python", "code": "def __exit__(self, *args):\n \"\"\"\n Cleanup any necessary opened files\n \"\"\"\n\n if self._output_file_handle:\n self._output_file_handle.close()\n self._output_file_handle = None", "code_tokens": "def __exit__ ( self , * args ) : if self . _output_file_handle : self . _output_file_handle . close ( ) self . _output_file_handle = None", "docstring_tokens": "Cleanup any necessary opened files", "label": 0 }, { "idx": "cosqa-dev-391", "doc": "change gui window title python", "code": "def title(msg):\n \"\"\"Sets the title of the console window.\"\"\"\n if sys.platform.startswith(\"win\"):\n ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))", "code_tokens": "def title ( msg ) : if sys . platform . startswith ( \"win\" ) : ctypes . windll . kernel32 . SetConsoleTitleW ( tounicode ( msg ) )", "docstring_tokens": "Sets the title of the console window .", "label": 1 }, { "idx": "cosqa-dev-392", "doc": "flush stdin python child", "code": "def correspond(text):\n \"\"\"Communicate with the child process without closing stdin.\"\"\"\n subproc.stdin.write(text)\n subproc.stdin.flush()\n return drain()", "code_tokens": "def correspond ( text ) : subproc . stdin . write ( text ) subproc . stdin . flush ( ) return drain ( )", "docstring_tokens": "Communicate with the child process without closing stdin .", "label": 0 }, { "idx": "cosqa-dev-393", "doc": "python flask boolean to html", "code": "def boolean(value):\n \"\"\"\n Configuration-friendly boolean type converter.\n\n Supports both boolean-valued and string-valued inputs (e.g. from env vars).\n\n \"\"\"\n if isinstance(value, bool):\n return value\n\n if value == \"\":\n return False\n\n return strtobool(value)", "code_tokens": "def boolean ( value ) : if isinstance ( value , bool ) : return value if value == \"\" : return False return strtobool ( value )", "docstring_tokens": "Configuration - friendly boolean type converter .", "label": 0 }, { "idx": "cosqa-dev-394", "doc": "python unique items of a list", "code": "def unique_items(seq):\n \"\"\"Return the unique items from iterable *seq* (in order).\"\"\"\n seen = set()\n return [x for x in seq if not (x in seen or seen.add(x))]", "code_tokens": "def unique_items ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]", "docstring_tokens": "Return the unique items from iterable * seq * ( in order ) .", "label": 1 }, { "idx": "cosqa-dev-395", "doc": "return largest subsequence in python", "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 }, { "idx": "cosqa-dev-396", "doc": "how to merge two object in python", "code": "def dictmerge(x, y):\n \"\"\"\n merge two dictionaries\n \"\"\"\n z = x.copy()\n z.update(y)\n return z", "code_tokens": "def dictmerge ( x , y ) : z = x . copy ( ) z . update ( y ) return z", "docstring_tokens": "merge two dictionaries", "label": 1 }, { "idx": "cosqa-dev-397", "doc": "python postgres bind variables", "code": "def get_pg_connection(host, user, port, password, database, ssl={}):\n \"\"\" PostgreSQL connection \"\"\"\n\n return psycopg2.connect(host=host,\n user=user,\n port=port,\n password=password,\n dbname=database,\n sslmode=ssl.get('sslmode', None),\n sslcert=ssl.get('sslcert', None),\n sslkey=ssl.get('sslkey', None),\n sslrootcert=ssl.get('sslrootcert', None),\n )", "code_tokens": "def get_pg_connection ( host , user , port , password , database , ssl = { } ) : return psycopg2 . connect ( host = host , user = user , port = port , password = password , dbname = database , sslmode = ssl . get ( 'sslmode' , None ) , sslcert = ssl . get ( 'sslcert' , None ) , sslkey = ssl . get ( 'sslkey' , None ) , sslrootcert = ssl . get ( 'sslrootcert' , None ) , )", "docstring_tokens": "PostgreSQL connection", "label": 0 }, { "idx": "cosqa-dev-398", "doc": "python hashlib of entire file", "code": "def _hash_the_file(hasher, filename):\n \"\"\"Helper function for creating hash functions.\n\n See implementation of :func:`dtoolcore.filehasher.shasum`\n for more usage details.\n \"\"\"\n BUF_SIZE = 65536\n with open(filename, 'rb') as f:\n buf = f.read(BUF_SIZE)\n while len(buf) > 0:\n hasher.update(buf)\n buf = f.read(BUF_SIZE)\n return hasher", "code_tokens": "def _hash_the_file ( hasher , filename ) : BUF_SIZE = 65536 with open ( filename , 'rb' ) as f : buf = f . read ( BUF_SIZE ) while len ( buf ) > 0 : hasher . update ( buf ) buf = f . read ( BUF_SIZE ) return hasher", "docstring_tokens": "Helper function for creating hash functions .", "label": 1 }, { "idx": "cosqa-dev-399", "doc": "cant change permissions of a file from python", "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": 0 }, { "idx": "cosqa-dev-400", "doc": "python output colors from a string", "code": "def write_color(string, name, style='normal', when='auto'):\n \"\"\" Write the given colored string to standard out. \"\"\"\n write(color(string, name, style, when))", "code_tokens": "def write_color ( string , name , style = 'normal' , when = 'auto' ) : write ( color ( string , name , style , when ) )", "docstring_tokens": "Write the given colored string to standard out .", "label": 1 }, { "idx": "cosqa-dev-401", "doc": "retrieve json file python", "code": "def open_json(file_name):\n \"\"\"\n returns json contents as string\n \"\"\"\n with open(file_name, \"r\") as json_data:\n data = json.load(json_data)\n return data", "code_tokens": "def open_json ( file_name ) : with open ( file_name , \"r\" ) as json_data : data = json . load ( json_data ) return data", "docstring_tokens": "returns json contents as string", "label": 0 }, { "idx": "cosqa-dev-402", "doc": "python compress leading whitespace", "code": "def clean_whitespace(string, compact=False):\n \"\"\"Return string with compressed whitespace.\"\"\"\n for a, b in (('\\r\\n', '\\n'), ('\\r', '\\n'), ('\\n\\n', '\\n'),\n ('\\t', ' '), (' ', ' ')):\n string = string.replace(a, b)\n if compact:\n for a, b in (('\\n', ' '), ('[ ', '['),\n (' ', ' '), (' ', ' '), (' ', ' ')):\n string = string.replace(a, b)\n return string.strip()", "code_tokens": "def clean_whitespace ( string , compact = False ) : for a , b in ( ( '\\r\\n' , '\\n' ) , ( '\\r' , '\\n' ) , ( '\\n\\n' , '\\n' ) , ( '\\t' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) if compact : for a , b in ( ( '\\n' , ' ' ) , ( '[ ' , '[' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) , ( ' ' , ' ' ) ) : string = string . replace ( a , b ) return string . strip ( )", "docstring_tokens": "Return string with compressed whitespace .", "label": 1 }, { "idx": "cosqa-dev-403", "doc": "python check for numeric type", "code": "def is_numeric_dtype(dtype):\n \"\"\"Return ``True`` if ``dtype`` is a numeric type.\"\"\"\n dtype = np.dtype(dtype)\n return np.issubsctype(getattr(dtype, 'base', None), np.number)", "code_tokens": "def is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )", "docstring_tokens": "Return True if dtype is a numeric type .", "label": 1 }, { "idx": "cosqa-dev-404", "doc": "python cast hex string to int", "code": "def hex_to_int(value):\n \"\"\"\n Convert hex string like \"\\x0A\\xE3\" to 2787.\n \"\"\"\n if version_info.major >= 3:\n return int.from_bytes(value, \"big\")\n return int(value.encode(\"hex\"), 16)", "code_tokens": "def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , \"big\" ) return int ( value . encode ( \"hex\" ) , 16 )", "docstring_tokens": "Convert hex string like \\ x0A \\ xE3 to 2787 .", "label": 1 }, { "idx": "cosqa-dev-405", "doc": "apply function to a column in a table python", "code": "def interpolate(table, field, fmt, **kwargs):\n \"\"\"\n Convenience function to interpolate all values in the given `field` using\n the `fmt` string.\n\n The ``where`` keyword argument can be given with a callable or expression\n which is evaluated on each row and which should return True if the\n conversion should be applied on that row, else False.\n\n \"\"\"\n\n conv = lambda v: fmt % v\n return convert(table, field, conv, **kwargs)", "code_tokens": "def interpolate ( table , field , fmt , * * kwargs ) : conv = lambda v : fmt % v return convert ( table , field , conv , * * kwargs )", "docstring_tokens": "Convenience function to interpolate all values in the given field using the fmt string .", "label": 0 }, { "idx": "cosqa-dev-406", "doc": "python hdf5 h5py unable to create fie exists", "code": "def get_h5file(file_path, mode='r'):\n \"\"\" Return the h5py.File given its file path.\n\n Parameters\n ----------\n file_path: string\n HDF5 file path\n\n mode: string\n r Readonly, file must exist\n r+ Read/write, file must exist\n w Create file, truncate if exists\n w- Create file, fail if exists\n a Read/write if exists, create otherwise (default)\n\n Returns\n -------\n h5file: h5py.File\n \"\"\"\n if not op.exists(file_path):\n raise IOError('Could not find file {}.'.format(file_path))\n\n try:\n h5file = h5py.File(file_path, mode=mode)\n except:\n raise\n else:\n return h5file", "code_tokens": "def get_h5file ( file_path , mode = 'r' ) : if not op . exists ( file_path ) : raise IOError ( 'Could not find file {}.' . format ( file_path ) ) try : h5file = h5py . File ( file_path , mode = mode ) except : raise else : return h5file", "docstring_tokens": "Return the h5py . File given its file path .", "label": 0 }, { "idx": "cosqa-dev-407", "doc": "how to turn concantate tuples in python", "code": "def compose_all(tups):\n \"\"\"Compose all given tuples together.\"\"\"\n from . import ast # I weep for humanity\n return functools.reduce(lambda x, y: x.compose(y), map(ast.make_tuple, tups), ast.make_tuple({}))", "code_tokens": "def compose_all ( tups ) : from . import ast # I weep for humanity return functools . reduce ( lambda x , y : x . compose ( y ) , map ( ast . make_tuple , tups ) , ast . make_tuple ( { } ) )", "docstring_tokens": "Compose all given tuples together .", "label": 0 }, { "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 }, { "idx": "cosqa-dev-409", "doc": "datetime to epoch python2", "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 }, { "idx": "cosqa-dev-410", "doc": "opening a serial port in python", "code": "def do_serial(self, p):\n\t\t\"\"\"Set the serial port, e.g.: /dev/tty.usbserial-A4001ib8\"\"\"\n\t\ttry:\n\t\t\tself.serial.port = p\n\t\t\tself.serial.open()\n\t\t\tprint 'Opening serial port: %s' % p\n\t\texcept Exception, e:\n\t\t\tprint 'Unable to open serial port: %s' % p", "code_tokens": "def do_serial ( self , p ) : try : self . serial . port = p self . serial . open ( ) print 'Opening serial port: %s' % p except Exception , e : print 'Unable to open serial port: %s' % p", "docstring_tokens": "Set the serial port e . g . : / dev / tty . usbserial - A4001ib8", "label": 1 }, { "idx": "cosqa-dev-411", "doc": "python clean up 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": 0 }, { "idx": "cosqa-dev-412", "doc": "unresolved reference 'self' in python", "code": "def _id(self):\n \"\"\"What this object is equal to.\"\"\"\n return (self.__class__, self.number_of_needles, self.needle_positions,\n self.left_end_needle)", "code_tokens": "def _id ( self ) : return ( self . __class__ , self . number_of_needles , self . needle_positions , self . left_end_needle )", "docstring_tokens": "What this object is equal to .", "label": 0 }, { "idx": "cosqa-dev-413", "doc": "python remove elements from list not match regex", "code": "def not_matching_list(self):\n \"\"\"\n Return a list of string which don't match the\n given regex.\n \"\"\"\n\n pre_result = comp(self.regex)\n\n return [x for x in self.data if not pre_result.search(str(x))]", "code_tokens": "def not_matching_list ( self ) : pre_result = comp ( self . regex ) return [ x for x in self . data if not pre_result . search ( str ( x ) ) ]", "docstring_tokens": "Return a list of string which don t match the given regex .", "label": 1 }, { "idx": "cosqa-dev-414", "doc": "xor two bytearrays python", "code": "def xor(a, b):\n \"\"\"Bitwise xor on equal length bytearrays.\"\"\"\n return bytearray(i ^ j for i, j in zip(a, b))", "code_tokens": "def xor ( a , b ) : return bytearray ( i ^ j for i , j in zip ( a , b ) )", "docstring_tokens": "Bitwise xor on equal length bytearrays .", "label": 1 }, { "idx": "cosqa-dev-415", "doc": "python interpolating function 3d", "code": "def interp(x, xp, *args, **kwargs):\n \"\"\"Wrap interpolate_1d for deprecated interp.\"\"\"\n return interpolate_1d(x, xp, *args, **kwargs)", "code_tokens": "def interp ( x , xp , * args , * * kwargs ) : return interpolate_1d ( x , xp , * args , * * kwargs )", "docstring_tokens": "Wrap interpolate_1d for deprecated interp .", "label": 0 }, { "idx": "cosqa-dev-416", "doc": "how to drop all columns with string values python", "code": "def _drop_str_columns(df):\n \"\"\"\n\n Parameters\n ----------\n df : DataFrame\n\n Returns\n -------\n\n \"\"\"\n str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())\n str_column_names = list(map(lambda pair: pair[0], str_columns))\n\n return df.drop(str_column_names)", "code_tokens": "def _drop_str_columns ( df ) : str_columns = filter ( lambda pair : pair [ 1 ] . char == 'S' , df . _gather_dtypes ( ) . items ( ) ) str_column_names = list ( map ( lambda pair : pair [ 0 ] , str_columns ) ) return df . drop ( str_column_names )", "docstring_tokens": "", "label": 1 }, { "idx": "cosqa-dev-417", "doc": "using a data file as a data source python", "code": "def get_data_table(filename):\n \"\"\"Returns a DataTable instance built from either the filename, or STDIN if filename is None.\"\"\"\n with get_file_object(filename, \"r\") as rf:\n return DataTable(list(csv.reader(rf)))", "code_tokens": "def get_data_table ( filename ) : with get_file_object ( filename , \"r\" ) as rf : return DataTable ( list ( csv . reader ( rf ) ) )", "docstring_tokens": "Returns a DataTable instance built from either the filename or STDIN if filename is None .", "label": 1 }, { "idx": "cosqa-dev-418", "doc": "python tokenize string by spaces", "code": "def tokenize(string):\n \"\"\"Match and yield all the tokens of the input string.\"\"\"\n for match in TOKENS_REGEX.finditer(string):\n yield Token(match.lastgroup, match.group().strip(), match.span())", "code_tokens": "def tokenize ( string ) : for match in TOKENS_REGEX . finditer ( string ) : yield Token ( match . lastgroup , match . group ( ) . strip ( ) , match . span ( ) )", "docstring_tokens": "Match and yield all the tokens of the input string .", "label": 1 }, { "idx": "cosqa-dev-419", "doc": "python get the object address", "code": "def objectproxy_realaddress(obj):\n \"\"\"\n Obtain a real address as an integer from an objectproxy.\n \"\"\"\n voidp = QROOT.TPython.ObjectProxy_AsVoidPtr(obj)\n return C.addressof(C.c_char.from_buffer(voidp))", "code_tokens": "def objectproxy_realaddress ( obj ) : voidp = QROOT . TPython . ObjectProxy_AsVoidPtr ( obj ) return C . addressof ( C . c_char . from_buffer ( voidp ) )", "docstring_tokens": "Obtain a real address as an integer from an objectproxy .", "label": 1 }, { "idx": "cosqa-dev-420", "doc": "python transfer to sparse matrix", "code": "def scipy_sparse_to_spmatrix(A):\n \"\"\"Efficient conversion from scipy sparse matrix to cvxopt sparse matrix\"\"\"\n coo = A.tocoo()\n SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)\n return SP", "code_tokens": "def scipy_sparse_to_spmatrix ( A ) : coo = A . tocoo ( ) SP = spmatrix ( coo . data . tolist ( ) , coo . row . tolist ( ) , coo . col . tolist ( ) , size = A . shape ) return SP", "docstring_tokens": "Efficient conversion from scipy sparse matrix to cvxopt sparse matrix", "label": 0 }, { "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 }, { "idx": "cosqa-dev-422", "doc": "use input and string tohether in python", "code": "def get_input(input_func, input_str):\n \"\"\"\n Get input from the user given an input function and an input string\n \"\"\"\n val = input_func(\"Please enter your {0}: \".format(input_str))\n while not val or not len(val.strip()):\n val = input_func(\"You didn't enter a valid {0}, please try again: \".format(input_str))\n return val", "code_tokens": "def get_input ( input_func , input_str ) : val = input_func ( \"Please enter your {0}: \" . format ( input_str ) ) while not val or not len ( val . strip ( ) ) : val = input_func ( \"You didn't enter a valid {0}, please try again: \" . format ( input_str ) ) return val", "docstring_tokens": "Get input from the user given an input function and an input string", "label": 1 }, { "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 }, { "idx": "cosqa-dev-424", "doc": "python max count in a column", "code": "def get_max(qs, field):\n \"\"\"\n get max for queryset.\n\n qs: queryset\n field: The field name to max.\n \"\"\"\n max_field = '%s__max' % field\n num = qs.aggregate(Max(field))[max_field]\n return num if num else 0", "code_tokens": "def get_max ( qs , field ) : max_field = '%s__max' % field num = qs . aggregate ( Max ( field ) ) [ max_field ] return num if num else 0", "docstring_tokens": "get max for queryset .", "label": 0 }, { "idx": "cosqa-dev-425", "doc": "how to make a list not a none type in python", "code": "def is_a_sequence(var, allow_none=False):\n \"\"\" Returns True if var is a list or a tuple (but not a string!)\n \"\"\"\n return isinstance(var, (list, tuple)) or (var is None and allow_none)", "code_tokens": "def is_a_sequence ( var , allow_none = False ) : return isinstance ( var , ( list , tuple ) ) or ( var is None and allow_none )", "docstring_tokens": "Returns True if var is a list or a tuple ( but not a string! )", "label": 0 }, { "idx": "cosqa-dev-426", "doc": "python os remove files with wildcard", "code": "def rmglob(pattern: str) -> None:\n \"\"\"\n Deletes all files whose filename matches the glob ``pattern`` (via\n :func:`glob.glob`).\n \"\"\"\n for f in glob.glob(pattern):\n os.remove(f)", "code_tokens": "def rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )", "docstring_tokens": "Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .", "label": 0 }, { "idx": "cosqa-dev-427", "doc": "how to add last update in python", "code": "def _elapsed(self):\n \"\"\" Returns elapsed time at update. \"\"\"\n self.last_time = time.time()\n return self.last_time - self.start", "code_tokens": "def _elapsed ( self ) : self . last_time = time . time ( ) return self . last_time - self . start", "docstring_tokens": "Returns elapsed time at update .", "label": 0 }, { "idx": "cosqa-dev-428", "doc": "python remap image to uint8", "code": "def uint32_to_uint8(cls, img):\n \"\"\"\n Cast uint32 RGB image to 4 uint8 channels.\n \"\"\"\n return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))", "code_tokens": "def uint32_to_uint8 ( cls , img ) : return np . flipud ( img . view ( dtype = np . uint8 ) . reshape ( img . shape + ( 4 , ) ) )", "docstring_tokens": "Cast uint32 RGB image to 4 uint8 channels .", "label": 1 }, { "idx": "cosqa-dev-429", "doc": "python latex to png", "code": "def print_display_png(o):\n \"\"\"\n A function to display sympy expression using display style LaTeX in PNG.\n \"\"\"\n s = latex(o, mode='plain')\n s = s.strip('$')\n # As matplotlib does not support display style, dvipng backend is\n # used here.\n png = latex_to_png('$$%s$$' % s, backend='dvipng')\n return png", "code_tokens": "def print_display_png ( o ) : s = latex ( o , mode = 'plain' ) s = s . strip ( '$' ) # As matplotlib does not support display style, dvipng backend is # used here. png = latex_to_png ( '$$%s$$' % s , backend = 'dvipng' ) return png", "docstring_tokens": "A function to display sympy expression using display style LaTeX in PNG .", "label": 1 }, { "idx": "cosqa-dev-430", "doc": "python set form default value using request", "code": "def get(key, default=None):\n \"\"\" return the key from the request\n \"\"\"\n data = get_form() or get_query_string()\n return data.get(key, default)", "code_tokens": "def get ( key , default = None ) : data = get_form ( ) or get_query_string ( ) return data . get ( key , default )", "docstring_tokens": "return the key from the request", "label": 0 }, { "idx": "cosqa-dev-431", "doc": "python how to setuptools", "code": "def main(argv, version=DEFAULT_VERSION):\n \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n tarball = download_setuptools()\n _install(tarball, _build_install_args(argv))", "code_tokens": "def main ( argv , version = DEFAULT_VERSION ) : tarball = download_setuptools ( ) _install ( tarball , _build_install_args ( argv ) )", "docstring_tokens": "Install or upgrade setuptools and EasyInstall", "label": 0 }, { "idx": "cosqa-dev-432", "doc": "untuple a tuple python", "code": "def _parse_tuple_string(argument):\n \"\"\" Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) \"\"\"\n if isinstance(argument, str):\n return tuple(int(p.strip()) for p in argument.split(','))\n return argument", "code_tokens": "def _parse_tuple_string ( argument ) : if isinstance ( argument , str ) : return tuple ( int ( p . strip ( ) ) for p in argument . split ( ',' ) ) return argument", "docstring_tokens": "Return a tuple from parsing a b c d - > ( a b c d )", "label": 0 }, { "idx": "cosqa-dev-433", "doc": "how to set a null value to an int in python", "code": "def strictly_positive_int_or_none(val):\n \"\"\"Parse `val` into either `None` or a strictly positive integer.\"\"\"\n val = positive_int_or_none(val)\n if val is None or val > 0:\n return val\n raise ValueError('\"{}\" must be strictly positive'.format(val))", "code_tokens": "def strictly_positive_int_or_none ( val ) : val = positive_int_or_none ( val ) if val is None or val > 0 : return val raise ValueError ( '\"{}\" must be strictly positive' . format ( val ) )", "docstring_tokens": "Parse val into either None or a strictly positive integer .", "label": 0 }, { "idx": "cosqa-dev-434", "doc": "get timestamp of files in directories in python", "code": "def dir_modtime(dpath):\n \"\"\"\n Returns the latest modification time of all files/subdirectories in a\n directory\n \"\"\"\n return max(os.path.getmtime(d) for d, _, _ in os.walk(dpath))", "code_tokens": "def dir_modtime ( dpath ) : return max ( os . path . getmtime ( d ) for d , _ , _ in os . walk ( dpath ) )", "docstring_tokens": "Returns the latest modification time of all files / subdirectories in a directory", "label": 0 }, { "idx": "cosqa-dev-435", "doc": "python close a file if it is open", "code": "def file_read(filename):\n \"\"\"Read a file and close it. Returns the file source.\"\"\"\n fobj = open(filename,'r');\n source = fobj.read();\n fobj.close()\n return source", "code_tokens": "def file_read ( filename ) : fobj = open ( filename , 'r' ) source = fobj . read ( ) fobj . close ( ) return source", "docstring_tokens": "Read a file and close it . Returns the file source .", "label": 1 }, { "idx": "cosqa-dev-436", "doc": "python calculate sigmoid function", "code": "def elliot_function( signal, derivative=False ):\n \"\"\" A fast approximation of sigmoid \"\"\"\n s = 1 # steepness\n \n abs_signal = (1 + np.abs(signal * s))\n if derivative:\n return 0.5 * s / abs_signal**2\n else:\n # Return the activation signal\n return 0.5*(signal * s) / abs_signal + 0.5", "code_tokens": "def elliot_function ( signal , derivative = False ) : s = 1 # steepness abs_signal = ( 1 + np . abs ( signal * s ) ) if derivative : return 0.5 * s / abs_signal ** 2 else : # Return the activation signal return 0.5 * ( signal * s ) / abs_signal + 0.5", "docstring_tokens": "A fast approximation of sigmoid", "label": 1 }, { "idx": "cosqa-dev-437", "doc": "python index of last string", "code": "def _rindex(mylist: Sequence[T], x: T) -> int:\n \"\"\"Index of the last occurrence of x in the sequence.\"\"\"\n return len(mylist) - mylist[::-1].index(x) - 1", "code_tokens": "def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1", "docstring_tokens": "Index of the last occurrence of x in the sequence .", "label": 1 }, { "idx": "cosqa-dev-438", "doc": "how to view columns of a python array", "code": "def length(self):\n \"\"\"Array of vector lengths\"\"\"\n return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray)", "code_tokens": "def length ( self ) : return np . sqrt ( np . sum ( self ** 2 , axis = 1 ) ) . view ( np . ndarray )", "docstring_tokens": "Array of vector lengths", "label": 0 }, { "idx": "cosqa-dev-439", "doc": "remove non alphabets python string isalpha", "code": "def strip_accents(string):\n \"\"\"\n Strip all the accents from the string\n \"\"\"\n return u''.join(\n (character for character in unicodedata.normalize('NFD', string)\n if unicodedata.category(character) != 'Mn'))", "code_tokens": "def strip_accents ( string ) : return u'' . join ( ( character for character in unicodedata . normalize ( 'NFD' , string ) if unicodedata . category ( character ) != 'Mn' ) )", "docstring_tokens": "Strip all the accents from the string", "label": 0 }, { "idx": "cosqa-dev-440", "doc": "how to read yaml file from python", "code": "def load_yaml(filepath):\n \"\"\"Convenience function for loading yaml-encoded data from disk.\"\"\"\n with open(filepath) as f:\n txt = f.read()\n return yaml.load(txt)", "code_tokens": "def load_yaml ( filepath ) : with open ( filepath ) as f : txt = f . read ( ) return yaml . load ( txt )", "docstring_tokens": "Convenience function for loading yaml - encoded data from disk .", "label": 1 }, { "idx": "cosqa-dev-441", "doc": "python test if key exists in jso", "code": "def has_key(cls, *args):\n \"\"\"\n Check whether flyweight object with specified key has already been created.\n\n Returns:\n bool: True if already created, False if not\n \"\"\"\n key = args if len(args) > 1 else args[0]\n return key in cls._instances", "code_tokens": "def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances", "docstring_tokens": "Check whether flyweight object with specified key has already been created .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-443", "doc": "python parse true or false", "code": "def _parse_boolean(value, default=False):\n \"\"\"\n Attempt to cast *value* into a bool, returning *default* if it fails.\n \"\"\"\n if value is None:\n return default\n try:\n return bool(value)\n except ValueError:\n return default", "code_tokens": "def _parse_boolean ( value , default = False ) : if value is None : return default try : return bool ( value ) except ValueError : return default", "docstring_tokens": "Attempt to cast * value * into a bool returning * default * if it fails .", "label": 1 }, { "idx": "cosqa-dev-444", "doc": "python tweepy get users tweets", "code": "def twitter_timeline(screen_name, since_id=None):\n \"\"\" Return relevant twitter timeline \"\"\"\n consumer_key = twitter_credential('consumer_key')\n consumer_secret = twitter_credential('consumer_secret')\n access_token = twitter_credential('access_token')\n access_token_secret = twitter_credential('access_secret')\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n return get_all_tweets(screen_name, api, since_id)", "code_tokens": "def twitter_timeline ( screen_name , since_id = None ) : consumer_key = twitter_credential ( 'consumer_key' ) consumer_secret = twitter_credential ( 'consumer_secret' ) access_token = twitter_credential ( 'access_token' ) access_token_secret = twitter_credential ( 'access_secret' ) auth = tweepy . OAuthHandler ( consumer_key , consumer_secret ) auth . set_access_token ( access_token , access_token_secret ) api = tweepy . API ( auth ) return get_all_tweets ( screen_name , api , since_id )", "docstring_tokens": "Return relevant twitter timeline", "label": 0 }, { "idx": "cosqa-dev-445", "doc": "python inner join data frames", "code": "def _join(verb):\n \"\"\"\n Join helper\n \"\"\"\n data = pd.merge(verb.x, verb.y, **verb.kwargs)\n\n # Preserve x groups\n if isinstance(verb.x, GroupedDataFrame):\n data.plydata_groups = list(verb.x.plydata_groups)\n return data", "code_tokens": "def _join ( verb ) : data = pd . merge ( verb . x , verb . y , * * verb . kwargs ) # Preserve x groups if isinstance ( verb . x , GroupedDataFrame ) : data . plydata_groups = list ( verb . x . plydata_groups ) return data", "docstring_tokens": "Join helper", "label": 1 }, { "idx": "cosqa-dev-446", "doc": "python set sys stdout encoding", "code": "def sys_pipes_forever(encoding=_default_encoding):\n \"\"\"Redirect all C output to sys.stdout/err\n \n This is not a context manager; it turns on C-forwarding permanently.\n \"\"\"\n global _mighty_wurlitzer\n if _mighty_wurlitzer is None:\n _mighty_wurlitzer = sys_pipes(encoding)\n _mighty_wurlitzer.__enter__()", "code_tokens": "def sys_pipes_forever ( encoding = _default_encoding ) : global _mighty_wurlitzer if _mighty_wurlitzer is None : _mighty_wurlitzer = sys_pipes ( encoding ) _mighty_wurlitzer . __enter__ ( )", "docstring_tokens": "Redirect all C output to sys . stdout / err This is not a context manager ; it turns on C - forwarding permanently .", "label": 0 }, { "idx": "cosqa-dev-447", "doc": "python compare ints in sets", "code": "def isetdiff_flags(list1, list2):\n \"\"\"\n move to util_iter\n \"\"\"\n set2 = set(list2)\n return (item not in set2 for item in list1)", "code_tokens": "def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 )", "docstring_tokens": "move to util_iter", "label": 1 }, { "idx": "cosqa-dev-448", "doc": "python set add iterable", "code": "def update(self, iterable):\n \"\"\"\n Return a new PSet with elements in iterable added\n\n >>> s1 = s(1, 2)\n >>> s1.update([3, 4, 4])\n pset([1, 2, 3, 4])\n \"\"\"\n e = self.evolver()\n for element in iterable:\n e.add(element)\n\n return e.persistent()", "code_tokens": "def update ( self , iterable ) : e = self . evolver ( ) for element in iterable : e . add ( element ) return e . persistent ( )", "docstring_tokens": "Return a new PSet with elements in iterable added", "label": 1 }, { "idx": "cosqa-dev-449", "doc": "python json loads is string not dict", "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": 0 }, { "idx": "cosqa-dev-450", "doc": "how to see the type of items in list python", "code": "def get_list_dimensions(_list):\n \"\"\"\n Takes a nested list and returns the size of each dimension followed\n by the element type in the list\n \"\"\"\n if isinstance(_list, list) or isinstance(_list, tuple):\n return [len(_list)] + get_list_dimensions(_list[0])\n return []", "code_tokens": "def get_list_dimensions ( _list ) : if isinstance ( _list , list ) or isinstance ( _list , tuple ) : return [ len ( _list ) ] + get_list_dimensions ( _list [ 0 ] ) return [ ]", "docstring_tokens": "Takes a nested list and returns the size of each dimension followed by the element type in the list", "label": 0 }, { "idx": "cosqa-dev-451", "doc": "python delete variable from globals", "code": "def clear_global(self):\n \"\"\"Clear only any cached global data.\n\n \"\"\"\n vname = self.varname\n logger.debug(f'global clearning {vname}')\n if vname in globals():\n logger.debug('removing global instance var: {}'.format(vname))\n del globals()[vname]", "code_tokens": "def clear_global ( self ) : vname = self . varname logger . debug ( f'global clearning {vname}' ) if vname in globals ( ) : logger . debug ( 'removing global instance var: {}' . format ( vname ) ) del globals ( ) [ vname ]", "docstring_tokens": "Clear only any cached global data .", "label": 1 }, { "idx": "cosqa-dev-452", "doc": "enum contructor sample python code", "code": "def _Enum(docstring, *names):\n \"\"\"Utility to generate enum classes used by annotations.\n\n Args:\n docstring: Docstring for the generated enum class.\n *names: Enum names.\n\n Returns:\n A class that contains enum names as attributes.\n \"\"\"\n enums = dict(zip(names, range(len(names))))\n reverse = dict((value, key) for key, value in enums.iteritems())\n enums['reverse_mapping'] = reverse\n enums['__doc__'] = docstring\n return type('Enum', (object,), enums)", "code_tokens": "def _Enum ( docstring , * names ) : enums = dict ( zip ( names , range ( len ( names ) ) ) ) reverse = dict ( ( value , key ) for key , value in enums . iteritems ( ) ) enums [ 'reverse_mapping' ] = reverse enums [ '__doc__' ] = docstring return type ( 'Enum' , ( object , ) , enums )", "docstring_tokens": "Utility to generate enum classes used by annotations .", "label": 0 }, { "idx": "cosqa-dev-453", "doc": "python get the name of an object as string", "code": "def class_name(obj):\n \"\"\"\n Get the name of an object, including the module name if available.\n \"\"\"\n\n name = obj.__name__\n module = getattr(obj, '__module__')\n\n if module:\n name = f'{module}.{name}'\n return name", "code_tokens": "def class_name ( obj ) : name = obj . __name__ module = getattr ( obj , '__module__' ) if module : name = f'{module}.{name}' return name", "docstring_tokens": "Get the name of an object including the module name if available .", "label": 1 }, { "idx": "cosqa-dev-454", "doc": "unabe to post data on api json using python", "code": "def multipart_parse_json(api_url, data):\n \"\"\"\n Send a post request and parse the JSON response (potentially containing\n non-ascii characters).\n @param api_url: the url endpoint to post to.\n @param data: a dictionary that will be passed to requests.post\n \"\"\"\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n response_text = requests.post(api_url, data=data, headers=headers)\\\n .text.encode('ascii', errors='replace')\n\n return json.loads(response_text.decode())", "code_tokens": "def multipart_parse_json ( api_url , data ) : headers = { 'Content-Type' : 'application/x-www-form-urlencoded' } response_text = requests . post ( api_url , data = data , headers = headers ) . text . encode ( 'ascii' , errors = 'replace' ) return json . loads ( response_text . decode ( ) )", "docstring_tokens": "Send a post request and parse the JSON response ( potentially containing non - ascii characters ) .", "label": 0 }, { "idx": "cosqa-dev-455", "doc": "str to timestamp data type python", "code": "def is_timestamp(instance):\n \"\"\"Validates data is a timestamp\"\"\"\n if not isinstance(instance, (int, str)):\n return True\n return datetime.fromtimestamp(int(instance))", "code_tokens": "def is_timestamp ( instance ) : if not isinstance ( instance , ( int , str ) ) : return True return datetime . fromtimestamp ( int ( instance ) )", "docstring_tokens": "Validates data is a timestamp", "label": 1 }, { "idx": "cosqa-dev-456", "doc": "python setuptools extra requirment", "code": "def main(argv, version=DEFAULT_VERSION):\n \"\"\"Install or upgrade setuptools and EasyInstall\"\"\"\n tarball = download_setuptools()\n _install(tarball, _build_install_args(argv))", "code_tokens": "def main ( argv , version = DEFAULT_VERSION ) : tarball = download_setuptools ( ) _install ( tarball , _build_install_args ( argv ) )", "docstring_tokens": "Install or upgrade setuptools and EasyInstall", "label": 0 }, { "idx": "cosqa-dev-457", "doc": "building a url with a query string python", "code": "def url_concat(url, args):\n \"\"\"Concatenate url and argument dictionary regardless of whether\n url has existing query parameters.\n\n >>> url_concat(\"http://example.com/foo?a=b\", dict(c=\"d\"))\n 'http://example.com/foo?a=b&c=d'\n \"\"\"\n if not args: return url\n if url[-1] not in ('?', '&'):\n url += '&' if ('?' in url) else '?'\n return url + urllib.urlencode(args)", "code_tokens": "def url_concat ( url , args ) : if not args : return url if url [ - 1 ] not in ( '?' , '&' ) : url += '&' if ( '?' in url ) else '?' return url + urllib . urlencode ( args )", "docstring_tokens": "Concatenate url and argument dictionary regardless of whether url has existing query parameters .", "label": 0 }, { "idx": "cosqa-dev-458", "doc": "python turn json into a dictionary", "code": "def _unjsonify(x, isattributes=False):\n \"\"\"Convert JSON string to an ordered defaultdict.\"\"\"\n if isattributes:\n obj = json.loads(x)\n return dict_class(obj)\n return json.loads(x)", "code_tokens": "def _unjsonify ( x , isattributes = False ) : if isattributes : obj = json . loads ( x ) return dict_class ( obj ) return json . loads ( x )", "docstring_tokens": "Convert JSON string to an ordered defaultdict .", "label": 1 }, { "idx": "cosqa-dev-459", "doc": "how to multiply object in list python", "code": "def multiply(self, number):\n \"\"\"Return a Vector as the product of the vector and a real number.\"\"\"\n return self.from_list([x * number for x in self.to_list()])", "code_tokens": "def multiply ( self , number ) : return self . from_list ( [ x * number for x in self . to_list ( ) ] )", "docstring_tokens": "Return a Vector as the product of the vector and a real number .", "label": 1 }, { "idx": "cosqa-dev-460", "doc": "how to make linspace integer in python", "code": "def to_linspace(self):\n \"\"\"\n convert from arange to linspace\n \"\"\"\n num = int((self.stop-self.start)/(self.step))\n return Linspace(self.start, self.stop-self.step, num)", "code_tokens": "def to_linspace ( self ) : num = int ( ( self . stop - self . start ) / ( self . step ) ) return Linspace ( self . start , self . stop - self . step , num )", "docstring_tokens": "convert from arange to linspace", "label": 1 }, { "idx": "cosqa-dev-461", "doc": "python reading file remove spaces/newlines", "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 }, { "idx": "cosqa-dev-462", "doc": "python detect if a tab is closed", "code": "def _name_exists(self, name):\n \"\"\"\n Checks if we already have an opened tab with the same name.\n \"\"\"\n for i in range(self.count()):\n if self.tabText(i) == name:\n return True\n return False", "code_tokens": "def _name_exists ( self , name ) : for i in range ( self . count ( ) ) : if self . tabText ( i ) == name : return True return False", "docstring_tokens": "Checks if we already have an opened tab with the same name .", "label": 1 }, { "idx": "cosqa-dev-463", "doc": "get max value from dictionary keys in python", "code": "def get_keys_of_max_n(dict_obj, n):\n \"\"\"Returns the keys that maps to the top n max values in the given dict.\n\n Example:\n --------\n >>> dict_obj = {'a':2, 'b':1, 'c':5}\n >>> get_keys_of_max_n(dict_obj, 2)\n ['a', 'c']\n \"\"\"\n return sorted([\n item[0]\n for item in sorted(\n dict_obj.items(), key=lambda item: item[1], reverse=True\n )[:n]\n ])", "code_tokens": "def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] )", "docstring_tokens": "Returns the keys that maps to the top n max values in the given dict .", "label": 1 }, { "idx": "cosqa-dev-464", "doc": "python empty an existing data frame to keep the column names", "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": 0 }, { "idx": "cosqa-dev-465", "doc": "checking what linux distibution is being used with python", "code": "def is_archlinux():\n \"\"\"return True if the current distribution is running on debian like OS.\"\"\"\n if platform.system().lower() == 'linux':\n if platform.linux_distribution() == ('', '', ''):\n # undefined distribution. Fixed in python 3.\n if os.path.exists('/etc/arch-release'):\n return True\n return False", "code_tokens": "def is_archlinux ( ) : if platform . system ( ) . lower ( ) == 'linux' : if platform . linux_distribution ( ) == ( '' , '' , '' ) : # undefined distribution. Fixed in python 3. if os . path . exists ( '/etc/arch-release' ) : return True return False", "docstring_tokens": "return True if the current distribution is running on debian like OS .", "label": 1 }, { "idx": "cosqa-dev-466", "doc": "downsampling 2d python array", "code": "def downsample_with_striding(array, factor):\n \"\"\"Downsample x by factor using striding.\n\n @return: The downsampled array, of the same type as x.\n \"\"\"\n return array[tuple(np.s_[::f] for f in factor)]", "code_tokens": "def downsample_with_striding ( array , factor ) : return array [ tuple ( np . s_ [ : : f ] for f in factor ) ]", "docstring_tokens": "Downsample x by factor using striding .", "label": 1 }, { "idx": "cosqa-dev-467", "doc": "python covert tensorflow to numpy", "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": 0 }, { "idx": "cosqa-dev-468", "doc": "python get pixel color from image frame", "code": "def get_pixel(framebuf, x, y):\n \"\"\"Get the color of a given pixel\"\"\"\n index = (y >> 3) * framebuf.stride + x\n offset = y & 0x07\n return (framebuf.buf[index] >> offset) & 0x01", "code_tokens": "def get_pixel ( framebuf , x , y ) : index = ( y >> 3 ) * framebuf . stride + x offset = y & 0x07 return ( framebuf . buf [ index ] >> offset ) & 0x01", "docstring_tokens": "Get the color of a given pixel", "label": 1 }, { "idx": "cosqa-dev-469", "doc": "normalize data frame python", "code": "def normalize(self):\n \"\"\" Normalize data. \"\"\"\n\n if self.preprocessed_data.empty:\n data = self.original_data\n else:\n data = self.preprocessed_data\n\n data = pd.DataFrame(preprocessing.normalize(data), columns=data.columns, index=data.index)\n self.preprocessed_data = data", "code_tokens": "def normalize ( self ) : if self . preprocessed_data . empty : data = self . original_data else : data = self . preprocessed_data data = pd . DataFrame ( preprocessing . normalize ( data ) , columns = data . columns , index = data . index ) self . preprocessed_data = data", "docstring_tokens": "Normalize data .", "label": 1 }, { "idx": "cosqa-dev-470", "doc": "get value from series except null values python", "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": 0 }, { "idx": "cosqa-dev-471", "doc": "how to make a range of weekly dates in python", "code": "def this_week():\n \"\"\" Return start and end date of the current week. \"\"\"\n since = TODAY + delta(weekday=MONDAY(-1))\n until = since + delta(weeks=1)\n return Date(since), Date(until)", "code_tokens": "def this_week ( ) : since = TODAY + delta ( weekday = MONDAY ( - 1 ) ) until = since + delta ( weeks = 1 ) return Date ( since ) , Date ( until )", "docstring_tokens": "Return start and end date of the current week .", "label": 1 }, { "idx": "cosqa-dev-472", "doc": "how to know the data type of an object 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": 0 }, { "idx": "cosqa-dev-473", "doc": "python boto3 read s3 object as json", "code": "def get_as_bytes(self, s3_path):\n \"\"\"\n Get the contents of an object stored in S3 as bytes\n\n :param s3_path: URL for target S3 location\n :return: File contents as pure bytes\n \"\"\"\n (bucket, key) = self._path_to_bucket_and_key(s3_path)\n obj = self.s3.Object(bucket, key)\n contents = obj.get()['Body'].read()\n return contents", "code_tokens": "def get_as_bytes ( self , s3_path ) : ( bucket , key ) = self . _path_to_bucket_and_key ( s3_path ) obj = self . s3 . Object ( bucket , key ) contents = obj . get ( ) [ 'Body' ] . read ( ) return contents", "docstring_tokens": "Get the contents of an object stored in S3 as bytes", "label": 0 }, { "idx": "cosqa-dev-474", "doc": "python update minify js file", "code": "def minify(path):\n \"\"\"\n Load a javascript file and minify.\n\n Parameters\n ------------\n path: str, path of resource\n \"\"\"\n\n if 'http' in path:\n data = requests.get(path).content.decode(\n 'ascii', errors='ignore')\n else:\n with open(path, 'rb') as f:\n # some of these assholes use unicode spaces -_-\n data = f.read().decode('ascii',\n errors='ignore')\n # don't re- minify\n if '.min.' in path:\n return data\n\n try:\n return jsmin.jsmin(data)\n except BaseException:\n return data", "code_tokens": "def minify ( path ) : if 'http' in path : data = requests . get ( path ) . content . decode ( 'ascii' , errors = 'ignore' ) else : with open ( path , 'rb' ) as f : # some of these assholes use unicode spaces -_- data = f . read ( ) . decode ( 'ascii' , errors = 'ignore' ) # don't re- minify if '.min.' in path : return data try : return jsmin . jsmin ( data ) except BaseException : return data", "docstring_tokens": "Load a javascript file and minify .", "label": 1 }, { "idx": "cosqa-dev-475", "doc": "python logging highlight colors in log", "code": "def print_log(value_color=\"\", value_noncolor=\"\"):\n \"\"\"set the colors for text.\"\"\"\n HEADER = '\\033[92m'\n ENDC = '\\033[0m'\n print(HEADER + value_color + ENDC + str(value_noncolor))", "code_tokens": "def print_log ( value_color = \"\" , value_noncolor = \"\" ) : HEADER = '\\033[92m' ENDC = '\\033[0m' print ( HEADER + value_color + ENDC + str ( value_noncolor ) )", "docstring_tokens": "set the colors for text .", "label": 1 }, { "idx": "cosqa-dev-476", "doc": "python validating an int", "code": "def clean_int(x) -> int:\n \"\"\"\n Returns its parameter as an integer, or raises\n ``django.forms.ValidationError``.\n \"\"\"\n try:\n return int(x)\n except ValueError:\n raise forms.ValidationError(\n \"Cannot convert to integer: {}\".format(repr(x)))", "code_tokens": "def clean_int ( x ) -> int : try : return int ( x ) except ValueError : raise forms . ValidationError ( \"Cannot convert to integer: {}\" . format ( repr ( x ) ) )", "docstring_tokens": "Returns its parameter as an integer or raises django . forms . ValidationError .", "label": 0 }, { "idx": "cosqa-dev-477", "doc": "how to make python unittest 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": 0 }, { "idx": "cosqa-dev-478", "doc": "how to cut off beginning of a string in python", "code": "def _clip(sid, prefix):\n \"\"\"Clips a prefix from the beginning of a string if it exists.\"\"\"\n return sid[len(prefix):] if sid.startswith(prefix) else sid", "code_tokens": "def _clip ( sid , prefix ) : return sid [ len ( prefix ) : ] if sid . startswith ( prefix ) else sid", "docstring_tokens": "Clips a prefix from the beginning of a string if it exists .", "label": 1 }, { "idx": "cosqa-dev-479", "doc": "python show image object", "code": "def display_pil_image(im):\n \"\"\"Displayhook function for PIL Images, rendered as PNG.\"\"\"\n from IPython.core import display\n b = BytesIO()\n im.save(b, format='png')\n data = b.getvalue()\n\n ip_img = display.Image(data=data, format='png', embed=True)\n return ip_img._repr_png_()", "code_tokens": "def display_pil_image ( im ) : from IPython . core import display b = BytesIO ( ) im . save ( b , format = 'png' ) data = b . getvalue ( ) ip_img = display . Image ( data = data , format = 'png' , embed = True ) return ip_img . _repr_png_ ( )", "docstring_tokens": "Displayhook function for PIL Images rendered as PNG .", "label": 1 }, { "idx": "cosqa-dev-480", "doc": "splitting to words from sting in python", "code": "def split_into_words(s):\n \"\"\"Split a sentence into list of words.\"\"\"\n s = re.sub(r\"\\W+\", \" \", s)\n s = re.sub(r\"[_0-9]+\", \" \", s)\n return s.split()", "code_tokens": "def split_into_words ( s ) : s = re . sub ( r\"\\W+\" , \" \" , s ) s = re . sub ( r\"[_0-9]+\" , \" \" , s ) return s . split ( )", "docstring_tokens": "Split a sentence into list of words .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-482", "doc": "how to check for a symbol in a string python", "code": "def is_identifier(string):\n \"\"\"Check if string could be a valid python identifier\n\n :param string: string to be tested\n :returns: True if string can be a python identifier, False otherwise\n :rtype: bool\n \"\"\"\n matched = PYTHON_IDENTIFIER_RE.match(string)\n return bool(matched) and not keyword.iskeyword(string)", "code_tokens": "def is_identifier ( string ) : matched = PYTHON_IDENTIFIER_RE . match ( string ) return bool ( matched ) and not keyword . iskeyword ( string )", "docstring_tokens": "Check if string could be a valid python identifier", "label": 0 }, { "idx": "cosqa-dev-483", "doc": "python get memory usage of an object", "code": "def memory():\n \"\"\"Determine memory specifications of the machine.\n\n Returns\n -------\n mem_info : dictonary\n Holds the current values for the total, free and used memory of the system.\n \"\"\"\n\n mem_info = dict()\n\n for k, v in psutil.virtual_memory()._asdict().items():\n mem_info[k] = int(v)\n \n return mem_info", "code_tokens": "def memory ( ) : mem_info = dict ( ) for k , v in psutil . virtual_memory ( ) . _asdict ( ) . items ( ) : mem_info [ k ] = int ( v ) return mem_info", "docstring_tokens": "Determine memory specifications of the machine .", "label": 1 }, { "idx": "cosqa-dev-484", "doc": "python check if file ends with any allowed extension", "code": "def watched_extension(extension):\n \"\"\"Return True if the given extension is one of the watched extensions\"\"\"\n for ext in hamlpy.VALID_EXTENSIONS:\n if extension.endswith('.' + ext):\n return True\n return False", "code_tokens": "def watched_extension ( extension ) : for ext in hamlpy . VALID_EXTENSIONS : if extension . endswith ( '.' + ext ) : return True return False", "docstring_tokens": "Return True if the given extension is one of the watched extensions", "label": 1 }, { "idx": "cosqa-dev-485", "doc": "python subplot set the whole title", "code": "def set_title(self, title, **kwargs):\n \"\"\"Sets the title on the underlying matplotlib AxesSubplot.\"\"\"\n ax = self.get_axes()\n ax.set_title(title, **kwargs)", "code_tokens": "def set_title ( self , title , * * kwargs ) : ax = self . get_axes ( ) ax . set_title ( title , * * kwargs )", "docstring_tokens": "Sets the title on the underlying matplotlib AxesSubplot .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-487", "doc": "python correlation pearson coefficient", "code": "def cor(y_true, y_pred):\n \"\"\"Compute Pearson correlation coefficient.\n \"\"\"\n y_true, y_pred = _mask_nan(y_true, y_pred)\n return np.corrcoef(y_true, y_pred)[0, 1]", "code_tokens": "def cor ( y_true , y_pred ) : y_true , y_pred = _mask_nan ( y_true , y_pred ) return np . corrcoef ( y_true , y_pred ) [ 0 , 1 ]", "docstring_tokens": "Compute Pearson correlation coefficient .", "label": 1 }, { "idx": "cosqa-dev-488", "doc": "python api converto string to latitude longitude", "code": "def latlng(arg):\n \"\"\"Converts a lat/lon pair to a comma-separated string.\n\n For example:\n\n sydney = {\n \"lat\" : -33.8674869,\n \"lng\" : 151.2069902\n }\n\n convert.latlng(sydney)\n # '-33.8674869,151.2069902'\n\n For convenience, also accepts lat/lon pair as a string, in\n which case it's returned unchanged.\n\n :param arg: The lat/lon pair.\n :type arg: string or dict or list or tuple\n \"\"\"\n if is_string(arg):\n return arg\n\n normalized = normalize_lat_lng(arg)\n return \"%s,%s\" % (format_float(normalized[0]), format_float(normalized[1]))", "code_tokens": "def latlng ( arg ) : if is_string ( arg ) : return arg normalized = normalize_lat_lng ( arg ) return \"%s,%s\" % ( format_float ( normalized [ 0 ] ) , format_float ( normalized [ 1 ] ) )", "docstring_tokens": "Converts a lat / lon pair to a comma - separated string .", "label": 0 }, { "idx": "cosqa-dev-489", "doc": "python divide array into chunks", "code": "def chunks(arr, size):\n \"\"\"Splits a list into chunks\n\n :param arr: list to split\n :type arr: :class:`list`\n :param size: number of elements in each chunk\n :type size: :class:`int`\n :return: generator object\n :rtype: :class:`generator`\n \"\"\"\n for i in _range(0, len(arr), size):\n yield arr[i:i+size]", "code_tokens": "def chunks ( arr , size ) : for i in _range ( 0 , len ( arr ) , size ) : yield arr [ i : i + size ]", "docstring_tokens": "Splits a list into chunks", "label": 1 }, { "idx": "cosqa-dev-490", "doc": "python recursive dictionary change value", "code": "def map_keys_deep(f, dct):\n \"\"\"\n Implementation of map that recurses. This tests the same keys at every level of dict and in lists\n :param f: 2-ary function expecting a key and value and returns a modified key\n :param dct: Dict for deep processing\n :return: Modified dct with matching props mapped\n \"\"\"\n return _map_deep(lambda k, v: [f(k, v), v], dct)", "code_tokens": "def map_keys_deep ( f , dct ) : return _map_deep ( lambda k , v : [ f ( k , v ) , v ] , dct )", "docstring_tokens": "Implementation of map that recurses . This tests the same keys at every level of dict and in lists : param f : 2 - ary function expecting a key and value and returns a modified key : param dct : Dict for deep processing : return : Modified dct with matching props mapped", "label": 0 }, { "idx": "cosqa-dev-491", "doc": "python raise original but with different type", "code": "def reraise(error):\n \"\"\"Re-raises the error that was processed by prepare_for_reraise earlier.\"\"\"\n if hasattr(error, \"_type_\"):\n six.reraise(type(error), error, error._traceback)\n raise error", "code_tokens": "def reraise ( error ) : if hasattr ( error , \"_type_\" ) : six . reraise ( type ( error ) , error , error . _traceback ) raise error", "docstring_tokens": "Re - raises the error that was processed by prepare_for_reraise earlier .", "label": 0 }, { "idx": "cosqa-dev-492", "doc": "python string replace source", "code": "def replace(scope, strings, source, dest):\n \"\"\"\n Returns a copy of the given string (or list of strings) in which all\n occurrences of the given source are replaced by the given dest.\n\n :type strings: string\n :param strings: A string, or a list of strings.\n :type source: string\n :param source: What to replace.\n :type dest: string\n :param dest: What to replace it with.\n :rtype: string\n :return: The resulting string, or list of strings.\n \"\"\"\n return [s.replace(source[0], dest[0]) for s in strings]", "code_tokens": "def replace ( scope , strings , source , dest ) : return [ s . replace ( source [ 0 ] , dest [ 0 ] ) for s in strings ]", "docstring_tokens": "Returns a copy of the given string ( or list of strings ) in which all occurrences of the given source are replaced by the given dest .", "label": 1 }, { "idx": "cosqa-dev-493", "doc": "string representing a category python", "code": "def get_category(self):\n \"\"\"Get the category of the item.\n\n :return: the category of the item.\n :returntype: `unicode`\"\"\"\n var = self.xmlnode.prop(\"category\")\n if not var:\n var = \"?\"\n return var.decode(\"utf-8\")", "code_tokens": "def get_category ( self ) : var = self . xmlnode . prop ( \"category\" ) if not var : var = \"?\" return var . decode ( \"utf-8\" )", "docstring_tokens": "Get the category of the item .", "label": 0 }, { "idx": "cosqa-dev-494", "doc": "how to campare date from string in python", "code": "def datetime_from_str(string):\n \"\"\"\n\n Args:\n string: string of the form YYMMDD-HH_MM_SS, e.g 160930-18_43_01\n\n Returns: a datetime object\n\n \"\"\"\n\n\n return datetime.datetime(year=2000+int(string[0:2]), month=int(string[2:4]), day=int(string[4:6]), hour=int(string[7:9]), minute=int(string[10:12]),second=int(string[13:15]))", "code_tokens": "def datetime_from_str ( string ) : return datetime . datetime ( year = 2000 + int ( string [ 0 : 2 ] ) , month = int ( string [ 2 : 4 ] ) , day = int ( string [ 4 : 6 ] ) , hour = int ( string [ 7 : 9 ] ) , minute = int ( string [ 10 : 12 ] ) , second = int ( string [ 13 : 15 ] ) )", "docstring_tokens": "", "label": 0 }, { "idx": "cosqa-dev-495", "doc": "draw lines between 2d points in python", "code": "def _draw_lines_internal(self, coords, colour, bg):\n \"\"\"Helper to draw lines connecting a set of nodes that are scaled for the Screen.\"\"\"\n for i, (x, y) in enumerate(coords):\n if i == 0:\n self._screen.move(x, y)\n else:\n self._screen.draw(x, y, colour=colour, bg=bg, thin=True)", "code_tokens": "def _draw_lines_internal ( self , coords , colour , bg ) : for i , ( x , y ) in enumerate ( coords ) : if i == 0 : self . _screen . move ( x , y ) else : self . _screen . draw ( x , y , colour = colour , bg = bg , thin = True )", "docstring_tokens": "Helper to draw lines connecting a set of nodes that are scaled for the Screen .", "label": 1 }, { "idx": "cosqa-dev-496", "doc": "python l1 norm between vectors", "code": "def l2_norm(arr):\n \"\"\"\n The l2 norm of an array is is defined as: sqrt(||x||), where ||x|| is the\n dot product of the vector.\n \"\"\"\n arr = np.asarray(arr)\n return np.sqrt(np.dot(arr.ravel().squeeze(), arr.ravel().squeeze()))", "code_tokens": "def l2_norm ( arr ) : arr = np . asarray ( arr ) return np . sqrt ( np . dot ( arr . ravel ( ) . squeeze ( ) , arr . ravel ( ) . squeeze ( ) ) )", "docstring_tokens": "The l2 norm of an array is is defined as : sqrt ( ||x|| ) where ||x|| is the dot product of the vector .", "label": 0 }, { "idx": "cosqa-dev-497", "doc": "python remove first n item", "code": "def prune(self, n):\n \"\"\"prune all but the first (=best) n items\"\"\"\n if self.minimize:\n self.data = self.data[:n]\n else:\n self.data = self.data[-1 * n:]", "code_tokens": "def prune ( self , n ) : if self . minimize : self . data = self . data [ : n ] else : self . data = self . data [ - 1 * n : ]", "docstring_tokens": "prune all but the first ( = best ) n items", "label": 1 }, { "idx": "cosqa-dev-498", "doc": "linkedlist with tail in python", "code": "def get_tail(self):\n \"\"\"Gets tail\n\n :return: Tail of linked list\n \"\"\"\n node = self.head\n last_node = self.head\n\n while node is not None:\n last_node = node\n node = node.next_node\n\n return last_node", "code_tokens": "def get_tail ( self ) : node = self . head last_node = self . head while node is not None : last_node = node node = node . next_node return last_node", "docstring_tokens": "Gets tail", "label": 1 }, { "idx": "cosqa-dev-499", "doc": "python flat a 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 }, { "idx": "cosqa-dev-500", "doc": "make an array of zeros in python", "code": "def zeros(self, name, **kwargs):\n \"\"\"Create an array. Keyword arguments as per\n :func:`zarr.creation.zeros`.\"\"\"\n return self._write_op(self._zeros_nosync, name, **kwargs)", "code_tokens": "def zeros ( self , name , * * kwargs ) : return self . _write_op ( self . _zeros_nosync , name , * * kwargs )", "docstring_tokens": "Create an array . Keyword arguments as per : func : zarr . creation . zeros .", "label": 0 }, { "idx": "cosqa-dev-501", "doc": "parsing a query string with python", "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 }, { "idx": "cosqa-dev-502", "doc": "python print killed on the screeen", "code": "def safe_exit(output):\n \"\"\"exit without breaking pipes.\"\"\"\n try:\n sys.stdout.write(output)\n sys.stdout.flush()\n except IOError:\n pass", "code_tokens": "def safe_exit ( output ) : try : sys . stdout . write ( output ) sys . stdout . flush ( ) except IOError : pass", "docstring_tokens": "exit without breaking pipes .", "label": 0 }, { "idx": "cosqa-dev-503", "doc": "get last record sql python", "code": "def get_last_id(self, cur, table='reaction'):\n \"\"\"\n Get the id of the last written row in table\n\n Parameters\n ----------\n cur: database connection().cursor() object\n table: str\n 'reaction', 'publication', 'publication_system', 'reaction_system'\n\n Returns: id\n \"\"\"\n cur.execute(\"SELECT seq FROM sqlite_sequence WHERE name='{0}'\"\n .format(table))\n result = cur.fetchone()\n if result is not None:\n id = result[0]\n else:\n id = 0\n return id", "code_tokens": "def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( \"SELECT seq FROM sqlite_sequence WHERE name='{0}'\" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id", "docstring_tokens": "Get the id of the last written row in table", "label": 1 }, { "idx": "cosqa-dev-504", "doc": "code to clear all entries in python", "code": "def trim(self):\n \"\"\"Clear not used counters\"\"\"\n for key, value in list(iteritems(self.counters)):\n if value.empty():\n del self.counters[key]", "code_tokens": "def trim ( self ) : for key , value in list ( iteritems ( self . counters ) ) : if value . empty ( ) : del self . counters [ key ]", "docstring_tokens": "Clear not used counters", "label": 0 }, { "idx": "cosqa-dev-505", "doc": "remove character type coloumns from dataset using python", "code": "def strip_columns(tab):\n \"\"\"Strip whitespace from string columns.\"\"\"\n for colname in tab.colnames:\n if tab[colname].dtype.kind in ['S', 'U']:\n tab[colname] = np.core.defchararray.strip(tab[colname])", "code_tokens": "def strip_columns ( tab ) : for colname in tab . colnames : if tab [ colname ] . dtype . kind in [ 'S' , 'U' ] : tab [ colname ] = np . core . defchararray . strip ( tab [ colname ] )", "docstring_tokens": "Strip whitespace from string columns .", "label": 0 }, { "idx": "cosqa-dev-506", "doc": "python argparse set variable", "code": "def add_to_parser(self, parser):\n \"\"\"\n Adds the argument to an argparse.ArgumentParser instance\n\n @param parser An argparse.ArgumentParser instance\n \"\"\"\n kwargs = self._get_kwargs()\n args = self._get_args()\n parser.add_argument(*args, **kwargs)", "code_tokens": "def add_to_parser ( self , parser ) : kwargs = self . _get_kwargs ( ) args = self . _get_args ( ) parser . add_argument ( * args , * * kwargs )", "docstring_tokens": "Adds the argument to an argparse . ArgumentParser instance", "label": 0 }, { "idx": "cosqa-dev-507", "doc": "python colormap use only 20 colorls", "code": "def _truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):\n \"\"\"\n Truncates a colormap to use.\n Code originall from http://stackoverflow.com/questions/18926031/how-to-extract-a-subset-of-a-colormap-as-a-new-colormap-in-matplotlib\n \"\"\"\n new_cmap = LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),\n cmap(numpy.linspace(minval, maxval, n))\n )\n return new_cmap", "code_tokens": "def _truncate_colormap ( cmap , minval = 0.0 , maxval = 1.0 , n = 100 ) : new_cmap = LinearSegmentedColormap . from_list ( 'trunc({n},{a:.2f},{b:.2f})' . format ( n = cmap . name , a = minval , b = maxval ) , cmap ( numpy . linspace ( minval , maxval , n ) ) ) return new_cmap", "docstring_tokens": "Truncates a colormap to use . Code originall from http : // stackoverflow . com / questions / 18926031 / how - to - extract - a - subset - of - a - colormap - as - a - new - colormap - in - matplotlib", "label": 0 }, { "idx": "cosqa-dev-508", "doc": "python base64 to image file", "code": "def base64ToImage(imgData, out_path, out_file):\n \"\"\" converts a base64 string to a file \"\"\"\n fh = open(os.path.join(out_path, out_file), \"wb\")\n fh.write(imgData.decode('base64'))\n fh.close()\n del fh\n return os.path.join(out_path, out_file)", "code_tokens": "def base64ToImage ( imgData , out_path , out_file ) : fh = open ( os . path . join ( out_path , out_file ) , \"wb\" ) fh . write ( imgData . decode ( 'base64' ) ) fh . close ( ) del fh return os . path . join ( out_path , out_file )", "docstring_tokens": "converts a base64 string to a file", "label": 1 }, { "idx": "cosqa-dev-509", "doc": "python calculate distance points to line", "code": "def distance_to_line(a, b, p):\n \"\"\"Closest distance between a line segment and a point\n\n Args:\n a ([float, float]): x and y coordinates. Line start\n b ([float, float]): x and y coordinates. Line end\n p ([float, float]): x and y coordinates. Point to compute the distance\n Returns:\n float\n \"\"\"\n return distance(closest_point(a, b, p), p)", "code_tokens": "def distance_to_line ( a , b , p ) : return distance ( closest_point ( a , b , p ) , p )", "docstring_tokens": "Closest distance between a line segment and a point", "label": 1 }, { "idx": "cosqa-dev-510", "doc": "python lambda function with only kwargs inputs", "code": "def apply_kwargs(func, **kwargs):\n \"\"\"Call *func* with kwargs, but only those kwargs that it accepts.\n \"\"\"\n new_kwargs = {}\n params = signature(func).parameters\n for param_name in params.keys():\n if param_name in kwargs:\n new_kwargs[param_name] = kwargs[param_name]\n return func(**new_kwargs)", "code_tokens": "def apply_kwargs ( func , * * kwargs ) : new_kwargs = { } params = signature ( func ) . parameters for param_name in params . keys ( ) : if param_name in kwargs : new_kwargs [ param_name ] = kwargs [ param_name ] return func ( * * new_kwargs )", "docstring_tokens": "Call * func * with kwargs but only those kwargs that it accepts .", "label": 0 }, { "idx": "cosqa-dev-511", "doc": "how to test for equality using python", "code": "def hard_equals(a, b):\n \"\"\"Implements the '===' operator.\"\"\"\n if type(a) != type(b):\n return False\n return a == b", "code_tokens": "def hard_equals ( a , b ) : if type ( a ) != type ( b ) : return False return a == b", "docstring_tokens": "Implements the === operator .", "label": 1 }, { "idx": "cosqa-dev-512", "doc": "how to get a random float between 0 and 1 in python", "code": "def money(min=0, max=10):\n \"\"\"Return a str of decimal with two digits after a decimal mark.\"\"\"\n value = random.choice(range(min * 100, max * 100))\n return \"%1.2f\" % (float(value) / 100)", "code_tokens": "def money ( min = 0 , max = 10 ) : value = random . choice ( range ( min * 100 , max * 100 ) ) return \"%1.2f\" % ( float ( value ) / 100 )", "docstring_tokens": "Return a str of decimal with two digits after a decimal mark .", "label": 1 }, { "idx": "cosqa-dev-513", "doc": "python threadpool join hang", "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 }, { "idx": "cosqa-dev-514", "doc": "python detect object from image and segment", "code": "def region_from_segment(image, segment):\n \"\"\"given a segment (rectangle) and an image, returns it's corresponding subimage\"\"\"\n x, y, w, h = segment\n return image[y:y + h, x:x + w]", "code_tokens": "def region_from_segment ( image , segment ) : x , y , w , h = segment return image [ y : y + h , x : x + w ]", "docstring_tokens": "given a segment ( rectangle ) and an image returns it s corresponding subimage", "label": 0 }, { "idx": "cosqa-dev-515", "doc": "python query mongodb to object", "code": "def _obj_cursor_to_dictionary(self, cursor):\n \"\"\"Handle conversion of pymongo cursor into a JSON object formatted for UI consumption\n\n :param dict cursor: a mongo document that should be converted to primitive types for the client code\n :returns: a primitive dictionary\n :rtype: dict\n \"\"\"\n if not cursor:\n return cursor\n\n cursor = json.loads(json.dumps(cursor, cls=BSONEncoder))\n\n if cursor.get(\"_id\"):\n cursor[\"id\"] = cursor.get(\"_id\")\n del cursor[\"_id\"]\n\n return cursor", "code_tokens": "def _obj_cursor_to_dictionary ( self , cursor ) : if not cursor : return cursor cursor = json . loads ( json . dumps ( cursor , cls = BSONEncoder ) ) if cursor . get ( \"_id\" ) : cursor [ \"id\" ] = cursor . get ( \"_id\" ) del cursor [ \"_id\" ] return cursor", "docstring_tokens": "Handle conversion of pymongo cursor into a JSON object formatted for UI consumption", "label": 0 }, { "idx": "cosqa-dev-516", "doc": "python scipy wav bytes write", "code": "def write_wav(path, samples, sr=16000):\n \"\"\"\n Write to given samples to a wav file.\n The samples are expected to be floating point numbers\n in the range of -1.0 to 1.0.\n\n Args:\n path (str): The path to write the wav to.\n samples (np.array): A float array .\n sr (int): The sampling rate.\n \"\"\"\n max_value = np.abs(np.iinfo(np.int16).min)\n data = (samples * max_value).astype(np.int16)\n scipy.io.wavfile.write(path, sr, data)", "code_tokens": "def write_wav ( path , samples , sr = 16000 ) : max_value = np . abs ( np . iinfo ( np . int16 ) . min ) data = ( samples * max_value ) . astype ( np . int16 ) scipy . io . wavfile . write ( path , sr , data )", "docstring_tokens": "Write to given samples to a wav file . The samples are expected to be floating point numbers in the range of - 1 . 0 to 1 . 0 .", "label": 1 }, { "idx": "cosqa-dev-517", "doc": "python datetime today date only", "code": "def created_today(self):\n \"\"\"Return True if created today.\"\"\"\n if self.datetime.date() == datetime.today().date():\n return True\n return False", "code_tokens": "def created_today ( self ) : if self . datetime . date ( ) == datetime . today ( ) . date ( ) : return True return False", "docstring_tokens": "Return True if created today .", "label": 0 }, { "idx": "cosqa-dev-518", "doc": "turn python dict into strings", "code": "def stringify_dict_contents(dct):\n \"\"\"Turn dict keys and values into native strings.\"\"\"\n return {\n str_if_nested_or_str(k): str_if_nested_or_str(v)\n for k, v in dct.items()\n }", "code_tokens": "def stringify_dict_contents ( dct ) : return { str_if_nested_or_str ( k ) : str_if_nested_or_str ( v ) for k , v in dct . items ( ) }", "docstring_tokens": "Turn dict keys and values into native strings .", "label": 1 }, { "idx": "cosqa-dev-519", "doc": "python check if image file is corrupt", "code": "def is_image_file_valid(file_path_name):\n \"\"\"\n Indicate whether the specified image file is valid or not.\n\n\n @param file_path_name: absolute path and file name of an image.\n\n\n @return: ``True`` if the image file is valid, ``False`` if the file is\n truncated or does not correspond to a supported image.\n \"\"\"\n # Image.verify is only implemented for PNG images, and it only verifies\n # the CRC checksum in the image. The only way to check from within\n # Pillow is to load the image in a try/except and check the error. If\n # as much info as possible is from the image is needed,\n # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it\n # will attempt to parse as much as possible.\n try:\n with Image.open(file_path_name) as image:\n image.load()\n except IOError:\n return False\n\n return True", "code_tokens": "def is_image_file_valid ( file_path_name ) : # Image.verify is only implemented for PNG images, and it only verifies # the CRC checksum in the image. The only way to check from within # Pillow is to load the image in a try/except and check the error. If # as much info as possible is from the image is needed, # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it # will attempt to parse as much as possible. try : with Image . open ( file_path_name ) as image : image . load ( ) except IOError : return False return True", "docstring_tokens": "Indicate whether the specified image file is valid or not .", "label": 1 }, { "idx": "cosqa-dev-520", "doc": "python flask if and else jinja", "code": "def rstjinja(app, docname, source):\n \"\"\"\n Render our pages as a jinja template for fancy templating goodness.\n \"\"\"\n # Make sure we're outputting HTML\n if app.builder.format != 'html':\n return\n src = source[0]\n rendered = app.builder.templates.render_string(\n src, app.config.html_context\n )\n source[0] = rendered", "code_tokens": "def rstjinja ( app , docname , source ) : # Make sure we're outputting HTML if app . builder . format != 'html' : return src = source [ 0 ] rendered = app . builder . templates . render_string ( src , app . config . html_context ) source [ 0 ] = rendered", "docstring_tokens": "Render our pages as a jinja template for fancy templating goodness .", "label": 0 }, { "idx": "cosqa-dev-521", "doc": "python code to test tensorflow", "code": "def main(argv=None):\n \"\"\"Run a Tensorflow model on the Iris dataset.\"\"\"\n args = parse_arguments(sys.argv if argv is None else argv)\n\n tf.logging.set_verbosity(tf.logging.INFO)\n learn_runner.run(\n experiment_fn=get_experiment_fn(args),\n output_dir=args.job_dir)", "code_tokens": "def main ( argv = None ) : args = parse_arguments ( sys . argv if argv is None else argv ) tf . logging . set_verbosity ( tf . logging . INFO ) learn_runner . run ( experiment_fn = get_experiment_fn ( args ) , output_dir = args . job_dir )", "docstring_tokens": "Run a Tensorflow model on the Iris dataset .", "label": 1 }, { "idx": "cosqa-dev-522", "doc": "python mkdirs with permission", "code": "def makedirs(path, mode=0o777, exist_ok=False):\n \"\"\"A wrapper of os.makedirs().\"\"\"\n os.makedirs(path, mode, exist_ok)", "code_tokens": "def makedirs ( path , mode = 0o777 , exist_ok = False ) : os . makedirs ( path , mode , exist_ok )", "docstring_tokens": "A wrapper of os . makedirs () .", "label": 1 }, { "idx": "cosqa-dev-523", "doc": "python checking if zip file is open", "code": "def current_zipfile():\n \"\"\"A function to vend the current zipfile, if any\"\"\"\n if zipfile.is_zipfile(sys.argv[0]):\n fd = open(sys.argv[0], \"rb\")\n return zipfile.ZipFile(fd)", "code_tokens": "def current_zipfile ( ) : if zipfile . is_zipfile ( sys . argv [ 0 ] ) : fd = open ( sys . argv [ 0 ] , \"rb\" ) return zipfile . ZipFile ( fd )", "docstring_tokens": "A function to vend the current zipfile if any", "label": 0 }, { "idx": "cosqa-dev-524", "doc": "python3 string to bytestring", "code": "def strtobytes(input, encoding):\n \"\"\"Take a str and transform it into a byte array.\"\"\"\n py_version = sys.version_info[0]\n if py_version >= 3:\n return _strtobytes_py3(input, encoding)\n return _strtobytes_py2(input, encoding)", "code_tokens": "def strtobytes ( input , encoding ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _strtobytes_py3 ( input , encoding ) return _strtobytes_py2 ( input , encoding )", "docstring_tokens": "Take a str and transform it into a byte array .", "label": 1 }, { "idx": "cosqa-dev-525", "doc": "determine precision of float returned in python", "code": "def round_to_float(number, precision):\n \"\"\"Round a float to a precision\"\"\"\n rounded = Decimal(str(floor((number + precision / 2) // precision))\n ) * Decimal(str(precision))\n return float(rounded)", "code_tokens": "def round_to_float ( number , precision ) : rounded = Decimal ( str ( floor ( ( number + precision / 2 ) // precision ) ) ) * Decimal ( str ( precision ) ) return float ( rounded )", "docstring_tokens": "Round a float to a precision", "label": 0 }, { "idx": "cosqa-dev-526", "doc": "python numpy topk array index", "code": "def rank(self):\n \"\"\"how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys\"\"\"\n r = np.empty(self.size, np.int)\n r[self.sorter] = np.arange(self.size)\n return r", "code_tokens": "def rank ( self ) : r = np . empty ( self . size , np . int ) r [ self . sorter ] = np . arange ( self . size ) return r", "docstring_tokens": "how high in sorted list each key is . inverse permutation of sorter such that sorted [ rank ] == keys", "label": 1 }, { "idx": "cosqa-dev-527", "doc": "python how to normalize rgb from 0 to 1", "code": "def _normalize(mat: np.ndarray):\n \"\"\"rescales a numpy array, so that min is 0 and max is 255\"\"\"\n return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8)", "code_tokens": "def _normalize ( mat : np . ndarray ) : return ( ( mat - mat . min ( ) ) * ( 255 / mat . max ( ) ) ) . astype ( np . uint8 )", "docstring_tokens": "rescales a numpy array so that min is 0 and max is 255", "label": 1 }, { "idx": "cosqa-dev-528", "doc": "sorting python list on a special key stack overflow", "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": 0 }, { "idx": "cosqa-dev-529", "doc": "if return url python", "code": "def get_url_nofollow(url):\n\t\"\"\" \n\tfunction to get return code of a url\n\n\tCredits: http://blog.jasonantman.com/2013/06/python-script-to-check-a-list-of-urls-for-return-code-and-final-return-code-if-redirected/\n\t\"\"\"\n\ttry:\n\t\tresponse = urlopen(url)\n\t\tcode = response.getcode()\n\t\treturn code\n\texcept HTTPError as e:\n\t\treturn e.code\n\texcept:\n\t\treturn 0", "code_tokens": "def get_url_nofollow ( url ) : try : response = urlopen ( url ) code = response . getcode ( ) return code except HTTPError as e : return e . code except : return 0", "docstring_tokens": "function to get return code of a url", "label": 0 }, { "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 }, { "idx": "cosqa-dev-531", "doc": "check iterable property in python", "code": "def is_lazy_iterable(obj):\n \"\"\"\n Returns whether *obj* is iterable lazily, such as generators, range objects, etc.\n \"\"\"\n return isinstance(obj,\n (types.GeneratorType, collections.MappingView, six.moves.range, enumerate))", "code_tokens": "def is_lazy_iterable ( obj ) : return isinstance ( obj , ( types . GeneratorType , collections . MappingView , six . moves . range , enumerate ) )", "docstring_tokens": "Returns whether * obj * is iterable lazily such as generators range objects etc .", "label": 1 }, { "idx": "cosqa-dev-532", "doc": "include equals in min max python", "code": "def _digits(minval, maxval):\n \"\"\"Digits needed to comforatbly display values in [minval, maxval]\"\"\"\n if minval == maxval:\n return 3\n else:\n return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))", "code_tokens": "def _digits ( minval , maxval ) : if minval == maxval : return 3 else : return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) )", "docstring_tokens": "Digits needed to comforatbly display values in [ minval maxval ]", "label": 0 }, { "idx": "cosqa-dev-533", "doc": "python dir mkdir permissions", "code": "def makedirs(path, mode=0o777, exist_ok=False):\n \"\"\"A wrapper of os.makedirs().\"\"\"\n os.makedirs(path, mode, exist_ok)", "code_tokens": "def makedirs ( path , mode = 0o777 , exist_ok = False ) : os . makedirs ( path , mode , exist_ok )", "docstring_tokens": "A wrapper of os . makedirs () .", "label": 1 }, { "idx": "cosqa-dev-534", "doc": "f strings number rounding formatting python", "code": "def _saferound(value, decimal_places):\n \"\"\"\n Rounds a float value off to the desired precision\n \"\"\"\n try:\n f = float(value)\n except ValueError:\n return ''\n format = '%%.%df' % decimal_places\n return format % f", "code_tokens": "def _saferound ( value , decimal_places ) : try : f = float ( value ) except ValueError : return '' format = '%%.%df' % decimal_places return format % f", "docstring_tokens": "Rounds a float value off to the desired precision", "label": 1 }, { "idx": "cosqa-dev-535", "doc": "in python not returing the collection list in mongo db", "code": "def __getitem__(self, name):\n \"\"\"\n A pymongo-like behavior for dynamically obtaining a collection of documents\n \"\"\"\n if name not in self._collections:\n self._collections[name] = Collection(self.db, name)\n return self._collections[name]", "code_tokens": "def __getitem__ ( self , name ) : if name not in self . _collections : self . _collections [ name ] = Collection ( self . db , name ) return self . _collections [ name ]", "docstring_tokens": "A pymongo - like behavior for dynamically obtaining a collection of documents", "label": 0 }, { "idx": "cosqa-dev-536", "doc": "nonlocal and nested function scopes and python", "code": "def ex(self, cmd):\n \"\"\"Execute a normal python statement in user namespace.\"\"\"\n with self.builtin_trap:\n exec cmd in self.user_global_ns, self.user_ns", "code_tokens": "def ex ( self , cmd ) : with self . builtin_trap : exec cmd in self . user_global_ns , self . user_ns", "docstring_tokens": "Execute a normal python statement in user namespace .", "label": 0 }, { "idx": "cosqa-dev-537", "doc": "how to do dot product vectors in python", "code": "def dot_v3(v, w):\n \"\"\"Return the dotproduct of two vectors.\"\"\"\n\n return sum([x * y for x, y in zip(v, w)])", "code_tokens": "def dot_v3 ( v , w ) : return sum ( [ x * y for x , y in zip ( v , w ) ] )", "docstring_tokens": "Return the dotproduct of two vectors .", "label": 1 }, { "idx": "cosqa-dev-538", "doc": "python save image array as jpeg", "code": "def write_image(filename, image):\n \"\"\" Write image data to PNG, JPG file\n\n :param filename: name of PNG or JPG file to write data to\n :type filename: str\n :param image: image data to write to file\n :type image: numpy array\n \"\"\"\n data_format = get_data_format(filename)\n if data_format is MimeType.JPG:\n LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.')\n return Image.fromarray(image).save(filename)", "code_tokens": "def write_image ( filename , image ) : data_format = get_data_format ( filename ) if data_format is MimeType . JPG : LOGGER . warning ( 'Warning: jpeg is a lossy format therefore saved data will be modified.' ) return Image . fromarray ( image ) . save ( filename )", "docstring_tokens": "Write image data to PNG JPG file", "label": 1 }, { "idx": "cosqa-dev-539", "doc": "how to return to previous line in python", "code": "def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):\n \"\"\"\n If we're not on the first line (of a multiline input) go a line up,\n otherwise go back in history. (If nothing is selected.)\n \"\"\"\n if self.complete_state:\n self.complete_previous(count=count)\n elif self.document.cursor_position_row > 0:\n self.cursor_up(count=count)\n elif not self.selection_state:\n self.history_backward(count=count)\n\n # Go to the start of the line?\n if go_to_start_of_line_if_history_changes:\n self.cursor_position += self.document.get_start_of_line_position()", "code_tokens": "def auto_up ( self , count = 1 , go_to_start_of_line_if_history_changes = False ) : if self . complete_state : self . complete_previous ( count = count ) elif self . document . cursor_position_row > 0 : self . cursor_up ( count = count ) elif not self . selection_state : self . history_backward ( count = count ) # Go to the start of the line? if go_to_start_of_line_if_history_changes : self . cursor_position += self . document . get_start_of_line_position ( )", "docstring_tokens": "If we re not on the first line ( of a multiline input ) go a line up otherwise go back in history . ( If nothing is selected . )", "label": 1 }, { "idx": "cosqa-dev-540", "doc": "x y coordinates in python on a canvas", "code": "def c2s(self,p=[0,0]):\n \"\"\"Convert from canvas to screen coordinates\"\"\"\n\n return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))", "code_tokens": "def c2s ( self , p = [ 0 , 0 ] ) : return ( ( p [ 0 ] - self . canvasx ( self . cx1 ) , p [ 1 ] - self . canvasy ( self . cy1 ) ) )", "docstring_tokens": "Convert from canvas to screen coordinates", "label": 1 }, { "idx": "cosqa-dev-541", "doc": "implementation of saliency models in python", "code": "def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None):\n \"\"\"Compute the LSR estimate of model parameters given dense data.\n\n This function implements the Luce Spectral Ranking inference algorithm\n [MG15]_ for dense pairwise-comparison data.\n\n The data is described by a pairwise-comparison matrix ``comp_mat`` such\n that ``comp_mat[i,j]`` contains the number of times that item ``i`` wins\n against item ``j``.\n\n In comparison to :func:`~choix.lsr_pairwise`, this function is particularly\n efficient for dense pairwise-comparison datasets (i.e., containing many\n comparisons for a large fraction of item pairs).\n\n The argument ``initial_params`` can be used to iteratively refine an\n existing parameter estimate (see the implementation of\n :func:`~choix.ilsr_pairwise` for an idea on how this works). If it is set\n to `None` (the default), the all-ones vector is used.\n\n The transition rates of the LSR Markov chain are initialized with\n ``alpha``. When ``alpha > 0``, this corresponds to a form of regularization\n (see :ref:`regularization` for details).\n\n Parameters\n ----------\n comp_mat : np.array\n 2D square matrix describing the pairwise-comparison outcomes.\n alpha : float, optional\n Regularization parameter.\n initial_params : array_like, optional\n Parameters used to build the transition rates of the LSR Markov chain.\n\n Returns\n -------\n params : np.array\n An estimate of model parameters.\n \"\"\"\n n_items = comp_mat.shape[0]\n ws, chain = _init_lsr(n_items, alpha, initial_params)\n denom = np.tile(ws, (n_items, 1))\n chain += comp_mat.T / (denom + denom.T)\n chain -= np.diag(chain.sum(axis=1))\n return log_transform(statdist(chain))", "code_tokens": "def lsr_pairwise_dense ( comp_mat , alpha = 0.0 , initial_params = None ) : n_items = comp_mat . shape [ 0 ] ws , chain = _init_lsr ( n_items , alpha , initial_params ) denom = np . tile ( ws , ( n_items , 1 ) ) chain += comp_mat . T / ( denom + denom . T ) chain -= np . diag ( chain . sum ( axis = 1 ) ) return log_transform ( statdist ( chain ) )", "docstring_tokens": "Compute the LSR estimate of model parameters given dense data .", "label": 0 }, { "idx": "cosqa-dev-542", "doc": "how to deprecate a function in python", "code": "def deprecate(func):\n \"\"\" A deprecation warning emmiter as a decorator. \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n warn(\"Deprecated, this will be removed in the future\", DeprecationWarning)\n return func(*args, **kwargs)\n wrapper.__doc__ = \"Deprecated.\\n\" + (wrapper.__doc__ or \"\")\n return wrapper", "code_tokens": "def deprecate ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : warn ( \"Deprecated, this will be removed in the future\" , DeprecationWarning ) return func ( * args , * * kwargs ) wrapper . __doc__ = \"Deprecated.\\n\" + ( wrapper . __doc__ or \"\" ) return wrapper", "docstring_tokens": "A deprecation warning emmiter as a decorator .", "label": 0 }, { "idx": "cosqa-dev-543", "doc": "python check if an item in a list is a string", "code": "def all_strings(arr):\n \"\"\"\n Ensures that the argument is a list that either is empty or contains only strings\n :param arr: list\n :return:\n \"\"\"\n if not isinstance([], list):\n raise TypeError(\"non-list value found where list is expected\")\n return all(isinstance(x, str) for x in arr)", "code_tokens": "def all_strings ( arr ) : if not isinstance ( [ ] , list ) : raise TypeError ( \"non-list value found where list is expected\" ) return all ( isinstance ( x , str ) for x in arr )", "docstring_tokens": "Ensures that the argument is a list that either is empty or contains only strings : param arr : list : return :", "label": 1 }, { "idx": "cosqa-dev-544", "doc": "python get elemets satisfying condition", "code": "def getElementsBy(self, cond: Callable[[Element], bool]) -> NodeList:\n \"\"\"Get elements in this document which matches condition.\"\"\"\n return getElementsBy(self, cond)", "code_tokens": "def getElementsBy ( self , cond : Callable [ [ Element ] , bool ] ) -> NodeList : return getElementsBy ( self , cond )", "docstring_tokens": "Get elements in this document which matches condition .", "label": 1 }, { "idx": "cosqa-dev-545", "doc": "series drop a condition for value python", "code": "def na_if(series, *values):\n \"\"\"\n If values in a series match a specified value, change them to `np.nan`.\n\n Args:\n series: Series or vector, often symbolic.\n *values: Value(s) to convert to `np.nan` in the series.\n \"\"\"\n\n series = pd.Series(series)\n series[series.isin(values)] = np.nan\n return series", "code_tokens": "def na_if ( series , * values ) : series = pd . Series ( series ) series [ series . isin ( values ) ] = np . nan return series", "docstring_tokens": "If values in a series match a specified value change them to np . nan .", "label": 1 }, { "idx": "cosqa-dev-546", "doc": "python appmetrics print for every query", "code": "def print_statements(self):\n \"\"\"Print all INDRA Statements collected by the processors.\"\"\"\n for i, stmt in enumerate(self.statements):\n print(\"%s: %s\" % (i, stmt))", "code_tokens": "def print_statements ( self ) : for i , stmt in enumerate ( self . statements ) : print ( \"%s: %s\" % ( i , stmt ) )", "docstring_tokens": "Print all INDRA Statements collected by the processors .", "label": 1 }, { "idx": "cosqa-dev-547", "doc": "boto3 delete all item in table python", "code": "def clean_all_buckets(self):\n \"\"\"\n Removes all buckets from all hashes and their content.\n \"\"\"\n bucket_keys = self.redis_object.keys(pattern='nearpy_*')\n if len(bucket_keys) > 0:\n self.redis_object.delete(*bucket_keys)", "code_tokens": "def clean_all_buckets ( self ) : bucket_keys = self . redis_object . keys ( pattern = 'nearpy_*' ) if len ( bucket_keys ) > 0 : self . redis_object . delete ( * bucket_keys )", "docstring_tokens": "Removes all buckets from all hashes and their content .", "label": 0 }, { "idx": "cosqa-dev-548", "doc": "from string to bit vector python", "code": "def frombits(cls, bits):\n \"\"\"Series from binary string arguments.\"\"\"\n return cls.frombitsets(map(cls.BitSet.frombits, bits))", "code_tokens": "def frombits ( cls , bits ) : return cls . frombitsets ( map ( cls . BitSet . frombits , bits ) )", "docstring_tokens": "Series from binary string arguments .", "label": 0 }, { "idx": "cosqa-dev-549", "doc": "python limiting trailing zeros", "code": "def __remove_trailing_zeros(self, collection):\n \"\"\"Removes trailing zeroes from indexable collection of numbers\"\"\"\n index = len(collection) - 1\n while index >= 0 and collection[index] == 0:\n index -= 1\n\n return collection[:index + 1]", "code_tokens": "def __remove_trailing_zeros ( self , collection ) : index = len ( collection ) - 1 while index >= 0 and collection [ index ] == 0 : index -= 1 return collection [ : index + 1 ]", "docstring_tokens": "Removes trailing zeroes from indexable collection of numbers", "label": 1 }, { "idx": "cosqa-dev-550", "doc": "string to callable name python", "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": 0 }, { "idx": "cosqa-dev-551", "doc": "how to keep going after an error in python", "code": "def retry_on_signal(function):\n \"\"\"Retries function until it doesn't raise an EINTR error\"\"\"\n while True:\n try:\n return function()\n except EnvironmentError, e:\n if e.errno != errno.EINTR:\n raise", "code_tokens": "def retry_on_signal ( function ) : while True : try : return function ( ) except EnvironmentError , e : if e . errno != errno . EINTR : raise", "docstring_tokens": "Retries function until it doesn t raise an EINTR error", "label": 0 }, { "idx": "cosqa-dev-552", "doc": "python str to date 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 }, { "idx": "cosqa-dev-553", "doc": "python ensure utf8 string", "code": "def safe_unicode(string):\n \"\"\"If Python 2, replace non-ascii characters and return encoded string.\"\"\"\n if not PY3:\n uni = string.replace(u'\\u2019', \"'\")\n return uni.encode('utf-8')\n \n return string", "code_tokens": "def safe_unicode ( string ) : if not PY3 : uni = string . replace ( u'\\u2019' , \"'\" ) return uni . encode ( 'utf-8' ) return string", "docstring_tokens": "If Python 2 replace non - ascii characters and return encoded string .", "label": 1 }, { "idx": "cosqa-dev-554", "doc": "draw tree recursivly in python", "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": 0 }, { "idx": "cosqa-dev-555", "doc": "python show data type of columns", "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 }, { "idx": "cosqa-dev-556", "doc": "python is not datetime if", "code": "def is_date_type(cls):\n \"\"\"Return True if the class is a date type.\"\"\"\n if not isinstance(cls, type):\n return False\n return issubclass(cls, date) and not issubclass(cls, datetime)", "code_tokens": "def is_date_type ( cls ) : if not isinstance ( cls , type ) : return False return issubclass ( cls , date ) and not issubclass ( cls , datetime )", "docstring_tokens": "Return True if the class is a date type .", "label": 0 }, { "idx": "cosqa-dev-557", "doc": "python convolve array and kernel", "code": "def convolve_gaussian_2d(image, gaussian_kernel_1d):\n \"\"\"Convolve 2d gaussian.\"\"\"\n result = scipy.ndimage.filters.correlate1d(\n image, gaussian_kernel_1d, axis=0)\n result = scipy.ndimage.filters.correlate1d(\n result, gaussian_kernel_1d, axis=1)\n return result", "code_tokens": "def convolve_gaussian_2d ( image , gaussian_kernel_1d ) : result = scipy . ndimage . filters . correlate1d ( image , gaussian_kernel_1d , axis = 0 ) result = scipy . ndimage . filters . correlate1d ( result , gaussian_kernel_1d , axis = 1 ) return result", "docstring_tokens": "Convolve 2d gaussian .", "label": 1 }, { "idx": "cosqa-dev-558", "doc": "python how to clear all variables", "code": "def clear(self):\n \"\"\"Remove all items.\"\"\"\n self._fwdm.clear()\n self._invm.clear()\n self._sntl.nxt = self._sntl.prv = self._sntl", "code_tokens": "def clear ( self ) : self . _fwdm . clear ( ) self . _invm . clear ( ) self . _sntl . nxt = self . _sntl . prv = self . _sntl", "docstring_tokens": "Remove all items .", "label": 1 }, { "idx": "cosqa-dev-559", "doc": "python code to read file from s3 bucket", "code": "def s3_get(url: str, temp_file: IO) -> None:\n \"\"\"Pull a file directly from S3.\"\"\"\n s3_resource = boto3.resource(\"s3\")\n bucket_name, s3_path = split_s3_path(url)\n s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "code_tokens": "def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( \"s3\" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )", "docstring_tokens": "Pull a file directly from S3 .", "label": 1 }, { "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 }, { "idx": "cosqa-dev-561", "doc": "python check if directory access", "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 }, { "idx": "cosqa-dev-562", "doc": "python load jsonlines file to object", "code": "def load(cls, fp, **kwargs):\n \"\"\"wrapper for :py:func:`json.load`\"\"\"\n json_obj = json.load(fp, **kwargs)\n return parse(cls, json_obj)", "code_tokens": "def load ( cls , fp , * * kwargs ) : json_obj = json . load ( fp , * * kwargs ) return parse ( cls , json_obj )", "docstring_tokens": "wrapper for : py : func : json . load", "label": 1 }, { "idx": "cosqa-dev-563", "doc": "python flask get hostname from request", "code": "def get_site_name(request):\n \"\"\"Return the domain:port part of the URL without scheme.\n Eg: facebook.com, 127.0.0.1:8080, etc.\n \"\"\"\n urlparts = request.urlparts\n return ':'.join([urlparts.hostname, str(urlparts.port)])", "code_tokens": "def get_site_name ( request ) : urlparts = request . urlparts return ':' . join ( [ urlparts . hostname , str ( urlparts . port ) ] )", "docstring_tokens": "Return the domain : port part of the URL without scheme . Eg : facebook . com 127 . 0 . 0 . 1 : 8080 etc .", "label": 1 }, { "idx": "cosqa-dev-564", "doc": "extract number from tuple python", "code": "def version_triple(tag):\n \"\"\"\n returns: a triple of integers from a version tag\n \"\"\"\n groups = re.match(r'v?(\\d+)\\.(\\d+)\\.(\\d+)', tag).groups()\n return tuple(int(n) for n in groups)", "code_tokens": "def version_triple ( tag ) : groups = re . match ( r'v?(\\d+)\\.(\\d+)\\.(\\d+)' , tag ) . groups ( ) return tuple ( int ( n ) for n in groups )", "docstring_tokens": "returns : a triple of integers from a version tag", "label": 0 }, { "idx": "cosqa-dev-565", "doc": "show multiple plots in sequence and save them python", "code": "def strip_figures(figure):\n\t\"\"\"\n\tStrips a figure into multiple figures with a trace on each of them\n\n\tParameters:\n\t-----------\n\t\tfigure : Figure\n\t\t\tPlotly Figure\n\t\"\"\"\n\tfig=[]\n\tfor trace in figure['data']:\n\t\tfig.append(dict(data=[trace],layout=figure['layout']))\n\treturn fig", "code_tokens": "def strip_figures ( figure ) : fig = [ ] for trace in figure [ 'data' ] : fig . append ( dict ( data = [ trace ] , layout = figure [ 'layout' ] ) ) return fig", "docstring_tokens": "Strips a figure into multiple figures with a trace on each of them", "label": 0 }, { "idx": "cosqa-dev-566", "doc": "python how to see if string is an exact match to list of patterns", "code": "def matches_glob_list(path, glob_list):\n \"\"\"\n Given a list of glob patterns, returns a boolean\n indicating if a path matches any glob in the list\n \"\"\"\n for glob in glob_list:\n try:\n if PurePath(path).match(glob):\n return True\n except TypeError:\n pass\n return False", "code_tokens": "def matches_glob_list ( path , glob_list ) : for glob in glob_list : try : if PurePath ( path ) . match ( glob ) : return True except TypeError : pass return False", "docstring_tokens": "Given a list of glob patterns returns a boolean indicating if a path matches any glob in the list", "label": 0 }, { "idx": "cosqa-dev-567", "doc": "python urllib 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 }, { "idx": "cosqa-dev-568", "doc": "python ctypes byte buffer", "code": "def getBuffer(x):\n \"\"\"\n Copy @x into a (modifiable) ctypes byte array\n \"\"\"\n b = bytes(x)\n return (c_ubyte * len(b)).from_buffer_copy(bytes(x))", "code_tokens": "def getBuffer ( x ) : b = bytes ( x ) return ( c_ubyte * len ( b ) ) . from_buffer_copy ( bytes ( x ) )", "docstring_tokens": "Copy", "label": 0 }, { "idx": "cosqa-dev-569", "doc": "how to get certain columns from tables python", "code": "def get_column_keys_and_names(table):\n \"\"\"\n Return a generator of tuples k, c such that k is the name of the python attribute for\n the column and c is the name of the column in the sql table.\n \"\"\"\n ins = inspect(table)\n return ((k, c.name) for k, c in ins.mapper.c.items())", "code_tokens": "def get_column_keys_and_names ( table ) : ins = inspect ( table ) return ( ( k , c . name ) for k , c in ins . mapper . c . items ( ) )", "docstring_tokens": "Return a generator of tuples k c such that k is the name of the python attribute for the column and c is the name of the column in the sql table .", "label": 0 }, { "idx": "cosqa-dev-570", "doc": "repeat every element of python n times", "code": "def stretch(iterable, n=2):\n r\"\"\"Repeat each item in `iterable` `n` times.\n\n Example:\n\n >>> list(stretch(range(3), 2))\n [0, 0, 1, 1, 2, 2]\n \"\"\"\n times = range(n)\n for item in iterable:\n for i in times: yield item", "code_tokens": "def stretch ( iterable , n = 2 ) : times = range ( n ) for item in iterable : for i in times : yield item", "docstring_tokens": "r Repeat each item in iterable n times .", "label": 1 }, { "idx": "cosqa-dev-571", "doc": "how to get median in 2d array in python", "code": "def fast_median(a):\n \"\"\"Fast median operation for masked array using 50th-percentile\n \"\"\"\n a = checkma(a)\n #return scoreatpercentile(a.compressed(), 50)\n if a.count() > 0:\n out = np.percentile(a.compressed(), 50)\n else:\n out = np.ma.masked\n return out", "code_tokens": "def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out", "docstring_tokens": "Fast median operation for masked array using 50th - percentile", "label": 1 }, { "idx": "cosqa-dev-572", "doc": "python elements that do not match between two sets", "code": "def isetdiff_flags(list1, list2):\n \"\"\"\n move to util_iter\n \"\"\"\n set2 = set(list2)\n return (item not in set2 for item in list1)", "code_tokens": "def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 )", "docstring_tokens": "move to util_iter", "label": 1 }, { "idx": "cosqa-dev-573", "doc": "python insert a line to the front of the file", "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 }, { "idx": "cosqa-dev-574", "doc": "how to show the plot in python", "code": "def show(self, title=''):\n \"\"\"\n Display Bloch sphere and corresponding data sets.\n \"\"\"\n self.render(title=title)\n if self.fig:\n plt.show(self.fig)", "code_tokens": "def show ( self , title = '' ) : self . render ( title = title ) if self . fig : plt . show ( self . fig )", "docstring_tokens": "Display Bloch sphere and corresponding data sets .", "label": 1 }, { "idx": "cosqa-dev-575", "doc": "how to close figure windows opened in a loop in python", "code": "def close_all():\n r\"\"\"Close all opened windows.\"\"\"\n\n # Windows can be closed by releasing all references to them so they can be\n # garbage collected. May not be necessary to call close().\n global _qtg_windows\n for window in _qtg_windows:\n window.close()\n _qtg_windows = []\n\n global _qtg_widgets\n for widget in _qtg_widgets:\n widget.close()\n _qtg_widgets = []\n\n global _plt_figures\n for fig in _plt_figures:\n _, plt, _ = _import_plt()\n plt.close(fig)\n _plt_figures = []", "code_tokens": "def close_all ( ) : # Windows can be closed by releasing all references to them so they can be # garbage collected. May not be necessary to call close(). global _qtg_windows for window in _qtg_windows : window . close ( ) _qtg_windows = [ ] global _qtg_widgets for widget in _qtg_widgets : widget . close ( ) _qtg_widgets = [ ] global _plt_figures for fig in _plt_figures : _ , plt , _ = _import_plt ( ) plt . close ( fig ) _plt_figures = [ ]", "docstring_tokens": "r Close all opened windows .", "label": 1 }, { "idx": "cosqa-dev-576", "doc": "python show attributes of object", "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 }, { "idx": "cosqa-dev-577", "doc": "how to see if two python arrays are equal", "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 }, { "idx": "cosqa-dev-578", "doc": "changing the size of text for graph labels and titles in python", "code": "def ylabelsize(self, size, index=1):\n \"\"\"Set the size of the label.\n\n Parameters\n ----------\n size : int\n\n Returns\n -------\n Chart\n\n \"\"\"\n self.layout['yaxis' + str(index)]['titlefont']['size'] = size\n return self", "code_tokens": "def ylabelsize ( self , size , index = 1 ) : self . layout [ 'yaxis' + str ( index ) ] [ 'titlefont' ] [ 'size' ] = size return self", "docstring_tokens": "Set the size of the label .", "label": 1 }, { "idx": "cosqa-dev-579", "doc": "how to get maximum of a column in python", "code": "def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:\n \"\"\"\n Takes a list of rows and a column name and returns a list containing a single row (dict from\n columns to cells) that has the maximum numerical value in the given column. We return a list\n instead of a single dict to be consistent with the return type of ``select`` and\n ``all_rows``.\n \"\"\"\n if not rows:\n return []\n value_row_pairs = [(row.values[column.name], row) for row in rows]\n if not value_row_pairs:\n return []\n # Returns a list containing the row with the max cell value.\n return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]", "code_tokens": "def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]", "docstring_tokens": "Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .", "label": 0 }, { "idx": "cosqa-dev-580", "doc": "python calculate latitude and longitude from distance", "code": "def Distance(lat1, lon1, lat2, lon2):\n \"\"\"Get distance between pairs of lat-lon points\"\"\"\n\n az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)\n return az21, dist", "code_tokens": "def Distance ( lat1 , lon1 , lat2 , lon2 ) : az12 , az21 , dist = wgs84_geod . inv ( lon1 , lat1 , lon2 , lat2 ) return az21 , dist", "docstring_tokens": "Get distance between pairs of lat - lon points", "label": 1 }, { "idx": "cosqa-dev-581", "doc": "python function that gives closest whole number", "code": "def get_closest_index(myList, myNumber):\n \"\"\"\n Assumes myList is sorted. Returns closest value to myNumber.\n If two numbers are equally close, return the smallest number.\n\n Parameters\n ----------\n myList : array\n The list in which to find the closest value to myNumber\n myNumber : float\n The number to find the closest to in MyList\n\n Returns\n -------\n closest_values_index : int\n The index in the array of the number closest to myNumber in myList\n \"\"\"\n closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]\n return closest_values_index", "code_tokens": "def get_closest_index ( myList , myNumber ) : closest_values_index = _np . where ( self . time == take_closest ( myList , myNumber ) ) [ 0 ] [ 0 ] return closest_values_index", "docstring_tokens": "Assumes myList is sorted . Returns closest value to myNumber . If two numbers are equally close return the smallest number .", "label": 1 }, { "idx": "cosqa-dev-582", "doc": "python removing property from dictionary", "code": "def remove_property(self, key=None, value=None):\n \"\"\"Remove all properties matching both key and value.\n\n :param str key: Key of the property.\n :param str value: Value of the property.\n \"\"\"\n for k, v in self.properties[:]:\n if (key is None or key == k) and (value is None or value == v):\n del(self.properties[self.properties.index((k, v))])", "code_tokens": "def remove_property ( self , key = None , value = None ) : for k , v in self . properties [ : ] : if ( key is None or key == k ) and ( value is None or value == v ) : del ( self . properties [ self . properties . index ( ( k , v ) ) ] )", "docstring_tokens": "Remove all properties matching both key and value .", "label": 1 }, { "idx": "cosqa-dev-583", "doc": "collecting the column names in python", "code": "def get_column_keys_and_names(table):\n \"\"\"\n Return a generator of tuples k, c such that k is the name of the python attribute for\n the column and c is the name of the column in the sql table.\n \"\"\"\n ins = inspect(table)\n return ((k, c.name) for k, c in ins.mapper.c.items())", "code_tokens": "def get_column_keys_and_names ( table ) : ins = inspect ( table ) return ( ( k , c . name ) for k , c in ins . mapper . c . items ( ) )", "docstring_tokens": "Return a generator of tuples k c such that k is the name of the python attribute for the column and c is the name of the column in the sql table .", "label": 1 }, { "idx": "cosqa-dev-584", "doc": "escaping characters for non printable characters in python mysql query", "code": "def _escape(s):\n \"\"\" Helper method that escapes parameters to a SQL query. \"\"\"\n e = s\n e = e.replace('\\\\', '\\\\\\\\')\n e = e.replace('\\n', '\\\\n')\n e = e.replace('\\r', '\\\\r')\n e = e.replace(\"'\", \"\\\\'\")\n e = e.replace('\"', '\\\\\"')\n return e", "code_tokens": "def _escape ( s ) : e = s e = e . replace ( '\\\\' , '\\\\\\\\' ) e = e . replace ( '\\n' , '\\\\n' ) e = e . replace ( '\\r' , '\\\\r' ) e = e . replace ( \"'\" , \"\\\\'\" ) e = e . replace ( '\"' , '\\\\\"' ) return e", "docstring_tokens": "Helper method that escapes parameters to a SQL query .", "label": 1 }, { "idx": "cosqa-dev-585", "doc": "python how to check if a resultset from a query is empty", "code": "def exists(self):\n \"\"\"\n Determine if any rows exist for the current query.\n\n :return: Whether the rows exist or not\n :rtype: bool\n \"\"\"\n limit = self.limit_\n\n result = self.limit(1).count() > 0\n\n self.limit(limit)\n\n return result", "code_tokens": "def exists ( self ) : limit = self . limit_ result = self . limit ( 1 ) . count ( ) > 0 self . limit ( limit ) return result", "docstring_tokens": "Determine if any rows exist for the current query .", "label": 0 }, { "idx": "cosqa-dev-586", "doc": "how to format python array in a string", "code": "def __str__(self):\n \"\"\"Return human readable string.\"\"\"\n return \", \".join(\"{:02x}{:02x}={:02x}{:02x}\".format(c[0][0], c[0][1], c[1][0], c[1][1]) for c in self.alias_array_)", "code_tokens": "def __str__ ( self ) : return \", \" . join ( \"{:02x}{:02x}={:02x}{:02x}\" . format ( c [ 0 ] [ 0 ] , c [ 0 ] [ 1 ] , c [ 1 ] [ 0 ] , c [ 1 ] [ 1 ] ) for c in self . alias_array_ )", "docstring_tokens": "Return human readable string .", "label": 1 }, { "idx": "cosqa-dev-587", "doc": "calculate the midpoint of a list of points python", "code": "def _mid(pt1, pt2):\n \"\"\"\n (Point, Point) -> Point\n Return the point that lies in between the two input points.\n \"\"\"\n (x0, y0), (x1, y1) = pt1, pt2\n return 0.5 * (x0 + x1), 0.5 * (y0 + y1)", "code_tokens": "def _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )", "docstring_tokens": "( Point Point ) - > Point Return the point that lies in between the two input points .", "label": 1 }, { "idx": "cosqa-dev-588", "doc": "python datetime as integer json decoder", "code": "def parse_json_date(value):\n \"\"\"\n Parses an ISO8601 formatted datetime from a string value\n \"\"\"\n if not value:\n return None\n\n return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)", "code_tokens": "def parse_json_date ( value ) : if not value : return None return datetime . datetime . strptime ( value , JSON_DATETIME_FORMAT ) . replace ( tzinfo = pytz . UTC )", "docstring_tokens": "Parses an ISO8601 formatted datetime from a string value", "label": 0 }, { "idx": "cosqa-dev-589", "doc": "addition of polynomials in python", "code": "def __add__(self, other):\n \"\"\"Left addition.\"\"\"\n return chaospy.poly.collection.arithmetics.add(self, other)", "code_tokens": "def __add__ ( self , other ) : return chaospy . poly . collection . arithmetics . add ( self , other )", "docstring_tokens": "Left addition .", "label": 0 }, { "idx": "cosqa-dev-590", "doc": "python sdate to string", "code": "def QA_util_datetime_to_strdate(dt):\n \"\"\"\n :param dt: pythone datetime.datetime\n :return: 1999-02-01 string type\n \"\"\"\n strdate = \"%04d-%02d-%02d\" % (dt.year, dt.month, dt.day)\n return strdate", "code_tokens": "def QA_util_datetime_to_strdate ( dt ) : strdate = \"%04d-%02d-%02d\" % ( dt . year , dt . month , dt . day ) return strdate", "docstring_tokens": ": param dt : pythone datetime . datetime : return : 1999 - 02 - 01 string type", "label": 1 }, { "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 }, { "idx": "cosqa-dev-592", "doc": "python 3 list cast all top string", "code": "def toHdlConversion(self, top, topName: str, saveTo: str) -> List[str]:\n \"\"\"\n :param top: object which is represenation of design\n :param topName: name which should be used for ipcore\n :param saveTo: path of directory where generated files should be stored\n\n :return: list of file namens in correct compile order\n \"\"\"\n raise NotImplementedError(\n \"Implement this function for your type of your top module\")", "code_tokens": "def toHdlConversion ( self , top , topName : str , saveTo : str ) -> List [ str ] : raise NotImplementedError ( \"Implement this function for your type of your top module\" )", "docstring_tokens": ": param top : object which is represenation of design : param topName : name which should be used for ipcore : param saveTo : path of directory where generated files should be stored", "label": 0 }, { "idx": "cosqa-dev-593", "doc": "python add string to logger", "code": "def debug(self, text):\n\t\t\"\"\" Ajout d'un message de log de type DEBUG \"\"\"\n\t\tself.logger.debug(\"{}{}\".format(self.message_prefix, text))", "code_tokens": "def debug ( self , text ) : self . logger . debug ( \"{}{}\" . format ( self . message_prefix , text ) )", "docstring_tokens": "Ajout d un message de log de type DEBUG", "label": 1 }, { "idx": "cosqa-dev-594", "doc": "run python test current directory", "code": "def test(): # pragma: no cover\n \"\"\"Execute the unit tests on an installed copy of unyt.\n\n Note that this function requires pytest to run. If pytest is not\n installed this function will raise ImportError.\n \"\"\"\n import pytest\n import os\n\n pytest.main([os.path.dirname(os.path.abspath(__file__))])", "code_tokens": "def test ( ) : # pragma: no cover import pytest import os pytest . main ( [ os . path . dirname ( os . path . abspath ( __file__ ) ) ] )", "docstring_tokens": "Execute the unit tests on an installed copy of unyt .", "label": 1 }, { "idx": "cosqa-dev-595", "doc": "get window title in python", "code": "def title(self):\n \"\"\" The title of this window \"\"\"\n with switch_window(self._browser, self.name):\n return self._browser.title", "code_tokens": "def title ( self ) : with switch_window ( self . _browser , self . name ) : return self . _browser . title", "docstring_tokens": "The title of this window", "label": 1 }, { "idx": "cosqa-dev-596", "doc": "request form get python flask", "code": "def parse_form(self, req, name, field):\n \"\"\"Pull a form value from the request.\"\"\"\n return get_value(req.body_arguments, name, field)", "code_tokens": "def parse_form ( self , req , name , field ) : return get_value ( req . body_arguments , name , field )", "docstring_tokens": "Pull a form value from the request .", "label": 0 }, { "idx": "cosqa-dev-597", "doc": "python add random gaussian noise image", "code": "def block(seed):\n \"\"\" Return block of normal random numbers\n\n Parameters\n ----------\n seed : {None, int}\n The seed to generate the noise.sd\n\n Returns\n --------\n noise : numpy.ndarray\n Array of random numbers\n \"\"\"\n num = SAMPLE_RATE * BLOCK_SIZE\n rng = RandomState(seed % 2**32)\n variance = SAMPLE_RATE / 2\n return rng.normal(size=num, scale=variance**0.5)", "code_tokens": "def block ( seed ) : num = SAMPLE_RATE * BLOCK_SIZE rng = RandomState ( seed % 2 ** 32 ) variance = SAMPLE_RATE / 2 return rng . normal ( size = num , scale = variance ** 0.5 )", "docstring_tokens": "Return block of normal random numbers", "label": 0 }, { "idx": "cosqa-dev-598", "doc": "if matches a set of strings python", "code": "def any_contains_any(strings, candidates):\n \"\"\"Whether any of the strings contains any of the candidates.\"\"\"\n for string in strings:\n for c in candidates:\n if c in string:\n return True", "code_tokens": "def any_contains_any ( strings , candidates ) : for string in strings : for c in candidates : if c in string : return True", "docstring_tokens": "Whether any of the strings contains any of the candidates .", "label": 1 }, { "idx": "cosqa-dev-599", "doc": "python loop skip first line", "code": "def _skip_section(self):\n \"\"\"Skip a section\"\"\"\n self._last = self._f.readline()\n while len(self._last) > 0 and len(self._last[0].strip()) == 0:\n self._last = self._f.readline()", "code_tokens": "def _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )", "docstring_tokens": "Skip a section", "label": 0 }, { "idx": "cosqa-dev-600", "doc": "python dict all values identical", "code": "def make_symmetric(dict):\n \"\"\"Makes the given dictionary symmetric. Values are assumed to be unique.\"\"\"\n for key, value in list(dict.items()):\n dict[value] = key\n return dict", "code_tokens": "def make_symmetric ( dict ) : for key , value in list ( dict . items ( ) ) : dict [ value ] = key return dict", "docstring_tokens": "Makes the given dictionary symmetric . Values are assumed to be unique .", "label": 0 }, { "idx": "cosqa-dev-601", "doc": "python detect type of namedtuple", "code": "def isnamedtuple(obj):\n \"\"\"Heuristic check if an object is a namedtuple.\"\"\"\n return isinstance(obj, tuple) \\\n and hasattr(obj, \"_fields\") \\\n and hasattr(obj, \"_asdict\") \\\n and callable(obj._asdict)", "code_tokens": "def isnamedtuple ( obj ) : return isinstance ( obj , tuple ) and hasattr ( obj , \"_fields\" ) and hasattr ( obj , \"_asdict\" ) and callable ( obj . _asdict )", "docstring_tokens": "Heuristic check if an object is a namedtuple .", "label": 1 }, { "idx": "cosqa-dev-602", "doc": "how to define a empty data frame in 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 }, { "idx": "cosqa-dev-603", "doc": "zstring pad zero python", "code": "def zfill(x, width):\n \"\"\"zfill(x, width) -> string\n\n Pad a numeric string x with zeros on the left, to fill a field\n of the specified width. The string x is never truncated.\n\n \"\"\"\n if not isinstance(x, basestring):\n x = repr(x)\n return x.zfill(width)", "code_tokens": "def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )", "docstring_tokens": "zfill ( x width ) - > string", "label": 1 } ]