code_tokens
stringlengths
60
3.94k
label
int64
0
1
doc
stringlengths
16
98
docstring_tokens
stringlengths
0
1.41k
idx
stringlengths
13
17
code
stringlengths
87
6.4k
def is_connected ( self ) : try : return self . socket is not None and self . socket . getsockname ( ) [ 1 ] != 0 and BaseTransport . is_connected ( self ) except socket . error : return False
1
python check if the server is network connected
Return true if the socket managed by this connection is connected
cosqa-train-12600
def is_connected(self): """ Return true if the socket managed by this connection is connected :rtype: bool """ try: return self.socket is not None and self.socket.getsockname()[1] != 0 and BaseTransport.is_connected(self) except socket.error: return False
def getBuffer ( x ) : b = bytes ( x ) return ( c_ubyte * len ( b ) ) . from_buffer_copy ( bytes ( x ) )
0
turning a ctype pointer into a python buffer
Copy
cosqa-train-12601
def getBuffer(x): """ Copy @x into a (modifiable) ctypes byte array """ b = bytes(x) return (c_ubyte * len(b)).from_buffer_copy(bytes(x))
def boxes_intersect ( box1 , box2 ) : xmin1 , xmax1 , ymin1 , ymax1 = box1 xmin2 , xmax2 , ymin2 , ymax2 = box2 if interval_intersection_width ( xmin1 , xmax1 , xmin2 , xmax2 ) and interval_intersection_width ( ymin1 , ymax1 , ymin2 , ymax2 ) : return True else : return False
1
python check if two intervals intersect
Determines if two rectangles each input as a tuple ( xmin xmax ymin ymax ) intersect .
cosqa-train-12602
def boxes_intersect(box1, box2): """Determines if two rectangles, each input as a tuple (xmin, xmax, ymin, ymax), intersect.""" xmin1, xmax1, ymin1, ymax1 = box1 xmin2, xmax2, ymin2, ymax2 = box2 if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \ interval_intersection_width(ymin1, ymax1, ymin2, ymax2): return True else: return False
def sbatch_template ( self ) : template = self . sbatch_template_str if template . startswith ( '#!' ) : # script is embedded in YAML return jinja_environment . from_string ( template ) return jinja_environment . get_template ( template )
1
twig template for python
: return Jinja sbatch template for the current tag
cosqa-train-12603
def sbatch_template(self): """:return Jinja sbatch template for the current tag""" template = self.sbatch_template_str if template.startswith('#!'): # script is embedded in YAML return jinja_environment.from_string(template) return jinja_environment.get_template(template)
def is_local_url ( target ) : ref_url = urlparse ( request . host_url ) test_url = urlparse ( urljoin ( request . host_url , target ) ) return test_url . scheme in ( 'http' , 'https' ) and ref_url . netloc == test_url . netloc
1
python check if url local
Determine if URL is safe to redirect to .
cosqa-train-12604
def is_local_url(target): """Determine if URL is safe to redirect to.""" ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc
def post_tweet ( user_id , message , additional_params = { } ) : url = "https://api.twitter.com/1.1/statuses/update.json" params = { "status" : message } params . update ( additional_params ) r = make_twitter_request ( url , user_id , params , request_type = 'POST' ) print ( r . text ) return "Successfully posted a tweet {}" . format ( message )
1
twitter api python tweeting with hashtag
Helper function to post a tweet
cosqa-train-12605
def post_tweet(user_id, message, additional_params={}): """ Helper function to post a tweet """ url = "https://api.twitter.com/1.1/statuses/update.json" params = { "status" : message } params.update(additional_params) r = make_twitter_request(url, user_id, params, request_type='POST') print (r.text) return "Successfully posted a tweet {}".format(message)
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
0
python check if user is root
Decorator to make sure that user is root .
cosqa-train-12606
def require_root(fn): """ Decorator to make sure, that user is root. """ @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
def sort_func ( self , key ) : if key == self . _KEYS . VALUE : return 'aaa' if key == self . _KEYS . SOURCE : return 'zzz' return key
1
two key for sort python
Sorting logic for Quantity objects .
cosqa-train-12607
def sort_func(self, key): """Sorting logic for `Quantity` objects.""" if key == self._KEYS.VALUE: return 'aaa' if key == self._KEYS.SOURCE: return 'zzz' return key
def is_enum_type ( type_ ) : return isinstance ( type_ , type ) and issubclass ( type_ , tuple ( _get_types ( Types . ENUM ) ) )
1
python check if value is enumvalue
Checks if the given type is an enum type .
cosqa-train-12608
def is_enum_type(type_): """ Checks if the given type is an enum type. :param type_: The type to check :return: True if the type is a enum type, otherwise False :rtype: bool """ return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))
def remove_from_lib ( self , name ) : self . __remove_path ( os . path . join ( self . root_dir , "lib" , name ) )
1
ubuntu remove item in pythonpath
Remove an object from the bin folder .
cosqa-train-12609
def remove_from_lib(self, name): """ Remove an object from the bin folder. """ self.__remove_path(os.path.join(self.root_dir, "lib", name))
def is_float_array ( l ) : if isinstance ( l , np . ndarray ) : if l . dtype . kind == 'f' : return True return False
1
python check if variable is list of floats
r Checks if l is a numpy array of floats ( any dimension
cosqa-train-12610
def is_float_array(l): r"""Checks if l is a numpy array of floats (any dimension """ if isinstance(l, np.ndarray): if l.dtype.kind == 'f': return True return False
def log_normalize ( data ) : if sp . issparse ( data ) : data = data . copy ( ) data . data = np . log2 ( data . data + 1 ) return data return np . log2 ( data . astype ( np . float64 ) + 1 )
1
un do log transformation in python
Perform log transform log ( x + 1 ) . Parameters ---------- data : array_like
cosqa-train-12611
def log_normalize(data): """Perform log transform log(x + 1). Parameters ---------- data : array_like """ if sp.issparse(data): data = data.copy() data.data = np.log2(data.data + 1) return data return np.log2(data.astype(np.float64) + 1)
def is_valid_image_extension ( file_path ) : valid_extensions = [ '.jpeg' , '.jpg' , '.gif' , '.png' ] _ , extension = os . path . splitext ( file_path ) return extension . lower ( ) in valid_extensions
1
python check is a file has a specific extension
is_valid_image_extension .
cosqa-train-12612
def is_valid_image_extension(file_path): """is_valid_image_extension.""" valid_extensions = ['.jpeg', '.jpg', '.gif', '.png'] _, extension = os.path.splitext(file_path) return extension.lower() in valid_extensions
def _config_section ( config , section ) : path = os . path . join ( config . get ( 'config_path' ) , config . get ( 'config_file' ) ) conf = _config_ini ( path ) return conf . get ( section )
1
unable to get section in configuration ini file in python
Read the configuration file and return a section .
cosqa-train-12613
def _config_section(config, section): """Read the configuration file and return a section.""" path = os.path.join(config.get('config_path'), config.get('config_file')) conf = _config_ini(path) return conf.get(section)
def is_sequence ( obj ) : return isinstance ( obj , Sequence ) and not ( isinstance ( obj , str ) or BinaryClass . is_valid_type ( obj ) )
0
python check is nonetype
Check if obj is a sequence but not a string or bytes .
cosqa-train-12614
def is_sequence(obj): """Check if `obj` is a sequence, but not a string or bytes.""" return isinstance(obj, Sequence) and not ( isinstance(obj, str) or BinaryClass.is_valid_type(obj))
def checkbox_uncheck ( self , force_check = False ) : if self . get_attribute ( 'checked' ) : self . click ( force_click = force_check )
1
unchecking a radio button python
Wrapper to uncheck a checkbox
cosqa-train-12615
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
def pid_exists ( pid ) : try : os . kill ( pid , 0 ) except OSError as exc : return exc . errno == errno . EPERM else : return True
1
python check process alive by pid
Determines if a system process identifer exists in process table .
cosqa-train-12616
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
def camelcase_underscore ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( )
1
underscore and double underscore in python
Convert camelcase names to underscore
cosqa-train-12617
def camelcase_underscore(name): """ Convert camelcase names to underscore """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def issubset ( self , other ) : self . _binary_sanity_check ( other ) return set . issubset ( self , other )
1
python check set contain subset
Report whether another set contains this RangeSet .
cosqa-train-12618
def issubset(self, other): """Report whether another set contains this RangeSet.""" self._binary_sanity_check(other) return set.issubset(self, other)
def unique_items ( seq ) : seen = set ( ) return [ x for x in seq if not ( x in seen or seen . add ( x ) ) ]
1
unique list python without set
Return the unique items from iterable * seq * ( in order ) .
cosqa-train-12619
def unique_items(seq): """Return the unique items from iterable *seq* (in order).""" seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
def stdin_readable ( ) : if not WINDOWS : try : return bool ( select ( [ sys . stdin ] , [ ] , [ ] , 0 ) [ 0 ] ) except Exception : logger . log_exc ( ) try : return not sys . stdin . isatty ( ) except Exception : logger . log_exc ( ) return False
1
python check stdin is not empty
Determine whether stdin has any data to read .
cosqa-train-12620
def stdin_readable(): """Determine whether stdin has any data to read.""" if not WINDOWS: try: return bool(select([sys.stdin], [], [], 0)[0]) except Exception: logger.log_exc() try: return not sys.stdin.isatty() except Exception: logger.log_exc() return False
def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests )
1
unit test python no unit tests were found
Run the unit tests .
cosqa-train-12621
def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
def any_contains_any ( strings , candidates ) : for string in strings : for c in candidates : if c in string : return True
1
python check string contains any string from a list
Whether any of the strings contains any of the candidates .
cosqa-train-12622
def any_contains_any(strings, candidates): """Whether any of the strings contains any of the candidates.""" for string in strings: for c in candidates: if c in string: return True
def date_to_timestamp ( date ) : date_tuple = date . timetuple ( ) timestamp = calendar . timegm ( date_tuple ) * 1000 return timestamp
1
unix timestamp milliseconds into date python
date to unix timestamp in milliseconds
cosqa-train-12623
def date_to_timestamp(date): """ date to unix timestamp in milliseconds """ date_tuple = date.timetuple() timestamp = calendar.timegm(date_tuple) * 1000 return timestamp
def starts_with_prefix_in_list ( text , prefixes ) : for prefix in prefixes : if text . startswith ( prefix ) : return True return False
1
python check string in another string prefix
Return True if the given string starts with one of the prefixes in the given list otherwise return False .
cosqa-train-12624
def starts_with_prefix_in_list(text, prefixes): """ Return True if the given string starts with one of the prefixes in the given list, otherwise return False. Arguments: text (str): Text to check for prefixes. prefixes (list): List of prefixes to check for. Returns: bool: True if the given text starts with any of the given prefixes, otherwise False. """ for prefix in prefixes: if text.startswith(prefix): return True return False
def OnUpdateFigurePanel ( self , event ) : if self . updating : return self . updating = True self . figure_panel . update ( self . get_figure ( self . code ) ) self . updating = False
1
update figure in python to show change
Redraw event handler for the figure panel
cosqa-train-12625
def OnUpdateFigurePanel(self, event): """Redraw event handler for the figure panel""" if self.updating: return self.updating = True self.figure_panel.update(self.get_figure(self.code)) self.updating = False
def cmp_contents ( filename1 , filename2 ) : with open_readable ( filename1 , 'rb' ) as fobj : contents1 = fobj . read ( ) with open_readable ( filename2 , 'rb' ) as fobj : contents2 = fobj . read ( ) return contents1 == contents2
1
python check two file same or not
Returns True if contents of the files are the same
cosqa-train-12626
def cmp_contents(filename1, filename2): """ Returns True if contents of the files are the same Parameters ---------- filename1 : str filename of first file to compare filename2 : str filename of second file to compare Returns ------- tf : bool True if binary contents of `filename1` is same as binary contents of `filename2`, False otherwise. """ with open_readable(filename1, 'rb') as fobj: contents1 = fobj.read() with open_readable(filename2, 'rb') as fobj: contents2 = fobj.read() return contents1 == contents2
def update_dict ( obj , dict , attributes ) : for attribute in attributes : if hasattr ( obj , attribute ) and getattr ( obj , attribute ) is not None : dict [ attribute ] = getattr ( obj , attribute )
1
updating object attributes in a function python
Update dict with fields from obj . attributes .
cosqa-train-12627
def update_dict(obj, dict, attributes): """Update dict with fields from obj.attributes. :param obj: the object updated into dict :param dict: the result dictionary :param attributes: a list of attributes belonging to obj """ for attribute in attributes: if hasattr(obj, attribute) and getattr(obj, attribute) is not None: dict[attribute] = getattr(obj, attribute)
def is_same_shape ( self , other_im , check_channels = False ) : if self . height == other_im . height and self . width == other_im . width : if check_channels and self . channels != other_im . channels : return False return True return False
1
python check two image same
Checks if two images have the same height and width ( and optionally channels ) .
cosqa-train-12628
def is_same_shape(self, other_im, check_channels=False): """ Checks if two images have the same height and width (and optionally channels). Parameters ---------- other_im : :obj:`Image` image to compare check_channels : bool whether or not to check equality of the channels Returns ------- bool True if the images are the same shape, False otherwise """ if self.height == other_im.height and self.width == other_im.width: if check_channels and self.channels != other_im.channels: return False return True return False
def get_url_args ( url ) : url_data = urllib . parse . urlparse ( url ) arg_dict = urllib . parse . parse_qs ( url_data . query ) return arg_dict
1
urlparse python 3 get params
Returns a dictionary from a URL params
cosqa-train-12629
def get_url_args(url): """ Returns a dictionary from a URL params """ url_data = urllib.parse.urlparse(url) arg_dict = urllib.parse.parse_qs(url_data.query) return arg_dict
def is_value_type_valid_for_exact_conditions ( self , value ) : # No need to check for bool since bool is a subclass of int if isinstance ( value , string_types ) or isinstance ( value , ( numbers . Integral , float ) ) : return True return False
1
python check type equals to
Method to validate if the value is valid for exact match type evaluation .
cosqa-train-12630
def is_value_type_valid_for_exact_conditions(self, value): """ Method to validate if the value is valid for exact match type evaluation. Args: value: Value to validate. Returns: Boolean: True if value is a string, boolean, or number. Otherwise False. """ # No need to check for bool since bool is a subclass of int if isinstance(value, string_types) or isinstance(value, (numbers.Integral, float)): return True return False
def input_int_default ( question = "" , default = 0 ) : answer = input_string ( question ) if answer == "" or answer == "yes" : return default else : return int ( answer )
0
use default value python
A function that works for both Python 2 . x and Python 3 . x . It asks the user for input and returns it as a string .
cosqa-train-12631
def input_int_default(question="", default=0): """A function that works for both, Python 2.x and Python 3.x. It asks the user for input and returns it as a string. """ answer = input_string(question) if answer == "" or answer == "yes": return default else: return int(answer)
def is_file ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_file ( ) except AttributeError : return os . path . isfile ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) )
0
python check whether a path is a file
Determine if a Path or string is a file on the file system .
cosqa-train-12632
def is_file(path): """Determine if a Path or string is a file on the file system.""" try: return path.expanduser().absolute().is_file() except AttributeError: return os.path.isfile(os.path.abspath(os.path.expanduser(str(path))))
def newest_file ( file_iterable ) : return max ( file_iterable , key = lambda fname : os . path . getmtime ( fname ) )
1
use most recent file in python
Returns the name of the newest file given an iterable of file names .
cosqa-train-12633
def newest_file(file_iterable): """ Returns the name of the newest file given an iterable of file names. """ return max(file_iterable, key=lambda fname: os.path.getmtime(fname))
def is_iterable ( value ) : return isinstance ( value , np . ndarray ) or isinstance ( value , list ) or isinstance ( value , tuple ) , value
1
python check whether a value is iterable
must be an iterable ( list array tuple )
cosqa-train-12634
def is_iterable(value): """must be an iterable (list, array, tuple)""" return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value
def setConfigKey ( key , value ) : configFile = ConfigurationManager . _configFile ( ) return JsonDataManager ( configFile ) . setKey ( key , value )
0
use python dictionary as configure file
Sets the config data value for the specified dictionary key
cosqa-train-12635
def setConfigKey(key, value): """ Sets the config data value for the specified dictionary key """ configFile = ConfigurationManager._configFile() return JsonDataManager(configFile).setKey(key, value)
def is_iterable_of_int ( l ) : if not is_iterable ( l ) : return False return all ( is_int ( value ) for value in l )
1
python checking equality of integr list element to integer
r Checks if l is iterable and contains only integral types
cosqa-train-12636
def is_iterable_of_int(l): r""" Checks if l is iterable and contains only integral types """ if not is_iterable(l): return False return all(is_int(value) for value in l)
def __next__ ( self , reward , ask_id , lbl ) : return self . next ( reward , ask_id , lbl )
1
use python next to iterate through
For Python3 compatibility of generator .
cosqa-train-12637
def __next__(self, reward, ask_id, lbl): """For Python3 compatibility of generator.""" return self.next(reward, ask_id, lbl)
def is_valid_file ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . exists ( arg ) : parser . error ( "The file %s does not exist!" % arg ) else : return arg
1
python checking that a file is there
Check if arg is a valid file that already exists on the file system .
cosqa-train-12638
def is_valid_file(parser, arg): """Check if arg is a valid file that already exists on the file system.""" arg = os.path.abspath(arg) if not os.path.exists(arg): parser.error("The file %s does not exist!" % arg) else: return arg
def update ( self , other_dict ) : for key , value in iter_multi_items ( other_dict ) : MultiDict . add ( self , key , value )
1
use update for dictionary inside of a comprehension in python
update () extends rather than replaces existing key lists .
cosqa-train-12639
def update(self, other_dict): """update() extends rather than replaces existing key lists.""" for key, value in iter_multi_items(other_dict): MultiDict.add(self, key, value)
def find_largest_contig ( contig_lengths_dict ) : # Initialise the dictionary longest_contig_dict = dict ( ) for file_name , contig_lengths in contig_lengths_dict . items ( ) : # As the list is sorted in descending order, the largest contig is the first entry in the list longest_contig_dict [ file_name ] = contig_lengths [ 0 ] return longest_contig_dict
1
python checking to see the longest list in a dictionary
Determine the largest contig for each strain : param contig_lengths_dict : dictionary of strain name : reverse - sorted list of all contig lengths : return : longest_contig_dict : dictionary of strain name : longest contig
cosqa-train-12640
def find_largest_contig(contig_lengths_dict): """ Determine the largest contig for each strain :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :return: longest_contig_dict: dictionary of strain name: longest contig """ # Initialise the dictionary longest_contig_dict = dict() for file_name, contig_lengths in contig_lengths_dict.items(): # As the list is sorted in descending order, the largest contig is the first entry in the list longest_contig_dict[file_name] = contig_lengths[0] return longest_contig_dict
def retry_call ( func , cleanup = lambda : None , retries = 0 , trap = ( ) ) : attempts = count ( ) if retries == float ( 'inf' ) else range ( retries ) for attempt in attempts : try : return func ( ) except trap : cleanup ( ) return func ( )
1
using a loop in a try catch block python
Given a callable func trap the indicated exceptions for up to retries times invoking cleanup on the exception . On the final attempt allow any exceptions to propagate .
cosqa-train-12641
def retry_call(func, cleanup=lambda: None, retries=0, trap=()): """ Given a callable func, trap the indicated exceptions for up to 'retries' times, invoking cleanup on the exception. On the final attempt, allow any exceptions to propagate. """ attempts = count() if retries == float('inf') else range(retries) for attempt in attempts: try: return func() except trap: cleanup() return func()
def kill_mprocess ( process ) : if process and proc_alive ( process ) : process . terminate ( ) process . communicate ( ) return not proc_alive ( process )
1
python child process not exit
kill process Args : process - Popen object for process
cosqa-train-12642
def kill_mprocess(process): """kill process Args: process - Popen object for process """ if process and proc_alive(process): process.terminate() process.communicate() return not proc_alive(process)
def inpaint ( self ) : import inpaint filled = inpaint . replace_nans ( np . ma . filled ( self . raster_data , np . NAN ) . astype ( np . float32 ) , 3 , 0.01 , 2 ) self . raster_data = np . ma . masked_invalid ( filled )
1
using mask in images python
Replace masked - out elements in an array using an iterative image inpainting algorithm .
cosqa-train-12643
def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """ import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
def getBitmap ( self ) : return PlatformManager . getBitmapFromRect ( self . x , self . y , self . w , self . h )
1
python circle in a square bitmap array
Captures screen area of this region at least the part that is on the screen
cosqa-train-12644
def getBitmap(self): """ Captures screen area of this region, at least the part that is on the screen Returns image as numpy array """ return PlatformManager.getBitmapFromRect(self.x, self.y, self.w, self.h)
def generate_uuid ( ) : r_uuid = base64 . urlsafe_b64encode ( uuid . uuid4 ( ) . bytes ) return r_uuid . decode ( ) . replace ( '=' , '' )
0
uuid not serializable python
Generate a UUID .
cosqa-train-12645
def generate_uuid(): """Generate a UUID.""" r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) return r_uuid.decode().replace('=', '')
def clear_matplotlib_ticks ( self , axis = "both" ) : ax = self . get_axes ( ) plotting . clear_matplotlib_ticks ( ax = ax , axis = axis )
1
python clear all plots from axis
Clears the default matplotlib ticks .
cosqa-train-12646
def clear_matplotlib_ticks(self, axis="both"): """Clears the default matplotlib ticks.""" ax = self.get_axes() plotting.clear_matplotlib_ticks(ax=ax, axis=axis)
def get_neg_infinity ( dtype ) : if issubclass ( dtype . type , ( np . floating , np . integer ) ) : return - np . inf if issubclass ( dtype . type , np . complexfloating ) : return - np . inf - 1j * np . inf return NINF
0
value for infinity in python
Return an appropriate positive infinity for this dtype .
cosqa-train-12647
def get_neg_infinity(dtype): """Return an appropriate positive infinity for this dtype. Parameters ---------- dtype : np.dtype Returns ------- fill_value : positive infinity value corresponding to this dtype. """ if issubclass(dtype.type, (np.floating, np.integer)): return -np.inf if issubclass(dtype.type, np.complexfloating): return -np.inf - 1j * np.inf return NINF
def _removeLru ( self ) : ( dataFile , handle ) = self . _cache . pop ( ) handle . close ( ) return dataFile
1
python clear lru cache
Remove the least recently used file handle from the cache . The pop method removes an element from the right of the deque . Returns the name of the file that has been removed .
cosqa-train-12648
def _removeLru(self): """ Remove the least recently used file handle from the cache. The pop method removes an element from the right of the deque. Returns the name of the file that has been removed. """ (dataFile, handle) = self._cache.pop() handle.close() return dataFile
def make_symmetric ( dict ) : for key , value in list ( dict . items ( ) ) : dict [ value ] = key return dict
1
values of a dictionary must be unique in python
Makes the given dictionary symmetric . Values are assumed to be unique .
cosqa-train-12649
def make_symmetric(dict): """Makes the given dictionary symmetric. Values are assumed to be unique.""" for key, value in list(dict.items()): dict[value] = key return dict
def _clear ( self ) : self . _finished = False self . _measurement = None self . _message = None self . _message_body = None
1
python clearing all variables
Resets all assigned data for the current message .
cosqa-train-12650
def _clear(self): """Resets all assigned data for the current message.""" self._finished = False self._measurement = None self._message = None self._message_body = None
def dot_v2 ( vec1 , vec2 ) : return vec1 . x * vec2 . x + vec1 . y * vec2 . y
1
vector for 2 points python
Return the dot product of two vectors
cosqa-train-12651
def dot_v2(vec1, vec2): """Return the dot product of two vectors""" return vec1.x * vec2.x + vec1.y * vec2.y
def underline ( self , msg ) : return click . style ( msg , underline = True ) if self . colorize else msg
1
python click color help output
Underline the input
cosqa-train-12652
def underline(self, msg): """Underline the input""" return click.style(msg, underline=True) if self.colorize else msg
def apply ( f , obj , * args , * * kwargs ) : return vectorize ( f ) ( obj , * args , * * kwargs )
1
vectorize a python function
Apply a function in parallel to each element of the input
cosqa-train-12653
def apply(f, obj, *args, **kwargs): """Apply a function in parallel to each element of the input""" return vectorize(f)(obj, *args, **kwargs)
def close_database_session ( session ) : try : session . close ( ) except OperationalError as e : raise DatabaseError ( error = e . orig . args [ 1 ] , code = e . orig . args [ 0 ] )
1
python closing an sql connection
Close connection with the database
cosqa-train-12654
def close_database_session(session): """Close connection with the database""" try: session.close() except OperationalError as e: raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0])
def nonull_dict ( self ) : return { k : v for k , v in six . iteritems ( self . dict ) if v and k != '_codes' }
1
view the variables that are not null in python
Like dict but does not hold any null values .
cosqa-train-12655
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
def eval ( e , amplitude , e_0 , alpha , beta ) : ee = e / e_0 eeponent = - alpha - beta * np . log ( ee ) return amplitude * ee ** eeponent
1
python code for exponential and logarithmic
One dimenional log parabola model function
cosqa-train-12656
def eval(e, amplitude, e_0, alpha, beta): """One dimenional log parabola model function""" ee = e / e_0 eeponent = -alpha - beta * np.log(ee) return amplitude * ee ** eeponent
def home ( ) : return dict ( links = dict ( api = '{}{}' . format ( request . url , PREFIX [ 1 : ] ) ) ) , HTTPStatus . OK
0
what api gateway expects from a lambda python if true return status code 200 else return 400
Temporary helper function to link to the API routes
cosqa-train-12657
def home(): """Temporary helper function to link to the API routes""" return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \ HTTPStatus.OK
def update_screen ( self ) : self . clock . tick ( self . FPS ) pygame . display . update ( )
1
python code for screen updating
Refresh the screen . You don t need to override this except to update only small portins of the screen .
cosqa-train-12658
def update_screen(self): """Refresh the screen. You don't need to override this except to update only small portins of the screen.""" self.clock.tick(self.FPS) pygame.display.update()
def visit_ellipsis ( self , node , parent ) : return nodes . Ellipsis ( getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent )
1
what's an ellipsis in python
visit an Ellipsis node by returning a fresh instance of it
cosqa-train-12659
def visit_ellipsis(self, node, parent): """visit an Ellipsis node by returning a fresh instance of it""" return nodes.Ellipsis( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
def track_update ( self ) : metadata = self . info ( ) metadata . updated_at = dt . datetime . now ( ) self . commit ( )
1
python code for update the edited date in the attribute table
Update the lastest updated date in the database .
cosqa-train-12660
def track_update(self): """Update the lastest updated date in the database.""" metadata = self.info() metadata.updated_at = dt.datetime.now() self.commit()
def struct2dict ( struct ) : return { x : getattr ( struct , x ) for x in dict ( struct . _fields_ ) . keys ( ) }
1
whats are struct fields in python
convert a ctypes structure to a dictionary
cosqa-train-12661
def struct2dict(struct): """convert a ctypes structure to a dictionary""" return {x: getattr(struct, x) for x in dict(struct._fields_).keys()}
def strip_comment_marker ( text ) : lines = [ ] for line in text . splitlines ( ) : lines . append ( line . lstrip ( '#' ) ) text = textwrap . dedent ( '\n' . join ( lines ) ) return text
0
python code how to align comments
Strip # markers at the front of a block of comment text .
cosqa-train-12662
def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text
def get_width ( ) : # Get terminal size ws = struct . pack ( "HHHH" , 0 , 0 , 0 , 0 ) ws = fcntl . ioctl ( sys . stdout . fileno ( ) , termios . TIOCGWINSZ , ws ) lines , columns , x , y = struct . unpack ( "HHHH" , ws ) width = min ( columns * 39 // 40 , columns - 2 ) return width
1
windows cmd python display width
Get terminal width
cosqa-train-12663
def get_width(): """Get terminal width""" # Get terminal size ws = struct.pack("HHHH", 0, 0, 0, 0) ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws) lines, columns, x, y = struct.unpack("HHHH", ws) width = min(columns * 39 // 40, columns - 2) return width
def is_cyclic ( graph ) : path = set ( ) def visit ( vertex ) : path . add ( vertex ) for neighbour in graph . get ( vertex , ( ) ) : if neighbour in path or visit ( neighbour ) : return True path . remove ( vertex ) return False return any ( visit ( v ) for v in graph )
1
python code that sees if a graph has a cycle
Return True if the directed graph g has a cycle . The directed graph should be represented as a dictionary mapping of edges for each node .
cosqa-train-12664
def is_cyclic(graph): """ Return True if the directed graph g has a cycle. The directed graph should be represented as a dictionary mapping of edges for each node. """ path = set() def visit(vertex): path.add(vertex) for neighbour in graph.get(vertex, ()): if neighbour in path or visit(neighbour): return True path.remove(vertex) return False return any(visit(v) for v in graph)
def coverage ( ctx , opts = "" ) : return test ( ctx , coverage = True , include_slow = True , opts = opts )
1
with coverage python unittest
Execute all tests ( normal and slow ) with coverage enabled .
cosqa-train-12665
def coverage(ctx, opts=""): """ Execute all tests (normal and slow) with coverage enabled. """ return test(ctx, coverage=True, include_slow=True, opts=opts)
def hex_escape ( bin_str ) : printable = string . ascii_letters + string . digits + string . punctuation + ' ' return '' . join ( ch if ch in printable else r'0x{0:02x}' . format ( ord ( ch ) ) for ch in bin_str )
1
python code to change binary to letters
Hex encode a binary string
cosqa-train-12666
def hex_escape(bin_str): """ Hex encode a binary string """ printable = string.ascii_letters + string.digits + string.punctuation + ' ' return ''.join(ch if ch in printable else r'0x{0:02x}'.format(ord(ch)) for ch in bin_str)
def scale_v2 ( vec , amount ) : return Vec2 ( vec . x * amount , vec . y * amount )
1
wrap a vector python
Return a new Vec2 with x and y from vec and multiplied by amount .
cosqa-train-12667
def scale_v2(vec, amount): """Return a new Vec2 with x and y from vec and multiplied by amount.""" return Vec2(vec.x * amount, vec.y * amount)
def allsame ( list_ , strict = True ) : if len ( list_ ) == 0 : return True first_item = list_ [ 0 ] return list_all_eq_to ( list_ , first_item , strict )
1
python code to check if all elements in a list are equal
checks to see if list is equal everywhere
cosqa-train-12668
def allsame(list_, strict=True): """ checks to see if list is equal everywhere Args: list_ (list): Returns: True if all items in the list are equal """ if len(list_) == 0: return True first_item = list_[0] return list_all_eq_to(list_, first_item, strict)
def software_fibonacci ( n ) : a , b = 0 , 1 for i in range ( n ) : a , b = b , a + b return a
1
write a function that returns a list of the numbers of the fibonacci series up to n python
a normal old python function to return the Nth fibonacci number .
cosqa-train-12669
def software_fibonacci(n): """ a normal old python function to return the Nth fibonacci number. """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a
def is_password_valid ( password ) : pattern = re . compile ( r"^.{4,75}$" ) return bool ( pattern . match ( password ) )
1
python code to check if password is valid regex
Check if a password is valid
cosqa-train-12670
def is_password_valid(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
def is_equal_strings_ignore_case ( first , second ) : if first and second : return first . upper ( ) == second . upper ( ) else : return not ( first or second )
1
write a function to compare two strings ignoring case in python
The function compares strings ignoring case
cosqa-train-12671
def is_equal_strings_ignore_case(first, second): """The function compares strings ignoring case""" if first and second: return first.upper() == second.upper() else: return not (first or second)
def is_adb_detectable ( self ) : serials = list_adb_devices ( ) if self . serial in serials : self . log . debug ( 'Is now adb detectable.' ) return True return False
1
python code to detect ble devices
Checks if USB is on and device is ready by verifying adb devices .
cosqa-train-12672
def is_adb_detectable(self): """Checks if USB is on and device is ready by verifying adb devices.""" serials = list_adb_devices() if self.serial in serials: self.log.debug('Is now adb detectable.') return True return False
def subsystem ( s ) : node_states ( s . state ) cut ( s . cut , s . cut_indices ) if config . VALIDATE_SUBSYSTEM_STATES : state_reachable ( s ) return True
1
write a python function to determine if is valid cut
Validate a |Subsystem| .
cosqa-train-12673
def subsystem(s): """Validate a |Subsystem|. Checks its state and cut. """ node_states(s.state) cut(s.cut, s.cut_indices) if config.VALIDATE_SUBSYSTEM_STATES: state_reachable(s) return True
def get_oauth_token ( ) : url = "{0}/token" . format ( DEFAULT_ORIGIN [ "Origin" ] ) r = s . get ( url = url ) return r . json ( ) [ "t" ]
1
python code to get refresh token on sandbox using oauth
Retrieve a simple OAuth Token for use with the local http client .
cosqa-train-12674
def get_oauth_token(): """Retrieve a simple OAuth Token for use with the local http client.""" url = "{0}/token".format(DEFAULT_ORIGIN["Origin"]) r = s.get(url=url) return r.json()["t"]
def write_line ( self , line , count = 1 ) : self . write ( line ) self . write_newlines ( count )
1
write another line after write python
writes the line and count newlines after the line
cosqa-train-12675
def write_line(self, line, count=1): """writes the line and count newlines after the line""" self.write(line) self.write_newlines(count)
def remove_from_lib ( self , name ) : self . __remove_path ( os . path . join ( self . root_dir , "lib" , name ) )
1
python code to remove file from a folder
Remove an object from the bin folder .
cosqa-train-12676
def remove_from_lib(self, name): """ Remove an object from the bin folder. """ self.__remove_path(os.path.join(self.root_dir, "lib", name))
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
1
python code to remove pixels from an image
Trim a PIL image and remove white space .
cosqa-train-12677
def _trim(image): """Trim a PIL image and remove white space.""" 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
def to_dotfile ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . write ( filename )
1
write graph data to gml in python
Output a networkx graph to a DOT file .
cosqa-train-12678
def to_dotfile(G: nx.DiGraph, filename: str): """ Output a networkx graph to a DOT file. """ A = to_agraph(G) A.write(filename)
def template_substitute ( text , * * kwargs ) : for name , value in kwargs . items ( ) : placeholder_pattern = "{%s}" % name if placeholder_pattern in text : text = text . replace ( placeholder_pattern , value ) return text
1
python code to replace data in a template text
Replace placeholders in text by using the data mapping . Other placeholders that is not represented by data is left untouched .
cosqa-train-12679
def template_substitute(text, **kwargs): """ Replace placeholders in text by using the data mapping. Other placeholders that is not represented by data is left untouched. :param text: Text to search and replace placeholders. :param data: Data mapping/dict for placeholder key and values. :return: Potentially modified text with replaced placeholders. """ for name, value in kwargs.items(): placeholder_pattern = "{%s}" % name if placeholder_pattern in text: text = text.replace(placeholder_pattern, value) return text
def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )
1
write image warp function python
Apply last 2D transforms
cosqa-train-12680
def post_process(self): """ Apply last 2D transforms""" self.image.putdata(self.pixels) self.image = self.image.transpose(Image.ROTATE_90)
def all_collections ( db ) : include_pattern = r'(?!system\.)' return ( db [ name ] for name in db . list_collection_names ( ) if re . match ( include_pattern , name ) )
1
python code to retrieve all the collections in the database of mongodb using pyhon
Yield all non - sytem collections in db .
cosqa-train-12681
def all_collections(db): """ Yield all non-sytem collections in db. """ include_pattern = r'(?!system\.)' return ( db[name] for name in db.list_collection_names() if re.match(include_pattern, name) )
def _serialize_json ( obj , fp ) : json . dump ( obj , fp , indent = 4 , default = serialize )
1
write json object to a file in python
Serialize obj as a JSON formatted stream to fp
cosqa-train-12682
def _serialize_json(obj, fp): """ Serialize ``obj`` as a JSON formatted stream to ``fp`` """ json.dump(obj, fp, indent=4, default=serialize)
def calculate_month ( birth_date ) : year = int ( birth_date . strftime ( '%Y' ) ) month = int ( birth_date . strftime ( '%m' ) ) + ( ( int ( year / 100 ) - 14 ) % 5 ) * 20 return month
1
python coding how to get month
Calculates and returns a month number basing on PESEL standard .
cosqa-train-12683
def calculate_month(birth_date): """ Calculates and returns a month number basing on PESEL standard. """ year = int(birth_date.strftime('%Y')) month = int(birth_date.strftime('%m')) + ((int(year / 100) - 14) % 5) * 20 return month
def _dump_spec ( spec ) : with open ( "spec.yaml" , "w" ) as f : yaml . dump ( spec , f , Dumper = MyDumper , default_flow_style = False )
1
writing single comment line to yaml in python
Dump bel specification dictionary using YAML
cosqa-train-12684
def _dump_spec(spec): """Dump bel specification dictionary using YAML Formats this with an extra indentation for lists to make it easier to use cold folding on the YAML version of the spec dictionary. """ with open("spec.yaml", "w") as f: yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)
def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . _freeze ( ) == other . _freeze ( )
1
writing test fro object equality python
Determine if two objects are equal .
cosqa-train-12685
def __eq__(self, other): """Determine if two objects are equal.""" return isinstance(other, self.__class__) \ and self._freeze() == other._freeze()
def onchange ( self , value ) : log . debug ( 'combo box. selected %s' % value ) self . select_by_value ( value ) return ( value , )
1
python combobox action value
Called when a new DropDownItem gets selected .
cosqa-train-12686
def onchange(self, value): """Called when a new DropDownItem gets selected. """ log.debug('combo box. selected %s' % value) self.select_by_value(value) return (value, )
def _tool_to_dict ( tool ) : out = { "name" : _id_to_name ( tool . tool [ "id" ] ) , "baseCommand" : " " . join ( tool . tool [ "baseCommand" ] ) , "arguments" : [ ] , "inputs" : [ _input_to_dict ( i ) for i in tool . tool [ "inputs" ] ] , "outputs" : [ _output_to_dict ( o ) for o in tool . tool [ "outputs" ] ] , "requirements" : _requirements_to_dict ( tool . requirements + tool . hints ) , "stdin" : None , "stdout" : None } return out
0
wsdl to python dict
Parse a tool definition into a cwl2wdl style dictionary .
cosqa-train-12687
def _tool_to_dict(tool): """Parse a tool definition into a cwl2wdl style dictionary. """ out = {"name": _id_to_name(tool.tool["id"]), "baseCommand": " ".join(tool.tool["baseCommand"]), "arguments": [], "inputs": [_input_to_dict(i) for i in tool.tool["inputs"]], "outputs": [_output_to_dict(o) for o in tool.tool["outputs"]], "requirements": _requirements_to_dict(tool.requirements + tool.hints), "stdin": None, "stdout": None} return out
def compare ( string1 , string2 ) : if len ( string1 ) != len ( string2 ) : return False result = True for c1 , c2 in izip ( string1 , string2 ) : result &= c1 == c2 return result
1
python compare each characters of two string
Compare two strings while protecting against timing attacks
cosqa-train-12688
def compare(string1, string2): """Compare two strings while protecting against timing attacks :param str string1: the first string :param str string2: the second string :returns: True if the strings are equal, False if not :rtype: :obj:`bool` """ if len(string1) != len(string2): return False result = True for c1, c2 in izip(string1, string2): result &= c1 == c2 return result
def on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )
1
wxpython can not close a window
Pop - up menu and wx . EVT_CLOSE closing event
cosqa-train-12689
def on_close(self, evt): """ Pop-up menu and wx.EVT_CLOSE closing event """ self.stop() # DoseWatcher if evt.EventObject is not self: # Avoid deadlocks self.Close() # wx.Frame evt.Skip()
def is_instance_or_subclass ( val , class_ ) : try : return issubclass ( val , class_ ) except TypeError : return isinstance ( val , class_ )
1
python compare is instance
Return True if val is either a subclass or instance of class_ .
cosqa-train-12690
def is_instance_or_subclass(val, class_): """Return True if ``val`` is either a subclass or instance of ``class_``.""" try: return issubclass(val, class_) except TypeError: return isinstance(val, class_)
def on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )
1
wxpython close panel on event
Pop - up menu and wx . EVT_CLOSE closing event
cosqa-train-12691
def on_close(self, evt): """ Pop-up menu and wx.EVT_CLOSE closing event """ self.stop() # DoseWatcher if evt.EventObject is not self: # Avoid deadlocks self.Close() # wx.Frame evt.Skip()
def _check_for_int ( x ) : try : y = int ( x ) except ( OverflowError , ValueError ) : pass else : # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x : return y return x
1
python comparison float int
This is a compatibility function that takes a C { float } and converts it to an C { int } if the values are equal .
cosqa-train-12692
def _check_for_int(x): """ This is a compatibility function that takes a C{float} and converts it to an C{int} if the values are equal. """ try: y = int(x) except (OverflowError, ValueError): pass else: # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x: return y return x
def disable_wx ( self ) : if self . _apps . has_key ( GUI_WX ) : self . _apps [ GUI_WX ] . _in_event_loop = False self . clear_inputhook ( )
1
wxpython discard event during disable
Disable event loop integration with wxPython .
cosqa-train-12693
def disable_wx(self): """Disable event loop integration with wxPython. This merely sets PyOS_InputHook to NULL. """ if self._apps.has_key(GUI_WX): self._apps[GUI_WX]._in_event_loop = False self.clear_inputhook()
def _compile ( pattern , flags ) : return re . compile ( WcParse ( pattern , flags & FLAG_MASK ) . parse ( ) )
1
python compile regex with flag
Compile the pattern to regex .
cosqa-train-12694
def _compile(pattern, flags): """Compile the pattern to regex.""" return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
def on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )
0
wxpython no close window
Pop - up menu and wx . EVT_CLOSE closing event
cosqa-train-12695
def on_close(self, evt): """ Pop-up menu and wx.EVT_CLOSE closing event """ self.stop() # DoseWatcher if evt.EventObject is not self: # Avoid deadlocks self.Close() # wx.Frame evt.Skip()
def generate_hash ( filepath ) : fr = FileReader ( filepath ) data = fr . read_bin ( ) return _calculate_sha256 ( data )
1
python compute hash of file
Public function that reads a local file and generates a SHA256 hash digest for it
cosqa-train-12696
def generate_hash(filepath): """Public function that reads a local file and generates a SHA256 hash digest for it""" fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(data)
def average ( iterator ) : count = 0 total = 0 for num in iterator : count += 1 total += num return float ( total ) / count
1
x for x in python means
Iterative mean .
cosqa-train-12697
def average(iterator): """Iterative mean.""" count = 0 total = 0 for num in iterator: count += 1 total += num return float(total)/count
def lower_ext ( abspath ) : fname , ext = os . path . splitext ( abspath ) return fname + ext . lower ( )
1
python concat file name to file extension with wildcard
Convert file extension to lowercase .
cosqa-train-12698
def lower_ext(abspath): """Convert file extension to lowercase. """ fname, ext = os.path.splitext(abspath) return fname + ext.lower()
def str_is_well_formed ( xml_str ) : try : str_to_etree ( xml_str ) except xml . etree . ElementTree . ParseError : return False else : return True
1
xml wellform check python
Args : xml_str : str DataONE API XML doc .
cosqa-train-12699
def str_is_well_formed(xml_str): """ Args: xml_str : str DataONE API XML doc. Returns: bool: **True** if XML doc is well formed. """ try: str_to_etree(xml_str) except xml.etree.ElementTree.ParseError: return False else: return True