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 _mid ( pt1 , pt2 ) : ( x0 , y0 ) , ( x1 , y1 ) = pt1 , pt2 return 0.5 * ( x0 + x1 ) , 0.5 * ( y0 + y1 )
| 0 |
midpoints between two points python
|
( Point Point ) - > Point Return the point that lies in between the two input points .
|
cosqa-train-17700
|
def _mid(pt1, pt2):
"""
(Point, Point) -> Point
Return the point that lies in between the two input points.
"""
(x0, y0), (x1, y1) = pt1, pt2
return 0.5 * (x0 + x1), 0.5 * (y0 + y1)
|
def snake_to_camel ( value ) : camel = "" . join ( word . title ( ) for word in value . split ( "_" ) ) return value [ : 1 ] . lower ( ) + camel [ 1 : ]
| 0 |
python covert string to camel case
|
Converts a snake_case_string to a camelCaseString .
|
cosqa-train-17701
|
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = "".join(word.title() for word in value.split("_"))
return value[:1].lower() + camel[1:]
|
def factorial ( n , mod = None ) : if not ( isinstance ( n , int ) and n >= 0 ) : raise ValueError ( "'n' must be a non-negative integer." ) if mod is not None and not ( isinstance ( mod , int ) and mod > 0 ) : raise ValueError ( "'mod' must be a positive integer" ) result = 1 if n == 0 : return 1 for i in range ( 2 , n + 1 ) : result *= i if mod : result %= mod return result
| 1 |
python how to write a factorial
|
Calculates factorial iteratively . If mod is not None then return ( n! % mod ) Time Complexity - O ( n )
|
cosqa-train-17702
|
def factorial(n, mod=None):
"""Calculates factorial iteratively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
result = 1
if n == 0:
return 1
for i in range(2, n+1):
result *= i
if mod:
result %= mod
return result
|
def ResetConsoleColor ( ) -> bool : if sys . stdout : sys . stdout . flush ( ) bool ( ctypes . windll . kernel32 . SetConsoleTextAttribute ( _ConsoleOutputHandle , _DefaultConsoleColor ) )
| 0 |
reset window color python
|
Reset to the default text color on console window . Return bool True if succeed otherwise False .
|
cosqa-train-17703
|
def ResetConsoleColor() -> bool:
"""
Reset to the default text color on console window.
Return bool, True if succeed otherwise False.
"""
if sys.stdout:
sys.stdout.flush()
bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
|
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 0 |
how to return the second smallest value in an array python
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-17704
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def Exit ( msg , code = 1 ) : print >> sys . stderr , msg sys . exit ( code )
| 0 |
exit not defined python
|
Exit execution with return code and message : param msg : Message displayed prior to exit : param code : code returned upon exiting
|
cosqa-train-17705
|
def Exit(msg, code=1):
"""Exit execution with return code and message
:param msg: Message displayed prior to exit
:param code: code returned upon exiting
"""
print >> sys.stderr, msg
sys.exit(code)
|
def has_synset ( word : str ) -> list : return wn . synsets ( lemmatize ( word , neverstem = True ) )
| 0 |
python how to lemmatize wordnetlemmatizer
|
Returns a list of synsets of a word after lemmatization .
|
cosqa-train-17706
|
def has_synset(word: str) -> list:
"""" Returns a list of synsets of a word after lemmatization. """
return wn.synsets(lemmatize(word, neverstem=True))
|
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
| 0 |
generating random number with gaussian distribution in python
|
Creates a variation from a base value
|
cosqa-train-17707
|
def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma))
|
def binary ( length ) : num = randint ( 1 , 999999 ) mask = '0' * length return ( mask + '' . join ( [ str ( num >> i & 1 ) for i in range ( 7 , - 1 , - 1 ) ] ) ) [ - length : ]
| 1 |
integer and returns a random bitstring of size python
|
returns a a random string that represent a binary representation
|
cosqa-train-17708
|
def binary(length):
"""
returns a a random string that represent a binary representation
:param length: number of bits
"""
num = randint(1, 999999)
mask = '0' * length
return (mask + ''.join([str(num >> i & 1) for i in range(7, -1, -1)]))[-length:]
|
def last_location_of_minimum ( x ) : x = np . asarray ( x ) return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN
| 0 |
python apply min to column
|
Returns the last location of the minimal value of x . The position is calculated relatively to the length of x .
|
cosqa-train-17709
|
def last_location_of_minimum(x):
"""
Returns the last location of the minimal value of x.
The position is calculated relatively to the length of x.
:param x: the time series to calculate the feature of
:type x: numpy.ndarray
:return: the value of this feature
:return type: float
"""
x = np.asarray(x)
return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN
|
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 1 |
get single file from s3 python
|
Pull a file directly from S3 .
|
cosqa-train-17710
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 1 |
list comprehension python flatten
|
takes a list of lists l and returns a flat list
|
cosqa-train-17711
|
def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l]
|
def url_host ( url : str ) -> str : from urllib . parse import urlparse res = urlparse ( url ) return res . netloc . split ( ':' ) [ 0 ] if res . netloc else ''
| 1 |
how to get domain part of a url in python
|
Parses hostname from URL . : param url : URL : return : hostname
|
cosqa-train-17712
|
def url_host(url: str) -> str:
"""
Parses hostname from URL.
:param url: URL
:return: hostname
"""
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else ''
|
def has_key ( cls , * args ) : key = args if len ( args ) > 1 else args [ 0 ] return key in cls . _instances
| 0 |
python access if key exists
|
Check whether flyweight object with specified key has already been created .
|
cosqa-train-17713
|
def has_key(cls, *args):
"""
Check whether flyweight object with specified key has already been created.
Returns:
bool: True if already created, False if not
"""
key = args if len(args) > 1 else args[0]
return key in cls._instances
|
def most_significant_bit ( lst : np . ndarray ) -> int : return np . argwhere ( np . asarray ( lst ) == 1 ) [ 0 ] [ 0 ]
| 1 |
python index of largest value of array
|
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s i . e . the first position where a 1 appears reading left to right .
|
cosqa-train-17714
|
def most_significant_bit(lst: np.ndarray) -> int:
"""
A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s,
i.e. the first position where a 1 appears, reading left to right.
:param lst: a 1d array of 0s and 1s with at least one 1
:return: the first position in lst that a 1 appears
"""
return np.argwhere(np.asarray(lst) == 1)[0][0]
|
def full ( self ) : return self . maxsize and len ( self . list ) >= self . maxsize or False
| 1 |
python how to check the queue lenght
|
Return True if the queue is full False otherwise ( not reliable! ) .
|
cosqa-train-17715
|
def full(self):
"""Return ``True`` if the queue is full, ``False``
otherwise (not reliable!).
Only applicable if :attr:`maxsize` is set.
"""
return self.maxsize and len(self.list) >= self.maxsize or False
|
def val_mb ( valstr : Union [ int , str ] ) -> str : try : return "{:.3f}" . format ( int ( valstr ) / ( 1024 * 1024 ) ) except ( TypeError , ValueError ) : return '?'
| 0 |
python conver megabyte to number
|
Converts a value in bytes ( in string format ) to megabytes .
|
cosqa-train-17716
|
def val_mb(valstr: Union[int, str]) -> str:
"""
Converts a value in bytes (in string format) to megabytes.
"""
try:
return "{:.3f}".format(int(valstr) / (1024 * 1024))
except (TypeError, ValueError):
return '?'
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 1 |
python request limit bandwidth
|
Rate limit a function .
|
cosqa-train-17717
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def moving_average ( iterable , n ) : it = iter ( iterable ) d = collections . deque ( itertools . islice ( it , n - 1 ) ) d . appendleft ( 0 ) s = sum ( d ) for elem in it : s += elem - d . popleft ( ) d . append ( elem ) yield s / float ( n )
| 0 |
python moving average nested loop
|
From Python collections module documentation
|
cosqa-train-17718
|
def moving_average(iterable, n):
"""
From Python collections module documentation
moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
"""
it = iter(iterable)
d = collections.deque(itertools.islice(it, n - 1))
d.appendleft(0)
s = sum(d)
for elem in it:
s += elem - d.popleft()
d.append(elem)
yield s / float(n)
|
def encode_list ( key , list_ ) : # type: (str, Iterable) -> Dict[str, str] if not list_ : return { } return { key : " " . join ( str ( i ) for i in list_ ) }
| 1 |
build a dict python using keys and value lists
|
Converts a list into a space - separated string and puts it in a dictionary
|
cosqa-train-17719
|
def encode_list(key, list_):
# type: (str, Iterable) -> Dict[str, str]
"""
Converts a list into a space-separated string and puts it in a dictionary
:param key: Dictionary key to store the list
:param list_: A list of objects
:return: A dictionary key->string or an empty dictionary
"""
if not list_:
return {}
return {key: " ".join(str(i) for i in list_)}
|
def _isint ( string ) : return type ( string ) is int or ( isinstance ( string , _binary_type ) or isinstance ( string , _text_type ) ) and _isconvertible ( int , string )
| 1 |
how to detect if a string is an int in python
|
>>> _isint ( 123 ) True >>> _isint ( 123 . 45 ) False
|
cosqa-train-17720
|
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or isinstance(string, _text_type)) and \
_isconvertible(int, string)
|
def _close ( self ) : self . _usb_handle . releaseInterface ( ) try : # If we're using PyUSB >= 1.0 we can re-attach the kernel driver here. self . _usb_handle . dev . attach_kernel_driver ( 0 ) except : pass self . _usb_int = None self . _usb_handle = None return True
| 0 |
reset usb device python windows
|
Release the USB interface again .
|
cosqa-train-17721
|
def _close(self):
"""
Release the USB interface again.
"""
self._usb_handle.releaseInterface()
try:
# If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.
self._usb_handle.dev.attach_kernel_driver(0)
except:
pass
self._usb_int = None
self._usb_handle = None
return True
|
def dag_longest_path ( graph , source , target ) : if source == target : return [ source ] allpaths = nx . all_simple_paths ( graph , source , target ) longest_path = [ ] for l in allpaths : if len ( l ) > len ( longest_path ) : longest_path = l return longest_path
| 0 |
whats the best way to calculate the shortest path in a python graph
|
Finds the longest path in a dag between two nodes
|
cosqa-train-17722
|
def dag_longest_path(graph, source, target):
"""
Finds the longest path in a dag between two nodes
"""
if source == target:
return [source]
allpaths = nx.all_simple_paths(graph, source, target)
longest_path = []
for l in allpaths:
if len(l) > len(longest_path):
longest_path = l
return longest_path
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 0 |
python most frequent item in a list
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17723
|
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
|
def normalize ( numbers ) : total = float ( sum ( numbers ) ) return [ n / total for n in numbers ]
| 0 |
change values to as a percentage python
|
Multiply each number by a constant such that the sum is 1 . 0 >>> normalize ( [ 1 2 1 ] ) [ 0 . 25 0 . 5 0 . 25 ]
|
cosqa-train-17724
|
def normalize(numbers):
"""Multiply each number by a constant such that the sum is 1.0
>>> normalize([1,2,1])
[0.25, 0.5, 0.25]
"""
total = float(sum(numbers))
return [n / total for n in numbers]
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 1 |
python hash function from big number to smaller
|
Simple helper hash function
|
cosqa-train-17725
|
def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res
|
def truncate ( value : Decimal , n_digits : int ) -> Decimal : return Decimal ( math . trunc ( value * ( 10 ** n_digits ) ) ) / ( 10 ** n_digits )
| 0 |
python how to truncate decimals
|
Truncates a value to a number of decimals places
|
cosqa-train-17726
|
def truncate(value: Decimal, n_digits: int) -> Decimal:
"""Truncates a value to a number of decimals places"""
return Decimal(math.trunc(value * (10 ** n_digits))) / (10 ** n_digits)
|
def debugTreePrint ( node , pfx = "->" ) : print pfx , node . item for c in node . children : debugTreePrint ( c , " " + pfx )
| 0 |
networkx python recursive print a tree
|
Purely a debugging aid : Ascii - art picture of a tree descended from node
|
cosqa-train-17727
|
def debugTreePrint(node,pfx="->"):
"""Purely a debugging aid: Ascii-art picture of a tree descended from node"""
print pfx,node.item
for c in node.children:
debugTreePrint(c," "+pfx)
|
def dict_of_sets_add ( dictionary , key , value ) : # type: (DictUpperBound, Any, Any) -> None set_objs = dictionary . get ( key , set ( ) ) set_objs . add ( value ) dictionary [ key ] = set_objs
| 0 |
how to add somethign to a set in python
|
Add value to a set in a dictionary by key
|
cosqa-train-17728
|
def dict_of_sets_add(dictionary, key, value):
# type: (DictUpperBound, Any, Any) -> None
"""Add value to a set in a dictionary by key
Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to set in dictionary
Returns:
None
"""
set_objs = dictionary.get(key, set())
set_objs.add(value)
dictionary[key] = set_objs
|
def camel_to_snake ( s : str ) -> str : return CAMEL_CASE_RE . sub ( r'_\1' , s ) . strip ( ) . lower ( )
| 1 |
string camel case method python
|
Convert string from camel case to snake case .
|
cosqa-train-17729
|
def camel_to_snake(s: str) -> str:
"""Convert string from camel case to snake case."""
return CAMEL_CASE_RE.sub(r'_\1', s).strip().lower()
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 0 |
turn list of strings into numbers python
|
Convert a list of strings to a list of integers .
|
cosqa-train-17730
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def most_frequent ( lst ) : lst = lst [ : ] highest_freq = 0 most_freq = None for val in unique ( lst ) : if lst . count ( val ) > highest_freq : most_freq = val highest_freq = lst . count ( val ) return most_freq
| 1 |
return most frequent element in list python
|
Returns the item that appears most frequently in the given list .
|
cosqa-train-17731
|
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
|
def _my_hash ( arg_list ) : # type: (List[Any]) -> int res = 0 for arg in arg_list : res = res * 31 + hash ( arg ) return res
| 0 |
how to hash a list in python
|
Simple helper hash function
|
cosqa-train-17732
|
def _my_hash(arg_list):
# type: (List[Any]) -> int
"""Simple helper hash function"""
res = 0
for arg in arg_list:
res = res * 31 + hash(arg)
return res
|
def fmt_camel ( name ) : words = split_words ( name ) assert len ( words ) > 0 first = words . pop ( 0 ) . lower ( ) return first + '' . join ( [ word . capitalize ( ) for word in words ] )
| 0 |
python first letter large caps the rest small
|
Converts name to lower camel case . Words are identified by capitalization dashes and underscores .
|
cosqa-train-17733
|
def fmt_camel(name):
"""
Converts name to lower camel case. Words are identified by capitalization,
dashes, and underscores.
"""
words = split_words(name)
assert len(words) > 0
first = words.pop(0).lower()
return first + ''.join([word.capitalize() for word in words])
|
def is_integer ( value : Any ) -> bool : return ( isinstance ( value , int ) and not isinstance ( value , bool ) ) or ( isinstance ( value , float ) and isfinite ( value ) and int ( value ) == value )
| 0 |
python is double or float
|
Return true if a value is an integer number .
|
cosqa-train-17734
|
def is_integer(value: Any) -> bool:
"""Return true if a value is an integer number."""
return (isinstance(value, int) and not isinstance(value, bool)) or (
isinstance(value, float) and isfinite(value) and int(value) == value
)
|
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
| 0 |
does python have a method to generate random numbers with a normal distribution
|
Creates a variation from a base value
|
cosqa-train-17735
|
def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma))
|
def zfill ( x , width ) : if not isinstance ( x , basestring ) : x = repr ( x ) return x . zfill ( width )
| 0 |
python 3 specify string width and padding
|
zfill ( x width ) - > string
|
cosqa-train-17736
|
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width)
|
def method_caller ( method_name , * args , * * kwargs ) : def call_method ( target ) : func = getattr ( target , method_name ) return func ( * args , * * kwargs ) return call_method
| 0 |
python function name should be lowercase
|
Return a function that will call a named method on the target object with optional positional and keyword arguments .
|
cosqa-train-17737
|
def method_caller(method_name, *args, **kwargs):
"""
Return a function that will call a named method on the
target object with optional positional and keyword
arguments.
>>> lower = method_caller('lower')
>>> lower('MyString')
'mystring'
"""
def call_method(target):
func = getattr(target, method_name)
return func(*args, **kwargs)
return call_method
|
def obj_in_list_always ( target_list , obj ) : for item in set ( target_list ) : if item is not obj : return False return True
| 0 |
python function for not in list
|
>>> l = [ 1 1 1 ] >>> obj_in_list_always ( l 1 ) True >>> l . append ( 2 ) >>> obj_in_list_always ( l 1 ) False
|
cosqa-train-17738
|
def obj_in_list_always(target_list, obj):
"""
>>> l = [1,1,1]
>>> obj_in_list_always(l, 1)
True
>>> l.append(2)
>>> obj_in_list_always(l, 1)
False
"""
for item in set(target_list):
if item is not obj:
return False
return True
|
def count ( args ) : counts = defaultdict ( int ) for arg in args : for item in arg : counts [ item ] = counts [ item ] + 1 return counts
| 0 |
how can you create a dictionary of letters and their counts based on a list of strings in python
|
count occurences in a list of lists >>> count ( [[ a b ] [ a ]] ) defaultdict ( int { a : 2 b : 1 } )
|
cosqa-train-17739
|
def count(args):
""" count occurences in a list of lists
>>> count([['a','b'],['a']])
defaultdict(int, {'a' : 2, 'b' : 1})
"""
counts = defaultdict(int)
for arg in args:
for item in arg:
counts[item] = counts[item] + 1
return counts
|
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 1 |
removing columnsns in data frame python
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-17740
|
def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
"""
f = df.copy()
f.columns = [col.strip() for col in f.columns]
return f
|
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
| 0 |
buffer dtype mismatch, expected 'python object' but got 'unsigned long'
|
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
|
cosqa-train-17741
|
def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0]
|
def _ ( f , x ) : return { k : v for k , v in x . items ( ) if f ( k , v ) }
| 0 |
python filter lambda two dict
|
filter for dict note f should have signature : f :: key - > value - > bool
|
cosqa-train-17742
|
def _(f, x):
"""
filter for dict, note `f` should have signature: `f::key->value->bool`
"""
return {k: v for k, v in x.items() if f(k, v)}
|
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
| 0 |
python length of column in numpy array
|
Return the number of dimensions of a tensor
|
cosqa-train-17743
|
def rank(tensor: BKTensor) -> int:
"""Return the number of dimensions of a tensor"""
if isinstance(tensor, np.ndarray):
return len(tensor.shape)
return len(tensor[0].size())
|
def cmd_dot ( conf : Config ) : build_context = BuildContext ( conf ) populate_targets_graph ( build_context , conf ) if conf . output_dot_file is None : write_dot ( build_context , conf , sys . stdout ) else : with open ( conf . output_dot_file , 'w' ) as out_file : write_dot ( build_context , conf , out_file )
| 0 |
python execute dot graphviz
|
Print out a neat targets dependency tree based on requested targets .
|
cosqa-train-17744
|
def cmd_dot(conf: Config):
"""Print out a neat targets dependency tree based on requested targets.
Use graphviz to render the dot file, e.g.:
> ybt dot :foo :bar | dot -Tpng -o graph.png
"""
build_context = BuildContext(conf)
populate_targets_graph(build_context, conf)
if conf.output_dot_file is None:
write_dot(build_context, conf, sys.stdout)
else:
with open(conf.output_dot_file, 'w') as out_file:
write_dot(build_context, conf, out_file)
|
def set_cell_value ( cell , value ) : if OPENPYXL_MAJOR_VERSION > 1 : cell . value = value else : cell . internal_value = value
| 1 |
python openpyxl set color
|
Convenience method for setting the value of an openpyxl cell
|
cosqa-train-17745
|
def set_cell_value(cell, value):
"""
Convenience method for setting the value of an openpyxl cell
This is necessary since the value property changed from internal_value
to value between version 1.* and 2.*.
"""
if OPENPYXL_MAJOR_VERSION > 1:
cell.value = value
else:
cell.internal_value = value
|
def valid_file ( path : str ) -> bool : path = Path ( path ) . expanduser ( ) log . debug ( "checking if %s is a valid file" , path ) return path . exists ( ) and path . is_file ( )
| 1 |
check if a variable is a file in python
|
Verifies that a string path actually exists and is a file
|
cosqa-train-17746
|
def valid_file(path: str) -> bool:
"""
Verifies that a string path actually exists and is a file
:param path: The path to verify
:return: **True** if path exist and is a file
"""
path = Path(path).expanduser()
log.debug("checking if %s is a valid file", path)
return path.exists() and path.is_file()
|
def mmap ( func , iterable ) : if sys . version_info [ 0 ] > 2 : return [ i for i in map ( func , iterable ) ] else : return map ( func , iterable )
| 1 |
python3 map 2d list
|
Wrapper to make map () behave the same on Py2 and Py3 .
|
cosqa-train-17747
|
def mmap(func, iterable):
"""Wrapper to make map() behave the same on Py2 and Py3."""
if sys.version_info[0] > 2:
return [i for i in map(func, iterable)]
else:
return map(func, iterable)
|
def tanimoto_set_similarity ( x : Iterable [ X ] , y : Iterable [ X ] ) -> float : a , b = set ( x ) , set ( y ) union = a | b if not union : return 0.0 return len ( a & b ) / len ( union )
| 1 |
how to calculate a similarity score of two synsets using nltk in python
|
Calculate the tanimoto set similarity .
|
cosqa-train-17748
|
def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float:
"""Calculate the tanimoto set similarity."""
a, b = set(x), set(y)
union = a | b
if not union:
return 0.0
return len(a & b) / len(union)
|
def get_column_names ( engine : Engine , tablename : str ) -> List [ str ] : return [ info . name for info in gen_columns_info ( engine , tablename ) ]
| 1 |
get table column names from database python
|
Get all the database column names for the specified table .
|
cosqa-train-17749
|
def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)]
|
def flatten_list ( l : List [ list ] ) -> list : return [ v for inner_l in l for v in inner_l ]
| 1 |
turn list of lists into list python
|
takes a list of lists l and returns a flat list
|
cosqa-train-17750
|
def flatten_list(l: List[list]) -> list:
""" takes a list of lists, l and returns a flat list
"""
return [v for inner_l in l for v in inner_l]
|
def argmax ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value. return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] , reverse = True ) [ 0 ] [ 1 ] ]
| 1 |
extract row with max value in python
|
Takes a list of rows and a column name and returns a list containing a single row ( dict from columns to cells ) that has the maximum numerical value in the given column . We return a list instead of a single dict to be consistent with the return type of select and all_rows .
|
cosqa-train-17751
|
def argmax(self, rows: List[Row], column: ComparableColumn) -> List[Row]:
"""
Takes a list of rows and a column name and returns a list containing a single row (dict from
columns to cells) that has the maximum numerical value in the given column. We return a list
instead of a single dict to be consistent with the return type of ``select`` and
``all_rows``.
"""
if not rows:
return []
value_row_pairs = [(row.values[column.name], row) for row in rows]
if not value_row_pairs:
return []
# Returns a list containing the row with the max cell value.
return [sorted(value_row_pairs, key=lambda x: x[0], reverse=True)[0][1]]
|
def cli_run ( ) : parser = argparse . ArgumentParser ( description = 'Stupidly simple code answers from StackOverflow' ) parser . add_argument ( 'query' , help = "What's the problem ?" , type = str , nargs = '+' ) parser . add_argument ( '-t' , '--tags' , help = 'semicolon separated tags -> python;lambda' ) args = parser . parse_args ( ) main ( args )
| 1 |
python pass argparse to function
|
docstring for argparse
|
cosqa-train-17752
|
def cli_run():
"""docstring for argparse"""
parser = argparse.ArgumentParser(description='Stupidly simple code answers from StackOverflow')
parser.add_argument('query', help="What's the problem ?", type=str, nargs='+')
parser.add_argument('-t','--tags', help='semicolon separated tags -> python;lambda')
args = parser.parse_args()
main(args)
|
def __remove_method ( m : lmap . Map , key : T ) -> lmap . Map : return m . dissoc ( key )
| 0 |
python map remove without raise
|
Swap the methods atom to remove method with key .
|
cosqa-train-17753
|
def __remove_method(m: lmap.Map, key: T) -> lmap.Map:
"""Swap the methods atom to remove method with key."""
return m.dissoc(key)
|
def _gauss ( mean : int , sigma : int ) -> int : return int ( random . gauss ( mean , sigma ) )
| 1 |
set random number from normal distribution in python
|
Creates a variation from a base value
|
cosqa-train-17754
|
def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma))
|
def returned ( n ) : ## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk for pos in randwalk ( ) >> drop ( 1 ) >> takei ( xrange ( n - 1 ) ) : if pos == Origin : return True return False
| 1 |
random walk with bound in python
|
Generate a random walk and return True if the walker has returned to the origin after taking n steps .
|
cosqa-train-17755
|
def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return False
|
def looks_like_url ( url ) : if not isinstance ( url , basestring ) : return False if not isinstance ( url , basestring ) or len ( url ) >= 1024 or not cre_url . match ( url ) : return False return True
| 0 |
python if str is url
|
Simplified check to see if the text appears to be a URL .
|
cosqa-train-17756
|
def looks_like_url(url):
""" Simplified check to see if the text appears to be a URL.
Similar to `urlparse` but much more basic.
Returns:
True if the url str appears to be valid.
False otherwise.
>>> url = looks_like_url("totalgood.org")
>>> bool(url)
True
"""
if not isinstance(url, basestring):
return False
if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url):
return False
return True
|
def clean_column_names ( df : DataFrame ) -> DataFrame : f = df . copy ( ) f . columns = [ col . strip ( ) for col in f . columns ] return f
| 1 |
remove columns from data frame python
|
Strip the whitespace from all column names in the given DataFrame and return the result .
|
cosqa-train-17757
|
def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
"""
f = df.copy()
f.columns = [col.strip() for col in f.columns]
return f
|
def get_domain ( url ) : parse_result = urlparse ( url ) domain = "{schema}://{netloc}" . format ( schema = parse_result . scheme , netloc = parse_result . netloc ) return domain
| 0 |
get url schema problem python
|
Get domain part of an url .
|
cosqa-train-17758
|
def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain
|
def preconnect ( self , size = - 1 ) : if size == - 1 and self . max_size == - 1 : raise ClientError ( "size=-1 not allowed with pool max_size=-1" ) limit = min ( size , self . max_size ) if size != - 1 else self . max_size clients = yield [ self . get_connected_client ( ) for _ in range ( 0 , limit ) ] for client in clients : self . release_client ( client )
| 0 |
python redis connection pool max size2**31
|
( pre ) Connects some or all redis clients inside the pool .
|
cosqa-train-17759
|
def preconnect(self, size=-1):
"""(pre)Connects some or all redis clients inside the pool.
Args:
size (int): number of redis clients to build and to connect
(-1 means all clients if pool max_size > -1)
Raises:
ClientError: when size == -1 and pool max_size == -1
"""
if size == -1 and self.max_size == -1:
raise ClientError("size=-1 not allowed with pool max_size=-1")
limit = min(size, self.max_size) if size != -1 else self.max_size
clients = yield [self.get_connected_client() for _ in range(0, limit)]
for client in clients:
self.release_client(client)
|
def min ( self ) : res = self . _qexec ( "min(%s)" % self . _name ) if len ( res ) > 0 : self . _min = res [ 0 ] [ 0 ] return self . _min
| 0 |
python get min val of column
|
: returns the minimum of the column
|
cosqa-train-17760
|
def min(self):
"""
:returns the minimum of the column
"""
res = self._qexec("min(%s)" % self._name)
if len(res) > 0:
self._min = res[0][0]
return self._min
|
def left_zero_pad ( s , blocksize ) : if blocksize > 0 and len ( s ) % blocksize : s = ( blocksize - len ( s ) % blocksize ) * b ( '\000' ) + s return s
| 1 |
python padding zeros in bytestring
|
Left padding with zero bytes to a given block size
|
cosqa-train-17761
|
def left_zero_pad(s, blocksize):
"""
Left padding with zero bytes to a given block size
:param s:
:param blocksize:
:return:
"""
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s
|
def dotproduct ( X , Y ) : return sum ( [ x * y for x , y in zip ( X , Y ) ] )
| 0 |
sum elements of two vectors python
|
Return the sum of the element - wise product of vectors x and y . >>> dotproduct ( [ 1 2 3 ] [ 1000 100 10 ] ) 1230
|
cosqa-train-17762
|
def dotproduct(X, Y):
"""Return the sum of the element-wise product of vectors x and y.
>>> dotproduct([1, 2, 3], [1000, 100, 10])
1230
"""
return sum([x * y for x, y in zip(X, Y)])
|
def s3_get ( url : str , temp_file : IO ) -> None : s3_resource = boto3 . resource ( "s3" ) bucket_name , s3_path = split_s3_path ( url ) s3_resource . Bucket ( bucket_name ) . download_fileobj ( s3_path , temp_file )
| 1 |
access s3 files from python
|
Pull a file directly from S3 .
|
cosqa-train-17763
|
def s3_get(url: str, temp_file: IO) -> None:
"""Pull a file directly from S3."""
s3_resource = boto3.resource("s3")
bucket_name, s3_path = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def year ( date ) : try : fmt = '%m/%d/%Y' return datetime . strptime ( date , fmt ) . timetuple ( ) . tm_year except ValueError : return 0
| 0 |
python get year from date string
|
Returns the year .
|
cosqa-train-17764
|
def year(date):
""" Returns the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> year('05/1/2015')
2015
"""
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0
|
def try_cast_int ( s ) : try : temp = re . findall ( '\d' , str ( s ) ) temp = '' . join ( temp ) return int ( temp ) except : return s
| 1 |
how to make string into int on python
|
( str ) - > int All the digits in a given string are concatenated and converted into a single number .
|
cosqa-train-17765
|
def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s
|
def str_upper ( x ) : sl = _to_string_sequence ( x ) . upper ( ) return column . ColumnStringArrow ( sl . bytes , sl . indices , sl . length , sl . offset , string_sequence = sl )
| 1 |
python column to upper
|
Converts all strings in a column to uppercase .
|
cosqa-train-17766
|
def str_upper(x):
"""Converts all strings in a column to uppercase.
:returns: an expression containing the converted strings.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.upper()
Expression = str_upper(text)
Length: 5 dtype: str (expression)
---------------------------------
0 SOMETHING
1 VERY PRETTY
2 IS COMING
3 OUR
4 WAY.
"""
sl = _to_string_sequence(x).upper()
return column.ColumnStringArrow(sl.bytes, sl.indices, sl.length, sl.offset, string_sequence=sl)
|
def rank ( tensor : BKTensor ) -> int : if isinstance ( tensor , np . ndarray ) : return len ( tensor . shape ) return len ( tensor [ 0 ] . size ( ) )
| 0 |
how to get the size of the matrix in python
|
Return the number of dimensions of a tensor
|
cosqa-train-17767
|
def rank(tensor: BKTensor) -> int:
"""Return the number of dimensions of a tensor"""
if isinstance(tensor, np.ndarray):
return len(tensor.shape)
return len(tensor[0].size())
|
def uuid ( self , version : int = None ) -> str : bits = self . random . getrandbits ( 128 ) return str ( uuid . UUID ( int = bits , version = version ) )
| 0 |
python3 generate random uuid
|
Generate random UUID .
|
cosqa-train-17768
|
def uuid(self, version: int = None) -> str:
"""Generate random UUID.
:param version: UUID version.
:return: UUID
"""
bits = self.random.getrandbits(128)
return str(uuid.UUID(int=bits, version=version))
|
def csv_to_numpy ( string_like , dtype = None ) : # type: (str) -> np.array stream = StringIO ( string_like ) return np . genfromtxt ( stream , dtype = dtype , delimiter = ',' )
| 1 |
read in csv as numpy array python
|
Convert a CSV object to a numpy array .
|
cosqa-train-17769
|
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array
"""Convert a CSV object to a numpy array.
Args:
string_like (str): CSV string.
dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the
contents of each column, individually. This argument can only be used to
'upcast' the array. For downcasting, use the .astype(t) method.
Returns:
(np.array): numpy array
"""
stream = StringIO(string_like)
return np.genfromtxt(stream, dtype=dtype, delimiter=',')
|
def setup_cache ( app : Flask , cache_config ) -> Optional [ Cache ] : if cache_config and cache_config . get ( 'CACHE_TYPE' ) != 'null' : return Cache ( app , config = cache_config ) return None
| 0 |
remove cache python flask
|
Setup the flask - cache on a flask app
|
cosqa-train-17770
|
def setup_cache(app: Flask, cache_config) -> Optional[Cache]:
"""Setup the flask-cache on a flask app"""
if cache_config and cache_config.get('CACHE_TYPE') != 'null':
return Cache(app, config=cache_config)
return None
|
def flatten_list ( x : List [ Any ] ) -> List [ Any ] : # noqa return [ item for sublist in x for item in sublist ]
| 1 |
flaten a list of list python
|
Converts a list of lists into a flat list . Args : x : list of lists
|
cosqa-train-17771
|
def flatten_list(x: List[Any]) -> List[Any]:
"""
Converts a list of lists into a flat list.
Args:
x: list of lists
Returns:
flat list
As per
http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
""" # noqa
return [item for sublist in x for item in sublist]
|
def fprint ( expr , print_ascii = False ) : if print_ascii : pprint ( expr , use_unicode = False , num_columns = 120 ) else : return expr
| 1 |
how to write or sympole in python
|
r This function chooses whether to use ascii characters to represent a symbolic expression in the notebook or to use sympy s pprint .
|
cosqa-train-17772
|
def fprint(expr, print_ascii=False):
r"""This function chooses whether to use ascii characters to represent
a symbolic expression in the notebook or to use sympy's pprint.
>>> from sympy import cos
>>> omega=Symbol("omega")
>>> fprint(cos(omega),print_ascii=True)
cos(omega)
"""
if print_ascii:
pprint(expr, use_unicode=False, num_columns=120)
else:
return expr
|
async def executemany ( self , sql : str , parameters : Iterable [ Iterable [ Any ] ] ) -> None : await self . _execute ( self . _cursor . executemany , sql , parameters )
| 0 |
python mysql query executemany
|
Execute the given multiquery .
|
cosqa-train-17773
|
async def executemany(self, sql: str, parameters: Iterable[Iterable[Any]]) -> None:
"""Execute the given multiquery."""
await self._execute(self._cursor.executemany, sql, parameters)
|
async def fetchall ( self ) -> Iterable [ sqlite3 . Row ] : return await self . _execute ( self . _cursor . fetchall )
| 1 |
python cursor fetchone iterable
|
Fetch all remaining rows .
|
cosqa-train-17774
|
async def fetchall(self) -> Iterable[sqlite3.Row]:
"""Fetch all remaining rows."""
return await self._execute(self._cursor.fetchall)
|
def proper_round ( n ) : return int ( n ) + ( n / abs ( n ) ) * int ( abs ( n - int ( n ) ) >= 0.5 ) if n != 0 else 0
| 0 |
python integer rounded to closest value
|
rounds float to closest int : rtype : int : param n : float
|
cosqa-train-17775
|
def proper_round(n):
"""
rounds float to closest int
:rtype: int
:param n: float
"""
return int(n) + (n / abs(n)) * int(abs(n - int(n)) >= 0.5) if n != 0 else 0
|
def rate_limited ( max_per_hour : int , * args : Any ) -> Callable [ ... , Any ] : return util . rate_limited ( max_per_hour , * args )
| 0 |
python api calls limit calls per limit
|
Rate limit a function .
|
cosqa-train-17776
|
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args)
|
def is_none ( string_ , default = 'raise' ) : none = [ 'none' , 'undefined' , 'unknown' , 'null' , '' ] if string_ . lower ( ) in none : return True elif not default : return False else : raise ValueError ( 'The value \'{}\' cannot be mapped to none.' . format ( string_ ) )
| 0 |
how to compare 'none' with none in python
|
Check if a string is equivalent to None .
|
cosqa-train-17777
|
def is_none(string_, default='raise'):
"""
Check if a string is equivalent to None.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "None" strings is detected.
Returns
-------
is_none : bool
Examples
--------
>>> is_none('2', default=False)
False
>>> is_none('undefined', default=False)
True
"""
none = ['none', 'undefined', 'unknown', 'null', '']
if string_.lower() in none:
return True
elif not default:
return False
else:
raise ValueError('The value \'{}\' cannot be mapped to none.'
.format(string_))
|
def samefile ( a : str , b : str ) -> bool : try : return os . path . samefile ( a , b ) except OSError : return os . path . normpath ( a ) == os . path . normpath ( b )
| 0 |
python check if paths are same
|
Check if two pathes represent the same file .
|
cosqa-train-17778
|
def samefile(a: str, b: str) -> bool:
"""Check if two pathes represent the same file."""
try:
return os.path.samefile(a, b)
except OSError:
return os.path.normpath(a) == os.path.normpath(b)
|
async def login ( username : str , password : str , brand : str , websession : ClientSession = None ) -> API : api = API ( brand , websession ) await api . authenticate ( username , password ) return api
| 1 |
how to login to jira dynamically using rest apis and python
|
Log in to the API .
|
cosqa-train-17779
|
async def login(
username: str, password: str, brand: str,
websession: ClientSession = None) -> API:
"""Log in to the API."""
api = API(brand, websession)
await api.authenticate(username, password)
return api
|
def should_rollover ( self , record : LogRecord ) -> bool : t = int ( time . time ( ) ) if t >= self . rollover_at : return True return False
| 1 |
python check for a roll over counter
|
Determine if rollover should occur .
|
cosqa-train-17780
|
def should_rollover(self, record: LogRecord) -> bool:
"""
Determine if rollover should occur.
record is not used, as we are just comparing times, but it is needed so
the method signatures are the same
"""
t = int(time.time())
if t >= self.rollover_at:
return True
return False
|
def do_quit ( self , _ : argparse . Namespace ) -> bool : self . _should_quit = True return self . _STOP_AND_EXIT
| 0 |
stop python none end
|
Exit this application
|
cosqa-train-17781
|
def do_quit(self, _: argparse.Namespace) -> bool:
"""Exit this application"""
self._should_quit = True
return self._STOP_AND_EXIT
|
def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
| 1 |
python apply median filter to part of the image
|
Fast median operation for masked array using 50th - percentile
|
cosqa-train-17782
|
def fast_median(a):
"""Fast median operation for masked array using 50th-percentile
"""
a = checkma(a)
#return scoreatpercentile(a.compressed(), 50)
if a.count() > 0:
out = np.percentile(a.compressed(), 50)
else:
out = np.ma.masked
return out
|
def strings_to_integers ( strings : Iterable [ str ] ) -> Iterable [ int ] : return strings_to_ ( strings , lambda x : int ( float ( x ) ) )
| 0 |
how to turn list of strings into integers python
|
Convert a list of strings to a list of integers .
|
cosqa-train-17783
|
def strings_to_integers(strings: Iterable[str]) -> Iterable[int]:
"""
Convert a list of strings to a list of integers.
:param strings: a list of string
:return: a list of converted integers
.. doctest::
>>> strings_to_integers(['1', '1.0', '-0.2'])
[1, 1, 0]
"""
return strings_to_(strings, lambda x: int(float(x)))
|
def is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : # either 'http(s)://...' or '//cdn...' and therefore absolute return False return True
| 1 |
python judge relative url
|
simple method to determine if a url is relative or absolute
|
cosqa-train-17784
|
def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True
|
def remove_blank_lines ( string ) : return "\n" . join ( line for line in string . split ( "\n" ) if len ( line . strip ( ) ) )
| 1 |
remove the blank in python string
|
Removes all blank lines in @string
|
cosqa-train-17785
|
def remove_blank_lines(string):
""" Removes all blank lines in @string
-> #str without blank lines
"""
return "\n".join(line
for line in string.split("\n")
if len(line.strip()))
|
def _request ( self , method : str , endpoint : str , params : dict = None , data : dict = None , headers : dict = None ) -> dict :
| 0 |
python rest call header
|
HTTP request method of interface implementation .
|
cosqa-train-17786
|
def _request(self, method: str, endpoint: str, params: dict = None, data: dict = None, headers: dict = None) -> dict:
"""HTTP request method of interface implementation."""
|
def after_epoch ( self , * * _ ) -> None : SaveEvery . save_model ( model = self . _model , name_suffix = self . _OUTPUT_NAME , on_failure = self . _on_save_failure )
| 1 |
how to sav model after epoch python
|
Save / override the latest model after every epoch .
|
cosqa-train-17787
|
def after_epoch(self, **_) -> None:
"""Save/override the latest model after every epoch."""
SaveEvery.save_model(model=self._model, name_suffix=self._OUTPUT_NAME, on_failure=self._on_save_failure)
|
def last ( self ) : if self . _last is UNDETERMINED : # not necessarily the last one... self . _last = self . sdat . tseries . index [ - 1 ] return self [ self . _last ]
| 0 |
how to get the last item in a series python
|
Last time step available .
|
cosqa-train-17788
|
def last(self):
"""Last time step available.
Example:
>>> sdat = StagyyData('path/to/run')
>>> assert(sdat.steps.last is sdat.steps[-1])
"""
if self._last is UNDETERMINED:
# not necessarily the last one...
self._last = self.sdat.tseries.index[-1]
return self[self._last]
|
def prevPlot ( self ) : if self . stacker . currentIndex ( ) > 0 : self . stacker . setCurrentIndex ( self . stacker . currentIndex ( ) - 1 )
| 0 |
python last poststep not showing on plot
|
Moves the displayed plot to the previous one
|
cosqa-train-17789
|
def prevPlot(self):
"""Moves the displayed plot to the previous one"""
if self.stacker.currentIndex() > 0:
self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)
|
def decodebytes ( input ) : py_version = sys . version_info [ 0 ] if py_version >= 3 : return _decodebytes_py3 ( input ) return _decodebytes_py2 ( input )
| 0 |
python3 decode not defined
|
Decode base64 string to byte array .
|
cosqa-train-17790
|
def decodebytes(input):
"""Decode base64 string to byte array."""
py_version = sys.version_info[0]
if py_version >= 3:
return _decodebytes_py3(input)
return _decodebytes_py2(input)
|
def check64bit ( current_system = "python" ) : if current_system == "python" : return sys . maxsize > 2147483647 elif current_system == "os" : import platform pm = platform . machine ( ) if pm != ".." and pm . endswith ( '64' ) : # recent Python (not Iron) return True else : if 'PROCESSOR_ARCHITEW6432' in os . environ : return True # 32 bit program running on 64 bit Windows try : # 64 bit Windows 64 bit program return os . environ [ 'PROCESSOR_ARCHITECTURE' ] . endswith ( '64' ) except IndexError : pass # not Windows try : # this often works in Linux return '64' in platform . architecture ( ) [ 0 ] except Exception : # is an older version of Python, assume also an older os@ # (best we can guess) return False
| 1 |
how to check if you have 64bit python
|
checks if you are on a 64 bit platform
|
cosqa-train-17791
|
def check64bit(current_system="python"):
"""checks if you are on a 64 bit platform"""
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'): # recent Python (not Iron)
return True
else:
if 'PROCESSOR_ARCHITEW6432' in os.environ:
return True # 32 bit program running on 64 bit Windows
try:
# 64 bit Windows 64 bit program
return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')
except IndexError:
pass # not Windows
try:
# this often works in Linux
return '64' in platform.architecture()[0]
except Exception:
# is an older version of Python, assume also an older os@
# (best we can guess)
return False
|
def is_prime ( n ) : if n % 2 == 0 and n > 2 : return False return all ( n % i for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) )
| 1 |
python function to determine if boolean is prime
|
Check if n is a prime number
|
cosqa-train-17792
|
def is_prime(n):
"""
Check if n is a prime number
"""
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
|
def recClearTag ( element ) : children = element . getchildren ( ) if len ( children ) > 0 : for child in children : recClearTag ( child ) element . tag = clearTag ( element . tag )
| 1 |
deleting xml elements with python element tree
|
Applies maspy . xml . clearTag () to the tag attribute of the element and recursively to all child elements .
|
cosqa-train-17793
|
def recClearTag(element):
"""Applies maspy.xml.clearTag() to the tag attribute of the "element" and
recursively to all child elements.
:param element: an :instance:`xml.etree.Element`
"""
children = element.getchildren()
if len(children) > 0:
for child in children:
recClearTag(child)
element.tag = clearTag(element.tag)
|
def array2string ( arr : numpy . ndarray ) -> str : shape = str ( arr . shape ) [ 1 : - 1 ] if shape . endswith ( "," ) : shape = shape [ : - 1 ] return numpy . array2string ( arr , threshold = 11 ) + "%s[%s]" % ( arr . dtype , shape )
| 1 |
python print string formate numpy array
|
Format numpy array as a string .
|
cosqa-train-17794
|
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
|
def sortBy ( self , keyfunc , ascending = True , numPartitions = None ) : return self . keyBy ( keyfunc ) . sortByKey ( ascending , numPartitions ) . values ( )
| 1 |
python dynamo query partition key and sort key
|
Sorts this RDD by the given keyfunc
|
cosqa-train-17795
|
def sortBy(self, keyfunc, ascending=True, numPartitions=None):
"""
Sorts this RDD by the given keyfunc
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[0]).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d', 4)]
>>> sc.parallelize(tmp).sortBy(lambda x: x[1]).collect()
[('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
"""
return self.keyBy(keyfunc).sortByKey(ascending, numPartitions).values()
|
def top ( self , topn = 10 ) : return [ self [ i ] for i in argsort ( list ( zip ( * self ) ) [ 1 ] ) [ : : - 1 ] [ : topn ] ]
| 0 |
return top ten in python
|
Get a list of the top topn features in this : class : . Feature \ .
|
cosqa-train-17796
|
def top(self, topn=10):
"""
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
Parameters
----------
topn : int
Returns
-------
list
"""
return [self[i] for i in argsort(list(zip(*self))[1])[::-1][:topn]]
|
def multiple_replace ( string , replacements ) : # type: (str, Dict[str,str]) -> str pattern = re . compile ( "|" . join ( [ re . escape ( k ) for k in sorted ( replacements , key = len , reverse = True ) ] ) , flags = re . DOTALL ) return pattern . sub ( lambda x : replacements [ x . group ( 0 ) ] , string )
| 1 |
python replace multiple strings with same string
|
Simultaneously replace multiple strigns in a string
|
cosqa-train-17797
|
def multiple_replace(string, replacements):
# type: (str, Dict[str,str]) -> str
"""Simultaneously replace multiple strigns in a string
Args:
string (str): Input string
replacements (Dict[str,str]): Replacements dictionary
Returns:
str: String with replacements
"""
pattern = re.compile("|".join([re.escape(k) for k in sorted(replacements, key=len, reverse=True)]), flags=re.DOTALL)
return pattern.sub(lambda x: replacements[x.group(0)], string)
|
def fast_median ( a ) : a = checkma ( a ) #return scoreatpercentile(a.compressed(), 50) if a . count ( ) > 0 : out = np . percentile ( a . compressed ( ) , 50 ) else : out = np . ma . masked return out
| 1 |
median of an array of arrays, python
|
Fast median operation for masked array using 50th - percentile
|
cosqa-train-17798
|
def fast_median(a):
"""Fast median operation for masked array using 50th-percentile
"""
a = checkma(a)
#return scoreatpercentile(a.compressed(), 50)
if a.count() > 0:
out = np.percentile(a.compressed(), 50)
else:
out = np.ma.masked
return out
|
def uniqued ( iterable ) : seen = set ( ) return [ item for item in iterable if item not in seen and not seen . add ( item ) ]
| 0 |
how to keep unqiue value in a list python
|
Return unique list of iterable items preserving order .
|
cosqa-train-17799
|
def uniqued(iterable):
"""Return unique list of ``iterable`` items preserving order.
>>> uniqued('spameggs')
['s', 'p', 'a', 'm', 'e', 'g']
"""
seen = set()
return [item for item in iterable if item not in seen and not seen.add(item)]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.