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 get_incomplete_path ( filename ) : random_suffix = "" . join ( random . choice ( string . ascii_uppercase + string . digits ) for _ in range ( 6 ) ) return filename + ".incomplete" + random_suffix
| 1 |
python ceate random file name
|
Returns a temporary filename based on filename .
|
cosqa-train-12500
|
def get_incomplete_path(filename):
"""Returns a temporary filename based on filename."""
random_suffix = "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
return filename + ".incomplete" + random_suffix
|
def _unzip_handle ( handle ) : if isinstance ( handle , basestring ) : handle = _gzip_open_filename ( handle ) else : handle = _gzip_open_handle ( handle ) return handle
| 1 |
stackoverflow python unzip file
|
Transparently unzip the file handle
|
cosqa-train-12501
|
def _unzip_handle(handle):
"""Transparently unzip the file handle"""
if isinstance(handle, basestring):
handle = _gzip_open_filename(handle)
else:
handle = _gzip_open_handle(handle)
return handle
|
def getCenter ( self ) : return Location ( self . x + ( self . w / 2 ) , self . y + ( self . h / 2 ) )
| 1 |
python center region in square
|
Return the Location of the center of this region
|
cosqa-train-12502
|
def getCenter(self):
""" Return the ``Location`` of the center of this region """
return Location(self.x+(self.w/2), self.y+(self.h/2))
|
def staticdir ( ) : root = os . path . abspath ( os . path . dirname ( __file__ ) ) return os . path . join ( root , "static" )
| 1 |
static folder config in python flask
|
Return the location of the static data directory .
|
cosqa-train-12503
|
def staticdir():
"""Return the location of the static data directory."""
root = os.path.abspath(os.path.dirname(__file__))
return os.path.join(root, "static")
|
def get ( key , default = None ) : data = get_form ( ) or get_query_string ( ) return data . get ( key , default )
| 1 |
python cgi form get value
|
return the key from the request
|
cosqa-train-12504
|
def get(key, default=None):
""" return the key from the request
"""
data = get_form() or get_query_string()
return data.get(key, default)
|
def _StopStatusUpdateThread ( self ) : self . _status_update_active = False if self . _status_update_thread . isAlive ( ) : self . _status_update_thread . join ( ) self . _status_update_thread = None
| 1 |
stop a running thread python
|
Stops the status update thread .
|
cosqa-train-12505
|
def _StopStatusUpdateThread(self):
"""Stops the status update thread."""
self._status_update_active = False
if self._status_update_thread.isAlive():
self._status_update_thread.join()
self._status_update_thread = None
|
def clean_with_zeros ( self , x ) : x [ ~ np . any ( np . isnan ( x ) | np . isinf ( x ) , axis = 1 ) ] = 0 return x
| 1 |
python change all column row values nan to zero
|
set nan and inf rows from x to zero
|
cosqa-train-12506
|
def clean_with_zeros(self,x):
""" set nan and inf rows from x to zero"""
x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0
return x
|
def _removeStopwords ( text_list ) : output_list = [ ] for word in text_list : if word . lower ( ) not in _stopwords : output_list . append ( word ) return output_list
| 1 |
stopwords list remove python
|
Removes stopwords contained in a list of words .
|
cosqa-train-12507
|
def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.lower() not in _stopwords:
output_list.append(word)
return output_list
|
def _to_corrected_pandas_type ( dt ) : import numpy as np if type ( dt ) == ByteType : return np . int8 elif type ( dt ) == ShortType : return np . int16 elif type ( dt ) == IntegerType : return np . int32 elif type ( dt ) == FloatType : return np . float32 else : return None
| 1 |
python change data type in data frame
|
When converting Spark SQL records to Pandas DataFrame the inferred data type may be wrong . This method gets the corrected data type for Pandas if that type may be inferred uncorrectly .
|
cosqa-train-12508
|
def _to_corrected_pandas_type(dt):
"""
When converting Spark SQL records to Pandas DataFrame, the inferred data type may be wrong.
This method gets the corrected data type for Pandas if that type may be inferred uncorrectly.
"""
import numpy as np
if type(dt) == ByteType:
return np.int8
elif type(dt) == ShortType:
return np.int16
elif type(dt) == IntegerType:
return np.int32
elif type(dt) == FloatType:
return np.float32
else:
return None
|
def to_list ( self ) : return [ [ int ( self . table . cell_values [ 0 ] [ 1 ] ) , int ( self . table . cell_values [ 0 ] [ 2 ] ) ] , [ int ( self . table . cell_values [ 1 ] [ 1 ] ) , int ( self . table . cell_values [ 1 ] [ 2 ] ) ] ]
| 1 |
store the column values as a list in python
|
Convert this confusion matrix into a 2x2 plain list of values .
|
cosqa-train-12509
|
def to_list(self):
"""Convert this confusion matrix into a 2x2 plain list of values."""
return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])],
[int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]
|
def convert_str_to_datetime ( df , * , column : str , format : str ) : df [ column ] = pd . to_datetime ( df [ column ] , format = format ) return df
| 0 |
python change date format of a column
|
Convert string column into datetime column
|
cosqa-train-12510
|
def convert_str_to_datetime(df, *, column: str, format: str):
"""
Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))
"""
df[column] = pd.to_datetime(df[column], format=format)
return df
|
def _strvar ( a , prec = '{:G}' ) : return ' ' . join ( [ prec . format ( i ) for i in np . atleast_1d ( a ) ] )
| 1 |
str function python precision
|
r Return variable as a string to print with given precision .
|
cosqa-train-12511
|
def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)])
|
def inc_date ( date_obj , num , date_fmt ) : return ( date_obj + timedelta ( days = num ) ) . strftime ( date_fmt )
| 1 |
python change date format of variable
|
Increment the date by a certain number and return date object . as the specific string format .
|
cosqa-train-12512
|
def inc_date(date_obj, num, date_fmt):
"""Increment the date by a certain number and return date object.
as the specific string format.
"""
return (date_obj + timedelta(days=num)).strftime(date_fmt)
|
def get_file_string ( filepath ) : with open ( os . path . abspath ( filepath ) ) as f : return f . read ( )
| 1 |
string get file from path python
|
Get string from file .
|
cosqa-train-12513
|
def get_file_string(filepath):
"""Get string from file."""
with open(os.path.abspath(filepath)) as f:
return f.read()
|
def styles ( self , dictobj ) : for k in dictobj : self . chart_style [ k ] = dictobj [ k ]
| 1 |
python change dictionary in for loop
|
Add or update styles
|
cosqa-train-12514
|
def styles(self, dictobj):
"""
Add or update styles
"""
for k in dictobj:
self.chart_style[k] = dictobj[k]
|
def string_to_int ( s ) : result = 0 for c in s : if not isinstance ( c , int ) : c = ord ( c ) result = 256 * result + c return result
| 1 |
string of binary to int python
|
Convert a string of bytes into an integer as per X9 . 62 .
|
cosqa-train-12515
|
def string_to_int( s ):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int): c = ord( c )
result = 256 * result + c
return result
|
def add_exec_permission_to ( target_file ) : mode = os . stat ( target_file ) . st_mode os . chmod ( target_file , mode | stat . S_IXUSR )
| 1 |
python change file permissions execution
|
Add executable permissions to the file
|
cosqa-train-12516
|
def add_exec_permission_to(target_file):
"""Add executable permissions to the file
:param target_file: the target file whose permission to be changed
"""
mode = os.stat(target_file).st_mode
os.chmod(target_file, mode | stat.S_IXUSR)
|
def string_to_int ( s ) : result = 0 for c in s : if not isinstance ( c , int ) : c = ord ( c ) result = 256 * result + c return result
| 1 |
string of binary to intpython
|
Convert a string of bytes into an integer as per X9 . 62 .
|
cosqa-train-12517
|
def string_to_int( s ):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int): c = ord( c )
result = 256 * result + c
return result
|
def flipwritable ( fn , mode = None ) : if os . access ( fn , os . W_OK ) : return None old_mode = os . stat ( fn ) . st_mode os . chmod ( fn , stat . S_IWRITE | old_mode ) return old_mode
| 1 |
python change file to readonly
|
Flip the writability of a file and return the old mode . Returns None if the file is already writable .
|
cosqa-train-12518
|
def flipwritable(fn, mode=None):
"""
Flip the writability of a file and return the old mode. Returns None
if the file is already writable.
"""
if os.access(fn, os.W_OK):
return None
old_mode = os.stat(fn).st_mode
os.chmod(fn, stat.S_IWRITE | old_mode)
return old_mode
|
def _sub_patterns ( patterns , text ) : for pattern , repl in patterns : text = re . sub ( pattern , repl , text ) return text
| 1 |
string replace python multiple substring
|
Apply re . sub to bunch of ( pattern repl )
|
cosqa-train-12519
|
def _sub_patterns(patterns, text):
"""
Apply re.sub to bunch of (pattern, repl)
"""
for pattern, repl in patterns:
text = re.sub(pattern, repl, text)
return text
|
def to_camel ( s ) : # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re . sub ( r'_([a-zA-Z])' , lambda m : m . group ( 1 ) . upper ( ) , '_' + s )
| 1 |
python change lowercase to uppercase input
|
: param string s : under_scored string to be CamelCased : return : CamelCase version of input : rtype : str
|
cosqa-train-12520
|
def to_camel(s):
"""
:param string s: under_scored string to be CamelCased
:return: CamelCase version of input
:rtype: str
"""
# r'(?!^)_([a-zA-Z]) original regex wasn't process first groups
return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s)
|
def covstr ( s ) : try : ret = int ( s ) except ValueError : ret = float ( s ) return ret
| 1 |
python change str to float
|
convert string to int or float .
|
cosqa-train-12521
|
def covstr(s):
""" convert string to int or float. """
try:
ret = int(s)
except ValueError:
ret = float(s)
return ret
|
def synth_hangul ( string ) : raise NotImplementedError return '' . join ( [ '' . join ( '' . join ( jamo_to_hcj ( _ ) ) for _ in string ) ] )
| 1 |
string transformation python hangman
|
Convert jamo characters in a string into hcj as much as possible .
|
cosqa-train-12522
|
def synth_hangul(string):
"""Convert jamo characters in a string into hcj as much as possible."""
raise NotImplementedError
return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)])
|
def str2int ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . str2int ( num )
| 1 |
python change str value to int
|
helper function for quick base conversions from strings to integers
|
cosqa-train-12523
|
def str2int(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from strings to integers"""
return NumConv(radix, alphabet).str2int(num)
|
def bitsToString ( arr ) : s = array ( 'c' , '.' * len ( arr ) ) for i in xrange ( len ( arr ) ) : if arr [ i ] == 1 : s [ i ] = '*' return s
| 1 |
string with spaces in single array python
|
Returns a string representing a numpy array of 0 s and 1 s
|
cosqa-train-12524
|
def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s
|
def deserialize_date ( string ) : try : from dateutil . parser import parse return parse ( string ) . date ( ) except ImportError : return string
| 1 |
python change string into date object
|
Deserializes string to date .
|
cosqa-train-12525
|
def deserialize_date(string):
"""
Deserializes string to date.
:param string: str.
:type string: str
:return: date.
:rtype: date
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
|
def quote ( self , s ) : if six . PY2 : from pipes import quote else : from shlex import quote return quote ( s )
| 1 |
strings python double or single quote
|
Return a shell - escaped version of the string s .
|
cosqa-train-12526
|
def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s)
|
def __init__ ( self , encoding = 'utf-8' ) : super ( StdinInputReader , self ) . __init__ ( sys . stdin , encoding = encoding )
| 1 |
python change the encoding of stdin
|
Initializes an stdin input reader .
|
cosqa-train-12527
|
def __init__(self, encoding='utf-8'):
"""Initializes an stdin input reader.
Args:
encoding (Optional[str]): input encoding.
"""
super(StdinInputReader, self).__init__(sys.stdin, encoding=encoding)
|
def strip_querystring ( url ) : p = six . moves . urllib . parse . urlparse ( url ) return p . scheme + "://" + p . netloc + p . path
| 1 |
strip fragment from url python
|
Remove the querystring from the end of a URL .
|
cosqa-train-12528
|
def strip_querystring(url):
"""Remove the querystring from the end of a URL."""
p = six.moves.urllib.parse.urlparse(url)
return p.scheme + "://" + p.netloc + p.path
|
def equal ( x , y ) : x = BigFloat . _implicit_convert ( x ) y = BigFloat . _implicit_convert ( y ) return mpfr . mpfr_equal_p ( x , y )
| 1 |
python check 2 float is equal
|
Return True if x == y and False otherwise .
|
cosqa-train-12529
|
def equal(x, y):
"""
Return True if x == y and False otherwise.
This function returns False whenever x and/or y is a NaN.
"""
x = BigFloat._implicit_convert(x)
y = BigFloat._implicit_convert(y)
return mpfr.mpfr_equal_p(x, y)
|
def load_from_file ( module_path ) : from imp import load_module , PY_SOURCE imported = None if module_path : with open ( module_path , 'r' ) as openfile : imported = load_module ( 'mod' , openfile , module_path , ( 'imported' , 'r' , PY_SOURCE ) ) return imported
| 1 |
style not loading if python compiled django
|
Load a python module from its absolute filesystem path
|
cosqa-train-12530
|
def load_from_file(module_path):
"""
Load a python module from its absolute filesystem path
Borrowed from django-cms
"""
from imp import load_module, PY_SOURCE
imported = None
if module_path:
with open(module_path, 'r') as openfile:
imported = load_module('mod', openfile, module_path, ('imported', 'r', PY_SOURCE))
return imported
|
def _is_iterable ( item ) : return isinstance ( item , collections . Iterable ) and not isinstance ( item , six . string_types )
| 1 |
python check a var is iterable
|
Checks if an item is iterable ( list tuple generator ) but not string
|
cosqa-train-12531
|
def _is_iterable(item):
""" Checks if an item is iterable (list, tuple, generator), but not string """
return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)
|
def submitbutton ( self , request , tag ) : return tags . input ( type = 'submit' , name = '__submit__' , value = self . _getDescription ( ) )
| 1 |
submit information to a form python
|
Render an INPUT element of type SUBMIT which will post this form to the server .
|
cosqa-train-12532
|
def submitbutton(self, request, tag):
"""
Render an INPUT element of type SUBMIT which will post this form to the
server.
"""
return tags.input(type='submit',
name='__submit__',
value=self._getDescription())
|
def _not_none ( items ) : if not isinstance ( items , ( tuple , list ) ) : items = ( items , ) return all ( item is not _none for item in items )
| 1 |
python check all are none or none are none
|
Whether the item is a placeholder or contains a placeholder .
|
cosqa-train-12533
|
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 correspond ( text ) : subproc . stdin . write ( text ) subproc . stdin . flush ( ) return drain ( )
| 0 |
subprocess stdin from python thread
|
Communicate with the child process without closing stdin .
|
cosqa-train-12534
|
def correspond(text):
"""Communicate with the child process without closing stdin."""
subproc.stdin.write(text)
subproc.stdin.flush()
return drain()
|
def is_readable ( fp , size = 1 ) : read_size = len ( fp . read ( size ) ) fp . seek ( - read_size , 1 ) return read_size == size
| 0 |
python check current file size
|
Check if the file - like object is readable .
|
cosqa-train-12535
|
def is_readable(fp, size=1):
"""
Check if the file-like object is readable.
:param fp: file-like object
:param size: byte size
:return: bool
"""
read_size = len(fp.read(size))
fp.seek(-read_size, 1)
return read_size == size
|
def filter_list_by_indices ( lst , indices ) : return [ x for i , x in enumerate ( lst ) if i in indices ]
| 1 |
subset a list using a list of indices in python
|
Return a modified list containing only the indices indicated .
|
cosqa-train-12536
|
def filter_list_by_indices(lst, indices):
"""Return a modified list containing only the indices indicated.
Args:
lst: Original list of values
indices: List of indices to keep from the original list
Returns:
list: Filtered list of values
"""
return [x for i, x in enumerate(lst) if i in indices]
|
def is_archlinux ( ) : if platform . system ( ) . lower ( ) == 'linux' : if platform . linux_distribution ( ) == ( '' , '' , '' ) : # undefined distribution. Fixed in python 3. if os . path . exists ( '/etc/arch-release' ) : return True return False
| 1 |
python check current os is linux
|
return True if the current distribution is running on debian like OS .
|
cosqa-train-12537
|
def is_archlinux():
"""return True if the current distribution is running on debian like OS."""
if platform.system().lower() == 'linux':
if platform.linux_distribution() == ('', '', ''):
# undefined distribution. Fixed in python 3.
if os.path.exists('/etc/arch-release'):
return True
return False
|
def maybeparens ( lparen , item , rparen ) : return item | lparen . suppress ( ) + item + rparen . suppress ( )
| 1 |
surrounding a variable with parentheses python
|
Wrap an item in optional parentheses only applying them if necessary .
|
cosqa-train-12538
|
def maybeparens(lparen, item, rparen):
"""Wrap an item in optional parentheses, only applying them if necessary."""
return item | lparen.suppress() + item + rparen.suppress()
|
def contains_empty ( features ) : if not features : return True for feature in features : if feature . shape [ 0 ] == 0 : return True return False
| 1 |
python check empty matrix
|
Check features data are not empty
|
cosqa-train-12539
|
def contains_empty(features):
"""Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else.
"""
if not features:
return True
for feature in features:
if feature.shape[0] == 0:
return True
return False
|
def get_python_dict ( scala_map ) : python_dict = { } keys = get_python_list ( scala_map . keys ( ) . toList ( ) ) for key in keys : python_dict [ key ] = scala_map . apply ( key ) return python_dict
| 1 |
swig c++ map to python dict
|
Return a dict from entries in a scala . collection . immutable . Map
|
cosqa-train-12540
|
def get_python_dict(scala_map):
"""Return a dict from entries in a scala.collection.immutable.Map"""
python_dict = {}
keys = get_python_list(scala_map.keys().toList())
for key in keys:
python_dict[key] = scala_map.apply(key)
return python_dict
|
def _pip_exists ( self ) : return os . path . isfile ( os . path . join ( self . path , 'bin' , 'pip' ) )
| 1 |
python check env is exists
|
Returns True if pip exists inside the virtual environment . Can be used as a naive way to verify that the environment is installed .
|
cosqa-train-12541
|
def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
|
def remove_na_arraylike ( arr ) : if is_extension_array_dtype ( arr ) : return arr [ notna ( arr ) ] else : return arr [ notna ( lib . values_from_object ( arr ) ) ]
| 1 |
take only non na values python
|
Return array - like containing only true / non - NaN values possibly empty .
|
cosqa-train-12542
|
def remove_na_arraylike(arr):
"""
Return array-like containing only true/non-NaN values, possibly empty.
"""
if is_extension_array_dtype(arr):
return arr[notna(arr)]
else:
return arr[notna(lib.values_from_object(arr))]
|
def watched_extension ( extension ) : for ext in hamlpy . VALID_EXTENSIONS : if extension . endswith ( '.' + ext ) : return True return False
| 1 |
python check filename in in a list of extension
|
Return True if the given extension is one of the watched extensions
|
cosqa-train-12543
|
def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False
|
def mean ( inlist ) : sum = 0 for item in inlist : sum = sum + item return sum / float ( len ( inlist ) )
| 1 |
taking the average of elements in a list python
|
Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) .
|
cosqa-train-12544
|
def mean(inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum / float(len(inlist))
|
def clean_float ( v ) : if v is None or not str ( v ) . strip ( ) : return None return float ( str ( v ) . replace ( ',' , '' ) )
| 0 |
python check for empty value in float object
|
Remove commas from a float
|
cosqa-train-12545
|
def clean_float(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', ''))
|
def test ( ) : debuglevel = 0 while sys . argv [ 1 : ] and sys . argv [ 1 ] == '-d' : debuglevel = debuglevel + 1 del sys . argv [ 1 ] host = 'localhost' if sys . argv [ 1 : ] : host = sys . argv [ 1 ] port = 0 if sys . argv [ 2 : ] : portstr = sys . argv [ 2 ] try : port = int ( portstr ) except ValueError : port = socket . getservbyname ( portstr , 'tcp' ) tn = Telnet ( ) tn . set_debuglevel ( debuglevel ) tn . open ( host , port ) tn . interact ( ) tn . close ( )
| 1 |
telnet connection test python loop
|
Test program for telnetlib .
|
cosqa-train-12546
|
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel + 1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port)
tn.interact()
tn.close()
|
def is_clicked ( self , MouseStateType ) : return self . previous_mouse_state . query_state ( MouseStateType ) and ( not self . current_mouse_state . query_state ( MouseStateType ) )
| 1 |
python check for mouse pointer
|
Did the user depress and release the button to signify a click? MouseStateType is the button to query . Values found under StateTypes . py
|
cosqa-train-12547
|
def is_clicked(self, MouseStateType):
"""
Did the user depress and release the button to signify a click?
MouseStateType is the button to query. Values found under StateTypes.py
"""
return self.previous_mouse_state.query_state(MouseStateType) and (
not self.current_mouse_state.query_state(MouseStateType))
|
def eof ( fd ) : b = fd . read ( 1 ) end = len ( b ) == 0 if not end : curpos = fd . tell ( ) fd . seek ( curpos - 1 ) return end
| 1 |
test end of file in python
|
Determine if end - of - file is reached for file fd .
|
cosqa-train-12548
|
def eof(fd):
"""Determine if end-of-file is reached for file fd."""
b = fd.read(1)
end = len(b) == 0
if not end:
curpos = fd.tell()
fd.seek(curpos - 1)
return end
|
def is_managed ( ) : for item in sys . argv : if re . search ( r'manage.py|django-admin|django' , item ) is not None : return True return False
| 1 |
python check for run as admin
|
Check if a Django project is being managed with manage . py or django - admin scripts
|
cosqa-train-12549
|
def is_managed():
"""
Check if a Django project is being managed with ``manage.py`` or
``django-admin`` scripts
:return: Check result
:rtype: bool
"""
for item in sys.argv:
if re.search(r'manage.py|django-admin|django', item) is not None:
return True
return False
|
def is_integer_array ( val ) : return is_np_array ( val ) and issubclass ( val . dtype . type , np . integer )
| 1 |
test if a variable is an array python
|
Checks whether a variable is a numpy integer array .
|
cosqa-train-12550
|
def is_integer_array(val):
"""
Checks whether a variable is a numpy integer array.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a numpy integer array. Otherwise False.
"""
return is_np_array(val) and issubclass(val.dtype.type, np.integer)
|
def All ( sequence ) : return bool ( reduce ( lambda x , y : x and y , sequence , True ) )
| 1 |
python check if all elements satisfy a condtion
|
: param sequence : Any sequence whose elements can be evaluated as booleans . : returns : true if all elements of the sequence satisfy True and x .
|
cosqa-train-12551
|
def All(sequence):
"""
:param sequence: Any sequence whose elements can be evaluated as booleans.
:returns: true if all elements of the sequence satisfy True and x.
"""
return bool(reduce(lambda x, y: x and y, sequence, True))
|
def run ( self , value ) : if self . pass_ and not value . strip ( ) : return True if not value : return False return True
| 1 |
test if field is empty python
|
Determines if value value is empty . Keyword arguments : value str -- the value of the associated field to compare
|
cosqa-train-12552
|
def run(self, value):
""" Determines if value value is empty.
Keyword arguments:
value str -- the value of the associated field to compare
"""
if self.pass_ and not value.strip():
return True
if not value:
return False
return True
|
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 ]
| 1 |
python check if dictionary are the same
|
Test two dictionary is equal on values . ( ignore order )
|
cosqa-train-12553
|
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 check_type_and_size_of_param_list ( param_list , expected_length ) : try : assert isinstance ( param_list , list ) assert len ( param_list ) == expected_length except AssertionError : msg = "param_list must be a list containing {} elements." raise ValueError ( msg . format ( expected_length ) ) return None
| 1 |
test lenght o list python
|
Ensure that param_list is a list with the expected length . Raises a helpful ValueError if this is not the case .
|
cosqa-train-12554
|
def check_type_and_size_of_param_list(param_list, expected_length):
"""
Ensure that param_list is a list with the expected length. Raises a helpful
ValueError if this is not the case.
"""
try:
assert isinstance(param_list, list)
assert len(param_list) == expected_length
except AssertionError:
msg = "param_list must be a list containing {} elements."
raise ValueError(msg.format(expected_length))
return None
|
def eof ( fd ) : b = fd . read ( 1 ) end = len ( b ) == 0 if not end : curpos = fd . tell ( ) fd . seek ( curpos - 1 ) return end
| 1 |
python check if end of file reached
|
Determine if end - of - file is reached for file fd .
|
cosqa-train-12555
|
def eof(fd):
"""Determine if end-of-file is reached for file fd."""
b = fd.read(1)
end = len(b) == 0
if not end:
curpos = fd.tell()
fd.seek(curpos - 1)
return end
|
def _size_36 ( ) : from shutil import get_terminal_size dim = get_terminal_size ( ) if isinstance ( dim , list ) : return dim [ 0 ] , dim [ 1 ] return dim . lines , dim . columns
| 1 |
text type and size in shell for python
|
returns the rows columns of terminal
|
cosqa-train-12556
|
def _size_36():
""" returns the rows, columns of terminal """
from shutil import get_terminal_size
dim = get_terminal_size()
if isinstance(dim, list):
return dim[0], dim[1]
return dim.lines, dim.columns
|
def is_enum_type ( type_ ) : return isinstance ( type_ , type ) and issubclass ( type_ , tuple ( _get_types ( Types . ENUM ) ) )
| 1 |
python check if enum is
|
Checks if the given type is an enum type .
|
cosqa-train-12557
|
def is_enum_type(type_):
""" Checks if the given type is an enum type.
:param type_: The type to check
:return: True if the type is a enum type, otherwise False
:rtype: bool
"""
return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM)))
|
def main ( argv = None ) : args = parse_arguments ( sys . argv if argv is None else argv ) tf . logging . set_verbosity ( tf . logging . INFO ) learn_runner . run ( experiment_fn = get_experiment_fn ( args ) , output_dir = args . job_dir )
| 1 |
tf idf during single testing python
|
Run a Tensorflow model on the Iris dataset .
|
cosqa-train-12558
|
def main(argv=None):
"""Run a Tensorflow model on the Iris dataset."""
args = parse_arguments(sys.argv if argv is None else argv)
tf.logging.set_verbosity(tf.logging.INFO)
learn_runner.run(
experiment_fn=get_experiment_fn(args),
output_dir=args.job_dir)
|
def check ( self , var ) : if not isinstance ( var , _str_type ) : return False return _enum_mangle ( var ) in self . _consts
| 1 |
python check if enum value exists
|
Check whether the provided value is a valid enum constant .
|
cosqa-train-12559
|
def check(self, var):
"""Check whether the provided value is a valid enum constant."""
if not isinstance(var, _str_type): return False
return _enum_mangle(var) in self._consts
|
def print_err ( * args , end = '\n' ) : print ( * args , end = end , file = sys . stderr ) sys . stderr . flush ( )
| 0 |
the begining charecterr for a print function python
|
Similar to print but prints to stderr .
|
cosqa-train-12560
|
def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush()
|
def run ( self , value ) : if self . pass_ and not value . strip ( ) : return True if not value : return False return True
| 1 |
python check if field is empty
|
Determines if value value is empty . Keyword arguments : value str -- the value of the associated field to compare
|
cosqa-train-12561
|
def run(self, value):
""" Determines if value value is empty.
Keyword arguments:
value str -- the value of the associated field to compare
"""
if self.pass_ and not value.strip():
return True
if not value:
return False
return True
|
def Load ( file ) : with open ( file , 'rb' ) as file : model = dill . load ( file ) return model
| 1 |
the best way to load a text file into python or matlab file
|
Loads a model from specified file
|
cosqa-train-12562
|
def Load(file):
""" Loads a model from specified file """
with open(file, 'rb') as file:
model = dill.load(file)
return model
|
def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )
| 1 |
python check if file can be opened
|
Check if file is a regular file and is readable .
|
cosqa-train-12563
|
def is_readable(filename):
"""Check if file is a regular file and is readable."""
return os.path.isfile(filename) and os.access(filename, os.R_OK)
|
def qth_pw ( self , q ) : return heapq . nlargest ( q + 2 , self . _T . iteritems ( ) , key = operator . itemgetter ( 1 ) ) [ - 1 ]
| 1 |
the kth largest in a array python
|
returns the qth most probable element in the dawg .
|
cosqa-train-12564
|
def qth_pw(self, q):
"""
returns the qth most probable element in the dawg.
"""
return heapq.nlargest(q + 2, self._T.iteritems(),
key=operator.itemgetter(1))[-1]
|
def remote_file_exists ( self , url ) : status = requests . head ( url ) . status_code if status != 200 : raise RemoteFileDoesntExist
| 1 |
python check if file excists on harddrive
|
Checks whether the remote file exists .
|
cosqa-train-12565
|
def remote_file_exists(self, url):
""" Checks whether the remote file exists.
:param url:
The url that has to be checked.
:type url:
String
:returns:
**True** if remote file exists and **False** if it doesn't exist.
"""
status = requests.head(url).status_code
if status != 200:
raise RemoteFileDoesntExist
|
def do_last ( environment , seq ) : try : return next ( iter ( reversed ( seq ) ) ) except StopIteration : return environment . undefined ( 'No last item, sequence was empty.' )
| 1 |
the last first element from the queue to the end python
|
Return the last item of a sequence .
|
cosqa-train-12566
|
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return next(iter(reversed(seq)))
except StopIteration:
return environment.undefined('No last item, sequence was empty.')
|
def watched_extension ( extension ) : for ext in hamlpy . VALID_EXTENSIONS : if extension . endswith ( '.' + ext ) : return True return False
| 1 |
python check if file has extension
|
Return True if the given extension is one of the watched extensions
|
cosqa-train-12567
|
def watched_extension(extension):
"""Return True if the given extension is one of the watched extensions"""
for ext in hamlpy.VALID_EXTENSIONS:
if extension.endswith('.' + ext):
return True
return False
|
def pop ( self ) : if not self . empty ( ) : val = self . stack [ - 1 ] del self . stack [ - 1 ] return val
| 1 |
the self python stack
|
return the last stack element and delete it from the list
|
cosqa-train-12568
|
def pop(self):
"""
return the last stack element and delete it from the list
"""
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val
|
def is_executable ( path ) : return os . path . isfile ( path ) and os . access ( path , os . X_OK )
| 1 |
python check if file is executable
|
Returns whether a path names an existing executable file .
|
cosqa-train-12569
|
def is_executable(path):
"""Returns whether a path names an existing executable file."""
return os.path.isfile(path) and os.access(path, os.X_OK)
|
def basic_word_sim ( word1 , word2 ) : return sum ( [ 1 for c in word1 if c in word2 ] ) / max ( len ( word1 ) , len ( word2 ) )
| 1 |
the similarity of sentences python code
|
Simple measure of similarity : Number of letters in common / max length
|
cosqa-train-12570
|
def basic_word_sim(word1, word2):
"""
Simple measure of similarity: Number of letters in common / max length
"""
return sum([1 for c in word1 if c in word2]) / max(len(word1), len(word2))
|
def is_readable ( filename ) : return os . path . isfile ( filename ) and os . access ( filename , os . R_OK )
| 1 |
python check if file is readable
|
Check if file is a regular file and is readable .
|
cosqa-train-12571
|
def is_readable(filename):
"""Check if file is a regular file and is readable."""
return os.path.isfile(filename) and os.access(filename, os.R_OK)
|
def hasattrs ( object , * names ) : for name in names : if not hasattr ( object , name ) : return False return True
| 1 |
to check if object doesnt have attribute valu python
|
Takes in an object and a variable length amount of named attributes and checks to see if the object has each property . If any of the attributes are missing this returns false .
|
cosqa-train-12572
|
def hasattrs(object, *names):
"""
Takes in an object and a variable length amount of named attributes,
and checks to see if the object has each property. If any of the
attributes are missing, this returns false.
:param object: an object that may or may not contain the listed attributes
:param names: a variable amount of attribute names to check for
:return: True if the object contains each named attribute, false otherwise
"""
for name in names:
if not hasattr(object, name):
return False
return True
|
def is_writable_by_others ( filename ) : mode = os . stat ( filename ) [ stat . ST_MODE ] return mode & stat . S_IWOTH
| 1 |
python check if file is writable
|
Check if file or directory is world writable .
|
cosqa-train-12573
|
def is_writable_by_others(filename):
"""Check if file or directory is world writable."""
mode = os.stat(filename)[stat.ST_MODE]
return mode & stat.S_IWOTH
|
async def iso ( self , source ) : from datetime import datetime unix_timestamp = int ( source ) return datetime . fromtimestamp ( unix_timestamp ) . isoformat ( )
| 0 |
to isoformat python no timezone
|
Convert to timestamp .
|
cosqa-train-12574
|
async def iso(self, source):
"""Convert to timestamp."""
from datetime import datetime
unix_timestamp = int(source)
return datetime.fromtimestamp(unix_timestamp).isoformat()
|
def is_valid_folder ( parser , arg ) : arg = os . path . abspath ( arg ) if not os . path . isdir ( arg ) : parser . error ( "The folder %s does not exist!" % arg ) else : return arg
| 0 |
python check if folder empty
|
Check if arg is a valid file that already exists on the file system .
|
cosqa-train-12575
|
def is_valid_folder(parser, arg):
"""Check if arg is a valid file that already exists on the file system."""
arg = os.path.abspath(arg)
if not os.path.isdir(arg):
parser.error("The folder %s does not exist!" % arg)
else:
return arg
|
def lower_ext ( abspath ) : fname , ext = os . path . splitext ( abspath ) return fname + ext . lower ( )
| 1 |
to replace the extension of a file in python
|
Convert file extension to lowercase .
|
cosqa-train-12576
|
def lower_ext(abspath):
"""Convert file extension to lowercase.
"""
fname, ext = os.path.splitext(abspath)
return fname + ext.lower()
|
def is_non_empty_string ( input_string ) : try : if not input_string . strip ( ) : raise ValueError ( ) except AttributeError as error : raise TypeError ( error ) return True
| 1 |
python check if input string is empty
|
Validate if non empty string
|
cosqa-train-12577
|
def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except AttributeError as error:
raise TypeError(error)
return True
|
def default_number_converter ( number_str ) : is_int = ( number_str . startswith ( '-' ) and number_str [ 1 : ] . isdigit ( ) ) or number_str . isdigit ( ) # FIXME: this handles a wider range of numbers than allowed by the json standard, # etc.: float('nan') and float('inf'). But is this a problem? return int ( number_str ) if is_int else float ( number_str )
| 1 |
to use json numeric value in python
|
Converts the string representation of a json number into its python object equivalent an int long float or whatever type suits .
|
cosqa-train-12578
|
def default_number_converter(number_str):
"""
Converts the string representation of a json number into its python object equivalent, an
int, long, float or whatever type suits.
"""
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()
# FIXME: this handles a wider range of numbers than allowed by the json standard,
# etc.: float('nan') and float('inf'). But is this a problem?
return int(number_str) if is_int else float(number_str)
|
def determine_interactive ( self ) : try : if not sys . stdout . isatty ( ) or os . getpgrp ( ) != os . tcgetpgrp ( sys . stdout . fileno ( ) ) : self . interactive = 0 return False except Exception : self . interactive = 0 return False if self . interactive == 0 : return False return True
| 1 |
python check if interactive
|
Determine whether we re in an interactive shell . Sets interactivity off if appropriate . cf http : // stackoverflow . com / questions / 24861351 / how - to - detect - if - python - script - is - being - run - as - a - background - process
|
cosqa-train-12579
|
def determine_interactive(self):
"""Determine whether we're in an interactive shell.
Sets interactivity off if appropriate.
cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process
"""
try:
if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()):
self.interactive = 0
return False
except Exception:
self.interactive = 0
return False
if self.interactive == 0:
return False
return True
|
def table_top_abs ( self ) : table_height = np . array ( [ 0 , 0 , self . table_full_size [ 2 ] ] ) return string_to_array ( self . floor . get ( "pos" ) ) + table_height
| 1 |
top values in column python
|
Returns the absolute position of table top
|
cosqa-train-12580
|
def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height
|
def is_int_vector ( l ) : if isinstance ( l , np . ndarray ) : if l . ndim == 1 and ( l . dtype . kind == 'i' or l . dtype . kind == 'u' ) : return True return False
| 1 |
python check if it is a vector
|
r Checks if l is a numpy array of integers
|
cosqa-train-12581
|
def is_int_vector(l):
r"""Checks if l is a numpy array of integers
"""
if isinstance(l, np.ndarray):
if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'):
return True
return False
|
def timed_call ( func , * args , log_level = 'DEBUG' , * * kwargs ) : start = time ( ) r = func ( * args , * * kwargs ) t = time ( ) - start log ( log_level , "Call to '{}' took {:0.6f}s" . format ( func . __name__ , t ) ) return r
| 1 |
track how long a function takes to run in python
|
Logs a function s run time
|
cosqa-train-12582
|
def timed_call(func, *args, log_level='DEBUG', **kwargs):
"""Logs a function's run time
:param func: The function to run
:param args: The args to pass to the function
:param kwargs: The keyword args to pass to the function
:param log_level: The log level at which to print the run time
:return: The function's return value
"""
start = time()
r = func(*args, **kwargs)
t = time() - start
log(log_level, "Call to '{}' took {:0.6f}s".format(func.__name__, t))
return r
|
def _get_line_no_from_comments ( py_line ) : matched = LINECOL_COMMENT_RE . match ( py_line ) if matched : return int ( matched . group ( 1 ) ) else : return 0
| 1 |
python check if line is a comment
|
Return the line number parsed from the comment or 0 .
|
cosqa-train-12583
|
def _get_line_no_from_comments(py_line):
"""Return the line number parsed from the comment or 0."""
matched = LINECOL_COMMENT_RE.match(py_line)
if matched:
return int(matched.group(1))
else:
return 0
|
def to_dotfile ( G : nx . DiGraph , filename : str ) : A = to_agraph ( G ) A . write ( filename )
| 1 |
transfer python network graph to javascript
|
Output a networkx graph to a DOT file .
|
cosqa-train-12584
|
def to_dotfile(G: nx.DiGraph, filename: str):
""" Output a networkx graph to a DOT file. """
A = to_agraph(G)
A.write(filename)
|
def all_strings ( arr ) : if not isinstance ( [ ] , list ) : raise TypeError ( "non-list value found where list is expected" ) return all ( isinstance ( x , str ) for x in arr )
| 1 |
python check if list is string
|
Ensures that the argument is a list that either is empty or contains only strings : param arr : list : return :
|
cosqa-train-12585
|
def all_strings(arr):
"""
Ensures that the argument is a list that either is empty or contains only strings
:param arr: list
:return:
"""
if not isinstance([], list):
raise TypeError("non-list value found where list is expected")
return all(isinstance(x, str) for x in arr)
|
def _to_array ( value ) : if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
| 1 |
transform 1d array to list python
|
As a convenience turn Python lists and tuples into NumPy arrays .
|
cosqa-train-12586
|
def _to_array(value):
"""As a convenience, turn Python lists and tuples into NumPy arrays."""
if isinstance(value, (tuple, list)):
return array(value)
elif isinstance(value, (float, int)):
return np.float64(value)
else:
return value
|
def empty_tree ( input_list ) : for item in input_list : if not isinstance ( item , list ) or not empty_tree ( item ) : return False return True
| 1 |
python check if nested list contain items
|
Recursively iterate through values in nested lists .
|
cosqa-train-12587
|
def empty_tree(input_list):
"""Recursively iterate through values in nested lists."""
for item in input_list:
if not isinstance(item, list) or not empty_tree(item):
return False
return True
|
def post_process ( self ) : self . image . putdata ( self . pixels ) self . image = self . image . transpose ( Image . ROTATE_90 )
| 1 |
transposing of an image in python
|
Apply last 2D transforms
|
cosqa-train-12588
|
def post_process(self):
""" Apply last 2D transforms"""
self.image.putdata(self.pixels)
self.image = self.image.transpose(Image.ROTATE_90)
|
def is_date_type ( cls ) : if not isinstance ( cls , type ) : return False return issubclass ( cls , date ) and not issubclass ( cls , datetime )
| 1 |
python check if object is dayetime
|
Return True if the class is a date type .
|
cosqa-train-12589
|
def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime)
|
def retry_call ( func , cleanup = lambda : None , retries = 0 , trap = ( ) ) : attempts = count ( ) if retries == float ( 'inf' ) else range ( retries ) for attempt in attempts : try : return func ( ) except trap : cleanup ( ) return func ( )
| 1 |
try catch retry python
|
Given a callable func trap the indicated exceptions for up to retries times invoking cleanup on the exception . On the final attempt allow any exceptions to propagate .
|
cosqa-train-12590
|
def retry_call(func, cleanup=lambda: None, retries=0, trap=()):
"""
Given a callable func, trap the indicated exceptions
for up to 'retries' times, invoking cleanup on the
exception. On the final attempt, allow any exceptions
to propagate.
"""
attempts = count() if retries == float('inf') else range(retries)
for attempt in attempts:
try:
return func()
except trap:
cleanup()
return func()
|
def is_iterable_but_not_string ( obj ) : return hasattr ( obj , '__iter__' ) and not isinstance ( obj , str ) and not isinstance ( obj , bytes )
| 1 |
python check if object is iterable but not string
|
Determine whether or not obj is iterable but not a string ( eg a list set tuple etc ) .
|
cosqa-train-12591
|
def is_iterable_but_not_string(obj):
"""
Determine whether or not obj is iterable but not a string (eg, a list, set, tuple etc).
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) and not isinstance(obj, bytes)
|
def cross_product_matrix ( vec ) : return np . array ( [ [ 0 , - vec [ 2 ] , vec [ 1 ] ] , [ vec [ 2 ] , 0 , - vec [ 0 ] ] , [ - vec [ 1 ] , vec [ 0 ] , 0 ] ] )
| 1 |
turn a matrix into a vector in python
|
Returns a 3x3 cross - product matrix from a 3 - element vector .
|
cosqa-train-12592
|
def cross_product_matrix(vec):
"""Returns a 3x3 cross-product matrix from a 3-element vector."""
return np.array([[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
|
def is_number ( obj ) : return isinstance ( obj , ( int , float , np . int_ , np . float_ ) )
| 0 |
python check if object is numeric
|
Check if obj is number .
|
cosqa-train-12593
|
def is_number(obj):
"""Check if obj is number."""
return isinstance(obj, (int, float, np.int_, np.float_))
|
def int_to_date ( date ) : year = date // 10 ** 4 month = date % 10 ** 4 // 10 ** 2 day = date % 10 ** 2 return datetime . date ( year , month , day )
| 1 |
turn an integer into date python
|
Convert an int of form yyyymmdd to a python date object .
|
cosqa-train-12594
|
def int_to_date(date):
"""
Convert an int of form yyyymmdd to a python date object.
"""
year = date // 10**4
month = date % 10**4 // 10**2
day = date % 10**2
return datetime.date(year, month, day)
|
def is_symlink ( self ) : try : return S_ISLNK ( self . lstat ( ) . st_mode ) except OSError as e : if e . errno != ENOENT : raise # Path doesn't exist return False
| 1 |
python check if path is symbolic link
|
Whether this path is a symbolic link .
|
cosqa-train-12595
|
def is_symlink(self):
"""
Whether this path is a symbolic link.
"""
try:
return S_ISLNK(self.lstat().st_mode)
except OSError as e:
if e.errno != ENOENT:
raise
# Path doesn't exist
return False
|
def toarray ( self ) : rdd = self . _rdd . map ( lambda x : x . toarray ( ) ) return np . concatenate ( rdd . collect ( ) )
| 1 |
turn an rdd into a list python
|
Returns the data as numpy . array from each partition .
|
cosqa-train-12596
|
def toarray(self):
"""Returns the data as numpy.array from each partition."""
rdd = self._rdd.map(lambda x: x.toarray())
return np.concatenate(rdd.collect())
|
def is_valid_row ( cls , row ) : for k in row . keys ( ) : if row [ k ] is None : return False return True
| 1 |
python check if row contains none
|
Indicates whether or not the given row contains valid data .
|
cosqa-train-12597
|
def is_valid_row(cls, row):
"""Indicates whether or not the given row contains valid data."""
for k in row.keys():
if row[k] is None:
return False
return True
|
def ishex ( obj ) : return isinstance ( obj , str ) and ( len ( obj ) == 1 ) and ( obj in string . hexdigits )
| 1 |
python check if string or heximal number
|
Test if the argument is a string representing a valid hexadecimal digit .
|
cosqa-train-12598
|
def ishex(obj):
"""
Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits)
|
def _str_to_list ( s ) : _list = s . split ( "," ) return list ( map ( lambda i : i . lstrip ( ) , _list ) )
| 1 |
turn string with commas into list python
|
Converts a comma separated string to a list
|
cosqa-train-12599
|
def _str_to_list(s):
"""Converts a comma separated string to a list"""
_list = s.split(",")
return list(map(lambda i: i.lstrip(), _list))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.