anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def c_array(ctype, values):
"""Convert a python string to c array."""
if isinstance(values, np.ndarray) and values.dtype.itemsize == ctypes.sizeof(ctype):
return (ctype * len(values)).from_buffer_copy(values)
return (ctype * len(values))(*values) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _numpy_bytes_to_char(arr):
"""Like netCDF4.stringtochar, but faster and more flexible.
"""
# ensure the array is contiguous
arr = np.array(arr, copy=False, order='C', dtype=np.string_)
return arr.reshape(arr.shape + (1,)).view('S1') |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num))
return numpy.frombuffer(in_bytes, dt) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1]) |
1d array in char datatype in python | def _convert_to_array(array_like, dtype):
"""
Convert Matrix attributes which are array-like or buffer to array.
"""
if isinstance(array_like, bytes):
return np.frombuffer(array_like, dtype=dtype)
return np.asarray(array_like, dtype=dtype) | def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def p_if_statement_2(self, p):
"""if_statement : IF LPAREN expr RPAREN statement ELSE statement"""
p[0] = ast.If(predicate=p[3], consequent=p[5], alternative=p[7]) |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def if_(*args):
"""Implements the 'if' operator with support for multiple elseif-s."""
for i in range(0, len(args) - 1, 2):
if args[i]:
return args[i + 1]
if len(args) % 2:
return args[-1]
else:
return None |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def _if(ctx, logical_test, value_if_true=0, value_if_false=False):
"""
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
"""
return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def notin(arg, values):
"""
Like isin, but checks whether this expression's value(s) are not
contained in the passed values. See isin docs for full usage.
"""
op = ops.NotContains(arg, values)
return op.to_expr() |
python condition non none | def _not(condition=None, **kwargs):
"""
Return the opposite of input condition.
:param condition: condition to process.
:result: not condition.
:rtype: bool
"""
result = True
if condition is not None:
result = not run(condition, **kwargs)
return result | def contains(self, element):
"""
Ensures :attr:`subject` contains *other*.
"""
self._run(unittest_case.assertIn, (element, self._subject))
return ChainInspector(self._subject) |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def get_matrix(self):
""" Use numpy to create a real matrix object from the data
:return: the matrix representation of the fvm
"""
return np.array([ self.get_row_list(i) for i in range(self.row_count()) ]) |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def cell(self, rowName, columnName):
"""
Returns the value of the cell on the given row and column.
"""
return self.matrix[self.rowIndices[rowName], self.columnIndices[columnName]] |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def load_data(filename):
"""
:rtype : numpy matrix
"""
data = pandas.read_csv(filename, header=None, delimiter='\t', skiprows=9)
return data.as_matrix() |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse array with n rows
"""
return sp.sparse.csc_matrix(X[:, self.feature][:, np.newaxis]) |
accessing a column from a matrix in python | def get_column(self, X, column):
"""Return a column of the given matrix.
Args:
X: `numpy.ndarray` or `pandas.DataFrame`.
column: `int` or `str`.
Returns:
np.ndarray: Selected column.
"""
if isinstance(X, pd.DataFrame):
return X[column].values
return X[:, column] | def trans_from_matrix(matrix):
""" Convert a vtk matrix to a numpy.ndarray """
t = np.zeros((4, 4))
for i in range(4):
for j in range(4):
t[i, j] = matrix.GetElement(i, j)
return t |
are python strings hashable | 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 | def update_hash_from_str(hsh, str_input):
"""
Convert a str to object supporting buffer API and update a hash with it.
"""
byte_input = str(str_input).encode("UTF-8")
hsh.update(byte_input) |
are python strings hashable | 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 | def dict_hash(dct):
"""Return a hash of the contents of a dictionary"""
dct_s = json.dumps(dct, sort_keys=True)
try:
m = md5(dct_s)
except TypeError:
m = md5(dct_s.encode())
return m.hexdigest() |
are python strings hashable | 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 | 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 = hash(type(it))
for value in it:
hash_value = hash((hash_value, value))
return hash_value |
are python strings hashable | 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 | def _hash_the_file(hasher, filename):
"""Helper function for creating hash functions.
See implementation of :func:`dtoolcore.filehasher.shasum`
for more usage details.
"""
BUF_SIZE = 65536
with open(filename, 'rb') as f:
buf = f.read(BUF_SIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BUF_SIZE)
return hasher |
are python strings hashable | 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 | 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, omnihash(v)) for k, v in obj.items()))
else:
return hash(obj) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def __call__(self, factory_name, *args, **kwargs):
"""Create object."""
return self.factories[factory_name](*args, **kwargs) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def load(obj, cls, default_factory):
"""Create or load an object if necessary.
Parameters
----------
obj : `object` or `dict` or `None`
cls : `type`
default_factory : `function`
Returns
-------
`object`
"""
if obj is None:
return default_factory()
if isinstance(obj, dict):
return cls.load(obj)
return obj |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def __call__(self, *args, **kwargs):
""" Instanciates a new *Document* from this collection """
kwargs["mongokat_collection"] = self
return self.document_class(*args, **kwargs) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def simple_generate(cls, create, **kwargs):
"""Generate a new instance.
The instance will be either 'built' or 'created'.
Args:
create (bool): whether to 'build' or 'create' the instance.
Returns:
object: the generated instance
"""
strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY
return cls.generate(strategy, **kwargs) |
python create object without class | def create_object(cls, members):
"""Promise an object of class `cls` with content `members`."""
obj = cls.__new__(cls)
obj.__dict__ = members
return obj | def add_object(self, obj):
"""Add object to local and app environment storage
:param obj: Instance of a .NET object
"""
if obj.top_level_object:
if isinstance(obj, DotNetNamespace):
self.namespaces[obj.name] = obj
self.objects[obj.id] = obj |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def get_range(self, start=None, stop=None):
"""Return a RangeMap for the range start to stop.
Returns:
A RangeMap
"""
return self.from_iterable(self.ranges(start, stop)) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def range(*args, interval=0):
"""Generate a given range of numbers.
It supports the same arguments as the builtin function.
An optional interval can be given to space the values out.
"""
agen = from_iterable.raw(builtins.range(*args))
return time.spaceout.raw(agen, interval) if interval else agen |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def add_range(self, sequence, begin, end):
"""Add a read_range primitive"""
sequence.parser_tree = parsing.Range(self.value(begin).strip("'"),
self.value(end).strip("'"))
return True |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def merge(self, other):
"""
Merge this range object with another (ranges need not overlap or abut).
:returns: a new Range object representing the interval containing both
ranges.
"""
newstart = min(self._start, other.start)
newend = max(self._end, other.end)
return Range(newstart, newend) |
python create range in steps | def _xxrange(self, start, end, step_count):
"""Generate n values between start and end."""
_step = (end - start) / float(step_count)
return (start + (i * _step) for i in xrange(int(step_count))) | def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
"""Returns a generator which creates the next value in the range on demand"""
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
current = start if start in date_interval else start + delta
while current in date_interval:
yield current
current = current + delta |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def All(sequence):
"""
:param sequence: Any sequence whose elements can be evaluated as booleans.
:returns: true if all elements of the sequence satisfy True and x.
"""
return bool(reduce(lambda x, y: x and y, sequence, True)) |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def _or(ctx, *logical):
"""
Returns TRUE if any argument is TRUE
"""
for arg in logical:
if conversions.to_boolean(arg, ctx):
return True
return False |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def _if(ctx, logical_test, value_if_true=0, value_if_false=False):
"""
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
"""
return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def visit_BoolOp(self, node):
""" Return type may come from any boolop operand. """
return sum((self.visit(value) for value in node.values), []) |
assure all true of a list of boolean python | def assert_exactly_one_true(bool_list):
"""This method asserts that only one value of the provided list is True.
:param bool_list: List of booleans to check
:return: True if only one value is True, False otherwise
"""
assert isinstance(bool_list, list)
counter = 0
for item in bool_list:
if item:
counter += 1
return counter == 1 | def _isbool(string):
"""
>>> _isbool(True)
True
>>> _isbool("False")
True
>>> _isbool(1)
False
"""
return isinstance(string, _bool_type) or\
(isinstance(string, (_binary_type, _text_type))
and
string in ("True", "False")) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def save_dict_to_file(filename, dictionary):
"""Saves dictionary as CSV file."""
with open(filename, 'w') as f:
writer = csv.writer(f)
for k, v in iteritems(dictionary):
writer.writerow([str(k), str(v)]) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def read_dict_from_file(file_path):
"""
Read a dictionary of strings from a file
"""
with open(file_path) as file:
lines = file.read().splitlines()
obj = {}
for line in lines:
key, value = line.split(':', maxsplit=1)
obj[key] = eval(value)
return obj |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def h5ToDict(h5, readH5pyDataset=True):
""" Read a hdf5 file into a dictionary """
h = h5py.File(h5, "r")
ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset)
if readH5pyDataset: h.close()
return ret |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def to_dicts(recarray):
"""convert record array to a dictionaries"""
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist())) |
python creating a dictionary from reading a csv file with dictreader | def csv_to_dicts(file, header=None):
"""Reads a csv and returns a List of Dicts with keys given by header row."""
with open(file) as csvfile:
return [row for row in csv.DictReader(csvfile, fieldnames=header)] | def load(cls, fname):
""" Loads the dictionary from json file
:param fname: file to load from
:return: loaded dictionary
"""
with open(fname) as f:
return Config(**json.load(f)) |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cint8_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)):
return np.fromiter(cptr, dtype=np.int8, count=length)
else:
raise RuntimeError('Expected int pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p) |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer') |
python ctypes array to pointer | def cfloat64_array_to_numpy(cptr, length):
"""Convert a ctypes double pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_double)):
return np.fromiter(cptr, dtype=np.float64, count=length)
else:
raise RuntimeError('Expected double pointer') | def POINTER(obj):
"""
Create ctypes pointer to object.
Notes
-----
This function converts None to a real NULL pointer because of bug
in how ctypes handles None on 64-bit platforms.
"""
p = ctypes.POINTER(obj)
if not isinstance(p.from_param, classmethod):
def from_param(cls, x):
if x is None:
return cls()
else:
return x
p.from_param = classmethod(from_param)
return p |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def __absolute__(self, uri):
""" Get the absolute uri for a file
:param uri: URI of the resource to be retrieved
:return: Absolute Path
"""
return op.abspath(op.join(self.__path__, uri)) |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def from_file_url(url):
""" Convert from file:// url to file path
"""
if url.startswith('file://'):
url = url[len('file://'):].replace('/', os.path.sep)
return url |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def get_file_name(url):
"""Returns file name of file at given url."""
return os.path.basename(urllib.parse.urlparse(url).path) or 'unknown_name' |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def rel_path(filename):
"""
Function that gets relative path to the filename
"""
return os.path.join(os.getcwd(), os.path.dirname(__file__), filename) |
best way to give file path in python | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) | def relpath(path):
"""Path helper, gives you a path relative to this file"""
return os.path.normpath(
os.path.join(os.path.abspath(os.path.dirname(__file__)), path)
) |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def top(n, width=WIDTH, style=STYLE):
"""Prints the top row of a table"""
return hrule(n, width, linestyle=STYLES[style].top) |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def head_and_tail_print(self, n=5):
"""Display the first and last n elements of a DataFrame."""
from IPython import display
display.display(display.HTML(self._head_and_tail_table(n))) |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def series_table_row_offset(self, series):
"""
Return the number of rows preceding the data table for *series* in
the Excel worksheet.
"""
title_and_spacer_rows = series.index * 2
data_point_rows = series.data_point_offset
return title_and_spacer_rows + data_point_rows |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def iter_except_top_row_tcs(self):
"""Generate each `a:tc` element in non-first rows of range."""
for tr in self._tbl.tr_lst[self._top + 1:self._bottom]:
for tc in tr.tc_lst[self._left:self._right]:
yield tc |
bottom 5 rows in python | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | def pop_row(self, idr=None, tags=False):
"""Pops a row, default the last"""
idr = idr if idr is not None else len(self.body) - 1
row = self.body.pop(idr)
return row if tags else [cell.childs[0] for cell in row] |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def rgb2gray(img):
"""Converts an RGB image to grayscale using matlab's algorithm."""
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * r + g_c * g + b_c * b |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def screen_cv2(self):
"""cv2 Image of current window screen"""
pil_image = self.screen.convert('RGB')
cv2_image = np.array(pil_image)
pil_image.close()
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1]
return cv2_image |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def normalize(im, invert=False, scale=None, dtype=np.float64):
"""
Normalize a field to a (min, max) exposure range, default is (0, 255).
(min, max) exposure values. Invert the image if requested.
"""
if dtype not in {np.float16, np.float32, np.float64}:
raise ValueError('dtype must be numpy.float16, float32, or float64.')
out = im.astype('float').copy()
scale = scale or (0.0, 255.0)
l, u = (float(i) for i in scale)
out = (out - l) / (u - l)
if invert:
out = -out + (out.max() + out.min())
return out.astype(dtype) |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def im2mat(I):
"""Converts and image to matrix (one pixel per line)"""
return I.reshape((I.shape[0] * I.shape[1], I.shape[2])) |
python cv2 np array to gray scale | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | def smooth_gaussian(image, sigma=1):
"""Returns Gaussian smoothed image.
:param image: numpy array or :class:`jicimagelib.image.Image`
:param sigma: standard deviation
:returns: :class:`jicimagelib.image.Image`
"""
return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest") |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(img, angle):
"""
querries scipy.ndimage.rotate routine
:param img: image to be rotated
:param angle: angle to be rotated (radian)
:return: rotated image
"""
imgR = scipy.ndimage.rotate(img, angle, reshape=False)
return imgR |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotateImage(image, angle):
"""
rotates a 2d array to a multiple of 90 deg.
0 = default
1 = 90 deg. cw
2 = 180 deg.
3 = 90 deg. ccw
"""
image = [list(row) for row in image]
for n in range(angle % 4):
image = list(zip(*image[::-1]))
return image |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def zoom_cv(x,z):
""" Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. """
if z==0: return x
r,c,*_ = x.shape
M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)
return cv2.warpAffine(x,M,(c,r)) |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def rotate_point(xorigin, yorigin, x, y, angle):
"""Rotate the given point by angle
"""
rotx = (x - xorigin) * np.cos(angle) - (y - yorigin) * np.sin(angle)
roty = (x - yorigin) * np.sin(angle) + (y - yorigin) * np.cos(angle)
return rotx, roty |
python cv2 rotate image 90 degrees | def rotate_img(im, deg, mode=cv2.BORDER_CONSTANT, interpolation=cv2.INTER_AREA):
""" Rotates an image by deg degrees
Arguments:
deg (float): degree to rotate.
"""
r,c,*_ = im.shape
M = cv2.getRotationMatrix2D((c//2,r//2),deg,1)
return cv2.warpAffine(im,M,(c,r), borderMode=mode, flags=cv2.WARP_FILL_OUTLIERS+interpolation) | def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation vector."""
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1])) |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def _distance(coord1, coord2):
"""
Return the distance between two points, `coord1` and `coord2`. These
parameters are assumed to be (x, y) tuples.
"""
xdist = coord1[0] - coord2[0]
ydist = coord1[1] - coord2[1]
return sqrt(xdist*xdist + ydist*ydist) |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def distL1(x1,y1,x2,y2):
"""Compute the L1-norm (Manhattan) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
return int(abs(x2-x1) + abs(y2-y1)+.5) |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def distance(vec1, vec2):
"""Calculate the distance between two Vectors"""
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
dist_vec = vec2 - vec1
return dist_vec.length()
else:
raise TypeError("vec1 and vec2 must be Vector2's") |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def dist_sq(self, other):
"""Distance squared to some other point."""
dx = self.x - other.x
dy = self.y - other.y
return dx**2 + dy**2 |
calculate distance between two coorinates python | def _calculate_distance(latlon1, latlon2):
"""Calculates the distance between two points on earth.
"""
lat1, lon1 = latlon1
lat2, lon2 = latlon2
dlon = lon2 - lon1
dlat = lat2 - lat1
R = 6371 # radius of the earth in kilometers
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2))**2
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1 - a)) / 180
return c | def _euclidean_dist(vector_a, vector_b):
"""
:param vector_a: A list of numbers.
:param vector_b: A list of numbers.
:returns: The euclidean distance between the two vectors.
"""
dist = 0
for (x, y) in zip(vector_a, vector_b):
dist += (x-y)*(x-y)
return math.sqrt(dist) |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def parse_date(s):
"""
Parse a date using dateutil.parser.parse if available,
falling back to datetime.datetime.strptime if not
"""
if isinstance(s, (datetime.datetime, datetime.date)):
return s
try:
from dateutil.parser import parse
except ImportError:
parse = lambda d: datetime.datetime.strptime(d, "%Y-%m-%d")
return parse(s) |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def parse_date(s):
"""Fast %Y-%m-%d parsing."""
try:
return datetime.date(int(s[:4]), int(s[5:7]), int(s[8:10]))
except ValueError: # other accepted format used in one-day data set
return datetime.datetime.strptime(s, '%d %B %Y').date() |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def deserialize_date(string):
"""
Deserializes string to date.
:param string: str.
:type string: str
:return: date.
:rtype: date
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def parse_json_date(value):
"""
Parses an ISO8601 formatted datetime from a string value
"""
if not value:
return None
return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC) |
python date parser without format | def parse(self, s):
"""
Parses a date string formatted like ``YYYY-MM-DD``.
"""
return datetime.datetime.strptime(s, self.date_format).date() | def Date(value):
"""Custom type for managing dates in the command-line."""
from datetime import datetime
try:
return datetime(*reversed([int(val) for val in value.split('/')]))
except Exception as err:
raise argparse.ArgumentTypeError("invalid date '%s'" % value) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def _format_title_string(self, title_string):
""" format mpv's title """
return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix)) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def __getattr__(self, item: str) -> Callable:
"""Get a callable that sends the actual API request internally."""
return functools.partial(self.call_action, item) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def show_tip(self, tip=""):
"""Show tip"""
QToolTip.showText(self.mapToGlobal(self.pos()), tip, self) |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def get_title(soup):
"""Given a soup, pick out a title"""
if soup.title:
return soup.title.string
if soup.h1:
return soup.h1.string
return '' |
callable title objects in python | def sortable_title(instance):
"""Uses the default Plone sortable_text index lower-case
"""
title = plone_sortable_title(instance)
if safe_callable(title):
title = title()
return title.lower() | def __getattr__(self, name):
"""Return wrapper to named api method."""
return functools.partial(self._obj.request, self._api_prefix + name) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def retrieve_asset(filename):
""" Retrieves a non-image asset associated with an entry """
record = model.Image.get(asset_name=filename)
if not record:
raise http_error.NotFound("File not found")
if not record.is_asset:
raise http_error.Forbidden()
return flask.send_file(record.file_path, conditional=True) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def url_to_image(url):
"""
Fetch an image from url and convert it into a Pillow Image object
"""
r = requests.get(url)
image = StringIO(r.content)
return image |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def _image_field(self):
"""
Try to automatically detect an image field
"""
for field in self.model._meta.fields:
if isinstance(field, ImageField):
return field.name |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def get_img_data(f, maxsize = (1200, 850), first = False):
"""Generate image data using PIL
"""
img = Image.open(f)
img.thumbnail(maxsize)
if first: # tkinter is inactive the first time
bio = io.BytesIO()
img.save(bio, format = "PNG")
del img
return bio.getvalue()
return ImageTk.PhotoImage(img) |
can we access img in django python | def show_image(self, key):
"""Show image (item is a PIL image)"""
data = self.model.get_data()
data[key].show() | def get_plain_image_as_widget(self):
"""Used for generating thumbnails. Does not include overlaid
graphics.
"""
arr = self.getwin_array(order=self.rgb_order)
image = self._get_qimage(arr, self.qimg_fmt)
return image |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def text_alignment(x, y):
"""
Align text labels based on the x- and y-axis coordinate values.
This function is used for computing the appropriate alignment of the text
label.
For example, if the text is on the "right" side of the plot, we want it to
be left-aligned. If the text is on the "top" side of the plot, we want it
to be bottom-aligned.
:param x, y: (`int` or `float`) x- and y-axis coordinate respectively.
:returns: A 2-tuple of strings, the horizontal and vertical alignments
respectively.
"""
if x == 0:
ha = "center"
elif x > 0:
ha = "left"
else:
ha = "right"
if y == 0:
va = "center"
elif y > 0:
va = "bottom"
else:
va = "top"
return ha, va |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def get_margin(length):
"""Add enough tabs to align in two columns"""
if length > 23:
margin_left = "\t"
chars = 1
elif length > 15:
margin_left = "\t\t"
chars = 2
elif length > 7:
margin_left = "\t\t\t"
chars = 3
else:
margin_left = "\t\t\t\t"
chars = 4
return margin_left |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def margin(text):
r"""Add a margin to both ends of each line in the string.
Example:
>>> margin('line1\nline2')
' line1 \n line2 '
"""
lines = str(text).split('\n')
return '\n'.join(' {} '.format(l) for l in lines) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def normalize_text(text, line_len=80, indent=""):
"""Wrap the text on the given line length."""
return "\n".join(
textwrap.wrap(
text, width=line_len, initial_indent=indent, subsequent_indent=indent
)
) |
center align text python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text.
"""
centered = []
for line in text.splitlines():
centered.append(line.center(width))
return "\n".join(centered) | def dumped(text, level, indent=2):
"""Put curly brackets round an indented text"""
return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n" |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def set_history_file(self, path):
"""Set path to history file. "" produces no file."""
if path:
self.history = prompt_toolkit.history.FileHistory(fixpath(path))
else:
self.history = prompt_toolkit.history.InMemoryHistory() |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def bin_open(fname: str):
"""
Returns a file descriptor for a plain text or gzipped file, binary read mode
for subprocess interaction.
:param fname: The filename to open.
:return: File descriptor in binary read mode.
"""
if fname.endswith(".gz"):
return gzip.open(fname, "rb")
return open(fname, "rb") |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def DeleteLog() -> None:
"""Delete log file."""
if os.path.exists(Logger.FileName):
os.remove(Logger.FileName) |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def dir_path(dir):
"""with dir_path(path) to change into a directory."""
old_dir = os.getcwd()
os.chdir(dir)
yield
os.chdir(old_dir) |
change path of log files using python rotatingfilehandler | def timed_rotating_file_handler(name, logname, filename, when='h',
interval=1, backupCount=0,
encoding=None, delay=False, utc=False):
"""
A Bark logging handler logging output to a named file. At
intervals specified by the 'when', the file will be rotated, under
control of 'backupCount'.
Similar to logging.handlers.TimedRotatingFileHandler.
"""
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) | def __init__(self, filename, mode, encoding=None):
"""Use the specified filename for streamed logging."""
FileHandler.__init__(self, filename, mode, encoding)
self.mode = mode
self.encoding = encoding |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def check_for_positional_argument(kwargs, name, default=False):
"""
@type kwargs: dict
@type name: str
@type default: bool, int, str
@return: bool, int
"""
if name in kwargs:
if str(kwargs[name]) == "True":
return True
elif str(kwargs[name]) == "False":
return False
else:
return kwargs[name]
return default |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def check_oneof(**kwargs):
"""Raise ValueError if more than one keyword argument is not none.
Args:
kwargs (dict): The keyword arguments sent to the function.
Returns: None
Raises:
ValueError: If more than one entry in kwargs is not none.
"""
# Sanity check: If no keyword arguments were sent, this is fine.
if not kwargs:
return None
not_nones = [val for val in kwargs.values() if val is not None]
if len(not_nones) > 1:
raise ValueError('Only one of {fields} should be set.'.format(
fields=', '.join(sorted(kwargs.keys())),
)) |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def validate_args(**args):
"""
function to check if input query is not None
and set missing arguments to default value
"""
if not args['query']:
print("\nMissing required query argument.")
sys.exit()
for key in DEFAULTS:
if key not in args:
args[key] = DEFAULTS[key]
return args |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def get_value(self, context):
"""Run python eval on the input string."""
if self.value:
return expressions.eval_string(self.value, context)
else:
# Empty input raises cryptic EOF syntax err, this more human
# friendly
raise ValueError('!py string expression is empty. It must be a '
'valid python expression instead.') |
python deter is an invalid keyword | def is_identifier(string):
"""Check if string could be a valid python identifier
:param string: string to be tested
:returns: True if string can be a python identifier, False otherwise
:rtype: bool
"""
matched = PYTHON_IDENTIFIER_RE.match(string)
return bool(matched) and not keyword.iskeyword(string) | def _check_valid(key, val, valid):
"""Helper to check valid options"""
if val not in valid:
raise ValueError('%s must be one of %s, not "%s"'
% (key, valid, val)) |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 15