anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
python logging highlight colors in log | def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | def print_log(text, *colors):
"""Print a log message to standard error."""
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n") |
python logging highlight colors in log | def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | def clog(color):
"""Same to ``log``, but this one centralizes the message first."""
logger = log(color)
return lambda msg: logger(centralize(msg).rstrip()) |
python logging highlight colors in log | def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | def logv(msg, *args, **kwargs):
"""
Print out a log message, only if verbose mode.
"""
if settings.VERBOSE:
log(msg, *args, **kwargs) |
python logging highlight colors in log | def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | def handle_logging(self):
"""
To allow devs to log as early as possible, logging will already be
handled here
"""
configure_logging(self.get_scrapy_options())
# Disable duplicates
self.__scrapy_options["LOG_ENABLED"] = False
# Now, after log-level is co... |
python logging highlight colors in log | def print_log(value_color="", value_noncolor=""):
"""set the colors for text."""
HEADER = '\033[92m'
ENDC = '\033[0m'
print(HEADER + value_color + ENDC + str(value_noncolor)) | def _debug_log(self, msg):
"""Debug log messages if debug=True"""
if not self.debug:
return
sys.stderr.write('{}\n'.format(msg)) |
python make array to string | def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | def toStringArray(name, a, width = 0):
"""
Returns an array (any sequence of floats, really) as a string.
"""
string = name + ": "
cnt = 0
for i in a:
string += "%4.2f " % i
if width > 0 and (cnt + 1) % width == 0:
string += '\n'
cnt += 1
return string |
python make array to string | def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape) |
python make array to string | def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | def string_list_to_array(l):
"""
Turns a Python unicode string list into a Java String array.
:param l: the string list
:type: list
:rtype: java string array
:return: JB_Object
"""
result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class("java/lang/String"... |
python make array to string | def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | def bytes_to_c_array(data):
"""
Make a C array using the given string.
"""
chars = [
"'{}'".format(encode_escape(i))
for i in decode_escape(data)
]
return ', '.join(chars) + ', 0' |
python make array to string | def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | def _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') |
how to clear cache in python | def __delitem__(self, resource):
"""Remove resource instance from internal cache"""
self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None) | def Flush(self):
"""Flush all items from cache."""
while self._age:
node = self._age.PopLeft()
self.KillObject(node.data)
self._hash = dict() |
how to clear cache in python | def __delitem__(self, resource):
"""Remove resource instance from internal cache"""
self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None) | def delete(self, name):
"""
Deletes the named entry in the cache.
:param name: the name.
:return: true if it is deleted.
"""
if name in self._cache:
del self._cache[name]
self.writeCache()
# TODO clean files
return True
... |
how to clear cache in python | def __delitem__(self, resource):
"""Remove resource instance from internal cache"""
self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None) | def purge_cache(self, object_type):
""" Purge the named cache of all values. If no cache exists for object_type, nothing is done """
if object_type in self.mapping:
cache = self.mapping[object_type]
log.debug("Purging [{}] cache of {} values.".format(object_type, len(cache)))
... |
how to clear cache in python | def __delitem__(self, resource):
"""Remove resource instance from internal cache"""
self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None) | def ExpireObject(self, key):
"""Expire a specific object from cache."""
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
self.KillObject(node.data)
return node.data |
how to clear cache in python | def __delitem__(self, resource):
"""Remove resource instance from internal cache"""
self.__caches[type(resource)].pop(resource.get_cache_internal_key(), None) | def teardown(self):
"""Cleanup cache tables."""
for table_spec in reversed(self._table_specs):
with self._conn:
table_spec.teardown(self._conn) |
how to close all threads in a thread array in python3 | def terminate(self):
"""Terminate all workers and threads."""
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def wait_until_exit(self):
""" Wait until all the threads are finished.
"""
[t.join() for t in self.threads]
self.threads = list() |
how to close all threads in a thread array in python3 | def terminate(self):
"""Terminate all workers and threads."""
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def remove_stopped_threads (self):
"""Remove the stopped threads from the internal thread list."""
self.threads = [t for t in self.threads if t.is_alive()] |
how to close all threads in a thread array in python3 | def terminate(self):
"""Terminate all workers and threads."""
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def stop(self):
"""Stop the resolver threads.
"""
with self.lock:
for dummy in self.threads:
self.queue.put(None) |
how to close all threads in a thread array in python3 | def terminate(self):
"""Terminate all workers and threads."""
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def Stop(self):
"""Stops the process status RPC server."""
self._Close()
if self._rpc_thread.isAlive():
self._rpc_thread.join()
self._rpc_thread = None |
how to close all threads in a thread array in python3 | def terminate(self):
"""Terminate all workers and threads."""
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | def stop(self, timeout=None):
"""Stop the thread."""
logger.debug("docker plugin - Close thread for container {}".format(self._container.name))
self._stopper.set() |
python matplotlib show multiple images | def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | def draw_image(self, ax, image):
"""Process a matplotlib image object and call renderer.draw_image"""
self.renderer.draw_image(imdata=utils.image_to_base64(image),
extent=image.get_extent(),
coordinates="data",
... |
python matplotlib show multiple images | def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | def extent(self):
"""Helper for matplotlib imshow"""
return (
self.intervals[1].pix1 - 0.5,
self.intervals[1].pix2 - 0.5,
self.intervals[0].pix1 - 0.5,
self.intervals[0].pix2 - 0.5,
) |
python matplotlib show multiple images | def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | def add_matplotlib_cmap(cm, name=None):
"""Add a matplotlib colormap."""
global cmaps
cmap = matplotlib_to_ginga_cmap(cm, name=name)
cmaps[cmap.name] = cmap |
python matplotlib show multiple images | def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | def matshow(*args, **kwargs):
"""
imshow without interpolation like as matshow
:param args:
:param kwargs:
:return:
"""
kwargs['interpolation'] = kwargs.pop('interpolation', 'none')
return plt.imshow(*args, **kwargs) |
python matplotlib show multiple images | def show(self, imgs, ax=None):
""" Visualize the persistence image
"""
ax = ax or plt.gca()
if type(imgs) is not list:
imgs = [imgs]
for i, img in enumerate(imgs):
ax.imshow(img, cmap=plt.get_cmap("plasma"))
ax.axis("off") | def sample_colormap(cmap_name, n_samples):
"""
Sample a colormap from matplotlib
"""
colors = []
colormap = cm.cmap_d[cmap_name]
for i in np.linspace(0, 1, n_samples):
colors.append(colormap(i))
return colors |
python minimum of np matrix | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | def Min(a, axis, keep_dims):
"""
Min reduction op.
"""
return np.amin(a, axis=axis if not isinstance(axis, np.ndarray) else tuple(axis),
keepdims=keep_dims), |
python minimum of np matrix | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | def check_precomputed_distance_matrix(X):
"""Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.
"""
tmp = X.copy()
tmp[np.isinf(tmp)] = 1
check_array(tmp) |
python minimum of np matrix | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | def local_minima(img, min_distance = 4):
r"""
Returns all local minima from an image.
Parameters
----------
img : array_like
The image.
min_distance : integer
The minimal distance between the minimas in voxels. If it is less, only the lower minima is returned.
Retur... |
python minimum of np matrix | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | def findMin(arr):
"""
in comparison to argrelmax() more simple and reliable peak finder
"""
out = np.zeros(shape=arr.shape, dtype=bool)
_calcMin(arr, out)
return out |
python minimum of np matrix | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) | def index_nearest(value, array):
"""
expects a _n.array
returns the global minimum of (value-array)^2
"""
a = (array-value)**2
return index(a.min(), a) |
how to create bucket through python scripts | def touch():
"""Create new bucket."""
from .models import Bucket
bucket = Bucket.create()
db.session.commit()
click.secho(str(bucket), fg='green') | def s3(ctx, bucket_name, data_file, region):
"""Use the S3 SWAG backend."""
if not ctx.data_file:
ctx.data_file = data_file
if not ctx.bucket_name:
ctx.bucket_name = bucket_name
if not ctx.region:
ctx.region = region
ctx.type = 's3' |
how to create bucket through python scripts | def touch():
"""Create new bucket."""
from .models import Bucket
bucket = Bucket.create()
db.session.commit()
click.secho(str(bucket), fg='green') | def download_file_from_bucket(self, bucket, file_path, key):
""" Download file from S3 Bucket """
with open(file_path, 'wb') as data:
self.__s3.download_fileobj(bucket, key, data)
return file_path |
how to create bucket through python scripts | def touch():
"""Create new bucket."""
from .models import Bucket
bucket = Bucket.create()
db.session.commit()
click.secho(str(bucket), fg='green') | def download_file(bucket_name, path, target, sagemaker_session):
"""Download a Single File from S3 into a local path
Args:
bucket_name (str): S3 bucket name
path (str): file path within the bucket
target (str): destination directory for the downloaded file.
sagemaker_session (:c... |
how to create bucket through python scripts | def touch():
"""Create new bucket."""
from .models import Bucket
bucket = Bucket.create()
db.session.commit()
click.secho(str(bucket), fg='green') | def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):
"""Creates an AWS Chalice project for deployment to AWS Lambda."""
from canari.commands.create_aws_lambda import create_aws_lambda
create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_acce... |
how to create bucket through python scripts | def touch():
"""Create new bucket."""
from .models import Bucket
bucket = Bucket.create()
db.session.commit()
click.secho(str(bucket), fg='green') | def sync_s3(self):
"""Walk the media/static directories and syncs files to S3"""
bucket, key = self.open_s3()
for directory in self.DIRECTORIES:
for root, dirs, files in os.walk(directory):
self.upload_s3((bucket, key, self.AWS_BUCKET_NAME, directory), root, files, di... |
how to cuont the number of items produced in python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | def cpu_count() -> int:
"""Returns the number of processors on this machine."""
if multiprocessing is None:
return 1
try:
return multiprocessing.cpu_count()
except NotImplementedError:
pass
try:
return os.sysconf("SC_NPROCESSORS_CONF")
except (AttributeError, Valu... |
how to cuont the number of items produced in python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | def count(self, elem):
"""
Return the number of elements equal to elem present in the queue
>>> pdeque([1, 2, 1]).count(1)
2
"""
return self._left_list.count(elem) + self._right_list.count(elem) |
how to cuont the number of items produced in python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | def get_count(self, query):
"""
Returns a number of query results. This is faster than .count() on the query
"""
count_q = query.statement.with_only_columns(
[func.count()]).order_by(None)
count = query.session.execute(count_q).scalar()
return count |
how to cuont the number of items produced in python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | def count_(self):
"""
Returns the number of rows of the main dataframe
"""
try:
num = len(self.df.index)
except Exception as e:
self.err(e, "Can not count data")
return
return num |
how to cuont the number of items produced in python | def count_generator(generator, memory_efficient=True):
"""Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory.
"""
if memory_efficient:
counter = 0
for _ in generator:
counte... | def get_memory_usage():
"""Gets RAM memory usage
:return: MB of memory used by this process
"""
process = psutil.Process(os.getpid())
mem = process.memory_info().rss
return mem / (1024 * 1024) |
how to delete an entry from the dictionary python | def __delitem__(self, key):
"""Remove a variable from this dataset.
"""
del self._variables[key]
self._coord_names.discard(key) | def rm_keys_from_dict(d, keys):
"""
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
"""
# Loop for each key given
for key in keys:
# Is the key in the ... |
how to delete an entry from the dictionary python | def __delitem__(self, key):
"""Remove a variable from this dataset.
"""
del self._variables[key]
self._coord_names.discard(key) | def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists.
"""
for d in dict_list:
d.pop(key, None) |
how to delete an entry from the dictionary python | def __delitem__(self, key):
"""Remove a variable from this dataset.
"""
del self._variables[key]
self._coord_names.discard(key) | def remove(self, entry):
"""Removes an entry"""
try:
list = self.cache[entry.key]
list.remove(entry)
except:
pass |
how to delete an entry from the dictionary python | def __delitem__(self, key):
"""Remove a variable from this dataset.
"""
del self._variables[key]
self._coord_names.discard(key) | def delete(self, key_name):
"""Delete the key and return true if the key was deleted, else false
"""
self.db.remove(Query().name == key_name)
return self.get(key_name) == {} |
how to delete an entry from the dictionary python | def __delitem__(self, key):
"""Remove a variable from this dataset.
"""
del self._variables[key]
self._coord_names.discard(key) | def __delitem__(self, key):
"""Remove item with given key from the mapping.
Runs in O(n), unless removing last item, then in O(1).
"""
index, value = self._dict.pop(key)
key2, value2 = self._list.pop(index)
assert key == key2
assert value is value2
self._fix_indices_after_delete(index) |
python name of parent window | def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | def title(self):
""" The title of this window """
with switch_window(self._browser, self.name):
return self._browser.title |
python name of parent window | def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | def parent(self, index):
"""Return the index of the parent for a given index of the
child. Unfortunately, the name of the method has to be parent,
even though a more verbose name like parentIndex, would avoid
confusion about what parent actually is - an index or an item.
"""
... |
python name of parent window | def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | def top_class(self):
"""reference to a parent class, which contains this class and defined
within a namespace
if this class is defined under a namespace, self will be returned"""
curr = self
parent = self.parent
while isinstance(parent, class_t):
curr = paren... |
python name of parent window | def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | def find_root(self):
""" Traverse parent refs to top. """
cmd = self
while cmd.parent:
cmd = cmd.parent
return cmd |
python name of parent window | def get_window(self):
"""
Returns the object's parent window. Returns None if no window found.
"""
x = self
while not x._parent == None and \
not isinstance(x._parent, Window):
x = x._parent
return x._parent | def _get_node_parent(self, age, pos):
"""Get the parent node of node, whch is located in tree's node list.
Returns:
object: The parent node.
"""
return self.nodes[age][int(pos / self.comp)] |
how to determine number of bins in a histogram python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | def shape(self) -> Tuple[int, ...]:
"""Shape of histogram's data.
Returns
-------
One-element tuple with the number of bins along each axis.
"""
return tuple(bins.bin_count for bins in self._binnings) |
how to determine number of bins in a histogram python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | def get_bin_indices(self, values):
"""Returns index tuple in histogram of bin which contains value"""
return tuple([self.get_axis_bin_index(values[ax_i], ax_i)
for ax_i in range(self.dimensions)]) |
how to determine number of bins in a histogram python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | def inverseHistogram(hist, bin_range):
"""sample data from given histogram and min, max values within range
Returns:
np.array: data that would create the same histogram as given
"""
data = hist.astype(float) / np.min(hist[np.nonzero(hist)])
new_data = np.empty(shape=np.sum(data, dtype=int))... |
how to determine number of bins in a histogram python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | def PyplotHistogram():
"""
=============================================================
Demo of the histogram (hist) function with multiple data sets
=============================================================
Plot histogram with multiple sample sets and demonstrate:
* Use of legend wit... |
how to determine number of bins in a histogram python | def _histplot_bins(column, bins=100):
"""Helper to get bins for histplot."""
col_min = np.min(column)
col_max = np.max(column)
return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1)) | def vals2bins(vals,res=100):
"""Maps values to bins
Args:
values (list or list of lists) - list of values to map to colors
res (int) - resolution of the color map (default: 100)
Returns:
list of numbers representing bins
"""
# flatten if list of lists
if any(isinstance(el, list) for ... |
python not showing up in documents | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | def setup(app):
"""Allow this package to be used as Sphinx extension.
This is also called from the top-level ``__init__.py``.
:type app: sphinx.application.Sphinx
"""
from .patches import patch_django_for_autodoc
# When running, make sure Django doesn't execute querysets
patch_django_for_a... |
python not showing up in documents | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)")
return True
else:
... |
python not showing up in documents | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | def _generate(self):
"""Parses a file or directory of files into a set of ``Document`` objects."""
doc_count = 0
for fp in self.all_files:
for doc in self._get_docs_for_path(fp):
yield doc
doc_count += 1
if doc_count >= self.max_docs:
... |
python not showing up in documents | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | def get_soup(page=''):
"""
Returns a bs4 object of the page requested
"""
content = requests.get('%s/%s' % (BASE_URL, page)).text
return BeautifulSoup(content) |
python not showing up in documents | def prepare(doc):
"""Sets the caption_found and plot_found variables to False."""
doc.caption_found = False
doc.plot_found = False
doc.listings_counter = 0 | def process_docstring(app, what, name, obj, options, lines):
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following set... |
how to determine the path of a directory in python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | def get_system_root_directory():
"""
Get system root directory (application installed root directory)
Returns
-------
string
A full path
"""
root = os.path.dirname(__file__)
root = os.path.dirname(root)
root = os.path.abspath(root)
return root |
how to determine the path of a directory in python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | def get_base_dir():
"""
Return the base directory
"""
return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] |
how to determine the path of a directory in python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | def relative_path(path):
"""
Return the given path relative to this file.
"""
return os.path.join(os.path.dirname(__file__), path) |
how to determine the path of a directory in python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | def path(self):
"""
Return the path always without the \\?\ prefix.
"""
path = super(WindowsPath2, self).path
if path.startswith("\\\\?\\"):
return path[4:]
return path |
how to determine the path of a directory in python | def path_for_import(name):
"""
Returns the directory path for the given package or module.
"""
return os.path.dirname(os.path.abspath(import_module(name).__file__)) | def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location |
python numpy array iterable | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def _npiter(arr):
"""Wrapper for iterating numpy array"""
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c |
python numpy array iterable | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def recarray(self):
"""Returns data as :class:`numpy.recarray`."""
return numpy.rec.fromrecords(self.records, names=self.names) |
python numpy array iterable | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def is_iterable(value):
"""must be an iterable (list, array, tuple)"""
return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value |
python numpy array iterable | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object
"""Convert an array like object to the NPY format.
To understand better what an array like object is see:
https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays
... |
python numpy array iterable | def A(*a):
"""convert iterable object into numpy array"""
return np.array(a[0]) if len(a)==1 else [np.array(o) for o in a] | def array(self):
"""
return the underlying numpy array
"""
return np.arange(self.start, self.stop, self.step) |
python open symbolic link on windows | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... | def symlink(source, destination):
"""Create a symbolic link"""
log("Symlinking {} as {}".format(source, destination))
cmd = [
'ln',
'-sf',
source,
destination,
]
subprocess.check_call(cmd) |
python open symbolic link on windows | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... | def replacing_symlink(source, link_name):
"""Create symlink that overwrites any existing target.
"""
with make_tmp_name(link_name) as tmp_link_name:
os.symlink(source, tmp_link_name)
replace_file_or_dir(link_name, tmp_link_name) |
python open symbolic link on windows | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... |
python open symbolic link on windows | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... | def is_symlink(self):
"""
Whether this path is a symbolic link.
"""
try:
return S_ISLNK(self.lstat().st_mode)
except OSError as e:
if e.errno != ENOENT:
raise
# Path doesn't exist
return False |
python open symbolic link on windows | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... | def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) |
how to drop all columns with string values python | def _drop_str_columns(df):
"""
Parameters
----------
df : DataFrame
Returns
-------
"""
str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())
str_column_names = list(map(lambda pair: pair[0], str_columns))
return df.drop(str_column_names) | def remove_columns(self, data, columns):
""" This method removes columns in data
:param data: original Pandas dataframe
:param columns: list of columns to remove
:type data: pandas.DataFrame
:type columns: list of strings
:returns: Pandas dataframe with removed columns
... |
how to drop all columns with string values python | def _drop_str_columns(df):
"""
Parameters
----------
df : DataFrame
Returns
-------
"""
str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())
str_column_names = list(map(lambda pair: pair[0], str_columns))
return df.drop(str_column_names) | def cols_strip(df,col_list, dest = False):
""" Performs str.strip() a column of a DataFrame
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to strip
dest - bool, default False
Whether to apply the result to the DataFrame or retur... |
how to drop all columns with string values python | def _drop_str_columns(df):
"""
Parameters
----------
df : DataFrame
Returns
-------
"""
str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())
str_column_names = list(map(lambda pair: pair[0], str_columns))
return df.drop(str_column_names) | def del_Unnamed(df):
"""
Deletes all the unnamed columns
:param df: pandas dataframe
"""
cols_del=[c for c in df.columns if 'Unnamed' in c]
return df.drop(cols_del,axis=1) |
how to drop all columns with string values python | def _drop_str_columns(df):
"""
Parameters
----------
df : DataFrame
Returns
-------
"""
str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())
str_column_names = list(map(lambda pair: pair[0], str_columns))
return df.drop(str_column_names) | def drop_column(self, tablename: str, fieldname: str) -> int:
"""Drops (deletes) a column from an existing table."""
sql = "ALTER TABLE {} DROP COLUMN {}".format(tablename, fieldname)
log.info(sql)
return self.db_exec_literal(sql) |
how to drop all columns with string values python | def _drop_str_columns(df):
"""
Parameters
----------
df : DataFrame
Returns
-------
"""
str_columns = filter(lambda pair: pair[1].char == 'S', df._gather_dtypes().items())
str_column_names = list(map(lambda pair: pair[0], str_columns))
return df.drop(str_column_names) | def clean_column_names(df: DataFrame) -> DataFrame:
"""
Strip the whitespace from all column names in the given DataFrame
and return the result.
"""
f = df.copy()
f.columns = [col.strip() for col in f.columns]
return f |
python out of range float values are not json compliant | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | def parse_reading(val: str) -> Optional[float]:
""" Convert reading value to float (if possible) """
try:
return float(val)
except ValueError:
logging.warning('Reading of "%s" is not a number', val)
return None |
python out of range float values are not json compliant | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | def default_number_converter(number_str):
"""
Converts the string representation of a json number into its python object equivalent, an
int, long, float or whatever type suits.
"""
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()
# FIXME: this handles a ... |
python out of range float values are not json compliant | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | def test_value(self, value):
"""Test if value is an instance of float."""
if not isinstance(value, float):
raise ValueError('expected float value: ' + str(type(value))) |
python out of range float values are not json compliant | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | def _validate_type_scalar(self, value):
""" Is not a list or a dict """
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True |
python out of range float values are not json compliant | def __get_float(section, name):
"""Get the forecasted float from json section."""
try:
return float(section[name])
except (ValueError, TypeError, KeyError):
return float(0) | def filter_float(n: Node, query: str) -> float:
"""
Filter and ensure that the returned value is of type int.
"""
return _scalariter2item(n, query, float) |
python output colors from a string | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | def stringc(text, color):
"""
Return a string with terminal colors.
"""
if has_colors:
text = str(text)
return "\033["+codeCodes[color]+"m"+text+"\033[0m"
else:
return text |
python output colors from a string | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | def color_string(color, string):
"""
Colorizes a given string, if coloring is available.
"""
if not color_available:
return string
return color + string + colorama.Fore.RESET |
python output colors from a string | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | def colorize(string, color, *args, **kwargs):
"""
Implements string formatting along with color specified in colorama.Fore
"""
string = string.format(*args, **kwargs)
return color + string + colorama.Fore.RESET |
python output colors from a string | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | def cprint(string, fg=None, bg=None, end='\n', target=sys.stdout):
"""Print a colored string to the target handle.
fg and bg specify foreground- and background colors, respectively. The
remaining keyword arguments are the same as for Python's built-in print
function. Colors are returned to their defaul... |
python output colors from a string | def write_color(string, name, style='normal', when='auto'):
""" Write the given colored string to standard out. """
write(color(string, name, style, when)) | def set(cls, color):
"""
Sets the terminal to the passed color.
:param color: one of the availabe colors.
"""
sys.stdout.write(cls.colors.get(color, cls.colors['RESET'])) |
python pass list to format | def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value) | def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",'
cmd = cmd[:-1]
return cmd |
python pass list to format | def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value) | def list_to_csv(value):
"""
Converts list to string with comma separated values. For string is no-op.
"""
if isinstance(value, (list, tuple, set)):
value = ",".join(value)
return value |
python pass list to format | def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value) | def list_i2str(ilist):
"""
Convert an integer list into a string list.
"""
slist = []
for el in ilist:
slist.append(str(el))
return slist |
python pass list to format | def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value) | def comma_delimited_to_list(list_param):
"""Convert comma-delimited list / string into a list of strings
:param list_param: Comma-delimited string
:type list_param: str | unicode
:return: A list of strings
:rtype: list
"""
if isinstance(list_param, list):
return list_param
if is... |
python pass list to format | def list_formatter(handler, item, value):
"""Format list."""
return u', '.join(str(v) for v in value) | def _return_comma_list(self, l):
""" get a list and return a string with comma separated list values
Examples ['to', 'ta'] will return 'to,ta'.
"""
if isinstance(l, (text_type, int)):
return l
if not isinstance(l, list):
raise TypeError(l, ' should be a l... |
how to flush text files in python | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def flush(self):
"""Ensure contents are written to file."""
for name in self.item_names:
item = self[name]
item.flush()
self.file.flush() |
how to flush text files in python | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def flush(self):
""" Force commit changes to the file and stdout """
if not self.nostdout:
self.stdout.flush()
if self.file is not None:
self.file.flush() |
how to flush text files in python | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def flush():
"""Try to flush all stdio buffers, both from python and from C."""
try:
sys.stdout.flush()
sys.stderr.flush()
except (AttributeError, ValueError, IOError):
pass # unsupported
try:
libc.fflush(None)
except (AttributeError, ValueError, IOError):
pa... |
how to flush text files in python | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def flush(self):
"""
Ensure all logging output has been flushed
"""
if len(self._buffer) > 0:
self.logger.log(self.level, self._buffer)
self._buffer = str() |
how to flush text files in python | def file_writelines_flush_sync(path, lines):
"""
Fill file at @path with @lines then flush all buffers
(Python and system buffers)
"""
fp = open(path, 'w')
try:
fp.writelines(lines)
flush_sync_file_object(fp)
finally:
fp.close() | def flush(self):
"""
Flush all unwritten data to disk.
"""
if self._cache_modified_count > 0:
self.storage.write(self.cache)
self._cache_modified_count = 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.