anchor
stringlengths
16
95
positive
stringlengths
87
6.25k
negative
stringlengths
87
6.4k
generate maps between entities in python
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns...
def _merge_maps(m1, m2): """merge two Mapping objects, keeping the type of the first mapping""" return type(m1)(chain(m1.items(), m2.items()))
generate maps between entities in python
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns...
def get_edge_relations(graph: BELGraph) -> Mapping[Tuple[BaseEntity, BaseEntity], Set[str]]: """Build a dictionary of {node pair: set of edge types}.""" return group_dict_set( ((u, v), d[RELATION]) for u, v, d in graph.edges(data=True) )
generate maps between entities in python
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns...
def map_with_obj(f, dct): """ Implementation of Ramda's mapObjIndexed without the final argument. This returns the original key with the mapped value. Use map_key_values to modify the keys too :param f: Called with a key and value :param dct: :return {dict}: Keyed by the original key, va...
generate maps between entities in python
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns...
def __add_method(m: lmap.Map, key: T, method: Method) -> lmap.Map: """Swap the methods atom to include method with key.""" return m.assoc(key, method)
generate maps between entities in python
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns...
def map_parameters(cls, params): """Maps parameters to form field names""" d = {} for k, v in six.iteritems(params): d[cls.FIELD_MAP.get(k.lower(), k)] = v return d
python how to get dict intersection
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
def compare_dict(da, db): """ Compare differencs from two dicts """ sa = set(da.items()) sb = set(db.items()) diff = sa & sb return dict(sa - diff), dict(sb - diff)
python how to get dict intersection
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
def compare(dicts): """Compare by iteration""" common_members = {} common_keys = reduce(lambda x, y: x & y, map(dict.keys, dicts)) for k in common_keys: common_members[k] = list( reduce(lambda x, y: x & y, [set(d[k]) for d in dicts])) return common_members
python how to get dict intersection
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
def _calc_overlap_count( markers1: dict, markers2: dict, ): """Calculate overlap count between the values of two dictionaries Note: dict values must be sets """ overlaps=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].intersecti...
python how to get dict intersection
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
def is_same_dict(d1, d2): """Test two dictionary is equal on values. (ignore order) """ for k, v in d1.items(): if isinstance(v, dict): is_same_dict(v, d2[k]) else: assert d1[k] == d2[k] for k, v in d2.items(): if isinstance(v, dict): is_same_...
python how to get dict intersection
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
def flattened_nested_key_indices(nested_dict): """ Combine the outer and inner keys of nested dictionaries into a single ordering. """ outer_keys, inner_keys = collect_nested_keys(nested_dict) combined_keys = list(sorted(set(outer_keys + inner_keys))) return {k: i for (i, k) in enumerate(com...
python how to get the index of a rank
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def zrank(self, name, value): """ Returns the rank of the element. :param name: str the name of the redis key :param value: the element in the sorted set """ with self.pipe as pipe: value = self.valueparse.encode(value) return pipe.zrank(self....
python how to get the index of a rank
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def get_index_nested(x, i): """ Description: Returns the first index of the array (vector) x containing the value i. Parameters: x: one-dimensional array i: search value """ for ind in range(len(x)): if i == x[ind]: return ind return -1
python how to get the index of a rank
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def sorted_index(values, x): """ For list, values, returns the index location of element x. If x does not exist will raise an error. :param values: list :param x: item :return: integer index """ i = bisect_left(values, x) j = bisect_right(values, x) return values[i:j].index(x) + i
python how to get the index of a rank
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def kindex(matrix, k): """ Returns indices to select the kth nearest neighbour""" ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k]) return ix
python how to get the index of a rank
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
generate string from array python
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def toStringArray(name, a, width = 0): """ Returns an array (any sequence of floats, really) as a string. """ string = name + ": " cnt = 0 for i in a: string += "%4.2f " % i if width > 0 and (cnt + 1) % width == 0: string += '\n' cnt += 1 return string
generate string from array python
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def string_list_to_array(l): """ Turns a Python unicode string list into a Java String array. :param l: the string list :type: list :rtype: java string array :return: JB_Object """ result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class("java/lang/String"...
generate string from array python
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def generate_random_string(chars=7): """ :param chars: :return: """ return u"".join(random.sample(string.ascii_letters * 2 + string.digits, chars))
generate string from array python
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def bytes_to_c_array(data): """ Make a C array using the given string. """ chars = [ "'{}'".format(encode_escape(i)) for i in decode_escape(data) ] return ', '.join(chars) + ', 0'
generate string from array python
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
def gen_random_string(str_len): """ generate random string with specified length """ return ''.join( random.choice(string.ascii_letters + string.digits) for _ in range(str_len))
python how to get the index of minimum value in an array
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
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 """ ...
python how to get the index of minimum value in an array
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
def fn_min(self, a, axis=None): """ Return the minimum of an array, ignoring any NaNs. :param a: The array. :return: The minimum value of the array. """ return numpy.nanmin(self._to_ndarray(a), axis=axis)
python how to get the index of minimum value in an array
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
def index_nearest(value, array): """ expects a _n.array returns the global minimum of (value-array)^2 """ a = (array-value)**2 return index(a.min(), a)
python how to get the index of minimum value in an array
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
def min_values(args): """ Return possible range for min function. """ return Interval(min(x.low for x in args), min(x.high for x in args))
python how to get the index of minimum value in an array
def find_nearest_index(arr, value): """For a given value, the function finds the nearest value in the array and returns its index.""" arr = np.array(arr) index = (abs(arr-value)).argmin() return index
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
get array with longest length python
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run...
def longest_run_1d(arr): """Return the length of the longest consecutive run of identical values. Parameters ---------- arr : bool array Input array Returns ------- int Length of longest run. """ v, rl = rle_1d(arr)[:2] return np.where(v, rl, 0).max()
get array with longest length python
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run...
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel...
get array with longest length python
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run...
def find_largest_contig(contig_lengths_dict): """ Determine the largest contig for each strain :param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths :return: longest_contig_dict: dictionary of strain name: longest contig """ # Initialise the dictionary ...
get array with longest length python
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run...
def get_longest_orf(orfs): """Find longest ORF from the given list of ORFs.""" sorted_orf = sorted(orfs, key=lambda x: len(x['sequence']), reverse=True)[0] return sorted_orf
get array with longest length python
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run...
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: ...
python how to make an iterable variable
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def __init__(self, iterable): """Initialize the cycle with some iterable.""" self._values = [] self._iterable = iterable self._initialized = False self._depleted = False self._offset = 0
python how to make an iterable variable
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def fromiterable(cls, itr): """Initialize from iterable""" x, y, z = itr return cls(x, y, z)
python how to make an iterable variable
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def ensure_iterable(inst): """ Wraps scalars or string types as a list, or returns the iterable instance. """ if isinstance(inst, string_types): return [inst] elif not isinstance(inst, collections.Iterable): return [inst] else: return inst
python how to make an iterable variable
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def concat(cls, iterables): """ Similar to #itertools.chain.from_iterable(). """ def generator(): for it in iterables: for element in it: yield element return cls(generator())
python how to make an iterable variable
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
def _varargs_to_iterable_method(func): """decorator to convert a *args method to one taking a iterable""" def wrapped(self, iterable, **kwargs): return func(self, *iterable, **kwargs) return wrapped
get distinct items in list python
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ o...
def distinct(xs): """Get the list of distinct values with preserving order.""" # don't use collections.OrderedDict because we do support Python 2.6 seen = set() return [x for x in xs if x not in seen and not seen.add(x)]
get distinct items in list python
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ o...
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)]
get distinct items in list python
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ o...
def uniqued(iterable): """Return unique list of items preserving order. >>> uniqued([3, 2, 1, 3, 2, 1, 0]) [3, 2, 1, 0] """ seen = set() add = seen.add return [i for i in iterable if i not in seen and not add(i)]
get distinct items in list python
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ o...
def unique_items(seq): """Return the unique items from iterable *seq* (in order).""" seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
get distinct items in list python
def unique(input_list): """ Return a list of unique items (similar to set functionality). Parameters ---------- input_list : list A list containg some items that can occur more than once. Returns ------- list A list with only unique occurances of an item. """ o...
def unique_element(ll): """ returns unique elements from a list preserving the original order """ seen = {} result = [] for item in ll: if item in seen: continue seen[item] = 1 result.append(item) return result
get factors of a number python
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
def computeFactorial(n): """ computes factorial of n """ sleep_walk(10) ret = 1 for i in range(n): ret = ret * (i + 1) return ret
get factors of a number python
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
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):...
get factors of a number python
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
def factors(n): """ Computes all the integer factors of the number `n` Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> import utool as ut >>> result = sorted(ut.factors(10)) >>> print(result) [1, 2, 5, 10] References: h...
get factors of a number python
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
get factors of a number python
def _factor_generator(n): """ From a given natural integer, returns the prime factors and their multiplicity :param n: Natural integer :return: """ p = prime_factors(n) factors = {} for p1 in p: try: factors[p1] += 1 except KeyError: factors[p1] = ...
def is_power_of_2(num): """Return whether `num` is a power of two""" log = math.log2(num) return int(log) == float(log)
python how to remove elements from an iterated list
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the f...
python how to remove elements from an iterated list
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def without(seq1, seq2): r"""Return a list with all elements in `seq2` removed from `seq1`, order preserved. Examples: >>> without([1,2,3,1,2], [1]) [2, 3, 2] """ if isSet(seq2): d2 = seq2 else: d2 = set(seq2) return [elt for elt in seq1 if elt not in d2]
python how to remove elements from an iterated list
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def dedup(seq): """Remove duplicates from a list while keeping order.""" seen = set() for item in seq: if item not in seen: seen.add(item) yield item
python how to remove elements from an iterated list
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
python how to remove elements from an iterated list
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
def rm_empty_indices(*args): """ Remove unwanted list indices. First argument is the list of indices to remove. Other elements are the lists to trim. """ rm_inds = args[0] if not rm_inds: return args[1:] keep_inds = [i for i in range(len(args[1])) if i not in rm_inds] retu...
python how to remove spaces and add hashtag
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(unicode(value)).striptags()
python how to remove spaces and add hashtag
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def slugify(string): """ Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names. Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python """ string = re.sub('[^\w .-]', '', string) string = string.replace(" ", "-") return string
python how to remove spaces and add hashtag
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet m...
python how to remove spaces and add hashtag
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def sanitize_word(s): """Remove non-alphanumerical characters from metric word. And trim excessive underscores. """ s = re.sub('[^\w-]+', '_', s) s = re.sub('__+', '_', s) return s.strip('_')
python how to remove spaces and add hashtag
def _add_hash(source): """Add a leading hash '#' at the beginning of every line in the source.""" source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
def urlize_twitter(text): """ Replace #hashtag and @username references in a tweet with HTML text. """ html = TwitterText(text).autolink.auto_link() return mark_safe(html.replace( 'twitter.com/search?q=', 'twitter.com/search/realtime/'))
python how to start a thread in bottle
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def start(self): """Create a background thread for httpd and serve 'forever'""" self._process = threading.Thread(target=self._background_runner) self._process.start()
python how to start a thread in bottle
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def run(self, forever=True): """start the bot""" loop = self.create_connection() self.add_signal_handlers() if forever: loop.run_forever()
python how to start a thread in bottle
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def start(self): """Start the receiver. """ if not self._is_running: self._do_run = True self._thread.start() return self
python how to start a thread in bottle
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def create_task(coro, loop): # pragma: no cover """Compatibility wrapper for the loop.create_task() call introduced in 3.4.2.""" if hasattr(loop, 'create_task'): return loop.create_task(coro) return asyncio.Task(coro, loop=loop)
python how to start a thread in bottle
def start(): """Starts the web server.""" global app bottle.run(app, host=conf.WebHost, port=conf.WebPort, debug=conf.WebAutoReload, reloader=conf.WebAutoReload, quiet=conf.WebQuiet)
def start(args): """Run server with provided command line arguments. """ application = tornado.web.Application([(r"/run", run.get_handler(args)), (r"/status", run.StatusHandler)]) application.runmonitor = RunMonitor() application.listen(args.port) torna...
get network details from device logs appium python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
def _get_device_id(self, bus): """ Find the device id """ _dbus = bus.get(SERVICE_BUS, PATH) devices = _dbus.devices() if self.device is None and self.device_id is None and len(devices) == 1: return devices[0] for id in devices: self._dev...
get network details from device logs appium python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
def autoscan(): """autoscan will check all of the serial ports to see if they have a matching VID:PID for a MicroPython board. """ for port in serial.tools.list_ports.comports(): if is_micropython_usb_device(port): connect_serial(port[0])
get network details from device logs appium python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
def device_state(device_id): """ Get device state via HTTP GET. """ if device_id not in devices: return jsonify(success=False) return jsonify(state=devices[device_id].state)
get network details from device logs appium python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
def get_services(): """ Retrieve a list of all system services. @see: L{get_active_services}, L{start_service}, L{stop_service}, L{pause_service}, L{resume_service} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descr...
get network details from device logs appium python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
def desc(self): """Get a short description of the device.""" return '{0} (ID: {1}) - {2} - {3}'.format( self.name, self.device_id, self.type, self.status)
python how to use a string to access list index
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
def _read_indexlist(self, name): """Read a list of indexes.""" setattr(self, '_' + name, [self._timeline[int(i)] for i in self.db.lrange('site:{0}'.format(name), 0, -1)])
python how to use a string to access list index
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
def index(self, item): """ Not recommended for use on large lists due to time complexity, but it works -> #int list index of @item """ for i, x in enumerate(self.iter()): if x == item: return i return None
python how to use a string to access list index
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
def get_model_index_properties(instance, index): """Return the list of properties specified for a model in an index.""" mapping = get_index_mapping(index) doc_type = instance._meta.model_name.lower() return list(mapping["mappings"][doc_type]["properties"].keys())
python how to use a string to access list index
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
def sorted_index(values, x): """ For list, values, returns the index location of element x. If x does not exist will raise an error. :param values: list :param x: item :return: integer index """ i = bisect_left(values, x) j = bisect_right(values, x) return values[i:j].index(x) + i
python how to use a string to access list index
def get_list_index(lst, index_or_name): """ Return the index of an element in the list. Args: lst (list): The list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the element in the list. """ if...
def get_index_nested(x, i): """ Description: Returns the first index of the array (vector) x containing the value i. Parameters: x: one-dimensional array i: search value """ for ind in range(len(x)): if i == x[ind]: return ind return -1
get only letters from string python
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def chars(string: any) -> str: """Return all (and only) the chars in the given string.""" return ''.join([c if c.isalpha() else '' for c in str(string)])
get only letters from string python
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def strip_accents(string): """ Strip all the accents from the string """ return u''.join( (character for character in unicodedata.normalize('NFD', string) if unicodedata.category(character) != 'Mn'))
get only letters from string python
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def lowercase_chars(string: any) -> str: """Return all (and only) the lowercase chars in the given string.""" return ''.join([c if c.islower() else '' for c in str(string)])
get only letters from string python
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def uppercase_chars(string: any) -> str: """Return all (and only) the uppercase chars in the given string.""" return ''.join([c if c.isupper() else '' for c in str(string)])
get only letters from string python
def return_letters_from_string(text): """Get letters from string only.""" out = "" for letter in text: if letter.isalpha(): out += letter return out
def _to_lower_alpha_only(s): """Return a lowercased string with non alphabetic chars removed. White spaces are not to be removed.""" s = re.sub(r'\n', ' ', s.lower()) return re.sub(r'[^a-z\s]', '', s)
get rid of spaces in str python
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def strip_spaces(s): """ Strip excess spaces from a string """ return u" ".join([c for c in s.split(u' ') if c])
get rid of spaces in str python
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def detokenize(s): """ Detokenize a string by removing spaces before punctuation.""" print(s) s = re.sub("\s+([;:,\.\?!])", "\\1", s) s = re.sub("\s+(n't)", "\\1", s) return s
get rid of spaces in str python
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def strip_accents(text): """ Strip agents from a string. """ normalized_str = unicodedata.normalize('NFD', text) return ''.join([ c for c in normalized_str if unicodedata.category(c) != 'Mn'])
get rid of spaces in str python
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def _repr_strip(mystring): """ Returns the string without any initial or final quotes. """ r = repr(mystring) if r.startswith("'") and r.endswith("'"): return r[1:-1] else: return r
get rid of spaces in str python
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def lowstrip(term): """Convert to lowercase and strip spaces""" term = re.sub('\s+', ' ', term) term = term.lower() return term
get sort index python numpy
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def sortlevel(self, level=None, ascending=True, sort_remaining=None): """ For internal compatibility with with the Index API. Sort the Index. This is for compat with MultiIndex Parameters ---------- ascending : boolean, default True False to sort in descendi...
get sort index python numpy
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def arglexsort(arrays): """ Returns the indices of the lexicographical sorting order of the supplied arrays. """ dtypes = ','.join(array.dtype.str for array in arrays) recarray = np.empty(len(arrays[0]), dtype=dtypes) for i, array in enumerate(arrays): recarray['f%s' % i] = array ...
get sort index python numpy
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def sort_key(val): """Sort key for sorting keys in grevlex order.""" return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val)
get sort index python numpy
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
get sort index python numpy
def argsort_indices(a, axis=-1): """Like argsort, but returns an index suitable for sorting the the original array even if that array is multidimensional """ a = np.asarray(a) ind = list(np.ix_(*[np.arange(d) for d in a.shape])) ind[axis] = a.argsort(axis) return tuple(ind)
def rank(self): """how high in sorted list each key is. inverse permutation of sorter, such that sorted[rank]==keys""" r = np.empty(self.size, np.int) r[self.sorter] = np.arange(self.size) return r
get te left most value of a column in python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
def _longest_val_in_column(self, col): """ get size of longest value in specific column :param col: str, column name :return int """ try: # +2 is for implicit separator return max([len(x[col]) for x in self.table if x[col]]) + 2 except Key...
get te left most value of a column in python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
def get_last_filled_cell(self, table=None): """Returns key for the bottommost rightmost cell with content Parameters ---------- table: Integer, defaults to None \tLimit search to this table """ maxrow = 0 maxcol = 0 for row, col, tab in self.di...
get te left most value of a column in python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
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
get te left most value of a column in python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
def index(self, value): """ Return the smallest index of the row(s) with this column equal to value. """ for i in xrange(len(self.parentNode)): if getattr(self.parentNode[i], self.Name) == value: return i raise ValueError(value)
get te left most value of a column in python
def find_le(a, x): """Find rightmost value less than or equal to x.""" i = bs.bisect_right(a, x) if i: return i - 1 raise ValueError
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...
get the data type in python code
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def _get_type(self, value): """Get the data type for *value*.""" if value is None: return type(None) elif type(value) in int_types: return int elif type(value) in float_types: return float elif isinstance(value, binary_type): return...
get the data type in python code
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types): return 'integer' elif type(value) is datetime....
get the data type in python code
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def gtype(n): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
get the data type in python code
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object ...
get the data type in python code
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
def validate_type(self, type_): """Take an str/unicode `type_` and raise a ValueError if it's not a valid type for the object. A valid type for a field is a value from the types_set attribute of that field's class. """ if type_ is not None and type_ n...
python image to buffer
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output ...
def url_to_image(url, flag=cv2.IMREAD_COLOR): """ download the image, convert it to a NumPy array, and then read it into OpenCV format """ resp = urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, flag) return image
python image to buffer
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output ...
def read_img(path): """ Reads image specified by path into numpy.ndarray""" img = cv2.resize(cv2.imread(path, 0), (80, 30)).astype(np.float32) / 255 img = np.expand_dims(img.transpose(1, 0), 0) return img
python image to buffer
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output ...
def uint32_to_uint8(cls, img): """ Cast uint32 RGB image to 4 uint8 channels. """ return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))
python image to buffer
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output ...
def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]: """ Load and pre-process the images specified with absolute paths. :param image_paths: List of images specified with paths. :param image_size: Tuple to resize the image to (Channels, Height, Width) :return: A...
python image to buffer
def get_buffer(self, data_np, header, format, output=None): """Get image as a buffer in (format). Format should be 'jpeg', 'png', etc. """ if not have_pil: raise Exception("Install PIL to use this method") image = PILimage.fromarray(data_np) buf = output ...
def read_image(filepath): """Returns an image tensor.""" im_bytes = tf.io.read_file(filepath) im = tf.image.decode_image(im_bytes, channels=CHANNELS) im = tf.image.convert_image_dtype(im, tf.float32) return im