anchor
stringlengths
16
95
positive
stringlengths
87
6.25k
negative
stringlengths
87
6.4k
getattr return property object python
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
def get_attr(self, method_name): """Get attribute from the target object""" return self.attrs.get(method_name) or self.get_callable_attr(method_name)
getattr return property object python
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
def __getattr__(self, name): """ For attributes not found in self, redirect to the properties dictionary """ try: return self.__dict__[name] except KeyError: if hasattr(self._properties,name): return getattr(self._properties, name)
getattr return property object python
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
def _make_proxy_property(bind_attr, attr_name): def proxy_property(self): """ proxy """ bind = getattr(self, bind_attr) return getattr(bind, attr_name) return property(proxy_property)
getattr return property object python
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
def get_all_attributes(klass_or_instance): """Get all attribute members (attribute, property style method). """ pairs = list() for attr, value in inspect.getmembers( klass_or_instance, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") or attr.endswith("__")): ...
getattr return property object python
def value(self): """Value of property.""" if self._prop.fget is None: raise AttributeError('Unable to read attribute') return self._prop.fget(self._obj)
def get_methods(*objs): """ Return the names of all callable attributes of an object""" return set( attr for obj in objs for attr in dir(obj) if not attr.startswith('_') and callable(getattr(obj, attr)) )
python insert a line to the front of the file
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def step_next_line(self): """Sets cursor as beginning of next line.""" self._eol.append(self.position) self._lineno += 1 self._col_offset = 0
python insert a line to the front of the file
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
python insert a line to the front of the file
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def write_line(self, line, count=1): """writes the line and count newlines after the line""" self.write(line) self.write_newlines(count)
python insert a line to the front of the file
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def append_text(self, txt): """ adds a line of text to a file """ with open(self.fullname, "a") as myfile: myfile.write(txt)
python insert a line to the front of the file
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
def move_to_start(self, column_label): """Move a column to the first in order.""" self._columns.move_to_end(column_label, last=False) return self
python instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
def ensure_list(iterable: Iterable[A]) -> List[A]: """ An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy. """ if isinstance(iterable, list): return iterable else: return list(iterable)
python instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
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 instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
def _listify(collection): """This is a workaround where Collections are no longer iterable when using JPype.""" new_list = [] for index in range(len(collection)): new_list.append(collection[index]) return new_list
python instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
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
python instance into list
def as_list(self): """Return all child objects in nested lists of strings.""" return [self.name, self.value, [x.as_list for x in self.children]]
def listify(a): """ Convert a scalar ``a`` to a list and all iterables to list as well. Examples -------- >>> listify(0) [0] >>> listify([1,2,3]) [1, 2, 3] >>> listify('a') ['a'] >>> listify(np.array([1,2,3])) [1, 2, 3] >>> listify('string') ['string'] ""...
how can i access dataimages from a dataset in hdf5 file in python
def _load_data(filepath): """Loads the images and latent values into Numpy arrays.""" with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array...
def save_hdf(self,filename,path=''): """Saves all relevant data to .h5 file; so state can be restored. """ self.dataframe.to_hdf(filename,'{}/df'.format(path))
how can i access dataimages from a dataset in hdf5 file in python
def _load_data(filepath): """Loads the images and latent values into Numpy arrays.""" with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array...
def _read_group_h5(filename, groupname): """Return group content. Args: filename (:class:`pathlib.Path`): path of hdf5 file. groupname (str): name of group to read. Returns: :class:`numpy.array`: content of group. """ with h5py.File(filename, 'r') as h5f: data = h5f[...
how can i access dataimages from a dataset in hdf5 file in python
def _load_data(filepath): """Loads the images and latent values into Numpy arrays.""" with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array...
def save_hdf5(X, y, path): """Save data as a HDF5 file. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. path (str): Path to the HDF5 file to save data. """ with h5py.File(path, 'w') as f: is_sparse = 1 if sparse.issparse(X) else 0 ...
how can i access dataimages from a dataset in hdf5 file in python
def _load_data(filepath): """Loads the images and latent values into Numpy arrays.""" with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array...
def hdf5_to_dict(filepath, group='/'): """load the content of an hdf5 file to a dict. # TODO: how to split domain_type_dev : parameter : value ? """ if not h5py.is_hdf5(filepath): raise RuntimeError(filepath, 'is not a valid HDF5 file.') with h5py.File(filepath, 'r') as handler: di...
how can i access dataimages from a dataset in hdf5 file in python
def _load_data(filepath): """Loads the images and latent values into Numpy arrays.""" with h5py.File(filepath, "r") as h5dataset: image_array = np.array(h5dataset["images"]) # The 'label' data set in the hdf5 file actually contains the float values # and not the class labels. values_array = np.array...
def load_tiff(file): """ Load a geotiff raster keeping ndv values using a masked array Usage: data = load_tiff(file) """ ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file) data = gdalnumeric.LoadFile(file) data = np.ma.masked_array(data, mask=data == ndv, fill_va...
how do i check if a string is in a list in python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def all_strings(arr): """ Ensures that the argument is a list that either is empty or contains only strings :param arr: list :return: """ if not isinstance([], list): raise TypeError("non-list value found where list is expected") return all(isinstance(...
how do i check if a string is in a list in python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def list_of(cls): """ Returns a function that checks that each element in a list is of a specific type. """ return lambda l: isinstance(l, list) and all(isinstance(x, cls) for x in l)
how do i check if a string is in a list in python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def validate_string_list(lst): """Validate that the input is a list of strings. Raises ValueError if not.""" if not isinstance(lst, list): raise ValueError('input %r must be a list' % lst) for x in lst: if not isinstance(x, basestring): raise ValueError('element %r in list m...
how do i check if a string is in a list in python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def is_list_of_ipachars(obj): """ Return ``True`` if the given object is a list of IPAChar objects. :param object obj: the object to test :rtype: bool """ if isinstance(obj, list): for e in obj: if not isinstance(e, IPAChar): return False return True ...
how do i check if a string is in a list in python
def isin(elems, line): """Check if an element from a list is in a string. :type elems: list :type line: str """ found = False for e in elems: if e in line.lower(): found = True break return found
def isin_alone(elems, line): """Check if an element from a list is the only element of a string. :type elems: list :type line: str """ found = False for e in elems: if line.strip().lower() == e.lower(): found = True break return found
how do i get sympy into python
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
def symbol_pos_int(*args, **kwargs): """Create a sympy.Symbol with positive and integer assumptions.""" kwargs.update({'positive': True, 'integer': True}) return sympy.Symbol(*args, **kwargs)
how do i get sympy into python
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
def _latex_format(obj: Any) -> str: """Format an object as a latex string.""" if isinstance(obj, float): try: return sympy.latex(symbolize(obj)) except ValueError: return "{0:.4g}".format(obj) return str(obj)
how do i get sympy into python
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
def access_to_sympy(self, var_name, access): """ Transform a (multidimensional) variable access to a flattend sympy expression. Also works with flat array accesses. """ base_sizes = self.variables[var_name][1] expr = sympy.Number(0) for dimension, a in enumerat...
how do i get sympy into python
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
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 pri...
how do i get sympy into python
def make_qs(n, m=None): """Make sympy symbols q0, q1, ... Args: n(int), m(int, optional): If specified both n and m, returns [qn, q(n+1), ..., qm], Only n is specified, returns[q0, q1, ..., qn]. Return: tuple(Symbol): Tuple of sympy symbols. """ try: ...
def print_latex(o): """A function to generate the latex representation of sympy expressions.""" if can_print_latex(o): s = latex(o, mode='plain') s = s.replace('\\dag','\\dagger') s = s.strip('$') return '$$%s$$' % s # Fallback to the string printer return None
how do you code in lemmatizer python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
def lemmatize(self, text, best_guess=True, return_frequencies=False): """Lemmatize all tokens in a string or a list. A string is first tokenized using punkt. Throw a type error if the input is neither a string nor a list. """ if isinstance(text, str): tokens = wordpunct_tokenize(text) elif isinstance(text...
how do you code in lemmatizer python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
def matrix_at_check(self, original, loc, tokens): """Check for Python 3.5 matrix multiplication.""" return self.check_py("35", "matrix multiplication", original, loc, tokens)
how do you code in lemmatizer python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
def get_highlighted_code(name, code, type='terminal'): """ If pygments are available on the system then returned output is colored. Otherwise unchanged content is returned. """ import logging try: import pygments pygments except ImportError: return code from p...
how do you code in lemmatizer python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
def match_paren(self, tokens, item): """Matches a paren.""" match, = tokens return self.match(match, item)
how do you code in lemmatizer python
def register_modele(self, modele: Modele): """ Register a modele onto the lemmatizer :param modele: Modele to register """ self.lemmatiseur._modeles[modele.gr()] = modele
def has_synset(word: str) -> list: """" Returns a list of synsets of a word after lemmatization. """ return wn.synsets(lemmatize(word, neverstem=True))
how do you load python numpy
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
def _openResources(self): """ Uses numpy.load to open the underlying file """ arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
how do you load python numpy
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
def to_np(*args): """ convert GPU arras to numpy and return them""" if len(args) > 1: return (cp.asnumpy(x) for x in args) else: return cp.asnumpy(args[0])
how do you load python numpy
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
def load_data(filename): """ :rtype : numpy matrix """ data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9) return data.as_matrix()
how do you load python numpy
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
def read_numpy(fd, byte_order, dtype, count): """Read tag data from file and return as numpy array.""" return numpy.fromfile(fd, byte_order+dtype[-1], count)
how do you load python numpy
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
def dump_nparray(self, obj, class_name=numpy_ndarray_class_name): """ ``numpy.ndarray`` dumper. """ return {"$" + class_name: self._json_convert(obj.tolist())}
python join only part of a list
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right...
def _grammatical_join_filter(l, arg=None): """ :param l: List of strings to join :param arg: A pipe-separated list of final_join (" and ") and initial_join (", ") strings. For example :return: A string that grammatically concatenates the items in the list. """ if not arg: arg = " and...
python join only part of a list
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right...
def right_outer(self): """ Performs Right Outer Join :return right_outer: dict """ self.get_collections_data() right_outer_join = self.merge_join_docs( set(self.collections_data['right'].keys())) return right_outer_join
python join only part of a list
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right...
def merge(left, right, how='inner', key=None, left_key=None, right_key=None, left_as='left', right_as='right'): """ Performs a join using the union join function. """ return join(left, right, how, key, left_key, right_key, join_fn=make_union_join(left_as, right_as))
python join only part of a list
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right...
def split_strings_in_list_retain_spaces(orig_list): """ Function to split every line in a list, and retain spaces for a rejoin :param orig_list: Original list :return: A List with split lines """ temp_list = list() for line in orig_list: line_split = __re.split(r'(\s+)', lin...
python join only part of a list
def get_join_cols(by_entry): """ helper function used for joins builds left and right join list for join function """ left_cols = [] right_cols = [] for col in by_entry: if isinstance(col, str): left_cols.append(col) right_cols.append(col) else: left_cols.append(col[0]) right...
def listunion(ListOfLists): """ Take the union of a list of lists. Take a Python list of Python lists:: [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]] and return the aggregated list:: [l11,l12, ..., l21, l22 , ...] For a list of two lists, e.g. `[a, b]`, this is...
how is a python script compiled
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
def generate(env): """Add Builders and construction variables for SGI MIPS C++ to an Environment.""" cplusplus.generate(env) env['CXX'] = 'CC' env['CXXFLAGS'] = SCons.Util.CLVar('-LANG:std') env['SHCXX'] = '$CXX' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE...
how is a python script compiled
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
def venv(): """Install venv + deps.""" try: import virtualenv # NOQA except ImportError: sh("%s -m pip install virtualenv" % PYTHON) if not os.path.isdir("venv"): sh("%s -m virtualenv venv" % PYTHON) sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT))
how is a python script compiled
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
def code(self): """Returns the code object for this BUILD file.""" return compile(self.source(), self.full_path, 'exec', flags=0, dont_inherit=True)
how is a python script compiled
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
def install_rpm_py(): """Install RPM Python binding.""" python_path = sys.executable cmd = '{0} install.py'.format(python_path) exit_status = os.system(cmd) if exit_status != 0: raise Exception('Command failed: {0}'.format(cmd))
how is a python script compiled
def IPYTHON_MAIN(): """Decide if the Ipython command line is running code.""" import pkg_resources runner_frame = inspect.getouterframes(inspect.currentframe())[-2] return ( getattr(runner_frame, "function", None) == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"...
def check_dependencies_remote(args): """ Invoke this command on a remote Python. """ cmd = [args.python, '-m', 'depends', args.requirement] env = dict(PYTHONPATH=os.path.dirname(__file__)) return subprocess.check_call(cmd, env=env)
python join to dict
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def update(dct, dct_merge): """Recursively merge dicts.""" for key, value in dct_merge.items(): if key in dct and isinstance(dct[key], dict): dct[key] = update(dct[key], value) else: dct[key] = value return dct
python join to dict
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def merge_dict(data, *args): """Merge any number of dictionaries """ results = {} for current in (data,) + args: results.update(current) return results
python join to dict
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def extend(a: dict, b: dict) -> dict: """Merge two dicts and return a new dict. Much like subclassing works.""" res = a.copy() res.update(b) return res
python join to dict
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def dictify(a_named_tuple): """Transform a named tuple into a dictionary""" return dict((s, getattr(a_named_tuple, s)) for s in a_named_tuple._fields)
python join to dict
def flatten_dict_join_keys(dct, join_symbol=" "): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :return: """ return dict( flatten_dict(dct, join=lambda a,b:a+join_symbol+b) )
def dictapply(d, fn): """ apply a function to all non-dict values in a dictionary """ for k, v in d.items(): if isinstance(v, dict): v = dictapply(v, fn) else: d[k] = fn(v) return d
how python hash a tuple
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value...
def __hash__(self): """Return ``hash(self)``.""" return hash((type(self), self.domain, self.range, self.partition))
how python hash a tuple
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value...
def omnihash(obj): """ recursively hash unhashable objects """ if isinstance(obj, set): return hash(frozenset(omnihash(e) for e in obj)) elif isinstance(obj, (tuple, list)): return hash(tuple(omnihash(e) for e in obj)) elif isinstance(obj, dict): return hash(frozenset((k, omnihas...
how python hash a tuple
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value...
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
how python hash a tuple
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value...
def _string_hash(s): """String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`).""" h = 5381 for c in s: h = h * 33 + ord(c) return h
how python hash a tuple
def hash_iterable(it): """Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ """ hash_value...
def np_hash(a): """Return a hash of a NumPy array.""" if a is None: return hash(None) # Ensure that hashes are equal whatever the ordering in memory (C or # Fortran) a = np.ascontiguousarray(a) # Compute the digest and return a decimal int return int(hashlib.sha1(a.view(a.dtype)).hex...
python json schema validation
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
def _validate(data, schema, ac_schema_safe=True, **options): """ See the descritpion of :func:`validate` for more details of parameters and return value. Validate target object 'data' with given schema object. """ try: jsonschema.validate(data, schema, **options) except (jsonschema...
python json schema validation
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
def validate(payload, schema): """Validate `payload` against `schema`, returning an error list. jsonschema provides lots of information in it's errors, but it can be a bit of work to extract all the information. """ v = jsonschema.Draft4Validator( schema, format_checker=jsonschema.FormatChe...
python json schema validation
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
def validate(datum, schema, field=None, raise_errors=True): """ Determine if a python datum is an instance of a schema. Parameters ---------- datum: Any Data being validated schema: dict Schema field: str, optional Record field being validated raise_errors: bool,...
python json schema validation
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
def schemaValidateFile(self, filename, options): """Do a schemas validation of the given resource, it will use the SAX streamable validation internally. """ ret = libxml2mod.xmlSchemaValidateFile(self._o, filename, options) return ret
python json schema validation
def validate(raw_schema, target=None, **kwargs): """ Given the python representation of a JSONschema as defined in the swagger spec, validate that the schema complies to spec. If `target` is provided, that target will be validated against the provided schema. """ schema = schema_validator(raw_s...
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]: """ Wraps jsonschema.validate, returning the same object passed in. Args: request: The deserialized-from-json request. schema: The jsonschema schema to validate against. Raises: jsonschema.ValidationEr...
how to add noise to sound in python
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
def add_noise(Y, sigma): """Adds noise to Y""" return Y + np.random.normal(0, sigma, Y.shape)
how to add noise to sound in python
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
def shot_noise(x, severity=1): """Shot noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added shot noise. """ c = [60, 25, 12, 5, 3][se...
how to add noise to sound in python
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
def get_data(): """ Currently pretends to talk to an instrument and get back the magnitud and phase of the measurement. """ # pretend we're measuring a noisy resonance at zero y = 1.0 / (1.0 + 1j*(n_x.get_value()-0.002)*1000) + _n.random.rand()*0.1 # and that it takes time to do so _t....
how to add noise to sound in python
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
def normal_noise(points): """Init a noise variable.""" return np.random.rand(1) * np.random.randn(points, 1) \ + random.sample([2, -2], 1)
how to add noise to sound in python
def synthesize(self, duration): """ Synthesize white noise Args: duration (numpy.timedelta64): The duration of the synthesized sound """ sr = self.samplerate.samples_per_second seconds = duration / Seconds(1) samples = np.random.uniform(low=-1., high=...
def calc_volume(self, sample: np.ndarray): """Find the RMS of the audio""" return sqrt(np.mean(np.square(sample)))
python judge empty dict
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") ...
def nonull_dict(self): """Like dict, but does not hold any null values. :return: """ return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'}
python judge empty dict
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") ...
def check_empty_dict(GET_dict): """ Returns True if the GET querstring contains on values, but it can contain empty keys. This is better than doing not bool(request.GET) as an empty key will return True """ empty = True for k, v in GET_dict.items(): # Don't disable on p(age) or '...
python judge empty dict
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") ...
def _remove_empty_items(d, required): """Return a new dict with any empty items removed. Note that this is not a deep check. If d contains a dictionary which itself contains empty items, those are never checked. This method exists to make to_serializable() functions cleaner. We could revisit this some day, ...
python judge empty dict
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") ...
def purge_dict(idict): """Remove null items from a dictionary """ odict = {} for key, val in idict.items(): if is_null(val): continue odict[key] = val return odict
python judge empty dict
def _clean_dict(target_dict, whitelist=None): """ Convenience function that removes a dicts keys that have falsy values """ assert isinstance(target_dict, dict) return { ustr(k).strip(): ustr(v).strip() for k, v in target_dict.items() if v not in (None, Ellipsis, [], (), "") ...
def _get_non_empty_list(cls, iter): """Return a list of the input, excluding all ``None`` values.""" res = [] for value in iter: if hasattr(value, 'items'): value = cls._get_non_empty_dict(value) or None if value is not None: res.append(val...
python keras get embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
def NeuralNetLearner(dataset, sizes): """Layered feed-forward network.""" activations = map(lambda n: [0.0 for i in range(n)], sizes) weights = [] def predict(example): unimplemented() return predict
python keras get embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
def decode_example(self, example): """Reconstruct the image from the tf example.""" img = tf.image.decode_image( example, channels=self._shape[-1], dtype=tf.uint8) img.set_shape(self._shape) return img
python keras get embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
def encode_dataset(dataset, vocabulary): """Encode from strings to token ids. Args: dataset: a tf.data.Dataset with string values. vocabulary: a mesh_tensorflow.transformer.Vocabulary Returns: a tf.data.Dataset with integer-vector values ending in EOS=1 """ def encode(features): return {k: vo...
python keras get embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
def mtf_image_transformer_cifar_mp_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_ff = 8192 return hparams
python keras get embedding
def calculate_embedding(self, batch_image_bytes): """Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output) """ return self.tf_session.run( self.embeddi...
def get_example_features(example): """Returns the non-sequence features from the provided example.""" return (example.features.feature if isinstance(example, tf.train.Example) else example.context.feature)
how to block python code before executing
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
def process_wait(process, timeout=0): """ Pauses script execution until a given process exists. :param process: :param timeout: :return: """ ret = AUTO_IT.AU3_ProcessWait(LPCWSTR(process), INT(timeout)) return ret
how to block python code before executing
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
def wait_run_in_executor(func, *args, **kwargs): """ Run blocking code in a different thread and wait for the result. :param func: Run this function in a different thread :param args: Parameters of the function :param kwargs: Keyword parameters of the function :returns: Return the result of...
how to block python code before executing
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
def print_statements(self): """Print all INDRA Statements collected by the processors.""" for i, stmt in enumerate(self.statements): print("%s: %s" % (i, stmt))
how to block python code before executing
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
def execute_only_once(): """ Each called in the code to this function is guaranteed to return True the first time and False afterwards. Returns: bool: whether this is the first time this function gets called from this line of code. Example: .. code-block:: python if ex...
how to block python code before executing
def wait_until_exit(self): """ Wait until thread exit Used for testing purpose only """ if self._timeout is None: raise Exception("Thread will never exit. Use stop or specify timeout when starting it!") self._thread.join() self.stop()
def _run_once(self): """Run once, should be called only from loop()""" try: self.do_wait() self._execute_wakeup_tasks() self._trigger_timers() except Exception as e: Log.error("Error occured during _run_once(): " + str(e)) Log.error(traceback.format_exc()) self.should_exi...
python list comprehension over two indexes
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
def listunion(ListOfLists): """ Take the union of a list of lists. Take a Python list of Python lists:: [[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]] and return the aggregated list:: [l11,l12, ..., l21, l22 , ...] For a list of two lists, e.g. `[a, b]`, this is...
python list comprehension over two indexes
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
def _indexes(arr): """ Returns the list of all indexes of the given array. Currently works for one and two-dimensional arrays """ myarr = np.array(arr) if myarr.ndim == 1: return list(range(len(myarr))) elif myarr.ndim == 2: return tuple(itertools.product(list(range(arr.shape[0...
python list comprehension over two indexes
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
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 list comprehension over two indexes
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
def _listify(collection): """This is a workaround where Collections are no longer iterable when using JPype.""" new_list = [] for index in range(len(collection)): new_list.append(collection[index]) return new_list
python list comprehension over two indexes
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
def _izip(*iterables): """ Iterate through multiple lists or arrays of equal size """ # This izip routine is from itertools # izip('ABCD', 'xy') --> Ax By iterators = map(iter, iterables) while iterators: yield tuple(map(next, iterators))
python load mnist data no numpy
def get_mnist(data_type="train", location="/tmp/mnist"): """ Get mnist dataset with features and label as ndarray. Data would be downloaded automatically if it doesn't present at the specific location. :param data_type: "train" for training data and "test" for testing data. :param location: Locatio...
def load_data(filename): """ :rtype : numpy matrix """ data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9) return data.as_matrix()
python load mnist data no numpy
def get_mnist(data_type="train", location="/tmp/mnist"): """ Get mnist dataset with features and label as ndarray. Data would be downloaded automatically if it doesn't present at the specific location. :param data_type: "train" for training data and "test" for testing data. :param location: Locatio...
def _openResources(self): """ Uses numpy.load to open the underlying file """ arr = np.load(self._fileName, allow_pickle=ALLOW_PICKLE) check_is_an_array(arr) self._array = arr
python load mnist data no numpy
def get_mnist(data_type="train", location="/tmp/mnist"): """ Get mnist dataset with features and label as ndarray. Data would be downloaded automatically if it doesn't present at the specific location. :param data_type: "train" for training data and "test" for testing data. :param location: Locatio...
def read_numpy(fd, byte_order, dtype, count): """Read tag data from file and return as numpy array.""" return numpy.fromfile(fd, byte_order+dtype[-1], count)
python load mnist data no numpy
def get_mnist(data_type="train", location="/tmp/mnist"): """ Get mnist dataset with features and label as ndarray. Data would be downloaded automatically if it doesn't present at the specific location. :param data_type: "train" for training data and "test" for testing data. :param location: Locatio...
def read_array(path, mmap_mode=None): """Read a .npy array.""" file_ext = op.splitext(path)[1] if file_ext == '.npy': return np.load(path, mmap_mode=mmap_mode) raise NotImplementedError("The file extension `{}` ".format(file_ext) + "is not currently supported.")
python load mnist data no numpy
def get_mnist(data_type="train", location="/tmp/mnist"): """ Get mnist dataset with features and label as ndarray. Data would be downloaded automatically if it doesn't present at the specific location. :param data_type: "train" for training data and "test" for testing data. :param location: Locatio...
def numpy(self): """ Grabs image data and converts it to a numpy array """ # load GDCM's image reading functionality image_reader = gdcm.ImageReader() image_reader.SetFileName(self.fname) if not image_reader.Read(): raise IOError("Could not read DICOM image") ...
how to check data type of variable in python
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
def get_typecast_value(self, value, type): """ Helper method to determine actual value based on type of feature variable. Args: value: Value in string form as it was parsed from datafile. type: Type denoting the feature flag type. Return: Value type-casted based on type of feature variab...
how to check data type of variable in python
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
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...
how to check data type of variable in python
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
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...
how to check data type of variable in python
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
def is_strict_numeric(n: Node) -> bool: """ numeric denotes typed literals with datatypes xsd:integer, xsd:decimal, xsd:float, and xsd:double. """ return is_typed_literal(n) and cast(Literal, n).datatype in [XSD.integer, XSD.decimal, XSD.float, XSD.double]
how to check data type of variable in python
def autoconvert(string): """Try to convert variables into datatypes.""" for fn in (boolify, int, float): try: return fn(string) except ValueError: pass return string
def parse_parameter(value): """ @return: The best approximation of a type of the given value. """ if any((isinstance(value, float), isinstance(value, int), isinstance(value, bool))): return value try: return int(value) except ValueError: try: return float(val...