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 center_text ( text , width = 80 ) : centered = [ ] for line in text . splitlines ( ) : centered . append ( line . center ( width ) ) return "\n" . join ( centered )
| 0 |
text align to center in python3
|
Center all lines of the text . It is assumed that all lines width is smaller then B { width } because the line width will not be checked . Args : text ( str ) : Text to wrap . width ( int ) : Maximum number of characters per line . Returns : str : Centered text .
|
cosqa-train-16800
|
def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered)
|
def connection_lost ( self , exc ) : if exc is None : self . log . warning ( 'eof from receiver?' ) else : self . log . warning ( 'Lost connection to receiver: %s' , exc ) self . transport = None if self . _connection_lost_callback : self . _loop . call_soon ( self . _connection_lost_callback )
| 1 |
python asyncio how to determine socket connection lost
|
Called when asyncio . Protocol loses the network connection .
|
cosqa-train-16801
|
def connection_lost(self, exc):
"""Called when asyncio.Protocol loses the network connection."""
if exc is None:
self.log.warning('eof from receiver?')
else:
self.log.warning('Lost connection to receiver: %s', exc)
self.transport = None
if self._connection_lost_callback:
self._loop.call_soon(self._connection_lost_callback)
|
def average ( iterator ) : count = 0 total = 0 for num in iterator : count += 1 total += num return float ( total ) / count
| 1 |
the sum of all squares between 1 and 100 (inclusive python with for loop
|
Iterative mean .
|
cosqa-train-16802
|
def average(iterator):
"""Iterative mean."""
count = 0
total = 0
for num in iterator:
count += 1
total += num
return float(total)/count
|
def StringIO ( * args , * * kwargs ) : raw = sync_io . StringIO ( * args , * * kwargs ) return AsyncStringIOWrapper ( raw )
| 0 |
python asyncio object is not subscriptable
|
StringIO constructor shim for the async wrapper .
|
cosqa-train-16803
|
def StringIO(*args, **kwargs):
"""StringIO constructor shim for the async wrapper."""
raw = sync_io.StringIO(*args, **kwargs)
return AsyncStringIOWrapper(raw)
|
def convert_timezone ( obj , timezone ) : if timezone is None : return obj . replace ( tzinfo = None ) return pytz . timezone ( timezone ) . localize ( obj )
| 0 |
timezone with z in python
|
Convert obj to the timezone timezone .
|
cosqa-train-16804
|
def convert_timezone(obj, timezone):
"""Convert `obj` to the timezone `timezone`.
Parameters
----------
obj : datetime.date or datetime.datetime
Returns
-------
type(obj)
"""
if timezone is None:
return obj.replace(tzinfo=None)
return pytz.timezone(timezone).localize(obj)
|
async def write ( self , data ) : await self . wait ( "write" ) start = _now ( ) await super ( ) . write ( data ) self . append ( "write" , data , start )
| 0 |
python asyncio transport write example
|
: py : func : asyncio . coroutine
|
cosqa-train-16805
|
async def write(self, data):
"""
:py:func:`asyncio.coroutine`
:py:meth:`aioftp.StreamIO.write` proxy
"""
await self.wait("write")
start = _now()
await super().write(data)
self.append("write", data, start)
|
def yview ( self , * args ) : self . after_idle ( self . __updateWnds ) ttk . Treeview . yview ( self , * args )
| 0 |
tkinter python 3 treeview scrollbars windows
|
Update inplace widgets position when doing vertical scroll
|
cosqa-train-16806
|
def yview(self, *args):
"""Update inplace widgets position when doing vertical scroll"""
self.after_idle(self.__updateWnds)
ttk.Treeview.yview(self, *args)
|
def debug_src ( src , pm = False , globs = None ) : testsrc = script_from_examples ( src ) debug_script ( testsrc , pm , globs )
| 0 |
python autogenerate python documentation using pydoc
|
Debug a single doctest docstring in argument src
|
cosqa-train-16807
|
def debug_src(src, pm=False, globs=None):
"""Debug a single doctest docstring, in argument `src`'"""
testsrc = script_from_examples(src)
debug_script(testsrc, pm, globs)
|
def _set_scroll_v ( self , * args ) : self . _canvas_categories . yview ( * args ) self . _canvas_scroll . yview ( * args )
| 0 |
tkinter scroll two canvas python
|
Scroll both categories Canvas and scrolling container
|
cosqa-train-16808
|
def _set_scroll_v(self, *args):
"""Scroll both categories Canvas and scrolling container"""
self._canvas_categories.yview(*args)
self._canvas_scroll.yview(*args)
|
def Distance ( lat1 , lon1 , lat2 , lon2 ) : az12 , az21 , dist = wgs84_geod . inv ( lon1 , lat1 , lon2 , lat2 ) return az21 , dist
| 0 |
python azimuth from lat and lon
|
Get distance between pairs of lat - lon points
|
cosqa-train-16809
|
def Distance(lat1, lon1, lat2, lon2):
"""Get distance between pairs of lat-lon points"""
az12, az21, dist = wgs84_geod.inv(lon1, lat1, lon2, lat2)
return az21, dist
|
def codebox ( msg = "" , title = " " , text = "" ) : return tb . textbox ( msg , title , text , codebox = 1 )
| 0 |
tkmessagebox use in python syntax
|
Display some text in a monospaced font with no line wrapping . This function is suitable for displaying code and text that is formatted using spaces .
|
cosqa-train-16810
|
def codebox(msg="", title=" ", text=""):
"""
Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is
formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be
displayed in the textbox.
:param str msg: the msg to be displayed
:param str title: the window title
:param str text: what to display in the textbox
"""
return tb.textbox(msg, title, text, codebox=1)
|
def pp_xml ( body ) : pretty = xml . dom . minidom . parseString ( body ) return pretty . toprettyxml ( indent = " " )
| 1 |
python beautiful xml string
|
Pretty print format some XML so it s readable .
|
cosqa-train-16811
|
def pp_xml(body):
"""Pretty print format some XML so it's readable."""
pretty = xml.dom.minidom.parseString(body)
return pretty.toprettyxml(indent=" ")
|
def isetdiff_flags ( list1 , list2 ) : set2 = set ( list2 ) return ( item not in set2 for item in list1 )
| 0 |
to compare set data in python
|
move to util_iter
|
cosqa-train-16812
|
def isetdiff_flags(list1, list2):
"""
move to util_iter
"""
set2 = set(list2)
return (item not in set2 for item in list1)
|
def csv_to_dicts ( file , header = None ) : with open ( file ) as csvfile : return [ row for row in csv . DictReader ( csvfile , fieldnames = header ) ]
| 1 |
python best way to get csv header list from a file ussing dictreader
|
Reads a csv and returns a List of Dicts with keys given by header row .
|
cosqa-train-16813
|
def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)]
|
def printComparison ( results , class_or_prop ) : data = [ ] Row = namedtuple ( 'Row' , [ class_or_prop , 'VALIDATED' ] ) for k , v in sorted ( results . items ( ) , key = lambda x : x [ 1 ] ) : data += [ Row ( k , str ( v ) ) ] pprinttable ( data )
| 0 |
to print the results in the form of table in python
|
print ( out the results of the comparison using a nice table )
|
cosqa-train-16814
|
def printComparison(results, class_or_prop):
"""
print(out the results of the comparison using a nice table)
"""
data = []
Row = namedtuple('Row',[class_or_prop,'VALIDATED'])
for k,v in sorted(results.items(), key=lambda x: x[1]):
data += [Row(k, str(v))]
pprinttable(data)
|
def rgb2gray ( img ) : T = np . linalg . inv ( np . array ( [ [ 1.0 , 0.956 , 0.621 ] , [ 1.0 , - 0.272 , - 0.647 ] , [ 1.0 , - 1.106 , 1.703 ] , ] ) ) r_c , g_c , b_c = T [ 0 ] r , g , b = np . rollaxis ( as_float_image ( img ) , axis = - 1 ) return r_c * r + g_c * g + b_c * b
| 1 |
python best way to transform image to grayscale
|
Converts an RGB image to grayscale using matlab s algorithm .
|
cosqa-train-16815
|
def rgb2gray(img):
"""Converts an RGB image to grayscale using matlab's algorithm."""
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * r + g_c * g + b_c * b
|
def xmltreefromfile ( filename ) : try : return ElementTree . parse ( filename , ElementTree . XMLParser ( collect_ids = False ) ) except TypeError : return ElementTree . parse ( filename , ElementTree . XMLParser ( ) )
| 1 |
to read xml files in python
|
Internal function to read an XML file
|
cosqa-train-16816
|
def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser())
|
def val_to_bin ( edges , x ) : ibin = np . digitize ( np . array ( x , ndmin = 1 ) , edges ) - 1 return ibin
| 0 |
python bin ranges not numpy
|
Convert axis coordinate to bin index .
|
cosqa-train-16817
|
def val_to_bin(edges, x):
"""Convert axis coordinate to bin index."""
ibin = np.digitize(np.array(x, ndmin=1), edges) - 1
return ibin
|
def split_long_sentence ( sentence , words_per_line ) : words = sentence . split ( ' ' ) split_sentence = '' for i in range ( len ( words ) ) : split_sentence = split_sentence + words [ i ] if ( i + 1 ) % words_per_line == 0 : split_sentence = split_sentence + '\n' elif i != len ( words ) - 1 : split_sentence = split_sentence + " " return split_sentence
| 0 |
too long sentences in python
|
Takes a sentence and adds a newline every words_per_line words .
|
cosqa-train-16818
|
def split_long_sentence(sentence, words_per_line):
"""Takes a sentence and adds a newline every "words_per_line" words.
Parameters
----------
sentence: str
Sentene to split
words_per_line: double
Add a newline every this many words
"""
words = sentence.split(' ')
split_sentence = ''
for i in range(len(words)):
split_sentence = split_sentence + words[i]
if (i+1) % words_per_line == 0:
split_sentence = split_sentence + '\n'
elif i != len(words) - 1:
split_sentence = split_sentence + " "
return split_sentence
|
def hook_focus_events ( self ) : widget = self . widget widget . focusInEvent = self . focusInEvent widget . focusOutEvent = self . focusOutEvent
| 0 |
python bind focusin focusout
|
Install the hooks for focus events .
|
cosqa-train-16819
|
def hook_focus_events(self):
""" Install the hooks for focus events.
This method may be overridden by subclasses as needed.
"""
widget = self.widget
widget.focusInEvent = self.focusInEvent
widget.focusOutEvent = self.focusOutEvent
|
def mouse_move_event ( self , event ) : self . example . mouse_position_event ( event . x ( ) , event . y ( ) )
| 1 |
track location of mouse click python
|
Forward mouse cursor position events to the example
|
cosqa-train-16820
|
def mouse_move_event(self, event):
"""
Forward mouse cursor position events to the example
"""
self.example.mouse_position_event(event.x(), event.y())
|
def adapter ( data , headers , * * kwargs ) : keys = ( 'sep_title' , 'sep_character' , 'sep_length' ) return vertical_table ( data , headers , * * filter_dict_by_key ( kwargs , keys ) )
| 1 |
python borderless table via format function
|
Wrap vertical table in a function for TabularOutputFormatter .
|
cosqa-train-16821
|
def adapter(data, headers, **kwargs):
"""Wrap vertical table in a function for TabularOutputFormatter."""
keys = ('sep_title', 'sep_character', 'sep_length')
return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))
|
def to_dicts ( recarray ) : for rec in recarray : yield dict ( zip ( recarray . dtype . names , rec . tolist ( ) ) )
| 1 |
transform array to dictionary python
|
convert record array to a dictionaries
|
cosqa-train-16822
|
def to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist()))
|
def needs_update ( self , cache_key ) : if not self . cacheable ( cache_key ) : # An uncacheable CacheKey is always out of date. return True return self . _read_sha ( cache_key ) != cache_key . hash
| 0 |
python boto3 check if sts is expiration and renew
|
Check if the given cached item is invalid .
|
cosqa-train-16823
|
def needs_update(self, cache_key):
"""Check if the given cached item is invalid.
:param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().
:returns: True if the cached version of the item is out of date.
"""
if not self.cacheable(cache_key):
# An uncacheable CacheKey is always out of date.
return True
return self._read_sha(cache_key) != cache_key.hash
|
def _trim ( self , somestr ) : tmp = RE_LSPACES . sub ( "" , somestr ) tmp = RE_TSPACES . sub ( "" , tmp ) return str ( tmp )
| 1 |
trim from left of python string
|
Trim left - right given string
|
cosqa-train-16824
|
def _trim(self, somestr):
""" Trim left-right given string """
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp)
|
def remove_file_from_s3 ( awsclient , bucket , key ) : client_s3 = awsclient . get_client ( 's3' ) response = client_s3 . delete_object ( Bucket = bucket , Key = key )
| 0 |
python boto3 delete file from s3 bucket
|
Remove a file from an AWS S3 bucket .
|
cosqa-train-16825
|
def remove_file_from_s3(awsclient, bucket, key):
"""Remove a file from an AWS S3 bucket.
:param awsclient:
:param bucket:
:param key:
:return:
"""
client_s3 = awsclient.get_client('s3')
response = client_s3.delete_object(Bucket=bucket, Key=key)
|
def update ( self , params ) : dev_info = self . json_state . get ( 'deviceInfo' ) dev_info . update ( { k : params [ k ] for k in params if dev_info . get ( k ) } )
| 0 |
try updating a dictionary in python
|
Update the dev_info data from a dictionary .
|
cosqa-train-16826
|
def update(self, params):
"""Update the dev_info data from a dictionary.
Only updates if it already exists in the device.
"""
dev_info = self.json_state.get('deviceInfo')
dev_info.update({k: params[k] for k in params if dev_info.get(k)})
|
def be_array_from_bytes ( fmt , data ) : arr = array . array ( str ( fmt ) , data ) return fix_byteorder ( arr )
| 0 |
python byte buffer as array
|
Reads an array from bytestring with big - endian data .
|
cosqa-train-16827
|
def be_array_from_bytes(fmt, data):
"""
Reads an array from bytestring with big-endian data.
"""
arr = array.array(str(fmt), data)
return fix_byteorder(arr)
|
async def packets_from_tshark ( self , packet_callback , packet_count = None , close_tshark = True ) : tshark_process = await self . _get_tshark_process ( packet_count = packet_count ) try : await self . _go_through_packets_from_fd ( tshark_process . stdout , packet_callback , packet_count = packet_count ) except StopCapture : pass finally : if close_tshark : await self . _close_async ( )
| 0 |
tshark command results in python
|
A coroutine which creates a tshark process runs the given callback on each packet that is received from it and closes the process when it is done .
|
cosqa-train-16828
|
async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):
"""
A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
closes the process when it is done.
Do not use interactively. Can be used in order to insert packets into your own eventloop.
"""
tshark_process = await self._get_tshark_process(packet_count=packet_count)
try:
await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)
except StopCapture:
pass
finally:
if close_tshark:
await self._close_async()
|
def _from_bytes ( bytes , byteorder = "big" , signed = False ) : return int . from_bytes ( bytes , byteorder = byteorder , signed = signed )
| 0 |
python byte indices must be integers or slices, not str
|
This is the same functionality as int . from_bytes in python 3
|
cosqa-train-16829
|
def _from_bytes(bytes, byteorder="big", signed=False):
"""This is the same functionality as ``int.from_bytes`` in python 3"""
return int.from_bytes(bytes, byteorder=byteorder, signed=signed)
|
def _to_array ( value ) : if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
| 0 |
turn array of arrays to list python
|
As a convenience turn Python lists and tuples into NumPy arrays .
|
cosqa-train-16830
|
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 cast_bytes ( s , encoding = None ) : if not isinstance ( s , bytes ) : return encode ( s , encoding ) return s
| 0 |
python bytes auto detect
|
Source : https : // github . com / ipython / ipython_genutils
|
cosqa-train-16831
|
def cast_bytes(s, encoding=None):
"""Source: https://github.com/ipython/ipython_genutils"""
if not isinstance(s, bytes):
return encode(s, encoding)
return s
|
def to_binary ( s , encoding = 'utf8' ) : if PY3 : # pragma: no cover return s if isinstance ( s , binary_type ) else binary_type ( s , encoding = encoding ) return binary_type ( s )
| 1 |
turn binary string into bytes object python
|
Portable cast function .
|
cosqa-train-16832
|
def to_binary(s, encoding='utf8'):
"""Portable cast function.
In python 2 the ``str`` function which is used to coerce objects to bytes does not
accept an encoding argument, whereas python 3's ``bytes`` function requires one.
:param s: object to be converted to binary_type
:return: binary_type instance, representing s.
"""
if PY3: # pragma: no cover
return s if isinstance(s, binary_type) else binary_type(s, encoding=encoding)
return binary_type(s)
|
def bin_to_int ( string ) : if isinstance ( string , str ) : return struct . unpack ( "b" , string ) [ 0 ] else : return struct . unpack ( "b" , bytes ( [ string ] ) ) [ 0 ]
| 1 |
python bytes to signed int
|
Convert a one element byte string to signed int for python 2 support .
|
cosqa-train-16833
|
def bin_to_int(string):
"""Convert a one element byte string to signed int for python 2 support."""
if isinstance(string, str):
return struct.unpack("b", string)[0]
else:
return struct.unpack("b", bytes([string]))[0]
|
def s2b ( s ) : ret = [ ] for c in s : ret . append ( bin ( ord ( c ) ) [ 2 : ] . zfill ( 8 ) ) return "" . join ( ret )
| 0 |
turn string to binaryn string python
|
String to binary .
|
cosqa-train-16834
|
def s2b(s):
"""
String to binary.
"""
ret = []
for c in s:
ret.append(bin(ord(c))[2:].zfill(8))
return "".join(ret)
|
def _bytes_to_json ( value ) : if isinstance ( value , bytes ) : value = base64 . standard_b64encode ( value ) . decode ( "ascii" ) return value
| 0 |
python bytestring to json
|
Coerce value to an JSON - compatible representation .
|
cosqa-train-16835
|
def _bytes_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value
|
def time2seconds ( t ) : return t . hour * 3600 + t . minute * 60 + t . second + float ( t . microsecond ) / 1e6
| 1 |
turn time return into seconds python
|
Returns seconds since 0h00 .
|
cosqa-train-16836
|
def time2seconds(t):
"""Returns seconds since 0h00."""
return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
|
def check_clang_apply_replacements_binary ( args ) : try : subprocess . check_call ( [ args . clang_apply_replacements_binary , '--version' ] ) except : print ( 'Unable to run clang-apply-replacements. Is clang-apply-replacements ' 'binary correctly specified?' , file = sys . stderr ) traceback . print_exc ( ) sys . exit ( 1 )
| 1 |
python c++ bindings clang
|
Checks if invoking supplied clang - apply - replacements binary works .
|
cosqa-train-16837
|
def check_clang_apply_replacements_binary(args):
"""Checks if invoking supplied clang-apply-replacements binary works."""
try:
subprocess.check_call([args.clang_apply_replacements_binary, '--version'])
except:
print('Unable to run clang-apply-replacements. Is clang-apply-replacements '
'binary correctly specified?', file=sys.stderr)
traceback.print_exc()
sys.exit(1)
|
def runiform ( lower , upper , size = None ) : return np . random . uniform ( lower , upper , size )
| 0 |
uniform variable [0,1] python
|
Random uniform variates .
|
cosqa-train-16838
|
def runiform(lower, upper, size=None):
"""
Random uniform variates.
"""
return np.random.uniform(lower, upper, size)
|
def getCachedDataKey ( engineVersionHash , key ) : cacheFile = CachedDataManager . _cacheFileForHash ( engineVersionHash ) return JsonDataManager ( cacheFile ) . getKey ( key )
| 0 |
python cache json http response
|
Retrieves the cached data value for the specified engine version hash and dictionary key
|
cosqa-train-16839
|
def getCachedDataKey(engineVersionHash, key):
"""
Retrieves the cached data value for the specified engine version hash and dictionary key
"""
cacheFile = CachedDataManager._cacheFileForHash(engineVersionHash)
return JsonDataManager(cacheFile).getKey(key)
|
def uniq ( seq ) : seen = set ( ) return [ x for x in seq if str ( x ) not in seen and not seen . add ( str ( x ) ) ]
| 1 |
uniqify a list preserve order+ python
|
Return a copy of seq without duplicates .
|
cosqa-train-16840
|
def uniq(seq):
""" Return a copy of seq without duplicates. """
seen = set()
return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
|
def get_labels ( labels ) : label_u = unique_labels ( labels ) label_u_line = [ i + "_line" for i in label_u ] return label_u , label_u_line
| 0 |
unique labels function in python
|
Create unique labels .
|
cosqa-train-16841
|
def get_labels(labels):
"""Create unique labels."""
label_u = unique_labels(labels)
label_u_line = [i + "_line" for i in label_u]
return label_u, label_u_line
|
def get_tri_area ( pts ) : a , b , c = pts [ 0 ] , pts [ 1 ] , pts [ 2 ] v1 = np . array ( b ) - np . array ( a ) v2 = np . array ( c ) - np . array ( a ) area_tri = abs ( sp . linalg . norm ( sp . cross ( v1 , v2 ) ) / 2 ) return area_tri
| 0 |
python calculate the area of several points
|
Given a list of coords for 3 points Compute the area of this triangle .
|
cosqa-train-16842
|
def get_tri_area(pts):
"""
Given a list of coords for 3 points,
Compute the area of this triangle.
Args:
pts: [a, b, c] three points
"""
a, b, c = pts[0], pts[1], pts[2]
v1 = np.array(b) - np.array(a)
v2 = np.array(c) - np.array(a)
area_tri = abs(sp.linalg.norm(sp.cross(v1, v2)) / 2)
return area_tri
|
def remove_duplicates ( seq ) : seen = set ( ) seen_add = seen . add return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ]
| 0 |
unique list of duplicates python
|
Return unique elements from list while preserving order . From https : // stackoverflow . com / a / 480227 / 2589328
|
cosqa-train-16843
|
def remove_duplicates(seq):
"""
Return unique elements from list while preserving order.
From https://stackoverflow.com/a/480227/2589328
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
def var ( series ) : if np . issubdtype ( series . dtype , np . number ) : return series . var ( ) else : return np . nan
| 0 |
python calculate variance of a series end with 0
|
Returns the variance of values in a series .
|
cosqa-train-16844
|
def var(series):
"""
Returns the variance of values in a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.var()
else:
return np.nan
|
def uniquify_list ( L ) : return [ e for i , e in enumerate ( L ) if L . index ( e ) == i ]
| 1 |
uniquify a list in python
|
Same order unique list using only a list compression .
|
cosqa-train-16845
|
def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i]
|
def sequence_molecular_weight ( seq ) : if 'X' in seq : warnings . warn ( _nc_warning_str , NoncanonicalWarning ) return sum ( [ residue_mwt [ aa ] * n for aa , n in Counter ( seq ) . items ( ) ] ) + water_mass
| 1 |
python calculating sum molecular weight from protein sequence
|
Returns the molecular weight of the polypeptide sequence .
|
cosqa-train-16846
|
def sequence_molecular_weight(seq):
"""Returns the molecular weight of the polypeptide sequence.
Notes
-----
Units = Daltons
Parameters
----------
seq : str
Sequence of amino acids.
"""
if 'X' in seq:
warnings.warn(_nc_warning_str, NoncanonicalWarning)
return sum(
[residue_mwt[aa] * n for aa, n in Counter(seq).items()]) + water_mass
|
def assert_is_not ( expected , actual , message = None , extra = None ) : assert expected is not actual , _assert_fail_message ( message , expected , actual , "is" , extra )
| 0 |
unittest python assert not equal
|
Raises an AssertionError if expected is actual .
|
cosqa-train-16847
|
def assert_is_not(expected, actual, message=None, extra=None):
"""Raises an AssertionError if expected is actual."""
assert expected is not actual, _assert_fail_message(
message, expected, actual, "is", extra
)
|
def do ( self ) : self . restore_point = self . obj . copy ( ) return self . do_method ( self . obj , * self . args )
| 0 |
python call a function that takes self
|
Set a restore point ( copy the object ) then call the method . : return : obj . do_method ( * args )
|
cosqa-train-16848
|
def do(self):
"""
Set a restore point (copy the object), then call the method.
:return: obj.do_method(*args)
"""
self.restore_point = self.obj.copy()
return self.do_method(self.obj, *self.args)
|
def __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
| 0 |
unix to windows paths python
|
stupid windows . converts the backslash to forwardslash for consistency
|
cosqa-train-16849
|
def __unixify(self, s):
""" stupid windows. converts the backslash to forwardslash for consistency """
return os.path.normpath(s).replace(os.sep, "/")
|
def python ( string : str ) : return underscore ( singularize ( string ) if Naming . _pluralize ( string ) else string )
| 1 |
python calling function with underscore
|
: param string : String can be type resource or python case
|
cosqa-train-16850
|
def python(string: str):
"""
:param string: String can be type, resource or python case
"""
return underscore(singularize(string) if Naming._pluralize(string) else string)
|
def update ( self ) : if not self . canvas : return for visual in self . canvas . visuals : self . update_program ( visual . program ) self . canvas . update ( )
| 1 |
updating a canvas in python
|
Update all visuals in the attached canvas .
|
cosqa-train-16851
|
def update(self):
"""Update all visuals in the attached canvas."""
if not self.canvas:
return
for visual in self.canvas.visuals:
self.update_program(visual.program)
self.canvas.update()
|
def min_or_none ( val1 , val2 ) : return min ( val1 , val2 , key = lambda x : sys . maxint if x is None else x )
| 1 |
python can none value be used outside variables
|
Returns min ( val1 val2 ) returning None only if both values are None
|
cosqa-train-16852
|
def min_or_none(val1, val2):
"""Returns min(val1, val2) returning None only if both values are None"""
return min(val1, val2, key=lambda x: sys.maxint if x is None else x)
|
def read_credentials ( fname ) : with open ( fname , 'r' ) as f : username = f . readline ( ) . strip ( '\n' ) password = f . readline ( ) . strip ( '\n' ) return username , password
| 0 |
use credentials from a text file python
|
read a simple text file from a private location to get username and password
|
cosqa-train-16853
|
def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password
|
def _parallel_compare_helper ( class_obj , pairs , x , x_link = None ) : return class_obj . _compute ( pairs , x , x_link )
| 0 |
python can not pickle local objects
|
Internal function to overcome pickling problem in python2 .
|
cosqa-train-16854
|
def _parallel_compare_helper(class_obj, pairs, x, x_link=None):
"""Internal function to overcome pickling problem in python2."""
return class_obj._compute(pairs, x, x_link)
|
def transformer_tall_pretrain_lm_tpu_adafactor ( ) : hparams = transformer_tall_pretrain_lm ( ) update_hparams_for_tpu ( hparams ) hparams . max_length = 1024 # For multi-problem on TPU we need it in absolute examples. hparams . batch_size = 8 hparams . multiproblem_vocab_size = 2 ** 16 return hparams
| 0 |
use maximum performance tensorflow gpu cuda a python
|
Hparams for transformer on LM pretraining ( with 64k vocab ) on TPU .
|
cosqa-train-16855
|
def transformer_tall_pretrain_lm_tpu_adafactor():
"""Hparams for transformer on LM pretraining (with 64k vocab) on TPU."""
hparams = transformer_tall_pretrain_lm()
update_hparams_for_tpu(hparams)
hparams.max_length = 1024
# For multi-problem on TPU we need it in absolute examples.
hparams.batch_size = 8
hparams.multiproblem_vocab_size = 2**16
return hparams
|
def out_shape_from_array ( arr ) : arr = np . asarray ( arr ) if arr . ndim == 1 : return arr . shape else : return ( arr . shape [ 1 ] , )
| 0 |
python can you get the shape of a npz
|
Get the output shape from an array .
|
cosqa-train-16856
|
def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],)
|
def isnumber ( * args ) : return all ( map ( lambda c : isinstance ( c , int ) or isinstance ( c , float ) , args ) )
| 1 |
use of any to compare an array element with an int in python
|
Checks if value is an integer long integer or float .
|
cosqa-train-16857
|
def isnumber(*args):
"""Checks if value is an integer, long integer or float.
NOTE: Treats booleans as numbers, where True=1 and False=0.
"""
return all(map(lambda c: isinstance(c, int) or isinstance(c, float), args))
|
def clear ( self ) : self . _imgobj = None try : # See if there is an image on the canvas self . canvas . delete_object_by_tag ( self . _canvas_img_tag ) self . redraw ( ) except KeyError : pass
| 1 |
python canvas remove image
|
Clear the displayed image .
|
cosqa-train-16858
|
def clear(self):
"""Clear the displayed image."""
self._imgobj = None
try:
# See if there is an image on the canvas
self.canvas.delete_object_by_tag(self._canvas_img_tag)
self.redraw()
except KeyError:
pass
|
def send ( socket , data , num_bytes = 20 ) : pickled_data = pickle . dumps ( data , - 1 ) length = str ( len ( pickled_data ) ) . zfill ( num_bytes ) socket . sendall ( length . encode ( ) ) socket . sendall ( pickled_data )
| 0 |
use pickle to send data over socket python
|
Send data to specified socket .
|
cosqa-train-16859
|
def send(socket, data, num_bytes=20):
"""Send data to specified socket.
:param socket: open socket instance
:param data: data to send
:param num_bytes: number of bytes to read
:return: received data
"""
pickled_data = pickle.dumps(data, -1)
length = str(len(pickled_data)).zfill(num_bytes)
socket.sendall(length.encode())
socket.sendall(pickled_data)
|
def decamelise ( text ) : s = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , text ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s ) . lower ( )
| 0 |
python capitalize word after
|
Convert CamelCase to lower_and_underscore .
|
cosqa-train-16860
|
def decamelise(text):
"""Convert CamelCase to lower_and_underscore."""
s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
|
def _request_modify_dns_record ( self , record ) : return self . _request_internal ( "Modify_DNS_Record" , domain = self . domain , record = record )
| 1 |
use python to change bind dns record
|
Sends Modify_DNS_Record request
|
cosqa-train-16861
|
def _request_modify_dns_record(self, record):
"""Sends Modify_DNS_Record request"""
return self._request_internal("Modify_DNS_Record",
domain=self.domain,
record=record)
|
def is_equal_strings_ignore_case ( first , second ) : if first and second : return first . upper ( ) == second . upper ( ) else : return not ( first or second )
| 1 |
python case insensitve string compare
|
The function compares strings ignoring case
|
cosqa-train-16862
|
def is_equal_strings_ignore_case(first, second):
"""The function compares strings ignoring case"""
if first and second:
return first.upper() == second.upper()
else:
return not (first or second)
|
def hclust_linearize ( U ) : from scipy . cluster import hierarchy Z = hierarchy . ward ( U ) return hierarchy . leaves_list ( hierarchy . optimal_leaf_ordering ( Z , U ) )
| 0 |
use sparse matrices with agglomerativeclustering in python
|
Sorts the rows of a matrix by hierarchical clustering .
|
cosqa-train-16863
|
def hclust_linearize(U):
"""Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows
"""
from scipy.cluster import hierarchy
Z = hierarchy.ward(U)
return hierarchy.leaves_list(hierarchy.optimal_leaf_ordering(Z, U))
|
def convert_array ( array ) : out = io . BytesIO ( array ) out . seek ( 0 ) return np . load ( out )
| 0 |
python cast data as array
|
Converts an ARRAY string stored in the database back into a Numpy array .
|
cosqa-train-16864
|
def convert_array(array):
"""
Converts an ARRAY string stored in the database back into a Numpy array.
Parameters
----------
array: ARRAY
The array object to be converted back into a Numpy array.
Returns
-------
array
The converted Numpy array.
"""
out = io.BytesIO(array)
out.seek(0)
return np.load(out)
|
def ask_str ( question : str , default : str = None ) : default_q = " [default: {0}]: " . format ( default ) if default is not None else "" answer = input ( "{0} [{1}]: " . format ( question , default_q ) ) if answer == "" : return default return answer
| 1 |
use the def function to ask a question in python
|
Asks for a simple string
|
cosqa-train-16865
|
def ask_str(question: str, default: str = None):
"""Asks for a simple string"""
default_q = " [default: {0}]: ".format(
default) if default is not None else ""
answer = input("{0} [{1}]: ".format(question, default_q))
if answer == "":
return default
return answer
|
def col_rename ( df , col_name , new_col_name ) : col_list = list ( df . columns ) for index , value in enumerate ( col_list ) : if value == col_name : col_list [ index ] = new_col_name break df . columns = col_list
| 0 |
python change a specific column name
|
Changes a column name in a DataFrame Parameters : df - DataFrame DataFrame to operate on col_name - string Name of column to change new_col_name - string New name of column
|
cosqa-train-16866
|
def col_rename(df,col_name,new_col_name):
""" Changes a column name in a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_name - string
Name of column to change
new_col_name - string
New name of column
"""
col_list = list(df.columns)
for index,value in enumerate(col_list):
if value == col_name:
col_list[index] = new_col_name
break
df.columns = col_list
|
def get_ctype ( rtype , cfunc , * args ) : val_p = backend . ffi . new ( rtype ) args = args + ( val_p , ) cfunc ( * args ) return val_p [ 0 ]
| 1 |
using ctypes to use c functions in python
|
Call a C function that takes a pointer as its last argument and return the C object that it contains after the function has finished .
|
cosqa-train-16867
|
def get_ctype(rtype, cfunc, *args):
""" Call a C function that takes a pointer as its last argument and
return the C object that it contains after the function has finished.
:param rtype: C data type is filled by the function
:param cfunc: C function to call
:param args: Arguments to call function with
:return: A pointer to the specified data type
"""
val_p = backend.ffi.new(rtype)
args = args + (val_p,)
cfunc(*args)
return val_p[0]
|
def convert_str_to_datetime ( df , * , column : str , format : str ) : df [ column ] = pd . to_datetime ( df [ column ] , format = format ) return df
| 1 |
python change column to datetime with different formats
|
Convert string column into datetime column
|
cosqa-train-16868
|
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 _openResources ( self ) : arr = np . load ( self . _fileName , allow_pickle = ALLOW_PICKLE ) check_is_an_array ( arr ) self . _array = arr
| 1 |
using pickle to store numpy array python
|
Uses numpy . load to open the underlying file
|
cosqa-train-16869
|
def _openResources(self):
""" Uses numpy.load to open the underlying file
"""
arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE)
check_is_an_array(arr)
self._array = arr
|
def _to_numeric ( val ) : if isinstance ( val , ( int , float , datetime . datetime , datetime . timedelta ) ) : return val return float ( val )
| 0 |
python change datatype from object to int
|
Helper function for conversion of various data types into numeric representation .
|
cosqa-train-16870
|
def _to_numeric(val):
"""
Helper function for conversion of various data types into numeric representation.
"""
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val)
|
def do_exit ( self , arg ) : if self . current : self . current . close ( ) self . resource_manager . close ( ) del self . resource_manager return True
| 0 |
using python 3 widget to terminate program
|
Exit the shell session .
|
cosqa-train-16871
|
def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True
|
def get_year_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( month = 1 ) . replace ( day = 1 )
| 1 |
python change date format to day month year
|
Returns January 1 of the given year .
|
cosqa-train-16872
|
def get_year_start(day=None):
"""Returns January 1 of the given year."""
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1)
|
def print_matrix ( X , decimals = 1 ) : for row in np . round ( X , decimals = decimals ) : print ( row )
| 0 |
using python print matrix equally spaced
|
Pretty printing for numpy matrix X
|
cosqa-train-16873
|
def print_matrix(X, decimals=1):
"""Pretty printing for numpy matrix X"""
for row in np.round(X, decimals=decimals):
print(row)
|
def closing_plugin ( self , cancelable = False ) : self . dialog_manager . close_all ( ) self . shell . exit_interpreter ( ) return True
| 1 |
python change default gui closing behavior
|
Perform actions before parent main window is closed
|
cosqa-train-16874
|
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main window is closed"""
self.dialog_manager.close_all()
self.shell.exit_interpreter()
return True
|
def CleanseComments ( line ) : commentpos = line . find ( '//' ) if commentpos != - 1 and not IsCppString ( line [ : commentpos ] ) : line = line [ : commentpos ] . rstrip ( ) # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS . sub ( '' , line )
| 0 |
using python to extract c++ comments
|
Removes // - comments and single - line C - style / * * / comments .
|
cosqa-train-16875
|
def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
|
def set_cursor ( self , x , y ) : curses . curs_set ( 1 ) self . screen . move ( y , x )
| 0 |
python change mouse cursor for window
|
Sets the cursor to the desired position .
|
cosqa-train-16876
|
def set_cursor(self, x, y):
"""
Sets the cursor to the desired position.
:param x: X position
:param y: Y position
"""
curses.curs_set(1)
self.screen.move(y, x)
|
def _remove_duplicate_files ( xs ) : seen = set ( [ ] ) out = [ ] for x in xs : if x [ "path" ] not in seen : out . append ( x ) seen . add ( x [ "path" ] ) return out
| 0 |
using python to remove duplicate files
|
Remove files specified multiple times in a list .
|
cosqa-train-16877
|
def _remove_duplicate_files(xs):
"""Remove files specified multiple times in a list.
"""
seen = set([])
out = []
for x in xs:
if x["path"] not in seen:
out.append(x)
seen.add(x["path"])
return out
|
def process_result_value ( self , value , dialect ) : if value is not None : value = simplejson . loads ( value ) return value
| 0 |
python change mysql data to json
|
convert value from json to a python object
|
cosqa-train-16878
|
def process_result_value(self, value, dialect):
"""convert value from json to a python object"""
if value is not None:
value = simplejson.loads(value)
return value
|
def multi_replace ( instr , search_list = [ ] , repl_list = None ) : repl_list = [ '' ] * len ( search_list ) if repl_list is None else repl_list for ser , repl in zip ( search_list , repl_list ) : instr = instr . replace ( ser , repl ) return instr
| 1 |
using replace in strings python
|
Does a string replace with a list of search and replacements
|
cosqa-train-16879
|
def multi_replace(instr, search_list=[], repl_list=None):
"""
Does a string replace with a list of search and replacements
TODO: rename
"""
repl_list = [''] * len(search_list) if repl_list is None else repl_list
for ser, repl in zip(search_list, repl_list):
instr = instr.replace(ser, repl)
return instr
|
def _zeep_to_dict ( cls , obj ) : res = serialize_object ( obj ) res = cls . _get_non_empty_dict ( res ) return res
| 1 |
python change object to dict
|
Convert a zeep object to a dictionary .
|
cosqa-train-16880
|
def _zeep_to_dict(cls, obj):
"""Convert a zeep object to a dictionary."""
res = serialize_object(obj)
res = cls._get_non_empty_dict(res)
return res
|
def test ( * args ) : subprocess . call ( [ "py.test-2.7" ] + list ( args ) ) subprocess . call ( [ "py.test-3.4" ] + list ( args ) )
| 1 |
using runpy with python unit tests
|
Run unit tests .
|
cosqa-train-16881
|
def test(*args):
"""
Run unit tests.
"""
subprocess.call(["py.test-2.7"] + list(args))
subprocess.call(["py.test-3.4"] + list(args))
|
def log_y_cb ( self , w , val ) : self . tab_plot . logy = val self . plot_two_columns ( )
| 0 |
python changing y axis to log
|
Toggle linear / log scale for Y - axis .
|
cosqa-train-16882
|
def log_y_cb(self, w, val):
"""Toggle linear/log scale for Y-axis."""
self.tab_plot.logy = val
self.plot_two_columns()
|
def main ( source ) : if source is None : click . echo ( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try : load ( source ) click . echo ( "Validation passed" ) return 0 except ValidationError as e : raise click . ClickException ( str ( e ) )
| 0 |
validate json to swagger in python
|
For a given command line supplied argument negotiate the content parse the schema and then return any issues to stdout or if no schema issues return success exit code .
|
cosqa-train-16883
|
def main(source):
"""
For a given command line supplied argument, negotiate the content, parse
the schema and then return any issues to stdout or if no schema issues,
return success exit code.
"""
if source is None:
click.echo(
"You need to supply a file or url to a schema to a swagger schema, for"
"the validator to work."
)
return 1
try:
load(source)
click.echo("Validation passed")
return 0
except ValidationError as e:
raise click.ClickException(str(e))
|
def hasattrs ( object , * names ) : for name in names : if not hasattr ( object , name ) : return False return True
| 1 |
python check all attributes of an object
|
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-16884
|
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 set_float ( val ) : out = None if not val in ( None , '' ) : try : out = float ( val ) except ValueError : return None if numpy . isnan ( out ) : out = default return out
| 1 |
value if a list is nan or is a string python
|
utility to set a floating value useful for converting from strings
|
cosqa-train-16885
|
def set_float(val):
""" utility to set a floating value,
useful for converting from strings """
out = None
if not val in (None, ''):
try:
out = float(val)
except ValueError:
return None
if numpy.isnan(out):
out = default
return out
|
def is_timestamp ( obj ) : return isinstance ( obj , datetime . datetime ) or is_string ( obj ) or is_int ( obj ) or is_float ( obj )
| 0 |
python check data type is datetime
|
Yaml either have automatically converted it to a datetime object or it is a string that will be validated later .
|
cosqa-train-16886
|
def is_timestamp(obj):
"""
Yaml either have automatically converted it to a datetime object
or it is a string that will be validated later.
"""
return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
|
def last_day ( year = _year , month = _month ) : last_day = calendar . monthrange ( year , month ) [ 1 ] return datetime . date ( year = year , month = month , day = last_day )
| 1 |
verify a date it is last day of a month python
|
get the current month s last day : param year : default to current year : param month : default to current month : return : month s last day
|
cosqa-train-16887
|
def last_day(year=_year, month=_month):
"""
get the current month's last day
:param year: default to current year
:param month: default to current month
:return: month's last day
"""
last_day = calendar.monthrange(year, month)[1]
return datetime.date(year=year, month=month, day=last_day)
|
def check_for_positional_argument ( kwargs , name , default = False ) : if name in kwargs : if str ( kwargs [ name ] ) == "True" : return True elif str ( kwargs [ name ] ) == "False" : return False else : return kwargs [ name ] return default
| 0 |
python check default optional arg in function
|
cosqa-train-16888
|
def check_for_positional_argument(kwargs, name, default=False):
"""
@type kwargs: dict
@type name: str
@type default: bool, int, str
@return: bool, int
"""
if name in kwargs:
if str(kwargs[name]) == "True":
return True
elif str(kwargs[name]) == "False":
return False
else:
return kwargs[name]
return default
|
|
def _validate_simple ( email ) : name , address = parseaddr ( email ) if not re . match ( '[^@]+@[^@]+\.[^@]+' , address ) : raise ValueError ( 'Invalid email :{email}' . format ( email = email ) ) return address
| 1 |
verify email format regex python
|
Does a simple validation of an email by matching it to a regexps
|
cosqa-train-16889
|
def _validate_simple(email):
"""Does a simple validation of an email by matching it to a regexps
:param email: The email to check
:return: The valid Email address
:raises: ValueError if value is not a valid email
"""
name, address = parseaddr(email)
if not re.match('[^@]+@[^@]+\.[^@]+', address):
raise ValueError('Invalid email :{email}'.format(email=email))
return address
|
def __contains__ ( self , key ) : assert isinstance ( key , basestring ) return dict . __contains__ ( self , key . lower ( ) )
| 0 |
python check dictionary key starts with a certain letter
|
Check lowercase key item .
|
cosqa-train-16890
|
def __contains__ (self, key):
"""Check lowercase key item."""
assert isinstance(key, basestring)
return dict.__contains__(self, key.lower())
|
def is_image_file_valid ( file_path_name ) : # Image.verify is only implemented for PNG images, and it only verifies # the CRC checksum in the image. The only way to check from within # Pillow is to load the image in a try/except and check the error. If # as much info as possible is from the image is needed, # ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it # will attempt to parse as much as possible. try : with Image . open ( file_path_name ) as image : image . load ( ) except IOError : return False return True
| 1 |
verify images if broken python
|
Indicate whether the specified image file is valid or not .
|
cosqa-train-16891
|
def is_image_file_valid(file_path_name):
"""
Indicate whether the specified image file is valid or not.
@param file_path_name: absolute path and file name of an image.
@return: ``True`` if the image file is valid, ``False`` if the file is
truncated or does not correspond to a supported image.
"""
# Image.verify is only implemented for PNG images, and it only verifies
# the CRC checksum in the image. The only way to check from within
# Pillow is to load the image in a try/except and check the error. If
# as much info as possible is from the image is needed,
# ``ImageFile.LOAD_TRUNCATED_IMAGES=True`` needs to bet set and it
# will attempt to parse as much as possible.
try:
with Image.open(file_path_name) as image:
image.load()
except IOError:
return False
return True
|
def do_last ( environment , seq ) : try : return next ( iter ( reversed ( seq ) ) ) except StopIteration : return environment . undefined ( 'No last item, sequence was empty.' )
| 0 |
visit last element python
|
Return the last item of a sequence .
|
cosqa-train-16892
|
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 is_numeric_dtype ( dtype ) : dtype = np . dtype ( dtype ) return np . issubsctype ( getattr ( dtype , 'base' , None ) , np . number )
| 1 |
python check for all numeric types
|
Return True if dtype is a numeric type .
|
cosqa-train-16893
|
def is_numeric_dtype(dtype):
"""Return ``True`` if ``dtype`` is a numeric type."""
dtype = np.dtype(dtype)
return np.issubsctype(getattr(dtype, 'base', None), np.number)
|
def stdout_display ( ) : if sys . version_info [ 0 ] == 2 : yield SmartBuffer ( sys . stdout ) else : yield SmartBuffer ( sys . stdout . buffer )
| 0 |
vs code python live output
|
Print results straight to stdout
|
cosqa-train-16894
|
def stdout_display():
""" Print results straight to stdout """
if sys.version_info[0] == 2:
yield SmartBuffer(sys.stdout)
else:
yield SmartBuffer(sys.stdout.buffer)
|
def has_field ( mc , field_name ) : try : mc . _meta . get_field ( field_name ) except FieldDoesNotExist : return False return True
| 1 |
python check for existence of property in model
|
detect if a model has a given field has
|
cosqa-train-16895
|
def has_field(mc, field_name):
"""
detect if a model has a given field has
:param field_name:
:param mc:
:return:
"""
try:
mc._meta.get_field(field_name)
except FieldDoesNotExist:
return False
return True
|
def readwav ( filename ) : from scipy . io . wavfile import read as readwav samplerate , signal = readwav ( filename ) return signal , samplerate
| 0 |
wav file to spectrogram python mathlab
|
Read a WAV file and returns the data and sample rate
|
cosqa-train-16896
|
def readwav(filename):
"""Read a WAV file and returns the data and sample rate
::
from spectrum.io import readwav
readwav()
"""
from scipy.io.wavfile import read as readwav
samplerate, signal = readwav(filename)
return signal, samplerate
|
def _rm_name_match ( s1 , s2 ) : m_len = min ( len ( s1 ) , len ( s2 ) ) return s1 [ : m_len ] == s2 [ : m_len ]
| 1 |
python check for overlapping matches in string
|
determine whether two sequence names from a repeatmasker alignment match .
|
cosqa-train-16897
|
def _rm_name_match(s1, s2):
"""
determine whether two sequence names from a repeatmasker alignment match.
:return: True if they are the same string, or if one forms a substring of the
other, else False
"""
m_len = min(len(s1), len(s2))
return s1[:m_len] == s2[:m_len]
|
def inside_softimage ( ) : try : import maya return False except ImportError : pass try : from win32com . client import Dispatch as disp disp ( 'XSI.Application' ) return True except : return False
| 0 |
way to tell if image is on screen python
|
Returns a boolean indicating if the code is executed inside softimage .
|
cosqa-train-16898
|
def inside_softimage():
"""Returns a boolean indicating if the code is executed inside softimage."""
try:
import maya
return False
except ImportError:
pass
try:
from win32com.client import Dispatch as disp
disp('XSI.Application')
return True
except:
return False
|
def _name_exists ( self , name ) : for i in range ( self . count ( ) ) : if self . tabText ( i ) == name : return True return False
| 1 |
python check for tab
|
Checks if we already have an opened tab with the same name .
|
cosqa-train-16899
|
def _name_exists(self, name):
"""
Checks if we already have an opened tab with the same name.
"""
for i in range(self.count()):
if self.tabText(i) == name:
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.