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 memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 0 |
limit memory allocated python gpu
|
Check if the memory is too full for further caching .
|
cosqa-train-17600
|
def memory_full():
"""Check if the memory is too full for further caching."""
current_process = psutil.Process(os.getpid())
return (current_process.memory_percent() >
config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
|
def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
| 0 |
python checking if value is in enum
|
True if specified value exists in int enum ; otherwise False .
|
cosqa-train-17601
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
def get_datatype ( self , table : str , column : str ) -> str : return self . flavour . get_datatype ( self , table , column ) . upper ( )
| 0 |
determine datatype of column python
|
Returns database SQL datatype for a column : e . g . VARCHAR .
|
cosqa-train-17602
|
def get_datatype(self, table: str, column: str) -> str:
"""Returns database SQL datatype for a column: e.g. VARCHAR."""
return self.flavour.get_datatype(self, table, column).upper()
|
def dict_to_enum_fn ( d : Dict [ str , Any ] , enum_class : Type [ Enum ] ) -> Enum : return enum_class [ d [ 'name' ] ]
| 1 |
add a type to the enum python
|
Converts an dict to a Enum .
|
cosqa-train-17603
|
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum:
"""
Converts an ``dict`` to a ``Enum``.
"""
return enum_class[d['name']]
|
def __replace_all ( repls : dict , input : str ) -> str : return re . sub ( '|' . join ( re . escape ( key ) for key in repls . keys ( ) ) , lambda k : repls [ k . group ( 0 ) ] , input )
| 1 |
python how to replace multiple characters of a string
|
Replaces from a string ** input ** all the occurrences of some symbols according to mapping ** repls ** .
|
cosqa-train-17604
|
def __replace_all(repls: dict, input: str) -> str:
""" Replaces from a string **input** all the occurrences of some
symbols according to mapping **repls**.
:param dict repls: where #key is the old character and
#value is the one to substitute with;
:param str input: original string where to apply the
replacements;
:return: *(str)* the string with the desired characters replaced
"""
return re.sub('|'.join(re.escape(key) for key in repls.keys()),
lambda k: repls[k.group(0)], input)
|
def str_to_time ( time_str : str ) -> datetime . datetime : pieces : Any = [ int ( piece ) for piece in time_str . split ( '-' ) ] return datetime . datetime ( * pieces )
| 0 |
transfer serise string to datetime python
|
Convert human readable string to datetime . datetime .
|
cosqa-train-17605
|
def str_to_time(time_str: str) -> datetime.datetime:
"""
Convert human readable string to datetime.datetime.
"""
pieces: Any = [int(piece) for piece in time_str.split('-')]
return datetime.datetime(*pieces)
|
def SwitchToThisWindow ( handle : int ) -> None : ctypes . windll . user32 . SwitchToThisWindow ( ctypes . c_void_p ( handle ) , 1 )
| 0 |
python user32 windll send to back window
|
SwitchToThisWindow from Win32 . handle : int the handle of a native window .
|
cosqa-train-17606
|
def SwitchToThisWindow(handle: int) -> None:
"""
SwitchToThisWindow from Win32.
handle: int, the handle of a native window.
"""
ctypes.windll.user32.SwitchToThisWindow(ctypes.c_void_p(handle), 1)
|
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
| 0 |
python tensor change dtype float
|
Cast to float tensor
|
cosqa-train-17607
|
def fcast(value: float) -> TensorLike:
"""Cast to float tensor"""
newvalue = tf.cast(value, FTYPE)
if DEVICE == 'gpu':
newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover
return newvalue
|
def get_versions ( reporev = True ) : import sys import platform import qtpy import qtpy . QtCore revision = None if reporev : from spyder . utils import vcs revision , branch = vcs . get_git_revision ( os . path . dirname ( __dir__ ) ) if not sys . platform == 'darwin' : # To avoid a crash with our Mac app system = platform . system ( ) else : system = 'Darwin' return { 'spyder' : __version__ , 'python' : platform . python_version ( ) , # "2.7.3" 'bitness' : 64 if sys . maxsize > 2 ** 32 else 32 , 'qt' : qtpy . QtCore . __version__ , 'qt_api' : qtpy . API_NAME , # PyQt5 'qt_api_ver' : qtpy . PYQT_VERSION , 'system' : system , # Linux, Windows, ... 'release' : platform . release ( ) , # XP, 10.6, 2.2.0, etc. 'revision' : revision , # '9fdf926eccce' }
| 0 |
spyder change from python 2 to 3
|
Get version information for components used by Spyder
|
cosqa-train-17608
|
def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
if not sys.platform == 'darwin': # To avoid a crash with our Mac app
system = platform.system()
else:
system = 'Darwin'
return {
'spyder': __version__,
'python': platform.python_version(), # "2.7.3"
'bitness': 64 if sys.maxsize > 2**32 else 32,
'qt': qtpy.QtCore.__version__,
'qt_api': qtpy.API_NAME, # PyQt5
'qt_api_ver': qtpy.PYQT_VERSION,
'system': system, # Linux, Windows, ...
'release': platform.release(), # XP, 10.6, 2.2.0, etc.
'revision': revision, # '9fdf926eccce'
}
|
def astensor ( array : TensorLike ) -> BKTensor : tensor = tf . convert_to_tensor ( value = array , dtype = CTYPE ) return tensor
| 0 |
python array to tensor object
|
Covert numpy array to tensorflow tensor
|
cosqa-train-17609
|
def astensor(array: TensorLike) -> BKTensor:
"""Covert numpy array to tensorflow tensor"""
tensor = tf.convert_to_tensor(value=array, dtype=CTYPE)
return tensor
|
def pretty_dict ( d ) : return '{%s}' % ', ' . join ( '%r: %r' % ( k , v ) for k , v in sorted ( d . items ( ) , key = repr ) )
| 1 |
python pretty print of dict
|
Return dictionary d s repr but with the items sorted . >>> pretty_dict ( { m : M a : A r : R k : K } ) { a : A k : K m : M r : R } >>> pretty_dict ( { z : C y : B x : A } ) { x : A y : B z : C }
|
cosqa-train-17610
|
def pretty_dict(d):
"""Return dictionary d's repr but with the items sorted.
>>> pretty_dict({'m': 'M', 'a': 'A', 'r': 'R', 'k': 'K'})
"{'a': 'A', 'k': 'K', 'm': 'M', 'r': 'R'}"
>>> pretty_dict({z: C, y: B, x: A})
'{x: A, y: B, z: C}'
"""
return '{%s}' % ', '.join('%r: %r' % (k, v)
for k, v in sorted(d.items(), key=repr))
|
def array_to_npy ( array_like ) : # type: (np.array or Iterable or int or float) -> object buffer = BytesIO ( ) np . save ( buffer , array_like ) return buffer . getvalue ( )
| 0 |
python numpy dumps to
|
Convert an array like object to the NPY format .
|
cosqa-train-17611
|
def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object
"""Convert an array like object to the NPY format.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
Args:
array_like (np.array or Iterable or int or float): array like object to be converted to NPY.
Returns:
(obj): NPY array.
"""
buffer = BytesIO()
np.save(buffer, array_like)
return buffer.getvalue()
|
def read_byte_data ( self , addr , cmd ) : self . _set_addr ( addr ) res = SMBUS . i2c_smbus_read_byte_data ( self . _fd , ffi . cast ( "__u8" , cmd ) ) if res == - 1 : raise IOError ( ffi . errno ) return res
| 1 |
read byte data smbus python
|
read_byte_data ( addr cmd ) - > result
|
cosqa-train-17612
|
def read_byte_data(self, addr, cmd):
"""read_byte_data(addr, cmd) -> result
Perform SMBus Read Byte Data transaction.
"""
self._set_addr(addr)
res = SMBUS.i2c_smbus_read_byte_data(self._fd, ffi.cast("__u8", cmd))
if res == -1:
raise IOError(ffi.errno)
return res
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 0 |
print the uppercase letters in the string python
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17613
|
def uppercase_chars(string: any) -> str:
"""Return all (and only) the uppercase chars in the given string."""
return ''.join([c if c.isupper() else '' for c in str(string)])
|
def get_last_day_of_month ( t : datetime ) -> int : tn = t + timedelta ( days = 32 ) tn = datetime ( year = tn . year , month = tn . month , day = 1 ) tt = tn - timedelta ( hours = 1 ) return tt . day
| 0 |
python get last of month
|
Returns day number of the last day of the month : param t : datetime : return : int
|
cosqa-train-17614
|
def get_last_day_of_month(t: datetime) -> int:
"""
Returns day number of the last day of the month
:param t: datetime
:return: int
"""
tn = t + timedelta(days=32)
tn = datetime(year=tn.year, month=tn.month, day=1)
tt = tn - timedelta(hours=1)
return tt.day
|
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 0 |
how to check if date format is correct python
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-17615
|
def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False
|
def decode ( self , bytes , raw = False ) : return struct . unpack ( self . format , buffer ( bytes ) ) [ 0 ]
| 1 |
python protobyf parse from byte
|
decode ( bytearray raw = False ) - > value
|
cosqa-train-17616
|
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray according to this PrimitiveType
definition.
NOTE: The parameter ``raw`` is present to adhere to the
``decode()`` inteface, but has no effect for PrimitiveType
definitions.
"""
return struct.unpack(self.format, buffer(bytes))[0]
|
def _parse_property ( self , node ) : # type: (ElementTree.Element) -> Tuple[str, Any] # Get information name = node . attrib [ ATTR_NAME ] vtype = node . attrib . get ( ATTR_VALUE_TYPE , TYPE_STRING ) # Look for a value as a single child node try : value_node = next ( iter ( node ) ) value = self . _parse_value_node ( vtype , value_node ) except StopIteration : # Value is an attribute value = self . _convert_value ( vtype , node . attrib [ ATTR_VALUE ] ) return name , value
| 0 |
parsing a childnode's attribute in python 3
|
Parses a property node
|
cosqa-train-17617
|
def _parse_property(self, node):
# type: (ElementTree.Element) -> Tuple[str, Any]
"""
Parses a property node
:param node: The property node
:return: A (name, value) tuple
:raise KeyError: Attribute missing
"""
# Get information
name = node.attrib[ATTR_NAME]
vtype = node.attrib.get(ATTR_VALUE_TYPE, TYPE_STRING)
# Look for a value as a single child node
try:
value_node = next(iter(node))
value = self._parse_value_node(vtype, value_node)
except StopIteration:
# Value is an attribute
value = self._convert_value(vtype, node.attrib[ATTR_VALUE])
return name, value
|
def validate_django_compatible_with_python ( ) : python_version = sys . version [ : 5 ] django_version = django . get_version ( ) if sys . version_info == ( 2 , 7 ) and django_version >= "2" : click . BadArgumentUsage ( "Please install Django v1.11 for Python {}, or switch to Python >= v3.4" . format ( python_version ) )
| 0 |
checking the current python versipn
|
Verify Django 1 . 11 is present if Python 2 . 7 is active
|
cosqa-train-17618
|
def validate_django_compatible_with_python():
"""
Verify Django 1.11 is present if Python 2.7 is active
Installation of pinax-cli requires the correct version of Django for
the active Python version. If the developer subsequently changes
the Python version the installed Django may no longer be compatible.
"""
python_version = sys.version[:5]
django_version = django.get_version()
if sys.version_info == (2, 7) and django_version >= "2":
click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
|
def is_intersection ( g , n ) : return len ( set ( g . predecessors ( n ) + g . successors ( n ) ) ) > 2
| 0 |
how to check if edge intersects in igraph python
|
Determine if a node is an intersection
|
cosqa-train-17619
|
def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
Returns
-------
bool
"""
return len(set(g.predecessors(n) + g.successors(n))) > 2
|
def interpolate ( f1 : float , f2 : float , factor : float ) -> float : return f1 + ( f2 - f1 ) * factor
| 0 |
blender python fcurves interpolation
|
Linearly interpolate between two float values .
|
cosqa-train-17620
|
def interpolate(f1: float, f2: float, factor: float) -> float:
""" Linearly interpolate between two float values. """
return f1 + (f2 - f1) * factor
|
def split ( text : str ) -> List [ str ] : return [ word for word in SEPARATOR . split ( text ) if word . strip ( ' \t' ) ]
| 1 |
split sentence by delimiter python
|
Split a text into a list of tokens .
|
cosqa-train-17621
|
def split(text: str) -> List[str]:
"""Split a text into a list of tokens.
:param text: the text to split
:return: tokens
"""
return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
cast a list of string in integer in python
|
Convert a list of strings to a list of integers .
|
cosqa-train-17622
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def clean ( ctx , text ) : text = conversions . to_string ( text , ctx ) return '' . join ( [ c for c in text if ord ( c ) >= 32 ] )
| 0 |
python delete all occurrences of character in string
|
Removes all non - printable characters from a text string
|
cosqa-train-17623
|
def clean(ctx, text):
"""
Removes all non-printable characters from a text string
"""
text = conversions.to_string(text, ctx)
return ''.join([c for c in text if ord(c) >= 32])
|
def reduce ( function , initval = None ) : if initval is None : return lambda s : __builtin__ . reduce ( function , s ) else : return lambda s : __builtin__ . reduce ( function , s , initval )
| 0 |
how to make a function return a fuction in python
|
Curried version of the built - in reduce . >>> reduce ( lambda x y : x + y ) ( [ 1 2 3 4 5 ] ) 15
|
cosqa-train-17624
|
def reduce(function, initval=None):
"""
Curried version of the built-in reduce.
>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
15
"""
if initval is None:
return lambda s: __builtin__.reduce(function, s)
else:
return lambda s: __builtin__.reduce(function, s, initval)
|
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 0 |
python get url domain
|
Get domain part of an url .
|
cosqa-train-17625
|
def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain
|
def tsv_escape ( x : Any ) -> str : if x is None : return "" x = str ( x ) return x . replace ( "\t" , "\\t" ) . replace ( "\n" , "\\n" )
| 0 |
python replace nulls with string in csv
|
Escape data for tab - separated value ( TSV ) format .
|
cosqa-train-17626
|
def tsv_escape(x: Any) -> str:
"""
Escape data for tab-separated value (TSV) format.
"""
if x is None:
return ""
x = str(x)
return x.replace("\t", "\\t").replace("\n", "\\n")
|
def memory_full ( ) : current_process = psutil . Process ( os . getpid ( ) ) return ( current_process . memory_percent ( ) > config . MAXIMUM_CACHE_MEMORY_PERCENTAGE )
| 0 |
how to check memory leak in python
|
Check if the memory is too full for further caching .
|
cosqa-train-17627
|
def memory_full():
"""Check if the memory is too full for further caching."""
current_process = psutil.Process(os.getpid())
return (current_process.memory_percent() >
config.MAXIMUM_CACHE_MEMORY_PERCENTAGE)
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 0 |
python limit times in a minute
|
Rate limit a function .
|
cosqa-train-17628
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 0 |
read a file from s3 bucket python
|
Pull a file directly from S3 .
|
cosqa-train-17629
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def read_set_from_file ( filename : str ) -> Set [ str ] : collection = set ( ) with open ( filename , 'r' ) as file_ : for line in file_ : collection . add ( line . rstrip ( ) ) return collection
| 1 |
how to read a text file into a set in python
|
Extract a de - duped collection ( set ) of text from a file . Expected file format is one item per line .
|
cosqa-train-17630
|
def read_set_from_file(filename: str) -> Set[str]:
"""
Extract a de-duped collection (set) of text from a file.
Expected file format is one item per line.
"""
collection = set()
with open(filename, 'r') as file_:
for line in file_:
collection.add(line.rstrip())
return collection
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 0 |
python xml delete all atributes from element
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17631
|
def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag)
|
def _str_to_list ( value , separator ) : value_list = [ item . strip ( ) for item in value . split ( separator ) ] value_list_sanitized = builtins . list ( filter ( None , value_list ) ) if len ( value_list_sanitized ) > 0 : return value_list_sanitized else : raise ValueError ( 'Invalid list variable.' )
| 0 |
python stringify list back to list
|
Convert a string to a list with sanitization .
|
cosqa-train-17632
|
def _str_to_list(value, separator):
"""Convert a string to a list with sanitization."""
value_list = [item.strip() for item in value.split(separator)]
value_list_sanitized = builtins.list(filter(None, value_list))
if len(value_list_sanitized) > 0:
return value_list_sanitized
else:
raise ValueError('Invalid list variable.')
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
least frequent element in a list python
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17633
|
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 1 |
how to turn a list of numbers into integers in python
|
Convert a list of strings to a list of integers .
|
cosqa-train-17634
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def to_int64 ( a ) : # build new dtype and replace i4 --> i8 def promote_i4 ( typestr ) : if typestr [ 1 : ] == 'i4' : typestr = typestr [ 0 ] + 'i8' return typestr dtype = [ ( name , promote_i4 ( typestr ) ) for name , typestr in a . dtype . descr ] return a . astype ( dtype )
| 1 |
python change array dtype to int
|
Return view of the recarray with all int32 cast to int64 .
|
cosqa-train-17635
|
def to_int64(a):
"""Return view of the recarray with all int32 cast to int64."""
# build new dtype and replace i4 --> i8
def promote_i4(typestr):
if typestr[1:] == 'i4':
typestr = typestr[0]+'i8'
return typestr
dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype.descr]
return a.astype(dtype)
|
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 0 |
python cast str into int
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-17636
|
def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s
|
def _validate_authority_uri_abs_path ( host , path ) : if len ( host ) > 0 and len ( path ) > 0 and not path . startswith ( "/" ) : raise ValueError ( "Path in a URL with authority " "should start with a slash ('/') if set" )
| 1 |
python validate a file path or uri
|
Ensure that path in URL with authority starts with a leading slash .
|
cosqa-train-17637
|
def _validate_authority_uri_abs_path(host, path):
"""Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not.
"""
if len(host) > 0 and len(path) > 0 and not path.startswith("/"):
raise ValueError(
"Path in a URL with authority " "should start with a slash ('/') if set"
)
|
def warn_if_nans_exist ( X ) : null_count = count_rows_with_nans ( X ) total = len ( X ) percent = 100 * null_count / total if null_count > 0 : warning_message = 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' 'complete rows will be plotted.' . format ( null_count , total , percent ) warnings . warn ( warning_message , DataWarning )
| 1 |
condition to see if nan in python
|
Warn if nans exist in a numpy array .
|
cosqa-train-17638
|
def warn_if_nans_exist(X):
"""Warn if nans exist in a numpy array."""
null_count = count_rows_with_nans(X)
total = len(X)
percent = 100 * null_count / total
if null_count > 0:
warning_message = \
'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \
'complete rows will be plotted.'.format(null_count, total, percent)
warnings.warn(warning_message, DataWarning)
|
def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , logger : Logger ) -> Dict [ str , Any ] : raise Exception ( 'This should never happen, since this parser relies on underlying parsers' )
| 0 |
python pyparsing two separate parsers
|
Implementation of AnyParser API
|
cosqa-train-17639
|
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],
logger: Logger) -> Dict[str, Any]:
"""
Implementation of AnyParser API
"""
raise Exception('This should never happen, since this parser relies on underlying parsers')
|
def remove_once ( gset , elem ) : remove = getattr ( gset , 'remove' , None ) if remove is not None : remove ( elem ) else : del gset [ elem ] return elem
| 1 |
delete an element from set python
|
Remove the element from a set lists or dict . >>> L = [ Lucy ] ; S = set ( [ Sky ] ) ; D = { Diamonds : True } ; >>> remove_once ( L Lucy ) ; remove_once ( S Sky ) ; remove_once ( D Diamonds ) ; >>> print L S D [] set ( [] ) {}
|
cosqa-train-17640
|
def remove_once(gset, elem):
"""Remove the element from a set, lists or dict.
>>> L = ["Lucy"]; S = set(["Sky"]); D = { "Diamonds": True };
>>> remove_once(L, "Lucy"); remove_once(S, "Sky"); remove_once(D, "Diamonds");
>>> print L, S, D
[] set([]) {}
Returns the element if it was removed. Raises one of the exceptions in
:obj:`RemoveError` otherwise.
"""
remove = getattr(gset, 'remove', None)
if remove is not None: remove(elem)
else: del gset[elem]
return elem
|
def sort_key ( x ) : name , ( r , u ) = x return - len ( u ) + u . count ( '}' ) * 100
| 1 |
how to create a sort key in python
|
>>> sort_key (( name ( ROUTE URL ))) - 3
|
cosqa-train-17641
|
def sort_key(x):
"""
>>> sort_key(('name', ('ROUTE', 'URL')))
-3
"""
name, (r, u) = x
return - len(u) + u.count('}') * 100
|
def inverted_dict_of_lists ( d ) : new_dict = { } for ( old_key , old_value_list ) in viewitems ( dict ( d ) ) : for new_key in listify ( old_value_list ) : new_dict [ new_key ] = old_key return new_dict
| 1 |
return inverted dictionary in python
|
Return a dict where the keys are all the values listed in the values of the original dict
|
cosqa-train-17642
|
def inverted_dict_of_lists(d):
"""Return a dict where the keys are all the values listed in the values of the original dict
>>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}
True
"""
new_dict = {}
for (old_key, old_value_list) in viewitems(dict(d)):
for new_key in listify(old_value_list):
new_dict[new_key] = old_key
return new_dict
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 1 |
multiply dot product of lists python
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-17643
|
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)])
|
def copy_without_prompts ( self ) : text = self . get_selected_text ( ) lines = text . split ( os . linesep ) for index , line in enumerate ( lines ) : if line . startswith ( '>>> ' ) or line . startswith ( '... ' ) : lines [ index ] = line [ 4 : ] text = os . linesep . join ( lines ) QApplication . clipboard ( ) . setText ( text )
| 1 |
get the text off the clipboard python
|
Copy text to clipboard without prompts
|
cosqa-train-17644
|
def copy_without_prompts(self):
"""Copy text to clipboard without prompts"""
text = self.get_selected_text()
lines = text.split(os.linesep)
for index, line in enumerate(lines):
if line.startswith('>>> ') or line.startswith('... '):
lines[index] = line[4:]
text = os.linesep.join(lines)
QApplication.clipboard().setText(text)
|
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 0 |
python check if a file path contains a file
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17645
|
def valid_file(path: str) -> bool:
"""
Verifies that a string path actually exists and is a file
:param path: The path to verify
:return: **True** if path exist and is a file
"""
path = Path(path).expanduser()
log.debug("checking if %s is a valid file", path)
return path.exists() and path.is_file()
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 0 |
dot product python using itertools
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-17646
|
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)])
|
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 1 |
how to get domain from url netloc python
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-17647
|
def url_host(url: str) -> str:
"""
Parses hostname from URL.
:param url: URL
:return: hostname
"""
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else ''
|
def maybe_infer_dtype_type ( element ) : tipo = None if hasattr ( element , 'dtype' ) : tipo = element . dtype elif is_list_like ( element ) : element = np . asarray ( element ) tipo = element . dtype return tipo
| 1 |
how to identify the data type in python without the built in function
|
Try to infer an object s dtype for use in arithmetic ops
|
cosqa-train-17648
|
def maybe_infer_dtype_type(element):
"""Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, and possibly the iterator
protocol.
Returns
-------
tipo : type
Examples
--------
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
numpy.int64
"""
tipo = None
if hasattr(element, 'dtype'):
tipo = element.dtype
elif is_list_like(element):
element = np.asarray(element)
tipo = element.dtype
return tipo
|
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
| 0 |
python wordnet lemmatize a word
|
Returns a list of synsets of a word after lemmatization .
|
cosqa-train-17649
|
def has_synset(word: str) -> list:
"""" Returns a list of synsets of a word after lemmatization. """
return wn.synsets(lemmatize(word, neverstem=True))
|
def hex_to_int ( value ) : if version_info . major >= 3 : return int . from_bytes ( value , "big" ) return int ( value . encode ( "hex" ) , 16 )
| 0 |
hex to integer converter in python
|
Convert hex string like \ x0A \ xE3 to 2787 .
|
cosqa-train-17650
|
def hex_to_int(value):
"""
Convert hex string like "\x0A\xE3" to 2787.
"""
if version_info.major >= 3:
return int.from_bytes(value, "big")
return int(value.encode("hex"), 16)
|
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
| 1 |
python count occurences in a list
|
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
|
cosqa-train-17651
|
def count(args):
""" count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1})
"""
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts
|
def uppercase_chars ( string : any ) -> str : return '' . join ( [ c if c . isupper ( ) else '' for c in str ( string ) ] )
| 1 |
make python string uppercase
|
Return all ( and only ) the uppercase chars in the given string .
|
cosqa-train-17652
|
def uppercase_chars(string: any) -> str:
"""Return all (and only) the uppercase chars in the given string."""
return ''.join([c if c.isupper() else '' for c in str(string)])
|
def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result
| 0 |
how to change string to a date in python
|
Creates a datetime from GnuCash 2 . 6 date string
|
cosqa-train-17653
|
def get_from_gnucash26_date(date_str: str) -> date:
""" Creates a datetime from GnuCash 2.6 date string """
date_format = "%Y%m%d"
result = datetime.strptime(date_str, date_format).date()
return result
|
def partition_items ( count , bin_size ) : num_bins = int ( math . ceil ( count / float ( bin_size ) ) ) bins = [ 0 ] * num_bins for i in range ( count ) : bins [ i % num_bins ] += 1 return bins
| 0 |
python design to break into equal sizes in 26 bins
|
Given the total number of items determine the number of items that can be added to each bin with a limit on the bin size .
|
cosqa-train-17654
|
def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if you only have ten items, you'll have two groups of three and
two of two.
>>> partition_items(10, 3)
[3, 3, 2, 2]
"""
num_bins = int(math.ceil(count / float(bin_size)))
bins = [0] * num_bins
for i in range(count):
bins[i % num_bins] += 1
return bins
|
async def async_run ( self ) -> None : self . main_task = self . loop . create_task ( self . main ( ) ) await self . main_task
| 1 |
python thread spawn async
|
Asynchronously run the worker does not close connections . Useful when testing .
|
cosqa-train-17655
|
async def async_run(self) -> None:
"""
Asynchronously run the worker, does not close connections. Useful when testing.
"""
self.main_task = self.loop.create_task(self.main())
await self.main_task
|
def _read_section ( self ) : lines = [ self . _last [ self . _last . find ( ":" ) + 1 : ] ] self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : lines . append ( self . _last ) self . _last = self . _f . readline ( ) return lines
| 1 |
python read last lines of file
|
Read and return an entire section
|
cosqa-train-17656
|
def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
return lines
|
def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
| 0 |
how to get the maximum value of the columns in python
|
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
|
cosqa-train-17657
|
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``.
"""
if not rows:
return []
value_row_pairs = [(row.values[column.name], row) for row in rows]
if not value_row_pairs:
return []
# Returns a list containing the row with the max cell value.
return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
|
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
python most negative number in an array
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-17658
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 0 |
python3 check if string validte date
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-17659
|
def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
most frequent element in list in python
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17660
|
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
|
def _get_ipv6_from_binary ( self , bin_addr ) : hi = bin_addr >> 64 lo = bin_addr & 0xFFFFFFFF return socket . inet_ntop ( socket . AF_INET6 , struct . pack ( "!QQ" , hi , lo ) )
| 1 |
python unpack ip packets
|
Converts binary address to Ipv6 format .
|
cosqa-train-17661
|
def _get_ipv6_from_binary(self, bin_addr):
"""Converts binary address to Ipv6 format."""
hi = bin_addr >> 64
lo = bin_addr & 0xFFFFFFFF
return socket.inet_ntop(socket.AF_INET6, struct.pack("!QQ", hi, lo))
|
def iprotate ( l , steps = 1 ) : if len ( l ) : steps %= len ( l ) if steps : firstPart = l [ : steps ] del l [ : steps ] l . extend ( firstPart ) return l
| 1 |
how to rotate the elements present in the list in python
|
r Like rotate but modifies l in - place .
|
cosqa-train-17662
|
def iprotate(l, steps=1):
r"""Like rotate, but modifies `l` in-place.
>>> l = [1,2,3]
>>> iprotate(l) is l
True
>>> l
[2, 3, 1]
>>> iprotate(iprotate(l, 2), -3)
[1, 2, 3]
"""
if len(l):
steps %= len(l)
if steps:
firstPart = l[:steps]
del l[:steps]
l.extend(firstPart)
return l
|
def has_value ( cls , value : int ) -> bool : return any ( value == item . value for item in cls )
| 1 |
check if value in enum python
|
True if specified value exists in int enum ; otherwise False .
|
cosqa-train-17663
|
def has_value(cls, value: int) -> bool:
"""True if specified value exists in int enum; otherwise, False."""
return any(value == item.value for item in cls)
|
def connect_to_database_odbc_access ( self , dsn : str , autocommit : bool = True ) -> None : self . connect ( engine = ENGINE_ACCESS , interface = INTERFACE_ODBC , dsn = dsn , autocommit = autocommit )
| 1 |
python how to connect to an established odbc connection oracle
|
Connects to an Access database via ODBC with the DSN prespecified .
|
cosqa-train-17664
|
def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit)
|
def encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) }
| 0 |
how to create a dictonary from a list of words in python
|
Converts a list into a space - separated string and puts it in a dictionary
|
cosqa-train-17665
|
def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)}
|
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 1 |
check a path is valid or not python
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17666
|
def valid_file(path: str) -> bool:
"""
Verifies that a string path actually exists and is a file
:param path: The path to verify
:return: **True** if path exist and is a file
"""
path = Path(path).expanduser()
log.debug("checking if %s is a valid file", path)
return path.exists() and path.is_file()
|
def valid_date ( x : str ) -> bool : try : if x != dt . datetime . strptime ( x , DATE_FORMAT ) . strftime ( DATE_FORMAT ) : raise ValueError return True except ValueError : return False
| 0 |
how to test whether the date is valid in python
|
Retrun True if x is a valid YYYYMMDD date ; otherwise return False .
|
cosqa-train-17667
|
def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False
|
def has_enumerated_namespace_name ( self , namespace : str , name : str ) -> bool : return self . has_enumerated_namespace ( namespace ) and name in self . namespace_to_terms [ namespace ]
| 0 |
how to check whether a namespace exists or not in gae python
|
Check that the namespace is defined by an enumeration and that the name is a member .
|
cosqa-train-17668
|
def has_enumerated_namespace_name(self, namespace: str, name: str) -> bool:
"""Check that the namespace is defined by an enumeration and that the name is a member."""
return self.has_enumerated_namespace(namespace) and name in self.namespace_to_terms[namespace]
|
def list_to_str ( lst ) : if len ( lst ) == 1 : str_ = lst [ 0 ] elif len ( lst ) == 2 : str_ = ' and ' . join ( lst ) elif len ( lst ) > 2 : str_ = ', ' . join ( lst [ : - 1 ] ) str_ += ', and {0}' . format ( lst [ - 1 ] ) else : raise ValueError ( 'List of length 0 provided.' ) return str_
| 1 |
python create string from list without commas
|
Turn a list into a comma - and / or and - separated string .
|
cosqa-train-17669
|
def list_to_str(lst):
"""
Turn a list into a comma- and/or and-separated string.
Parameters
----------
lst : :obj:`list`
A list of strings to join into a single string.
Returns
-------
str_ : :obj:`str`
A string with commas and/or ands separating th elements from ``lst``.
"""
if len(lst) == 1:
str_ = lst[0]
elif len(lst) == 2:
str_ = ' and '.join(lst)
elif len(lst) > 2:
str_ = ', '.join(lst[:-1])
str_ += ', and {0}'.format(lst[-1])
else:
raise ValueError('List of length 0 provided.')
return str_
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 1 |
python limit function time
|
Rate limit a function .
|
cosqa-train-17670
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def numchannels ( samples : np . ndarray ) -> int : if len ( samples . shape ) == 1 : return 1 else : return samples . shape [ 1 ]
| 1 |
extract number of channels in an image python
|
return the number of channels present in samples
|
cosqa-train-17671
|
def numchannels(samples:np.ndarray) -> int:
"""
return the number of channels present in samples
samples: a numpy array as returned by sndread
for multichannel audio, samples is always interleaved,
meaning that samples[n] returns always a frame, which
is either a single scalar for mono audio, or an array
for multichannel audio.
"""
if len(samples.shape) == 1:
return 1
else:
return samples.shape[1]
|
def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE )
| 1 |
check if a sttring has whitespaces in python
|
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected
|
cosqa-train-17672
|
def _check_whitespace(string):
"""
Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected
"""
if string.count(' ') + string.count('\t') + string.count('\n') > 0:
raise ValueError(INSTRUCTION_HAS_WHITESPACE)
|
def fcast ( value : float ) -> TensorLike : newvalue = tf . cast ( value , FTYPE ) if DEVICE == 'gpu' : newvalue = newvalue . gpu ( ) # Why is this needed? # pragma: no cover return newvalue
| 0 |
python pytorch change byte tensor to float tensor
|
Cast to float tensor
|
cosqa-train-17673
|
def fcast(value: float) -> TensorLike:
"""Cast to float tensor"""
newvalue = tf.cast(value, FTYPE)
if DEVICE == 'gpu':
newvalue = newvalue.gpu() # Why is this needed? # pragma: no cover
return newvalue
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 1 |
return to exit a function python
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-17674
|
def Exit(msg, code=1):
"""Exit execution with return code and message
:param msg: Message displayed prior to exit
:param code: code returned upon exiting
"""
print >> sys.stderr, msg
sys.exit(code)
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 0 |
all dtype of columns python
|
Returns all column names and their data types as a list .
|
cosqa-train-17675
|
def dtypes(self):
"""Returns all column names and their data types as a list.
>>> df.dtypes
[('age', 'int'), ('name', 'string')]
"""
return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
|
def _rindex ( mylist : Sequence [ T ] , x : T ) -> int : return len ( mylist ) - mylist [ : : - 1 ] . index ( x ) - 1
| 0 |
python get last index of char
|
Index of the last occurrence of x in the sequence .
|
cosqa-train-17676
|
def _rindex(mylist: Sequence[T], x: T) -> int:
"""Index of the last occurrence of x in the sequence."""
return len(mylist) - mylist[::-1].index(x) - 1
|
def rmglob ( pattern : str ) -> None : for f in glob . glob ( pattern ) : os . remove ( f )
| 0 |
python delete all files mathing regex
|
Deletes all files whose filename matches the glob pattern ( via : func : glob . glob ) .
|
cosqa-train-17677
|
def rmglob(pattern: str) -> None:
"""
Deletes all files whose filename matches the glob ``pattern`` (via
:func:`glob.glob`).
"""
for f in glob.glob(pattern):
os.remove(f)
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
python timing the execution of a function
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17678
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def are_token_parallel ( sequences : Sequence [ Sized ] ) -> bool : if not sequences or len ( sequences ) == 1 : return True return all ( len ( s ) == len ( sequences [ 0 ] ) for s in sequences )
| 0 |
python check is list is sequential
|
Returns True if all sequences in the list have the same length .
|
cosqa-train-17679
|
def are_token_parallel(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences in the list have the same length.
"""
if not sequences or len(sequences) == 1:
return True
return all(len(s) == len(sequences[0]) for s in sequences)
|
def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False
| 0 |
check queue empty python
|
Return True if the queue is full False otherwise ( not reliable! ) .
|
cosqa-train-17680
|
def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False
|
def is_iterable ( etype ) -> bool : return type ( etype ) is GenericMeta and issubclass ( etype . __extra__ , Iterable )
| 0 |
python check if list is empy
|
Determine whether etype is a List or other iterable
|
cosqa-train-17681
|
def is_iterable(etype) -> bool:
""" Determine whether etype is a List or other iterable """
return type(etype) is GenericMeta and issubclass(etype.__extra__, Iterable)
|
def extend ( a : dict , b : dict ) -> dict : res = a . copy ( ) res . update ( b ) return res
| 1 |
python dict from another python dict
|
Merge two dicts and return a new dict . Much like subclassing works .
|
cosqa-train-17682
|
def extend(a: dict, b: dict) -> dict:
"""Merge two dicts and return a new dict. Much like subclassing works."""
res = a.copy()
res.update(b)
return res
|
def _skip_section ( self ) : self . _last = self . _f . readline ( ) while len ( self . _last ) > 0 and len ( self . _last [ 0 ] . strip ( ) ) == 0 : self . _last = self . _f . readline ( )
| 0 |
how to skip the first line while looping over a file in python
|
Skip a section
|
cosqa-train-17683
|
def _skip_section(self):
"""Skip a section"""
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
self._last = self._f.readline()
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 1 |
giving the time a function took to execute python
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17684
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def de_duplicate ( items ) : result = [ ] for item in items : if item not in result : result . append ( item ) return result
| 1 |
removing a duplicate number in list python
|
Remove any duplicate item preserving order
|
cosqa-train-17685
|
def de_duplicate(items):
"""Remove any duplicate item, preserving order
>>> de_duplicate([1, 2, 1, 2])
[1, 2]
"""
result = []
for item in items:
if item not in result:
result.append(item)
return result
|
def lower_camel_case_from_underscores ( string ) : components = string . split ( '_' ) string = components [ 0 ] for component in components [ 1 : ] : string += component [ 0 ] . upper ( ) + component [ 1 : ] return string
| 1 |
python variable names starting with underscore
|
generate a lower - cased camelCase string from an underscore_string . For example : my_variable_name - > myVariableName
|
cosqa-train-17686
|
def lower_camel_case_from_underscores(string):
"""generate a lower-cased camelCase string from an underscore_string.
For example: my_variable_name -> myVariableName"""
components = string.split('_')
string = components[0]
for component in components[1:]:
string += component[0].upper() + component[1:]
return string
|
def butlast ( iterable ) : iterable = iter ( iterable ) try : first = next ( iterable ) except StopIteration : return for second in iterable : yield first first = second
| 1 |
python loop skip the last element of a list
|
Yield all items from iterable except the last one .
|
cosqa-train-17687
|
def butlast(iterable):
"""Yield all items from ``iterable`` except the last one.
>>> list(butlast(['spam', 'eggs', 'ham']))
['spam', 'eggs']
>>> list(butlast(['spam']))
[]
>>> list(butlast([]))
[]
"""
iterable = iter(iterable)
try:
first = next(iterable)
except StopIteration:
return
for second in iterable:
yield first
first = second
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
get timing of functions python
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17688
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def getIndex ( predicateFn : Callable [ [ T ] , bool ] , items : List [ T ] ) -> int : try : return next ( i for i , v in enumerate ( items ) if predicateFn ( v ) ) except StopIteration : return - 1
| 1 |
python get the index of element in a list with condition
|
Finds the index of an item in list which satisfies predicate : param predicateFn : predicate function to run on items of list : param items : list of tuples : return : first index for which predicate function returns True
|
cosqa-train-17689
|
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int:
"""
Finds the index of an item in list, which satisfies predicate
:param predicateFn: predicate function to run on items of list
:param items: list of tuples
:return: first index for which predicate function returns True
"""
try:
return next(i for i, v in enumerate(items) if predicateFn(v))
except StopIteration:
return -1
|
async def fetchall ( self ) -> Iterable [ sqlite3 . Row ] : return await self . _execute ( self . _cursor . fetchall )
| 1 |
python cursor select fetchall
|
Fetch all remaining rows .
|
cosqa-train-17690
|
async def fetchall(self) -> Iterable[sqlite3.Row]:
"""Fetch all remaining rows."""
return await self._execute(self._cursor.fetchall)
|
def is_natural ( x ) : try : is_integer = int ( x ) == x except ( TypeError , ValueError ) : return False return is_integer and x >= 0
| 0 |
how to disallow negative numbers in python
|
A non - negative integer .
|
cosqa-train-17691
|
def is_natural(x):
"""A non-negative integer."""
try:
is_integer = int(x) == x
except (TypeError, ValueError):
return False
return is_integer and x >= 0
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
how to check if a string is an int in python
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17692
|
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or isinstance(string, _text_type)) and \
_isconvertible(int, string)
|
def file_exists ( fname ) : try : return fname and os . path . exists ( fname ) and os . path . getsize ( fname ) > 0 except OSError : return False
| 1 |
check if directory is empty or has files with python
|
Check if a file exists and is non - empty .
|
cosqa-train-17693
|
def file_exists(fname):
"""Check if a file exists and is non-empty.
"""
try:
return fname and os.path.exists(fname) and os.path.getsize(fname) > 0
except OSError:
return False
|
def dtypes ( self ) : return [ ( str ( f . name ) , f . dataType . simpleString ( ) ) for f in self . schema . fields ]
| 1 |
show types python columns
|
Returns all column names and their data types as a list .
|
cosqa-train-17694
|
def dtypes(self):
"""Returns all column names and their data types as a list.
>>> df.dtypes
[('age', 'int'), ('name', 'string')]
"""
return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 0 |
elementtree remove element xml python
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17695
|
def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag)
|
def is_unicode ( string ) : str_type = str ( type ( string ) ) if str_type . find ( 'str' ) > 0 or str_type . find ( 'unicode' ) > 0 : return True return False
| 0 |
python check type of variable is string
|
Validates that the object itself is some kinda string
|
cosqa-train-17696
|
def is_unicode(string):
"""Validates that the object itself is some kinda string"""
str_type = str(type(string))
if str_type.find('str') > 0 or str_type.find('unicode') > 0:
return True
return False
|
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 1 |
how to read file from s3 bucket python
|
Pull a file directly from S3 .
|
cosqa-train-17697
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def timeit ( func , * args , * * kwargs ) : start_time = time . time ( ) res = func ( * args , * * kwargs ) timing = time . time ( ) - start_time return res , timing
| 0 |
python track the time it takes to run a function
|
Time execution of function . Returns ( res seconds ) .
|
cosqa-train-17698
|
def timeit(func, *args, **kwargs):
"""
Time execution of function. Returns (res, seconds).
>>> res, timing = timeit(time.sleep, 1)
"""
start_time = time.time()
res = func(*args, **kwargs)
timing = time.time() - start_time
return res, timing
|
def get_line_number ( line_map , offset ) : for lineno , line_offset in enumerate ( line_map , start = 1 ) : if line_offset > offset : return lineno return - 1
| 0 |
python call string positions from a line in a list
|
Find a line number given a line map and a character offset .
|
cosqa-train-17699
|
def get_line_number(line_map, offset):
"""Find a line number, given a line map and a character offset."""
for lineno, line_offset in enumerate(line_map, start=1):
if line_offset > offset:
return lineno
return -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.