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_callable ( * p ) : import symbols return all ( isinstance ( x , symbols . FUNCTION ) for x in p ) | 1 | check if arg is function python | True if all the args are functions and / or subroutines | cosqa-train-200 | def is_callable(*p):
""" True if all the args are functions and / or subroutines
"""
import symbols
return all(isinstance(x, symbols.FUNCTION) for x in p) |
async def disconnect ( self ) : if not self . connected : return self . writer . close ( ) self . reader = None self . writer = None | 1 | python disconnect shared connection | Disconnect from target . | cosqa-train-201 | async def disconnect(self):
""" Disconnect from target. """
if not self.connected:
return
self.writer.close()
self.reader = None
self.writer = None |
def is_dataframe ( obj ) : try : # This is the best method of type checking from pandas import DataFrame return isinstance ( obj , DataFrame ) except ImportError : # Pandas is not a dependency, so this is scary return obj . __class__ . __name__ == "DataFrame" | 1 | check if column is object in python | Returns True if the given object is a Pandas Data Frame . | cosqa-train-202 | def is_dataframe(obj):
"""
Returns True if the given object is a Pandas Data Frame.
Parameters
----------
obj: instance
The object to test whether or not is a Pandas DataFrame.
"""
try:
# This is the best method of type checking
from pandas import DataFrame
return isinstance(obj, DataFrame)
except ImportError:
# Pandas is not a dependency, so this is scary
return obj.__class__.__name__ == "DataFrame" |
def test ( ) : import unittest tests = unittest . TestLoader ( ) . discover ( 'tests' ) unittest . TextTestRunner ( verbosity = 2 ) . run ( tests ) | 0 | python discover unit tests | Run the unit tests . | cosqa-train-203 | def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests) |
def is_datetime_like ( dtype ) : return ( np . issubdtype ( dtype , np . datetime64 ) or np . issubdtype ( dtype , np . timedelta64 ) ) | 1 | check if datetime python | Check if a dtype is a subclass of the numpy datetime types | cosqa-train-204 | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) |
def serialize_json_string ( self , value ) : # Check if the value might be a json string if not isinstance ( value , six . string_types ) : return value # Make sure it starts with a brace if not value . startswith ( '{' ) or value . startswith ( '[' ) : return value # Try to load the string try : return json . loads ( value ) except : return value | 1 | python disctionary from json string | Tries to load an encoded json string back into an object : param json_string : : return : | cosqa-train-205 | def serialize_json_string(self, value):
"""
Tries to load an encoded json string back into an object
:param json_string:
:return:
"""
# Check if the value might be a json string
if not isinstance(value, six.string_types):
return value
# Make sure it starts with a brace
if not value.startswith('{') or value.startswith('['):
return value
# Try to load the string
try:
return json.loads(value)
except:
return value |
def is_defined ( self , objtxt , force_import = False ) : return self . interpreter . is_defined ( objtxt , force_import ) | 1 | check if function is defined python | Return True if object is defined | cosqa-train-206 | def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import) |
def get_hline ( ) : return Window ( width = LayoutDimension . exact ( 1 ) , height = LayoutDimension . exact ( 1 ) , content = FillControl ( '-' , token = Token . Line ) ) | 0 | python display horizontal line | gets a horiztonal line | cosqa-train-207 | def get_hline():
""" gets a horiztonal line """
return Window(
width=LayoutDimension.exact(1),
height=LayoutDimension.exact(1),
content=FillControl('-', token=Token.Line)) |
def group_exists ( groupname ) : try : grp . getgrnam ( groupname ) group_exists = True except KeyError : group_exists = False return group_exists | 0 | check if group exists python | Check if a group exists | cosqa-train-208 | def group_exists(groupname):
"""Check if a group exists"""
try:
grp.getgrnam(groupname)
group_exists = True
except KeyError:
group_exists = False
return group_exists |
def sync ( self , recursive = False ) : self . syncTree ( recursive = recursive ) self . syncView ( recursive = recursive ) | 0 | python displaying data in two treeviews | Syncs the information from this item to the tree and view . | cosqa-train-209 | def sync(self, recursive=False):
"""
Syncs the information from this item to the tree and view.
"""
self.syncTree(recursive=recursive)
self.syncView(recursive=recursive) |
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 | 0 | check if images are identical python | Checks if two images have the same height and width ( and optionally channels ) . | cosqa-train-210 | 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_distance_between_two_points ( self , one , two ) : dx = one . x - two . x dy = one . y - two . y return math . sqrt ( dx * dx + dy * dy ) | 0 | python distance two points | Returns the distance between two XYPoints . | cosqa-train-211 | def get_distance_between_two_points(self, one, two):
"""Returns the distance between two XYPoints."""
dx = one.x - two.x
dy = one.y - two.y
return math.sqrt(dx * dx + dy * dy) |
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 | 0 | check if images are similar python | Checks if two images have the same height and width ( and optionally channels ) . | cosqa-train-212 | 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 _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items ) | 0 | check if multiple variables are none python | Whether the item is a placeholder or contains a placeholder . | cosqa-train-213 | def _not_none(items):
"""Whether the item is a placeholder or contains a placeholder."""
if not isinstance(items, (tuple, list)):
items = (items,)
return all(item is not _none for item in items) |
def delete_all_from_db ( ) : # The models.CASCADE property is set on all ForeignKey fields, so tables can # be deleted in any order without breaking constraints. for model in django . apps . apps . get_models ( ) : model . objects . all ( ) . delete ( ) | 1 | python django delete all rows in table | Clear the database . | cosqa-train-214 | def delete_all_from_db():
"""Clear the database.
Used for testing and debugging.
"""
# The models.CASCADE property is set on all ForeignKey fields, so tables can
# be deleted in any order without breaking constraints.
for model in django.apps.apps.get_models():
model.objects.all().delete() |
def is_complex ( dtype ) : dtype = tf . as_dtype ( dtype ) if hasattr ( dtype , 'is_complex' ) : return dtype . is_complex return np . issubdtype ( np . dtype ( dtype ) , np . complex ) | 1 | check if number is complex python | Returns whether this is a complex floating point type . | cosqa-train-215 | def is_complex(dtype):
"""Returns whether this is a complex floating point type."""
dtype = tf.as_dtype(dtype)
if hasattr(dtype, 'is_complex'):
return dtype.is_complex
return np.issubdtype(np.dtype(dtype), np.complex) |
def delete ( build_folder ) : if _meta_ . del_build in [ "on" , "ON" ] and os . path . exists ( build_folder ) : shutil . rmtree ( build_folder ) | 0 | python django delete project | Delete build directory and all its contents . | cosqa-train-216 | def delete(build_folder):
"""Delete build directory and all its contents.
"""
if _meta_.del_build in ["on", "ON"] and os.path.exists(build_folder):
shutil.rmtree(build_folder) |
def _stdin_ready_posix ( ) : infds , outfds , erfds = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return bool ( infds ) | 0 | check if stdin exists python | Return True if there s something to read on stdin ( posix version ) . | cosqa-train-217 | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) |
def json_response ( data , status = 200 ) : from django . http import JsonResponse return JsonResponse ( data = data , status = status , safe = isinstance ( data , dict ) ) | 0 | python django return response status | Return a JsonResponse . Make sure you have django installed first . | cosqa-train-218 | def json_response(data, status=200):
"""Return a JsonResponse. Make sure you have django installed first."""
from django.http import JsonResponse
return JsonResponse(data=data, status=status, safe=isinstance(data, dict)) |
def _is_path ( s ) : if isinstance ( s , string_types ) : try : return op . exists ( s ) except ( OSError , ValueError ) : return False else : return False | 0 | check if string is file or directory python | Return whether an object is a path . | cosqa-train-219 | def _is_path(s):
"""Return whether an object is a path."""
if isinstance(s, string_types):
try:
return op.exists(s)
except (OSError, ValueError):
return False
else:
return False |
def see_doc ( obj_with_doc ) : def decorator ( fn ) : fn . __doc__ = obj_with_doc . __doc__ return fn return decorator | 0 | python doc comment of a field | Copy docstring from existing object to the decorated callable . | cosqa-train-220 | def see_doc(obj_with_doc):
"""Copy docstring from existing object to the decorated callable."""
def decorator(fn):
fn.__doc__ = obj_with_doc.__doc__
return fn
return decorator |
def isToneCal ( self ) : return self . ui . calTypeCmbbx . currentIndex ( ) == self . ui . calTypeCmbbx . count ( ) - 1 | 0 | check if the radiobutton is selected in python | Whether the currently selected calibration stimulus type is the calibration curve | cosqa-train-221 | def isToneCal(self):
"""Whether the currently selected calibration stimulus type is the calibration curve
:returns: boolean -- if the current combo box selection is calibration curve
"""
return self.ui.calTypeCmbbx.currentIndex() == self.ui.calTypeCmbbx.count() -1 |
def hmsToDeg ( h , m , s ) : return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec | 0 | python documentation radians to degrees | Convert RA hours minutes seconds into an angle in degrees . | cosqa-train-222 | def hmsToDeg(h, m, s):
"""Convert RA hours, minutes, seconds into an angle in degrees."""
return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec |
def is_date ( thing ) : # known date types date_types = ( datetime . datetime , datetime . date , DateTime ) return isinstance ( thing , date_types ) | 1 | check is string is date in python | Checks if the given thing represents a date | cosqa-train-223 | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date,
DateTime)
return isinstance(thing, date_types) |
def prepare ( doc ) : doc . caption_found = False doc . plot_found = False doc . listings_counter = 0 | 0 | python docx section' object has no attribute 'header' | Sets the caption_found and plot_found variables to False . | cosqa-train-224 | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 |
def validate ( key ) : if not isinstance ( key , ( str , bytes ) ) : raise KeyError ( 'Key must be of type str or bytes, found type {}' . format ( type ( key ) ) ) | 0 | check key type python | Check that the key is a string or bytestring . | cosqa-train-225 | def validate(key):
"""Check that the key is a string or bytestring.
That's the only valid type of key.
"""
if not isinstance(key, (str, bytes)):
raise KeyError('Key must be of type str or bytes, found type {}'.format(type(key))) |
def _normal_prompt ( self ) : sys . stdout . write ( self . __get_ps1 ( ) ) sys . stdout . flush ( ) return safe_input ( ) | 0 | python doesn't return prompt | Flushes the prompt before requesting the input | cosqa-train-226 | def _normal_prompt(self):
"""
Flushes the prompt before requesting the input
:return: The command line
"""
sys.stdout.write(self.__get_ps1())
sys.stdout.flush()
return safe_input() |
def maxDepth ( self , currentDepth = 0 ) : if not any ( ( self . left , self . right ) ) : return currentDepth result = 0 for child in ( self . left , self . right ) : if child : result = max ( result , child . maxDepth ( currentDepth + 1 ) ) return result | 0 | check max supported depth of recursion python | Compute the depth of the longest branch of the tree | cosqa-train-227 | def maxDepth(self, currentDepth=0):
"""Compute the depth of the longest branch of the tree"""
if not any((self.left, self.right)):
return currentDepth
result = 0
for child in (self.left, self.right):
if child:
result = max(result, child.maxDepth(currentDepth + 1))
return result |
def from_rectangle ( box ) : x = box . left + box . width * random . uniform ( 0 , 1 ) y = box . bottom + box . height * random . uniform ( 0 , 1 ) return Vector ( x , y ) | 1 | python draw a box at random coordinates | Create a vector randomly within the given rectangle . | cosqa-train-228 | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) |
def launched ( ) : if not PREFIX : return False return os . path . realpath ( sys . prefix ) == os . path . realpath ( PREFIX ) | 1 | check my python path | Test whether the current python environment is the correct lore env . | cosqa-train-229 | def launched():
"""Test whether the current python environment is the correct lore env.
:return: :any:`True` if the environment is launched
:rtype: bool
"""
if not PREFIX:
return False
return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX) |
def hline ( self , x , y , width , color ) : self . rect ( x , y , width , 1 , color , fill = True ) | 1 | python draw a line | Draw a horizontal line up to a given length . | cosqa-train-230 | def hline(self, x, y, width, color):
"""Draw a horizontal line up to a given length."""
self.rect(x, y, width, 1, color, fill=True) |
def is_sequence ( obj ) : return isinstance ( obj , Sequence ) and not ( isinstance ( obj , str ) or BinaryClass . is_valid_type ( obj ) ) | 0 | check not nonetype python | Check if obj is a sequence but not a string or bytes . | cosqa-train-231 | 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 starts_with_prefix_in_list ( text , prefixes ) : for prefix in prefixes : if text . startswith ( prefix ) : return True return False | 0 | check prefix of a list python | Return True if the given string starts with one of the prefixes in the given list otherwise return False . | cosqa-train-232 | 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 print_yaml ( o ) : print ( yaml . dump ( o , default_flow_style = False , indent = 4 , encoding = 'utf-8' ) ) | 0 | python dump dictionary to yaml pretty | Pretty print an object as YAML . | cosqa-train-233 | def print_yaml(o):
"""Pretty print an object as YAML."""
print(yaml.dump(o, default_flow_style=False, indent=4, encoding='utf-8')) |
def issuperset ( self , other ) : self . _binary_sanity_check ( other ) return set . issuperset ( self , other ) | 1 | check set covers other set python | Report whether this RangeSet contains another set . | cosqa-train-234 | def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) |
def deserialize_ndarray_npy ( d ) : with io . BytesIO ( ) as f : f . write ( json . loads ( d [ 'npy' ] ) . encode ( 'latin-1' ) ) f . seek ( 0 ) return np . load ( f ) | 0 | python dump numpy array to json | Deserializes a JSONified : obj : numpy . ndarray that was created using numpy s : obj : save function . | cosqa-train-235 | def deserialize_ndarray_npy(d):
"""
Deserializes a JSONified :obj:`numpy.ndarray` that was created using numpy's
:obj:`save` function.
Args:
d (:obj:`dict`): A dictionary representation of an :obj:`ndarray` object, created
using :obj:`numpy.save`.
Returns:
An :obj:`ndarray` object.
"""
with io.BytesIO() as f:
f.write(json.loads(d['npy']).encode('latin-1'))
f.seek(0)
return np.load(f) |
def 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 ) | 0 | check several strings empty in python | Check the text . | cosqa-train-236 | def check(text):
"""Check the text."""
err = "misc.currency"
msg = u"Incorrect use of symbols in {}."
symbols = [
"\$[\d]* ?(?:dollars|usd|us dollars)"
]
return existence_check(text, symbols, err, msg) |
def listlike ( obj ) : return hasattr ( obj , "__iter__" ) and not issubclass ( type ( obj ) , str ) and not issubclass ( type ( obj ) , unicode ) | 0 | python dynamic type of an object | Is an object iterable like a list ( and not a string ) ? | cosqa-train-237 | def listlike(obj):
"""Is an object iterable like a list (and not a string)?"""
return hasattr(obj, "__iter__") \
and not issubclass(type(obj), str)\
and not issubclass(type(obj), unicode) |
def required_header ( header ) : if header in IGNORE_HEADERS : return False if header . startswith ( 'HTTP_' ) or header == 'CONTENT_TYPE' : return True return False | 1 | check specific header in python | Function that verify if the header parameter is a essential header | cosqa-train-238 | def required_header(header):
"""Function that verify if the header parameter is a essential header
:param header: A string represented a header
:returns: A boolean value that represent if the header is required
"""
if header in IGNORE_HEADERS:
return False
if header.startswith('HTTP_') or header == 'CONTENT_TYPE':
return True
return False |
def _map_table_name ( self , model_names ) : for model in model_names : if isinstance ( model , tuple ) : model = model [ 0 ] try : model_cls = getattr ( self . models , model ) self . table_to_class [ class_mapper ( model_cls ) . tables [ 0 ] . name ] = model except AttributeError : pass | 0 | python dynamically make data go from one table to another | Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class tak si to namapujme | cosqa-train-239 | def _map_table_name(self, model_names):
"""
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class,
tak si to namapujme
"""
for model in model_names:
if isinstance(model, tuple):
model = model[0]
try:
model_cls = getattr(self.models, model)
self.table_to_class[class_mapper(model_cls).tables[0].name] = model
except AttributeError:
pass |
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 | 0 | check the status of windows service in python | Determine whether a system service is available | cosqa-train-240 | def service_available(service_name):
"""Determine whether a system service is available"""
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 |
def keys ( self ) : all_keys = [ k . decode ( 'utf-8' ) for k , v in self . rdb . hgetall ( self . session_hash ) . items ( ) ] return all_keys | 0 | python dynamodb export all hash key | Return a list of all keys in the dictionary . | cosqa-train-241 | def keys(self):
"""Return a list of all keys in the dictionary.
Returns:
list of str: [key1,key2,...,keyN]
"""
all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_keys |
def _valid_other_type ( x , types ) : return all ( any ( isinstance ( el , t ) for t in types ) for el in np . ravel ( x ) ) | 0 | check type throughout a list python | Do all elements of x have a type from types? | cosqa-train-242 | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) |
def escape_tex ( value ) : newval = value for pattern , replacement in LATEX_SUBS : newval = pattern . sub ( replacement , newval ) return newval | 0 | python editing text files to replace quotes in tex | Make text tex safe | cosqa-train-243 | def escape_tex(value):
"""
Make text tex safe
"""
newval = value
for pattern, replacement in LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval |
def update_index ( index ) : logger . info ( "Updating search index: '%s'" , index ) client = get_client ( ) responses = [ ] for model in get_index_models ( index ) : logger . info ( "Updating search index model: '%s'" , model . search_doc_type ) objects = model . objects . get_search_queryset ( index ) . iterator ( ) actions = bulk_actions ( objects , index = index , action = "index" ) response = helpers . bulk ( client , actions , chunk_size = get_setting ( "chunk_size" ) ) responses . append ( response ) return responses | 1 | python elasticsearch bulk index | Re - index every document in a named index . | cosqa-train-244 | def update_index(index):
"""Re-index every document in a named index."""
logger.info("Updating search index: '%s'", index)
client = get_client()
responses = []
for model in get_index_models(index):
logger.info("Updating search index model: '%s'", model.search_doc_type)
objects = model.objects.get_search_queryset(index).iterator()
actions = bulk_actions(objects, index=index, action="index")
response = helpers.bulk(client, actions, chunk_size=get_setting("chunk_size"))
responses.append(response)
return responses |
def is_datetime_like ( dtype ) : return ( np . issubdtype ( dtype , np . datetime64 ) or np . issubdtype ( dtype , np . timedelta64 ) ) | 0 | check whether column is datetime in python | Check if a dtype is a subclass of the numpy datetime types | cosqa-train-245 | def is_datetime_like(dtype):
"""Check if a dtype is a subclass of the numpy datetime types
"""
return (np.issubdtype(dtype, np.datetime64) or
np.issubdtype(dtype, np.timedelta64)) |
def hidden_cursor ( self ) : self . stream . write ( self . hide_cursor ) try : yield finally : self . stream . write ( self . normal_cursor ) | 0 | python empty cursor object | Return a context manager that hides the cursor while inside it and makes it visible on leaving . | cosqa-train-246 | def hidden_cursor(self):
"""Return a context manager that hides the cursor while inside it and
makes it visible on leaving."""
self.stream.write(self.hide_cursor)
try:
yield
finally:
self.stream.write(self.normal_cursor) |
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 | 0 | check windows service status from python | Determine whether a system service is available | cosqa-train-247 | def service_available(service_name):
"""Determine whether a system service is available"""
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 |
def copy ( doc , dest , src ) : return Target ( doc ) . copy ( dest , src ) . document | 0 | python emulate copy docx with style | Copy element from sequence member from mapping . | cosqa-train-248 | def copy(doc, dest, src):
"""Copy element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object
"""
return Target(doc).copy(dest, src).document |
def is_string ( val ) : try : basestring except NameError : return isinstance ( val , str ) return isinstance ( val , basestring ) | 0 | checking if something is a string in python 3 | Determines whether the passed value is a string safe for 2 / 3 . | cosqa-train-249 | def is_string(val):
"""Determines whether the passed value is a string, safe for 2/3."""
try:
basestring
except NameError:
return isinstance(val, str)
return isinstance(val, basestring) |
def read_from_file ( file_path , encoding = "utf-8" ) : with codecs . open ( file_path , "r" , encoding ) as f : return f . read ( ) | 0 | python encoding to read files | Read helper method | cosqa-train-250 | def read_from_file(file_path, encoding="utf-8"):
"""
Read helper method
:type file_path: str|unicode
:type encoding: str|unicode
:rtype: str|unicode
"""
with codecs.open(file_path, "r", encoding) as f:
return f.read() |
def _stdin_ready_posix ( ) : infds , outfds , erfds = select . select ( [ sys . stdin ] , [ ] , [ ] , 0 ) return bool ( infds ) | 0 | checking to see if there is input from a serial port python | Return True if there s something to read on stdin ( posix version ) . | cosqa-train-251 | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) |
def _is_root ( ) : import os import ctypes try : return os . geteuid ( ) == 0 except AttributeError : return ctypes . windll . shell32 . IsUserAnAdmin ( ) != 0 return False | 0 | python ensure current user root | Checks if the user is rooted . | cosqa-train-252 | def _is_root():
"""Checks if the user is rooted."""
import os
import ctypes
try:
return os.geteuid() == 0
except AttributeError:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
return False |
def _valid_other_type ( x , types ) : return all ( any ( isinstance ( el , t ) for t in types ) for el in np . ravel ( x ) ) | 1 | checking types of elements inside of an 2d array python | Do all elements of x have a type from types? | cosqa-train-253 | def _valid_other_type(x, types):
"""
Do all elements of x have a type from types?
"""
return all(any(isinstance(el, t) for t in types) for el in np.ravel(x)) |
def describe_enum_value ( enum_value ) : enum_value_descriptor = EnumValueDescriptor ( ) enum_value_descriptor . name = six . text_type ( enum_value . name ) enum_value_descriptor . number = enum_value . number return enum_value_descriptor | 0 | python enum custom members | Build descriptor for Enum instance . | cosqa-train-254 | def describe_enum_value(enum_value):
"""Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance.
"""
enum_value_descriptor = EnumValueDescriptor()
enum_value_descriptor.name = six.text_type(enum_value.name)
enum_value_descriptor.number = enum_value.number
return enum_value_descriptor |
def user_in_all_groups ( user , groups ) : return user_is_superuser ( user ) or all ( user_in_group ( user , group ) for group in groups ) | 0 | checking user in group python | Returns True if the given user is in all given groups | cosqa-train-255 | def user_in_all_groups(user, groups):
"""Returns True if the given user is in all given groups"""
return user_is_superuser(user) or all(user_in_group(user, group) for group in groups) |
def items ( self ) : return [ ( value_descriptor . name , value_descriptor . number ) for value_descriptor in self . _enum_type . values ] | 0 | python enum get all name | Return a list of the ( name value ) pairs of the enum . | cosqa-train-256 | def items(self):
"""Return a list of the (name, value) pairs of the enum.
These are returned in the order they were defined in the .proto file.
"""
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] |
def n_choose_k ( n , k ) : return int ( reduce ( MUL , ( Fraction ( n - i , i + 1 ) for i in range ( k ) ) , 1 ) ) | 0 | choose k from n python fact | get the number of quartets as n - choose - k . This is used in equal splits to decide whether a split should be exhaustively sampled or randomly sampled . Edges near tips can be exhaustive while highly nested edges probably have too many quartets | cosqa-train-257 | def n_choose_k(n, k):
""" get the number of quartets as n-choose-k. This is used
in equal splits to decide whether a split should be exhaustively sampled
or randomly sampled. Edges near tips can be exhaustive while highly nested
edges probably have too many quartets
"""
return int(reduce(MUL, (Fraction(n-i, i+1) for i in range(k)), 1)) |
def items ( cls ) : return [ cls . PRECIPITATION , cls . WIND , cls . TEMPERATURE , cls . PRESSURE ] | 0 | python enum get all values | All values for this enum : return : list of tuples | cosqa-train-258 | def items(cls):
"""
All values for this enum
:return: list of tuples
"""
return [
cls.PRECIPITATION,
cls.WIND,
cls.TEMPERATURE,
cls.PRESSURE
] |
def revnet_164_cifar ( ) : hparams = revnet_cifar_base ( ) hparams . bottleneck = True hparams . num_channels = [ 16 , 32 , 64 ] hparams . num_layers_per_block = [ 8 , 8 , 8 ] return hparams | 0 | cifar 10 python how to open | Tiny hparams suitable for CIFAR / etc . | cosqa-train-259 | def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams |
def items ( cls ) : return [ cls . PRECIPITATION , cls . WIND , cls . TEMPERATURE , cls . PRESSURE ] | 0 | python enum values to list | All values for this enum : return : list of tuples | cosqa-train-260 | def items(cls):
"""
All values for this enum
:return: list of tuples
"""
return [
cls.PRECIPITATION,
cls.WIND,
cls.TEMPERATURE,
cls.PRESSURE
] |
def mtf_image_transformer_cifar_mp_4x ( ) : hparams = mtf_image_transformer_base_cifar ( ) hparams . mesh_shape = "model:4;batch:8" hparams . layout = "batch:batch;d_ff:model;heads:model" hparams . batch_size = 32 hparams . num_heads = 8 hparams . d_ff = 8192 return hparams | 0 | cifar10 python tensorflow example | Data parallel CIFAR parameters . | cosqa-train-261 | def mtf_image_transformer_cifar_mp_4x():
"""Data parallel CIFAR parameters."""
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
return hparams |
def image_set_aspect ( aspect = 1.0 , axes = "gca" ) : if axes is "gca" : axes = _pylab . gca ( ) e = axes . get_images ( ) [ 0 ] . get_extent ( ) axes . set_aspect ( abs ( ( e [ 1 ] - e [ 0 ] ) / ( e [ 3 ] - e [ 2 ] ) ) / aspect ) | 0 | python equal aspect ratio | sets the aspect ratio of the current zoom level of the imshow image | cosqa-train-262 | def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
if axes is "gca": axes = _pylab.gca()
e = axes.get_images()[0].get_extent()
axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect) |
def Flush ( self ) : while self . _age : node = self . _age . PopLeft ( ) self . KillObject ( node . data ) self . _hash = dict ( ) | 0 | clear memory python after each loop | Flush all items from cache . | cosqa-train-263 | def Flush(self):
"""Flush all items from cache."""
while self._age:
node = self._age.PopLeft()
self.KillObject(node.data)
self._hash = dict() |
def _propagate_mean ( mean , linop , dist ) : return linop . matmul ( mean ) + dist . mean ( ) [ ... , tf . newaxis ] | 1 | python equivalent of matlab movmean function | Propagate a mean through linear Gaussian transformation . | cosqa-train-264 | def _propagate_mean(mean, linop, dist):
"""Propagate a mean through linear Gaussian transformation."""
return linop.matmul(mean) + dist.mean()[..., tf.newaxis] |
def invalidate_cache ( cpu , address , size ) : cache = cpu . instruction_cache for offset in range ( size ) : if address + offset in cache : del cache [ address + offset ] | 0 | clearing data from memory in python | remove decoded instruction from instruction cache | cosqa-train-265 | def invalidate_cache(cpu, address, size):
""" remove decoded instruction from instruction cache """
cache = cpu.instruction_cache
for offset in range(size):
if address + offset in cache:
del cache[address + offset] |
def convertToBool ( ) : if not OPTIONS . strictBool . value : return [ ] REQUIRES . add ( 'strictbool.asm' ) result = [ ] result . append ( 'pop af' ) result . append ( 'call __NORMALIZE_BOOLEAN' ) result . append ( 'push af' ) return result | 0 | python even or odd booleans only | Convert a byte value to boolean ( 0 or 1 ) if the global flag strictBool is True | cosqa-train-266 | def convertToBool():
""" Convert a byte value to boolean (0 or 1) if
the global flag strictBool is True
"""
if not OPTIONS.strictBool.value:
return []
REQUIRES.add('strictbool.asm')
result = []
result.append('pop af')
result.append('call __NORMALIZE_BOOLEAN')
result.append('push af')
return result |
def normalize ( x , min_value , max_value ) : x = ( x - min_value ) / ( max_value - min_value ) return clip ( x , 0 , 1 ) | 0 | clip python truncate extreme | Normalize value between min and max values . It also clips the values so that you cannot have values higher or lower than 0 - 1 . | cosqa-train-267 | def normalize(x, min_value, max_value):
"""Normalize value between min and max values.
It also clips the values, so that you cannot have values higher or lower
than 0 - 1."""
x = (x - min_value) / (max_value - min_value)
return clip(x, 0, 1) |
def prepare_for_reraise ( error , exc_info = None ) : if not hasattr ( error , "_type_" ) : if exc_info is None : exc_info = sys . exc_info ( ) error . _type_ = exc_info [ 0 ] error . _traceback = exc_info [ 2 ] return error | 0 | python excpetion add attributes and reraise | Prepares the exception for re - raising with reraise method . | cosqa-train-268 | def prepare_for_reraise(error, exc_info=None):
"""Prepares the exception for re-raising with reraise method.
This method attaches type and traceback info to the error object
so that reraise can properly reraise it using this info.
"""
if not hasattr(error, "_type_"):
if exc_info is None:
exc_info = sys.exc_info()
error._type_ = exc_info[0]
error._traceback = exc_info[2]
return error |
def close_all_but_this ( self ) : self . close_all_right ( ) for i in range ( 0 , self . get_stack_count ( ) - 1 ) : self . close_file ( 0 ) | 0 | close all figures at once python | Close all files but the current one | cosqa-train-269 | def close_all_but_this(self):
"""Close all files but the current one"""
self.close_all_right()
for i in range(0, self.get_stack_count()-1 ):
self.close_file(0) |
def eval_in_system_namespace ( self , exec_str ) : ns = self . cmd_namespace try : return eval ( exec_str , ns ) except Exception as e : self . logger . warning ( 'Could not execute %s, gave error %s' , exec_str , e ) return None | 0 | python exec string name not defined | Get Callable for specified string ( for GUI - based editing ) | cosqa-train-270 | def eval_in_system_namespace(self, exec_str):
"""
Get Callable for specified string (for GUI-based editing)
"""
ns = self.cmd_namespace
try:
return eval(exec_str, ns)
except Exception as e:
self.logger.warning('Could not execute %s, gave error %s', exec_str, e)
return None |
def _close_socket ( self ) : try : self . socket . shutdown ( socket . SHUT_RDWR ) except ( OSError , socket . error ) : pass self . socket . close ( ) | 0 | close connection in server using sockets in python | Shutdown and close the Socket . | cosqa-train-271 | def _close_socket(self):
"""Shutdown and close the Socket.
:return:
"""
try:
self.socket.shutdown(socket.SHUT_RDWR)
except (OSError, socket.error):
pass
self.socket.close() |
def exec_function ( ast , globals_map ) : locals_map = globals_map exec ast in globals_map , locals_map return locals_map | 1 | python execute function with locals | Execute a python code object in the given environment . | cosqa-train-272 | def exec_function(ast, globals_map):
"""Execute a python code object in the given environment.
Args:
globals_map: Dictionary to use as the globals context.
Returns:
locals_map: Dictionary of locals from the environment after execution.
"""
locals_map = globals_map
exec ast in globals_map, locals_map
return locals_map |
def cleanup ( self , app ) : if hasattr ( self . database . obj , 'close_all' ) : self . database . close_all ( ) | 1 | close connection python sqlalchemy | Close all connections . | cosqa-train-273 | def cleanup(self, app):
"""Close all connections."""
if hasattr(self.database.obj, 'close_all'):
self.database.close_all() |
def get_unicode_str ( obj ) : if isinstance ( obj , six . text_type ) : return obj if isinstance ( obj , six . binary_type ) : return obj . decode ( "utf-8" , errors = "ignore" ) return six . text_type ( obj ) | 0 | python expected byte like object not a string object | Makes sure obj is a unicode string . | cosqa-train-274 | def get_unicode_str(obj):
"""Makes sure obj is a unicode string."""
if isinstance(obj, six.text_type):
return obj
if isinstance(obj, six.binary_type):
return obj.decode("utf-8", errors="ignore")
return six.text_type(obj) |
def close_all_but_this ( self ) : self . close_all_right ( ) for i in range ( 0 , self . get_stack_count ( ) - 1 ) : self . close_file ( 0 ) | 0 | close figure python example | Close all files but the current one | cosqa-train-275 | def close_all_but_this(self):
"""Close all files but the current one"""
self.close_all_right()
for i in range(0, self.get_stack_count()-1 ):
self.close_file(0) |
def exp_fit_fun ( x , a , tau , c ) : # pylint: disable=invalid-name return a * np . exp ( - x / tau ) + c | 0 | python exponential function fit | Function used to fit the exponential decay . | cosqa-train-276 | def exp_fit_fun(x, a, tau, c):
"""Function used to fit the exponential decay."""
# pylint: disable=invalid-name
return a * np.exp(-x / tau) + c |
def _findNearest ( arr , value ) : arr = np . array ( arr ) # find nearest value in array idx = ( abs ( arr - value ) ) . argmin ( ) return arr [ idx ] | 0 | closest nonzero value in array python | Finds the value in arr that value is closest to | cosqa-train-277 | def _findNearest(arr, value):
""" Finds the value in arr that value is closest to
"""
arr = np.array(arr)
# find nearest value in array
idx = (abs(arr-value)).argmin()
return arr[idx] |
def gauss_pdf ( x , mu , sigma ) : return 1 / np . sqrt ( 2 * np . pi ) / sigma * np . exp ( - ( x - mu ) ** 2 / 2. / sigma ** 2 ) | 0 | python express gaussian function | Normalized Gaussian | cosqa-train-278 | def gauss_pdf(x, mu, sigma):
"""Normalized Gaussian"""
return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2) |
def remove_examples_all ( ) : d = examples_all_dir ( ) if d . exists ( ) : log . debug ( 'remove %s' , d ) d . rmtree ( ) else : log . debug ( 'nothing to remove: %s' , d ) | 1 | code that deletes any folder if empty python | remove arduino / examples / all directory . | cosqa-train-279 | def remove_examples_all():
"""remove arduino/examples/all directory.
:rtype: None
"""
d = examples_all_dir()
if d.exists():
log.debug('remove %s', d)
d.rmtree()
else:
log.debug('nothing to remove: %s', d) |
def resources ( self ) : return [ self . pdf . getPage ( i ) for i in range ( self . pdf . getNumPages ( ) ) ] | 0 | python extract 5 pages at once from pdf | Retrieve contents of each page of PDF | cosqa-train-280 | def resources(self):
"""Retrieve contents of each page of PDF"""
return [self.pdf.getPage(i) for i in range(self.pdf.getNumPages())] |
def cli_command_quit ( self , msg ) : if self . state == State . RUNNING and self . sprocess and self . sprocess . proc : self . sprocess . proc . kill ( ) else : sys . exit ( 0 ) | 0 | code to use to terminate a program on python | \ kills the child and exits | cosqa-train-281 | def cli_command_quit(self, msg):
"""\
kills the child and exits
"""
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.sprocess.proc.kill()
else:
sys.exit(0) |
def dot ( self , w ) : return sum ( [ x * y for x , y in zip ( self , w ) ] ) | 0 | python fast dot product between matrices | Return the dotproduct between self and another vector . | cosqa-train-282 | def dot(self, w):
"""Return the dotproduct between self and another vector."""
return sum([x * y for x, y in zip(self, w)]) |
def printc ( cls , txt , color = colors . red ) : print ( cls . color_txt ( txt , color ) ) | 0 | colors for text in python code | Print in color . | cosqa-train-283 | def printc(cls, txt, color=colors.red):
"""Print in color."""
print(cls.color_txt(txt, color)) |
def need_update ( a , b ) : a = listify ( a ) b = listify ( b ) return any ( ( not op . exists ( x ) ) for x in b ) or all ( ( os . stat ( x ) . st_size == 0 for x in b ) ) or any ( is_newer_file ( x , y ) for x in a for y in b ) | 0 | python fastest way to compare two files | Check if file a is newer than file b and decide whether or not to update file b . Can generalize to two lists . | cosqa-train-284 | def need_update(a, b):
"""
Check if file a is newer than file b and decide whether or not to update
file b. Can generalize to two lists.
"""
a = listify(a)
b = listify(b)
return any((not op.exists(x)) for x in b) or \
all((os.stat(x).st_size == 0 for x in b)) or \
any(is_newer_file(x, y) for x in a for y in b) |
def lengths ( self ) : return ( np . array ( [ math . sqrt ( sum ( row ** 2 ) ) for row in self . matrix ] ) ) | 0 | column and row of matrix python | The cell lengths . | cosqa-train-285 | def lengths( self ):
"""
The cell lengths.
Args:
None
Returns:
(np.array(a,b,c)): The cell lengths.
"""
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) |
def random_str ( size = 10 ) : return '' . join ( random . choice ( string . ascii_lowercase ) for _ in range ( size ) ) | 0 | python fastest way to create a string size n | create random string of selected size | cosqa-train-286 | def random_str(size=10):
"""
create random string of selected size
:param size: int, length of the string
:return: the string
"""
return ''.join(random.choice(string.ascii_lowercase) for _ in range(size)) |
def get_table_columns ( dbconn , tablename ) : cur = dbconn . cursor ( ) cur . execute ( "PRAGMA table_info('%s');" % tablename ) info = cur . fetchall ( ) cols = [ ( i [ 1 ] , i [ 2 ] ) for i in info ] return cols | 0 | column names in table sqlite3 python | Return a list of tuples specifying the column name and type | cosqa-train-287 | def get_table_columns(dbconn, tablename):
"""
Return a list of tuples specifying the column name and type
"""
cur = dbconn.cursor()
cur.execute("PRAGMA table_info('%s');" % tablename)
info = cur.fetchall()
cols = [(i[1], i[2]) for i in info]
return cols |
def remove_duplicates ( lst ) : dset = set ( ) return [ l for l in lst if l not in dset and not dset . add ( l ) ] | 0 | python fastest way to remove duplicates from a list | Emulate what a Python set () does but keeping the element s order . | cosqa-train-288 | def remove_duplicates(lst):
"""
Emulate what a Python ``set()`` does, but keeping the element's order.
"""
dset = set()
return [l for l in lst if l not in dset and not dset.add(l)] |
def _on_select ( self , * args ) : if callable ( self . __callback ) : self . __callback ( self . selection ) | 0 | combobox methods in tkinter python | Function bound to event of selection in the Combobox calls callback if callable : param args : Tkinter event | cosqa-train-289 | def _on_select(self, *args):
"""
Function bound to event of selection in the Combobox, calls callback if callable
:param args: Tkinter event
"""
if callable(self.__callback):
self.__callback(self.selection) |
def fft_spectrum ( frames , fft_points = 512 ) : SPECTRUM_VECTOR = np . fft . rfft ( frames , n = fft_points , axis = - 1 , norm = None ) return np . absolute ( SPECTRUM_VECTOR ) | 0 | python fft high amplitude at 0 | This function computes the one - dimensional n - point discrete Fourier Transform ( DFT ) of a real - valued array by means of an efficient algorithm called the Fast Fourier Transform ( FFT ) . Please refer to https : // docs . scipy . org / doc / numpy / reference / generated / numpy . fft . rfft . html for further details . | cosqa-train-290 | def fft_spectrum(frames, fft_points=512):
"""This function computes the one-dimensional n-point discrete Fourier
Transform (DFT) of a real-valued array by means of an efficient algorithm
called the Fast Fourier Transform (FFT). Please refer to
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.rfft.html
for further details.
Args:
frames (array): The frame array in which each row is a frame.
fft_points (int): The length of FFT. If fft_length is greater than frame_len, the frames will be zero-padded.
Returns:
array: The fft spectrum.
If frames is an num_frames x sample_per_frame matrix, output
will be num_frames x FFT_LENGTH.
"""
SPECTRUM_VECTOR = np.fft.rfft(frames, n=fft_points, axis=-1, norm=None)
return np.absolute(SPECTRUM_VECTOR) |
def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 ) | 0 | compare an empty set python | move to util_iter | cosqa-train-291 | def isetdiff_flags(list1, list2):
"""
move to util_iter
"""
set2 = set(list2)
return (item not in set2 for item in list1) |
def guess_file_type ( kind , filepath = None , youtube_id = None , web_url = None , encoding = None ) : if youtube_id : return FileTypes . YOUTUBE_VIDEO_FILE elif web_url : return FileTypes . WEB_VIDEO_FILE elif encoding : return FileTypes . BASE64_FILE else : ext = os . path . splitext ( filepath ) [ 1 ] [ 1 : ] . lower ( ) if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING [ kind ] : return FILE_TYPE_MAPPING [ kind ] [ ext ] return None | 1 | python file chooser restrict file types | guess_file_class : determines what file the content is Args : filepath ( str ) : filepath of file to check Returns : string indicating file s class | cosqa-train-292 | def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None):
""" guess_file_class: determines what file the content is
Args:
filepath (str): filepath of file to check
Returns: string indicating file's class
"""
if youtube_id:
return FileTypes.YOUTUBE_VIDEO_FILE
elif web_url:
return FileTypes.WEB_VIDEO_FILE
elif encoding:
return FileTypes.BASE64_FILE
else:
ext = os.path.splitext(filepath)[1][1:].lower()
if kind in FILE_TYPE_MAPPING and ext in FILE_TYPE_MAPPING[kind]:
return FILE_TYPE_MAPPING[kind][ext]
return None |
def is_same_dict ( d1 , d2 ) : for k , v in d1 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d2 [ k ] ) else : assert d1 [ k ] == d2 [ k ] for k , v in d2 . items ( ) : if isinstance ( v , dict ) : is_same_dict ( v , d1 [ k ] ) else : assert d1 [ k ] == d2 [ k ] | 0 | compare dict for equality python | Test two dictionary is equal on values . ( ignore order ) | cosqa-train-293 | def is_same_dict(d1, d2):
"""Test two dictionary is equal on values. (ignore order)
"""
for k, v in d1.items():
if isinstance(v, dict):
is_same_dict(v, d2[k])
else:
assert d1[k] == d2[k]
for k, v in d2.items():
if isinstance(v, dict):
is_same_dict(v, d1[k])
else:
assert d1[k] == d2[k] |
def file_writelines_flush_sync ( path , lines ) : fp = open ( path , 'w' ) try : fp . writelines ( lines ) flush_sync_file_object ( fp ) finally : fp . close ( ) | 0 | python file flush doesnot work | Fill file at | cosqa-train-294 | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() |
def make_kind_check ( python_types , numpy_kind ) : def check ( value ) : if hasattr ( value , 'dtype' ) : return value . dtype . kind == numpy_kind return isinstance ( value , python_types ) return check | 0 | compare numpy dtype to python type | Make a function that checks whether a scalar or array is of a given kind ( e . g . float int datetime timedelta ) . | cosqa-train-295 | def make_kind_check(python_types, numpy_kind):
"""
Make a function that checks whether a scalar or array is of a given kind
(e.g. float, int, datetime, timedelta).
"""
def check(value):
if hasattr(value, 'dtype'):
return value.dtype.kind == numpy_kind
return isinstance(value, python_types)
return check |
def file_empty ( fp ) : # for python 2 we need to use a homemade peek() if six . PY2 : contents = fp . read ( ) fp . seek ( 0 ) return not bool ( contents ) else : return not fp . peek ( ) | 0 | python file is empty or not | Determine if a file is empty or not . | cosqa-train-296 | def file_empty(fp):
"""Determine if a file is empty or not."""
# for python 2 we need to use a homemade peek()
if six.PY2:
contents = fp.read()
fp.seek(0)
return not bool(contents)
else:
return not fp.peek() |
def all_equal ( arg1 , arg2 ) : if all ( hasattr ( el , '_infinitely_iterable' ) for el in [ arg1 , arg2 ] ) : return arg1 == arg2 try : return all ( a1 == a2 for a1 , a2 in zip ( arg1 , arg2 ) ) except TypeError : return arg1 == arg2 | 0 | compare primitive arrays for equality python | Return a single boolean for arg1 == arg2 even for numpy arrays using element - wise comparison . | cosqa-train-297 | def all_equal(arg1,arg2):
"""
Return a single boolean for arg1==arg2, even for numpy arrays
using element-wise comparison.
Uses all(arg1==arg2) for sequences, and arg1==arg2 otherwise.
If both objects have an '_infinitely_iterable' attribute, they are
not be zipped together and are compared directly instead.
"""
if all(hasattr(el, '_infinitely_iterable') for el in [arg1,arg2]):
return arg1==arg2
try:
return all(a1 == a2 for a1, a2 in zip(arg1, arg2))
except TypeError:
return arg1==arg2 |
def get_file_size ( filename ) : if os . path . isfile ( filename ) : return convert_size ( os . path . getsize ( filename ) ) return None | 1 | python file size determination | Get the file size of a given file | cosqa-train-298 | def get_file_size(filename):
"""
Get the file size of a given file
:param filename: string: pathname of a file
:return: human readable filesize
"""
if os.path.isfile(filename):
return convert_size(os.path.getsize(filename))
return None |
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 | 0 | comparing floats and ints python | This is a compatibility function that takes a C { float } and converts it to an C { int } if the values are equal . | cosqa-train-299 | 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 |