anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
python pca based on covariance matrix | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.lin... | def _covariance_matrix(self, type='noise'):
"""
Constructs the covariance matrix from PCA
residuals
"""
if type == 'sampling':
return self.sigma**2/(self.n-1)
elif type == 'noise':
return 4*self.sigma*N.var(self.rotated(), axis=0) |
python pca based on covariance matrix | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.lin... | def cov_to_correlation(cov):
"""Compute the correlation matrix given the covariance matrix.
Parameters
----------
cov : `~numpy.ndarray`
N x N matrix of covariances among N parameters.
Returns
-------
corr : `~numpy.ndarray`
N x N matrix of correlations among N parameters.
... |
python pca based on covariance matrix | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.lin... | def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov) |
python pca based on covariance matrix | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.lin... | def Cinv(self):
"""Inverse of the noise covariance."""
try:
return np.linalg.inv(self.c)
except np.linalg.linalg.LinAlgError:
print('Warning: non-invertible noise covariance matrix c.')
return np.eye(self.c.shape[0]) |
python pca based on covariance matrix | def perform_pca(A):
"""
Computes eigenvalues and eigenvectors of covariance matrix of A.
The rows of a correspond to observations, the columns to variables.
"""
# First subtract the mean
M = (A-numpy.mean(A.T, axis=1)).T
# Get eigenvectors and values of covariance matrix
return numpy.lin... | def covariance(self,pt0,pt1):
""" get the covarince between two points implied by Vario2d
Parameters
----------
pt0 : (iterable of len 2)
first point x and y
pt1 : (iterable of len 2)
second point x and y
Returns
-------
cov : flo... |
python pil image frombytes | def from_bytes(cls, b):
"""Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG`
"""
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def to_bytes(self):
"""Convert the entire image to bytes.
:rtype: bytes
"""
chunks = [PNG_SIGN]
chunks.extend(c[1] for c in self.chunks)
return b"".join(chunks) |
python pil image frombytes | def from_bytes(cls, b):
"""Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG`
"""
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image |
python pil image frombytes | def from_bytes(cls, b):
"""Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG`
"""
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def img_encode(arr, **kwargs):
"""Encode ndarray to base64 string image data
Parameters
----------
arr: ndarray (rows, cols, depth)
kwargs: passed directly to matplotlib.image.imsave
"""
sio = BytesIO()
imsave(sio, arr, **kwargs)
sio.seek(0)
img_format = kwargs['format'] if ... |
python pil image frombytes | def from_bytes(cls, b):
"""Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG`
"""
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def get_buffer(self, data_np, header, format, output=None):
"""Get image as a buffer in (format).
Format should be 'jpeg', 'png', etc.
"""
if not have_pil:
raise Exception("Install PIL to use this method")
image = PILimage.fromarray(data_np)
buf = output
... |
python pil image frombytes | def from_bytes(cls, b):
"""Create :class:`PNG` from raw bytes.
:arg bytes b: The raw bytes of the PNG file.
:rtype: :class:`PNG`
"""
im = cls()
im.chunks = list(parse_chunks(b))
im.init()
return im | def load_image(fname):
""" read an image from file - PIL doesnt close nicely """
with open(fname, "rb") as f:
i = Image.open(fname)
#i.load()
return i |
python placeholder symble for boolean | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def boolean(value):
"""
Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars).
"""
if isinstance(value, bool):
return value
if value == "":
return False
return strtobool(value) |
python placeholder symble for boolean | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def _cast_boolean(value):
"""
Helper to convert config values to boolean as ConfigParser do.
"""
_BOOLEANS = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False, '': False}
value = str(value)
if value.lower() not in _BOOLEANS:... |
python placeholder symble for boolean | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def _type_bool(label,default=False):
"""Shortcut fot boolean like fields"""
return label, abstractSearch.nothing, abstractRender.boolen, default |
python placeholder symble for boolean | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def _parse_boolean(value, default=False):
"""
Attempt to cast *value* into a bool, returning *default* if it fails.
"""
if value is None:
return default
try:
return bool(value)
except ValueError:
return default |
python placeholder symble for boolean | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def str_to_boolean(input_str):
""" a conversion function for boolean
"""
if not isinstance(input_str, six.string_types):
raise ValueError(input_str)
input_str = str_quote_stripper(input_str)
return input_str.lower() in ("true", "t", "1", "y", "yes") |
how to get column names of df in python | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | def _get_str_columns(sf):
"""
Returns a list of names of columns that are string type.
"""
return [name for name in sf.column_names() if sf[name].dtype == str] |
how to get column names of df in python | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | def get_column_definition(self, table, column):
"""Retrieve the column definition statement for a column from a table."""
# Parse column definitions for match
for col in self.get_column_definition_all(table):
if col.strip('`').startswith(column):
return col.strip(',') |
how to get column names of df in python | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | def get_column_names(engine: Engine, tablename: str) -> List[str]:
"""
Get all the database column names for the specified table.
"""
return [info.name for info in gen_columns_info(engine, tablename)] |
how to get column names of df in python | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) |
how to get column names of df in python | def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | def clean_colnames(df):
""" Cleans the column names on a DataFrame
Parameters:
df - DataFrame
The DataFrame to clean
"""
col_list = []
for index in range(_dutils.cols(df)):
col_list.append(df.columns[index].strip().lower().replace(' ','_'))
df.columns = col_list |
python pos and mat to draw a cube | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) |
python pos and mat to draw a cube | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | def Pyramid(pos=(0, 0, 0), s=1, height=1, axis=(0, 0, 1), c="dg", alpha=1):
"""
Build a pyramid of specified base size `s` and `height`, centered at `pos`.
"""
return Cone(pos, s, height, axis, c, alpha, 4) |
python pos and mat to draw a cube | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | def point8_to_box(points):
"""
Args:
points: (nx4)x2
Returns:
nx4 boxes (x1y1x2y2)
"""
p = points.reshape((-1, 4, 2))
minxy = p.min(axis=1) # nx2
maxxy = p.max(axis=1) # nx2
return np.concatenate((minxy, maxxy), axis=1) |
python pos and mat to draw a cube | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | def circles_pycairo(width, height, color):
""" Implementation of circle border with PyCairo. """
cairo_color = color / rgb(255, 255, 255)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
# draw a circle in the center
ctx.new_path()
ctx.set_sour... |
python pos and mat to draw a cube | def paint_cube(self, x, y):
"""
Paints a cube at a certain position a color.
Parameters
----------
x: int
Horizontal position of the upper left corner of the cube.
y: int
Vertical position of the upper left corner of the cube.
"""
... | def CreateVertices(self, points):
"""
Returns a dictionary object with keys that are 2tuples
represnting a point.
"""
gr = digraph()
for z, x, Q in points:
node = (z, x, Q)
gr.add_nodes([node])
return gr |
python print contents of oredereddict | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | def printdict(adict):
"""printdict"""
dlist = list(adict.keys())
dlist.sort()
for i in range(0, len(dlist)):
print(dlist[i], adict[dlist[i]]) |
python print contents of oredereddict | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | def prettyprint(d):
"""Print dicttree in Json-like format. keys are sorted
"""
print(json.dumps(d, sort_keys=True,
indent=4, separators=("," , ": "))) |
python print contents of oredereddict | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | def _attrprint(d, delimiter=', '):
"""Print a dictionary of attributes in the DOT format"""
return delimiter.join(('"%s"="%s"' % item) for item in sorted(d.items())) |
python print contents of oredereddict | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | def pprint(self, stream=None, indent=1, width=80, depth=None):
"""
Pretty print the underlying literal Python object
"""
pp.pprint(to_literal(self), stream, indent, width, depth) |
python print contents of oredereddict | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | def pretty_describe(object, nestedness=0, indent=2):
"""Maintain dict ordering - but make string version prettier"""
if not isinstance(object, dict):
return str(object)
sep = f'\n{" " * nestedness * indent}'
out = sep.join((f'{k}: {pretty_describe(v, nestedness + 1)}' for k, v in object.items())... |
how to get keys of a table along with values in python | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | def primary_keys_full(cls):
"""Get primary key properties for a SQLAlchemy cls.
Taken from marshmallow_sqlalchemy
"""
mapper = cls.__mapper__
return [
mapper.get_property_by_column(column)
for column in mapper.primary_key
] |
how to get keys of a table along with values in python | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | def value_for_key(membersuite_object_data, key):
"""Return the value for `key` of membersuite_object_data.
"""
key_value_dicts = {
d['Key']: d['Value'] for d
in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]}
return key_value_dicts[key] |
how to get keys of a table along with values in python | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | def columns(self):
"""Return names of all the addressable columns (including foreign keys) referenced in user supplied model"""
res = [col['name'] for col in self.column_definitions]
res.extend([col['name'] for col in self.foreign_key_definitions])
return res |
how to get keys of a table along with values in python | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | def keys(self, index=None):
"""Returns a list of keys in the database
"""
with self._lmdb.begin() as txn:
return [key.decode() for key, _ in txn.cursor()] |
how to get keys of a table along with values in python | def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()] |
how to get number of lines of a file python | def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1 | def get_lines(handle, line):
"""
Get zero-indexed line from an open file-like.
"""
for i, l in enumerate(handle):
if i == line:
return l |
how to get number of lines of a file python | def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1 | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) |
how to get number of lines of a file python | def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1 | def get_line_number(line_map, offset):
"""Find a line number, given a line map and a character offset."""
for lineno, line_offset in enumerate(line_map, start=1):
if line_offset > offset:
return lineno
return -1 |
how to get number of lines of a file python | def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1 | def empty_line_count_at_the_end(self):
"""
Return number of empty lines at the end of the document.
"""
count = 0
for line in self.lines[::-1]:
if not line or line.isspace():
count += 1
else:
break
return count |
how to get number of lines of a file python | def line_count(fn):
""" Get line count of file
Args:
fn (str): Path to file
Return:
Number of lines in file (int)
"""
with open(fn) as f:
for i, l in enumerate(f):
pass
return i + 1 | def _size_36():
""" returns the rows, columns of terminal """
from shutil import get_terminal_size
dim = get_terminal_size()
if isinstance(dim, list):
return dim[0], dim[1]
return dim.lines, dim.columns |
python public proxy list | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | def _GetProxies(self):
"""Gather a list of proxies to use."""
# Detect proxies from the OS environment.
result = client_utils.FindProxies()
# Also try to connect directly if all proxies fail.
result.append("")
# Also try all proxies configured in the config system.
result.extend(config.CON... |
python public proxy list | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | def enable_proxy(self, host, port):
"""Enable a default web proxy"""
self.proxy = [host, _number(port)]
self.proxy_enabled = True |
python public proxy list | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | def setup(self, proxystr='', prompting=True):
"""
Sets the proxy handler given the option passed on the command
line. If an empty string is passed it looks at the HTTP_PROXY
environment variable.
"""
self.prompting = prompting
proxy = self.get_proxy(proxystr)
... |
python public proxy list | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | def set_proxy(proxy_url, transport_proxy=None):
"""Create the proxy to PyPI XML-RPC Server"""
global proxy, PYPI_URL
PYPI_URL = proxy_url
proxy = xmlrpc.ServerProxy(
proxy_url,
transport=RequestsTransport(proxy_url.startswith('https://')),
allow_none=True) |
python public proxy list | def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | async def set_http_proxy(cls, url: typing.Optional[str]):
"""See `get_http_proxy`."""
await cls.set_config("http_proxy", "" if url is None else url) |
how to get segment of array at a time in python | def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w] | def segments_to_numpy(segments):
"""given a list of 4-element tuples, transforms it into a numpy array"""
segments = numpy.array(segments, dtype=SEGMENT_DATATYPE, ndmin=2) # each segment in a row
segments = segments if SEGMENTS_DIRECTION == 0 else numpy.transpose(segments)
return segments |
how to get segment of array at a time in python | def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w] | def find_start_point(self):
"""
Find the first location in our array that is not empty
"""
for i, row in enumerate(self.data):
for j, _ in enumerate(row):
if self.data[i, j] != 0: # or not np.isfinite(self.data[i,j]):
return i, j |
how to get segment of array at a time in python | def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w] | def array(self):
"""
return the underlying numpy array
"""
return np.arange(self.start, self.stop, self.step) |
how to get segment of array at a time in python | def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w] | def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) |
how to get segment of array at a time in python | def region_from_segment(image, segment):
"""given a segment (rectangle) and an image, returns it's corresponding subimage"""
x, y, w, h = segment
return image[y:y + h, x:x + w] | def series_index(self, series):
"""
Return the integer index of *series* in this sequence.
"""
for idx, s in enumerate(self):
if series is s:
return idx
raise ValueError('series not in chart data object') |
python random uniform points with random coordinates | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | def _uniform_phi(M):
"""
Generate M random numbers in [-pi, pi).
"""
return np.random.uniform(-np.pi, np.pi, M) |
python random uniform points with random coordinates | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | def runiform(lower, upper, size=None):
"""
Random uniform variates.
"""
return np.random.uniform(lower, upper, size) |
python random uniform points with random coordinates | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | def uniform_noise(points):
"""Init a uniform noise variable."""
return np.random.rand(1) * np.random.uniform(points, 1) \
+ random.sample([2, -2], 1) |
python random uniform points with random coordinates | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | def normal_noise(points):
"""Init a noise variable."""
return np.random.rand(1) * np.random.randn(points, 1) \
+ random.sample([2, -2], 1) |
python random uniform points with random coordinates | def _rndPointDisposition(dx, dy):
"""Return random disposition point."""
x = int(random.uniform(-dx, dx))
y = int(random.uniform(-dy, dy))
return (x, y) | def from_rectangle(box):
""" Create a vector randomly within the given rectangle. """
x = box.left + box.width * random.uniform(0, 1)
y = box.bottom + box.height * random.uniform(0, 1)
return Vector(x, y) |
python raw strings single quote | def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | def string_format_func(s):
"""
Function used internally to format string data for output to XML.
Escapes back-slashes and quotes, and wraps the resulting string in
quotes.
"""
return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"") |
python raw strings single quote | def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | def decode_mysql_string_literal(text):
"""
Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences... |
python raw strings single quote | def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | def _repr_strip(mystring):
"""
Returns the string without any initial or final quotes.
"""
r = repr(mystring)
if r.startswith("'") and r.endswith("'"):
return r[1:-1]
else:
return r |
python raw strings single quote | def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | def represented_args(args, separator=" "):
"""
Args:
args (list | tuple | None): Arguments to represent
separator (str | unicode): Separator to use
Returns:
(str): Quoted as needed textual representation
"""
result = []
if args:
for text in args:
resu... |
python raw strings single quote | def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s) | def safe_quotes(text, escape_single_quotes=False):
"""htmlify string"""
if isinstance(text, str):
safe_text = text.replace('"', """)
if escape_single_quotes:
safe_text = safe_text.replace("'", "\'")
return safe_text.replace('True', 'true')
return text |
python read first line of a file to a string | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) |
python read first line of a file to a string | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
#print "every line: %r" % line
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
retu... |
python read first line of a file to a string | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | def readme(filename, encoding='utf8'):
"""
Read the contents of a file
"""
with io.open(filename, encoding=encoding) as source:
return source.read() |
python read first line of a file to a string | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | def read_text_from_file(path: str) -> str:
""" Reads text file contents """
with open(path) as text_file:
content = text_file.read()
return content |
python read first line of a file to a string | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
... |
how to insert underline in python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | def underline(self, msg):
"""Underline the input"""
return click.style(msg, underline=True) if self.colorize else msg |
how to insert underline in python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | 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" |
how to insert underline in python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | def _write_separator(self):
"""
Inserts a horizontal (commented) line tot the generated code.
"""
tmp = self._page_width - ((4 * self.__indent_level) + 2)
self._write_line('# ' + ('-' * tmp)) |
how to insert underline in python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | def _add_indent(string, indent):
"""Add indent of ``indent`` spaces to ``string.split("\n")[1:]``
Useful for formatting in strings to already indented blocks
"""
lines = string.split("\n")
first, lines = lines[0], lines[1:]
lines = ["{indent}{s}".format(indent=" " * indent, s=s)
fo... |
how to insert underline in python | def draw_header(self, stream, header):
"""Draw header with underline"""
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | def end_block(self):
"""Ends an indentation block, leaving an empty line afterwards"""
self.current_indent -= 1
# If we did not add a new line automatically yet, now it's the time!
if not self.auto_added_line:
self.writeln()
self.auto_added_line = True |
python read raw txt from url | def url_read_text(url, verbose=True):
r"""
Directly reads text data from url
"""
data = url_read(url, verbose)
text = data.decode('utf8')
return text | def wget(url):
"""
Download the page into a string
"""
import urllib.parse
request = urllib.request.urlopen(url)
filestring = request.read()
return filestring |
python read raw txt from url | def url_read_text(url, verbose=True):
r"""
Directly reads text data from url
"""
data = url_read(url, verbose)
text = data.decode('utf8')
return text | def download(url, encoding='utf-8'):
"""Returns the text fetched via http GET from URL, read as `encoding`"""
import requests
response = requests.get(url)
response.encoding = encoding
return response.text |
python read raw txt from url | def url_read_text(url, verbose=True):
r"""
Directly reads text data from url
"""
data = url_read(url, verbose)
text = data.decode('utf8')
return text | def read_from_file(file_path, encoding="utf-8"):
"""
Read helper method
:type file_path: str|unicode
:type encoding: str|unicode
:rtype: str|unicode
"""
with codecs.open(file_path, "r", encoding) as f:
return f.read() |
python read raw txt from url | def url_read_text(url, verbose=True):
r"""
Directly reads text data from url
"""
data = url_read(url, verbose)
text = data.decode('utf8')
return text | def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data |
python read raw txt from url | def url_read_text(url, verbose=True):
r"""
Directly reads text data from url
"""
data = url_read(url, verbose)
text = data.decode('utf8')
return text | def _read_text(self, filename):
"""
Helper that reads the UTF-8 content of the specified file, or
None if the file doesn't exist. This returns a unicode string.
"""
with io.open(filename, 'rt', encoding='utf-8') as f:
return f.read() |
python recommended way to check empty string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except Attribu... | def chkstr(s, v):
"""
Small routine for checking whether a string is empty
even a string
:param s: the string in question
:param v: variable name
"""
if type(s) != str:
raise TypeError("{var} must be str".format(var=v))
if not s:
raise ValueError("{var} cannot be empty".... |
python recommended way to check empty string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except Attribu... | def is_empty_object(n, last):
"""n may be the inside of block or object"""
if n.strip():
return False
# seems to be but can be empty code
last = last.strip()
markers = {
')',
';',
}
if not last or last[-1] in markers:
return False
return True |
python recommended way to check empty string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except Attribu... | def run(self, value):
""" Determines if value value is empty.
Keyword arguments:
value str -- the value of the associated field to compare
"""
if self.pass_ and not value.strip():
return True
if not value:
return False
return True |
python recommended way to check empty string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except Attribu... | def match_empty(self, el):
"""Check if element is empty (if requested)."""
is_empty = True
for child in self.get_children(el, tags=False):
if self.is_tag(child):
is_empty = False
break
elif self.is_content_string(child) and RE_NOT_EMPTY.se... |
python recommended way to check empty string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except Attribu... | def contains_empty(features):
"""Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else.
"""
if not features:
return True
for feature in features:
if featur... |
how to iterate over a json file in python | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
for line in f.readlines():
yield json.loads(line) | def _read_json_file(self, json_file):
""" Helper function to read JSON file as OrderedDict """
self.log.debug("Reading '%s' JSON file..." % json_file)
with open(json_file, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict) |
how to iterate over a json file in python | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
for line in f.readlines():
yield json.loads(line) | def read(self):
"""Iterate over all JSON input (Generator)"""
for line in self.io.read():
with self.parse_line(line) as j:
yield j |
how to iterate over a json file in python | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
for line in f.readlines():
yield json.loads(line) | def from_file(file_path) -> dict:
""" Load JSON file """
with io.open(file_path, 'r', encoding='utf-8') as json_stream:
return Json.parse(json_stream, True) |
how to iterate over a json file in python | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
for line in f.readlines():
yield json.loads(line) | def from_json_list(cls, api_client, data):
"""Convert a list of JSON values to a list of models
"""
return [cls.from_json(api_client, item) for item in data] |
how to iterate over a json file in python | def json_iter (path):
"""
iterator for JSON-per-line in a file pattern
"""
with open(path, 'r') as f:
for line in f.readlines():
yield json.loads(line) | def load(cls, fname):
"""
Loads the flow from a JSON file.
:param fname: the file to load
:type fname: str
:return: the flow
:rtype: Flow
"""
with open(fname) as f:
content = f.readlines()
return Flow.from_json(''.join(content)) |
python regex validity check | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | def is_valid_regex(regex):
"""Function for checking a valid regex."""
if len(regex) == 0:
return False
try:
re.compile(regex)
return True
except sre_constants.error:
return False |
python regex validity check | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | def is_valid_email(email):
"""
Check if email is valid
"""
pattern = re.compile(r'[\w\.-]+@[\w\.-]+[.]\w+')
return bool(pattern.match(email)) |
python regex validity check | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | 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)) |
python regex validity check | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | def _compile(pattern, flags):
"""Compile the pattern to regex."""
return re.compile(WcParse(pattern, flags & FLAG_MASK).parse()) |
python regex validity check | def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | def matches(self, s):
"""Whether the pattern matches anywhere in the string s."""
regex_matches = self.compiled_regex.search(s) is not None
return not regex_matches if self.inverted else regex_matches |
python regression with constraint | def linregress(x, y, return_stats=False):
"""linear regression calculation
Parameters
----
x : independent variable (series)
y : dependent variable (series)
return_stats : returns statistical values as well if required (bool)
Returns
----
list of parameters (an... | def fit_linear(X, y):
"""
Uses OLS to fit the regression.
"""
model = linear_model.LinearRegression()
model.fit(X, y)
return model |
python regression with constraint | def linregress(x, y, return_stats=False):
"""linear regression calculation
Parameters
----
x : independent variable (series)
y : dependent variable (series)
return_stats : returns statistical values as well if required (bool)
Returns
----
list of parameters (an... | def cric__lasso():
""" Lasso Regression
"""
model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002)
# we want to explain the raw probability outputs of the trees
model.predict = lambda X: model.predict_proba(X)[:,1]
return model |
python regression with constraint | def linregress(x, y, return_stats=False):
"""linear regression calculation
Parameters
----
x : independent variable (series)
y : dependent variable (series)
return_stats : returns statistical values as well if required (bool)
Returns
----
list of parameters (an... | def fit_select_best(X, y):
"""
Selects the best fit of the estimators already implemented by choosing the
model with the smallest mean square error metric for the trained values.
"""
models = [fit(X,y) for fit in [fit_linear, fit_quadratic]]
errors = map(lambda model: mse(y, model.predict(X)), m... |
python regression with constraint | def linregress(x, y, return_stats=False):
"""linear regression calculation
Parameters
----
x : independent variable (series)
y : dependent variable (series)
return_stats : returns statistical values as well if required (bool)
Returns
----
list of parameters (an... | def tree_predict(x, root, proba=False, regression=False):
"""Predicts a probabilities/value/label for the sample x.
"""
if isinstance(root, Leaf):
if proba:
return root.probabilities
elif regression:
return root.mean
else:
return root.most_frequen... |
python regression with constraint | def linregress(x, y, return_stats=False):
"""linear regression calculation
Parameters
----
x : independent variable (series)
y : dependent variable (series)
return_stats : returns statistical values as well if required (bool)
Returns
----
list of parameters (an... | def predict(self, X):
"""
Apply transforms to the data, and predict with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
yp ... |
how to make a square plot in python aspect ratio | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | def image_set_aspect(aspect=1.0, axes="gca"):
"""
sets the aspect ratio of the current zoom level of the imshow image
"""
if axes is "gca": axes = _pylab.gca()
e = axes.get_images()[0].get_extent()
axes.set_aspect(abs((e[1]-e[0])/(e[3]-e[2]))/aspect) |
how to make a square plot in python aspect ratio | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | def match_aspect_to_viewport(self):
"""Updates Camera.aspect to match the viewport's aspect ratio."""
viewport = self.viewport
self.aspect = float(viewport.width) / viewport.height |
how to make a square plot in python aspect ratio | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | def is_square_matrix(mat):
"""Test if an array is a square matrix."""
mat = np.array(mat)
if mat.ndim != 2:
return False
shape = mat.shape
return shape[0] == shape[1] |
how to make a square plot in python aspect ratio | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | def isSquare(matrix):
"""Check that ``matrix`` is square.
Returns
=======
is_square : bool
``True`` if ``matrix`` is square, ``False`` otherwise.
"""
try:
try:
dim1, dim2 = matrix.shape
except AttributeError:
dim1, dim2 = _np.array(matrix).shape
... |
how to make a square plot in python aspect ratio | def figsize(x=8, y=7., aspect=1.):
""" manually set the default figure size of plots
::Arguments::
x (float): x-axis size
y (float): y-axis size
aspect (float): aspect ratio scalar
"""
# update rcparams with adjusted figsize params
mpl.rcParams.update({'figure.figsize': (x*as... | def _scaleSinglePoint(point, scale=1, convertToInteger=True):
"""
Scale a single point
"""
x, y = point
if convertToInteger:
return int(round(x * scale)), int(round(y * scale))
else:
return (x * scale, y * scale) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.