code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return _handle_http_errors(
self.client.request(
'HEAD', timeout=self._TIMEOUT, **client_kwargs)).headers | def _head(self, client_kwargs) | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | 9.745249 | 11.473329 | 0.849383 |
# Get object part
response = self._client.request(
'GET', self.name, headers=dict(Range=self._http_range(start, end)),
timeout=self._TIMEOUT)
if response.status_code == 416:
# EOF
return b''
# Get object content
return _h... | def _read_range(self, start, end=0) | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | 6.462977 | 6.697308 | 0.965011 |
return _handle_http_errors(
self._client.request(
'GET', self.name, timeout=self._TIMEOUT)).content | def _readall(self) | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | 14.038928 | 18.173658 | 0.772488 |
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = self._seek
start = end - len(buffer)
# Clear buffer
self._write_buffer = bytearray()
... | def flush(self) | Flush the write buffers of the stream if applicable and
save the object on the cloud. | 7.725337 | 7.606868 | 1.015574 |
if not self._seekable:
raise UnsupportedOperation('seek')
# Flush before moving position
self.flush()
return self._update_seek(offset, whence) | def seek(self, offset, whence=SEEK_SET) | Change the stream position to the given byte offset.
Args:
offset (int): Offset is interpreted relative to the position
indicated by whence.
whence (int): The default value for whence is SEEK_SET.
Values for whence are:
SEEK_SET or 0 – sta... | 7.802305 | 9.291028 | 0.839768 |
# Flush buffer to specified range
buffer = self._get_buffer()
start = self._buffer_size * (self._seek - 1)
end = start + len(buffer)
future = self._workers.submit(
self._flush_range, buffer=buffer, start=start, end=end)
self._write_futures.append(fut... | def _flush(self) | Flush the write buffers of the stream if applicable.
In write mode, send the buffer content to the cloud object. | 4.958143 | 4.962717 | 0.999078 |
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | def _update_size(self, size, future) | Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size... | 16.024696 | 14.893603 | 1.075945 |
# On first call, Get file size if exists
with self._size_lock:
if not self._size_synched:
self._size_synched = True
try:
self._size = self.raw._size
except (ObjectNotFoundError, UnsupportedOperation):
... | def _flush_range(self, buffer, start, end) | Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer posi... | 7.319392 | 7.060374 | 1.036686 |
offset = 0
while True:
r = False
for elem in q.limit(chunk).offset(offset):
r = True
yield elem
offset += chunk
if not r:
break | def _page(q, chunk=1000) | Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world. | 4.256984 | 3.655195 | 1.164639 |
config_paths = context.config.get_main_option('fedmsg_config_dir')
filenames = fedmsg.config._gather_configs_in(config_paths)
config = fedmsg.config.load_config(filenames=filenames)
make_processors(**config)
engine = op.get_bind().engine
m.init(engine=engine)
for msg in _page(m.Mess... | def upgrade() | This takes a *really* long time. Like, hours. | 4.017689 | 3.961338 | 1.014225 |
status, output = commands.getstatusoutput(cmd)
if status:
print(output)
return status == 0 | def run(cmd) | Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use. | 4.005548 | 4.04964 | 0.989112 |
# TODO -- un-hardcode this filename when I need to run this next time.
#filename = "../myfile.json"
filename = "../datanommer-dump-2012-11-22.json"
print("Reading %s" % filename)
progress = progressbar.ProgressBar(widgets=[
progressbar.widgets.Percentage(),
progressbar.widgets.... | def read_datanommer_entries_from_filedump() | Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json | 4.061167 | 3.820375 | 1.063028 |
raise NotImplementedError | def create_or_update(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Tuple[object, bool] | Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of m... | 289.268677 | 1,340.914429 | 0.215725 |
raise NotImplementedError | def maybe_convert_values(self,
identifier: Identifier,
data: Dict[str, Any],
) -> Dict[str, Any] | Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instan... | 497.803558 | 2,426.197998 | 0.205178 |
with _handle_azure_exception():
self.client.copy_file(
copy_source=(other_system or self)._format_src_url(src, self),
**self.get_client_kwargs(dst)) | def copy(self, src, dst, other_system=None) | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system. | 8.94652 | 8.229467 | 1.087132 |
# Remove query string from URL
path = path.split('?', 1)[0]
share_name, relpath = self.split_locator(path)
kwargs = dict(share_name=share_name)
# Directory
if relpath and relpath[-1] == '/':
kwargs['directory_name'] = relpath.rstrip('/')
# ... | def get_client_kwargs(self, path) | Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args | 3.46533 | 3.801442 | 0.911583 |
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
result = self.client.get_file_properties(**client_kwargs)
# Directory
elif 'directory_name' in client_kwargs:
result = self.client.get_directory_prope... | def _head(self, client_kwargs) | Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | 2.841667 | 3.088861 | 0.919973 |
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | def _list_locators(self) | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | 9.927395 | 13.959636 | 0.71115 |
client_kwargs = self._update_listing_client_kwargs(
client_kwargs, max_request_entries)
with _handle_azure_exception():
for obj in self.client.list_directories_and_files(**client_kwargs):
yield (obj.name, self._model_to_dict(obj),
... | def _list_objects(self, client_kwargs, max_request_entries) | Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool | 4.820655 | 4.522659 | 1.06589 |
with _handle_azure_exception():
# Directory
if 'directory_name' in client_kwargs:
return self.client.create_directory(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'])
# S... | def _make_dir(self, client_kwargs) | Make a directory.
args:
client_kwargs (dict): Client arguments. | 3.526011 | 3.400434 | 1.03693 |
with _handle_azure_exception():
# File
if 'file_name' in client_kwargs:
return self.client.delete_file(
share_name=client_kwargs['share_name'],
directory_name=client_kwargs['directory_name'],
file_name=c... | def _remove(self, client_kwargs) | Remove an object.
args:
client_kwargs (dict): Client arguments. | 1.946468 | 1.929323 | 1.008886 |
self._client.update_range(data=data, **kwargs) | def _update_range(self, data, **kwargs) | Update range with data
Args:
data (bytes): data. | 8.105295 | 7.564007 | 1.071561 |
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('update', {}).get('submitter')
return username | def handle_bodhi(msg) | Given a bodhi message, return the FAS username. | 5.873066 | 4.852651 | 1.21028 |
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | def handle_wiki(msg) | Given a wiki message, return the FAS username. | 7.027679 | 5.893205 | 1.192505 |
if storage:
return True
split_url = url.split('://', 1)
if len(split_url) == 2 and split_url[0].lower() != 'file':
return True
return False | def is_storage(url, storage=None) | Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is lo... | 2.685886 | 3.534032 | 0.760006 |
if not hasattr(path, 'read'):
path = fsdecode(path).replace('\\', '/')
return path, is_storage(path)
return path, True | def format_and_is_storage(path) | Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage). | 5.336082 | 5.00542 | 1.066061 |
def decorate(cos_function):
@wraps(cos_function)
def decorated(path, *args, **kwargs):
# Handles path-like objects
path = fsdecode(path).replace('\\', '/')
# Storage object: Handle with Cloud object storage
# function
... | def equivalent_to(std_function) | Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function | 6.883046 | 5.820703 | 1.182511 |
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | def _handle_oss_error() | Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error. | 6.454247 | 7.134343 | 0.904673 |
copy_source = self.get_client_kwargs(src)
copy_destination = self.get_client_kwargs(dst)
with _handle_oss_error():
bucket = self._get_bucket(copy_destination)
bucket.copy_object(
source_bucket_name=copy_source['bucket_name'],
sourc... | def copy(self, src, dst, other_system=None) | Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused. | 3.305259 | 3.462592 | 0.954562 |
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | def _get_client(self) | OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client | 10.727146 | 7.027585 | 1.526434 |
return (
# OSS Scheme
# - oss://<bucket>/<key>
'oss://',
# URL (With common aliyuncs.com endpoint):
# - http://<bucket>.oss-<region>.aliyuncs.com/<key>
# - https://<bucket>.oss-<region>.aliyuncs.com/<key>
# Note: "os... | def _get_roots(self) | Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots | 8.809064 | 8.091348 | 1.088702 |
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | def _get_bucket(self, client_kwargs) | Get bucket object.
Returns:
oss2.Bucket | 8.135517 | 8.901894 | 0.913909 |
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in ('x-oss-object-type', 'type'):
try:
return header.pop(key) == 'Symlink'
except KeyError:
continue
return False | def islink(self, path=None, header=None) | Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink. | 4.912711 | 4.802712 | 1.022903 |
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.head_object(
key=client_kwargs['key']).headers
# Bucket
return bucket.get_bucket_info().... | def _head(self, client_kwargs) | Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header. | 4.6304 | 5.228666 | 0.88558 |
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.put_object(
key=client_kwargs['key'], data=b'')
# Bucket
return bucket.create_bucket() | def _make_dir(self, client_kwargs) | Make a directory.
args:
client_kwargs (dict): Client arguments. | 4.672074 | 4.67108 | 1.000213 |
with _handle_oss_error():
bucket = self._get_bucket(client_kwargs)
# Object
if 'key' in client_kwargs:
return bucket.delete_object(key=client_kwargs['key'])
# Bucket
return bucket.delete_bucket() | def _remove(self, client_kwargs) | Remove an object.
args:
client_kwargs (dict): Client arguments. | 4.077123 | 4.152565 | 0.981833 |
return {attr: value for attr, value in model.__dict__.items()
if not attr.startswith('_') and attr not in ignore} | def _model_to_dict(model, ignore) | Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version. | 3.174731 | 4.294225 | 0.739302 |
with _handle_oss_error():
response = _oss.Service(
self.client, endpoint=self._endpoint).list_buckets()
for bucket in response.buckets:
yield bucket.name, self._model_to_dict(bucket, ('name',)) | def _list_locators(self) | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | 11.403569 | 15.132197 | 0.753596 |
kwargs = dict()
if max_request_entries:
kwargs['max_keys'] = max_request_entries
bucket = self._get_bucket(client_kwargs)
while True:
with _handle_oss_error():
response = bucket.list_objects(prefix=path, **kwargs)
if not res... | def _list_objects(self, client_kwargs, path, max_request_entries) | Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object ... | 4.362694 | 4.565774 | 0.955521 |
if start >= self._size:
# EOF. Do not detect using 416 (Out of range) error, 200 returned.
return bytes()
# Get object bytes range
with _handle_oss_error():
response = self._bucket.get_object(key=self._key, headers=dict(
Range=self._h... | def _read_range(self, start, end=0) | Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read | 10.45919 | 10.958051 | 0.954475 |
with _handle_oss_error():
return self._bucket.get_object(key=self._key).read() | def _readall(self) | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content | 10.185246 | 12.103359 | 0.841522 |
with _handle_oss_error():
self._bucket.put_object(key=self._key, data=buffer.tobytes()) | def _flush(self, buffer) | Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content. | 9.062475 | 9.649824 | 0.939134 |
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
self._key).upload_id
# Upload part with workers
response = self._workers.submit(
... | def _flush(self) | Flush the write buffers of the stream. | 4.563211 | 4.411833 | 1.034312 |
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future in self._write_futures]
# Complete multipart upload
with _handle_oss_error():
try:
... | def _close_writable(self) | Close the object in write mode. | 3.931991 | 4.037951 | 0.973759 |
# Handles file-like objects:
if hasattr(file, 'read'):
with _text_io_wrapper(file, mode, encoding, errors, newline) as wrapped:
yield wrapped
return
# Handles path-like objects
file = fsdecode(file).replace('\\', '/')
# Storage object
if is_storage(file, storag... | def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs) | Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file... | 3.729394 | 3.990847 | 0.934487 |
# Text mode, if not already a text stream
# That has the "encoding" attribute
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
# Bina... | def _text_io_wrapper(stream, mode, encoding, errors, newline) | Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines | 5.714464 | 5.975939 | 0.956245 |
model_identifiers = ctx['model_identifiers'][model_class_name]
if not model_identifiers:
return 'None'
idx = random.randrange(0, len(model_identifiers))
return '"%s(%s)"' % (model_class_name, model_identifiers[idx]) | def random_model(ctx, model_class_name) | Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
... | 3.158728 | 3.553232 | 0.888973 |
model_identifiers = ctx['model_identifiers'][model_class_name]
num_models = random.randint(min_count, min(max_count, len(model_identifiers)))
if num_models == 0:
return '[]'
added = set()
while len(added) < num_models:
idx = random.randrange(0, len(model_identifiers))
a... | def random_models(ctx, model_class_name, min_count=0, max_count=3) | Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render... | 2.551736 | 2.863595 | 0.891095 |
entries = 0
next_values = []
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
objects = self._list_locators()
# Sub directory
else:
objects = self._list_objec... | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None) | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... | 3.867523 | 4.00946 | 0.964599 |
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | def hash_key(self, key) | "Hash" all keys in a timerange to the same value. | 7.663726 | 7.275071 | 1.053423 |
if not self._loaded:
self._load_data()
# build up a directed acyclic graph to determine the model instantiation order
dag = nx.DiGraph()
for model_class_name, dependencies in self.relationships.items():
dag.add_node(model_class_name)
for dep ... | def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object] | Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model inst... | 3.247988 | 3.042427 | 1.067565 |
if not identifiers:
return identifiers
def _create_or_update(identifier):
data = self._cache[identifier.key]
return self.factory.create_or_update(identifier, data)[0]
if isinstance(identifiers, Identifier):
return _create_or_update(ident... | def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]) | Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances. | 2.780395 | 2.550265 | 1.090238 |
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model fixture file, read it into the cache and get the
# list of identifier keys from it
for fixtures_dir in self.fixture_di... | def _load_data(self) | Load all fixtures from :attr:`fixtures_dir` | 4.842161 | 4.595031 | 1.053782 |
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
fixture_data, self.relationships[class_name] = self._post_process_yaml_data(
yaml.load(rendered_yaml),
self.factor... | def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]) | Load fixtures from the given filename | 4.734944 | 4.153512 | 1.139986 |
rv = {}
relationships = set()
if not fixture_data:
return rv, relationships
for identifier_id, data in fixture_data.items():
new_data = {}
for col_name, value in data.items():
if col_name not in relationship_columns:
... | def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]] | Convert and normalize identifier strings to Identifiers, as well as determine
class relationships. | 2.51217 | 2.2929 | 1.09563 |
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.seed(1234)
env.globals['faker'] = faker
... | def _ensure_env(self, env: Union[jinja2.Environment, None]) | Make sure the jinja environment is minimally configured. | 2.465731 | 2.268242 | 1.087067 |
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['random_model'] = jinja2.contextfunction(random_model)
ctx['random_models'] = jinj... | def _preloading_env(self) | A "stripped" jinja environment. | 3.504279 | 3.010525 | 1.164009 |
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
# Gets storage information
with _MOUNT_LOCK:
for root in MOUNTED:
if ((isinstance(root, Pattern) and root.match(name)) or
(not isinstance(root, Pattern) and... | def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs) | Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client ... | 3.684413 | 3.804776 | 0.968365 |
# Tries to infer storage from name
if storage is None:
if '://' in name:
storage = name.split('://', 1)[0].lower()
# Alias HTTPS to HTTP
storage = 'http' if storage == 'https' else storage
else:
raise ValueError(
'No storage sp... | def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None) | Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
... | 3.989393 | 4.024937 | 0.991169 |
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | def _system_parameters(**kwargs) | Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments. | 6.366413 | 6.394392 | 0.995624 |
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, c... | def manual_argument_parsing(argv) | sadness because argparse doesn't quite do what we want. | 3.02558 | 2.962151 | 1.021413 |
def entry(argv=None):
argv = argv if argv is not None else sys.argv[1:]
return main(
tuple(patches) + ('--', original_entry_point) + tuple(argv)
)
return entry | def make_entry_point(patches, original_entry_point) | Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip' | 4.466936 | 4.990387 | 0.895108 |
if self._client is None:
self._client = self._get_client()
return self._client | def client(self) | Storage client
Returns:
client | 3.481201 | 4.639484 | 0.750342 |
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is None:
raise
return assume_exists
return True | def exists(self, path=None, client_kwargs=None, assume_exists=None) | Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
... | 3.645016 | 3.488755 | 1.04479 |
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | def getctime(self, path=None, client_kwargs=None, header=None) | Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | 6.815568 | 9.029286 | 0.754829 |
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | def getmtime(self, path=None, client_kwargs=None, header=None) | Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | 6.503948 | 8.389962 | 0.775206 |
for key in keys:
try:
date_value = header.pop(key)
except KeyError:
continue
try:
# String to convert
return to_timestamp(parse(date_value))
except TypeError:
# Already number... | def _get_time(header, keys, name) | Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch | 6.436842 | 7.439194 | 0.865261 |
return self._getsize_from_header(self.head(path, client_kwargs, header)) | def getsize(self, path=None, client_kwargs=None, header=None) | Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes. | 5.537153 | 7.786792 | 0.711096 |
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
continue
else:
raise UnsupportedOperation('getsize') | def _getsize_from_header(self, header) | Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes. | 10.709393 | 11.073849 | 0.967089 |
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return True
if path[-1] == '/' or self.is_locator(relative, relative=True):
exists = self.exists(path=path, client_kwargs=client_kwargs,
... | def isdir(self, path=None, client_kwargs=None, virtual_dir=True,
assume_exists=None) | Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists virtually
if an object path if not exists as a specific object.
assume_exi... | 6.179873 | 6.208933 | 0.99532 |
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return False
if path[-1] != '/' and not self.is_locator(path, relative=True):
return self.exists(path=path, client_kwargs=client_kwargs,
... | def isfile(self, path=None, client_kwargs=None, assume_exists=None) | Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
... | 5.754293 | 6.559612 | 0.877231 |
if header is not None:
return header
elif client_kwargs is None:
client_kwargs = self.get_client_kwargs(path)
return self._head(client_kwargs) | def head(self, path=None, client_kwargs=None, header=None) | Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header. | 3.430662 | 4.097953 | 0.837165 |
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(root, Pattern):
match = root.match(path)
if not match:
continue
root = match.group(0)
# Split root and relative... | def relpath(self, path) | Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path. | 6.483225 | 6.671912 | 0.971719 |
if not relative:
path = self.relpath(path)
# Bucket is the main directory
return path and '/' not in path.rstrip('/') | def is_locator(self, path, relative=False) | Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator. | 11.75071 | 14.478294 | 0.811609 |
relative = self.relpath(path)
try:
locator, tail = relative.split('/', 1)
except ValueError:
locator = relative
tail = ''
return locator, tail | def split_locator(self, path) | Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path. | 4.285441 | 4.833155 | 0.886676 |
if not relative:
path = self.relpath(path)
self._make_dir(self.get_client_kwargs(self.ensure_dir_path(
path, relative=True))) | def make_dir(self, path, relative=False) | Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root. | 7.629674 | 8.594769 | 0.887711 |
if not relative:
path = self.relpath(path)
self._remove(self.get_client_kwargs(path)) | def remove(self, path, relative=False) | Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root. | 7.239601 | 9.361374 | 0.773348 |
if not relative:
rel_path = self.relpath(path)
else:
rel_path = path
# Locator
if self.is_locator(rel_path, relative=True):
path = path.rstrip('/')
# Directory
elif rel_path:
path = path.rstrip('/') + '/'
... | def ensure_dir_path(self, path, relative=False) | Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path | 5.037795 | 4.85045 | 1.038624 |
entries = 0
max_request_entries_arg = None
if not relative:
path = self.relpath(path)
# From root
if not path:
locators = self._list_locators()
# Yields locators
if first_level:
for locator in locators:
... | def list_objects(self, path='', relative=False, first_level=False,
max_request_entries=None) | List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... | 3.158224 | 3.180682 | 0.992939 |
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
("st_mtime", 0), ("st_ctime", 0)))
# Pop... | def stat(self, path=None, client_kwargs=None, header=None) | Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object | 3.264641 | 3.379058 | 0.966139 |
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warning("No db uri given. Using %r" % uri)
if uri and not engine:
engine = create_engine(uri)
if 'sqlite' in en... | def init(uri=None, alembic_ini=None, engine=None, create=False) | Initialize a connection. Create tables if requested. | 3.333348 | 3.289465 | 1.01334 |
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers... | def add(envelope) | Take a dict-like fedmsg envelope and store the headers and message
in the table. | 3.592633 | 3.570251 | 1.006269 |
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
except IntegrityError:
... | def get_or_create(cls, name) | Return the instance of the class with the specified name. If it doesn't
already exist, create it. | 2.543593 | 2.614149 | 0.97301 |
users = users or []
not_users = not_users or []
packages = packages or []
not_packs = not_packages or []
categories = categories or []
not_cats = not_categories or []
topics = topics or []
not_topics = not_topics or []
contains = contains... | def grep(cls, start=None, end=None,
page=1, rows_per_page=100,
order="asc", msg_id=None,
users=None, not_users=None,
packages=None, not_packages=None,
categories=None, not_categories=None,
topics=None, not_topics=None,
contains=N... | Flexible query interface for messages.
Arguments are filters. start and end should be :mod:`datetime` objs.
Other filters should be lists of strings. They are applied in a
conjunctive-normal-form (CNF) kind of way
for example, the following::
users = ['ralph', 'lmacken']
... | 2.037143 | 2.079441 | 0.979659 |
system = get_instance(path)
# User may use directory path without trailing '/'
# like on standard file systems
return system.isdir(system.ensure_dir_path(path)) | def isdir(path) | Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists. | 20.663582 | 26.04598 | 0.79335 |
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | def relpath(path, start=None) | Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a di... | 10.010911 | 12.221991 | 0.81909 |
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1... | def samefile(path1, path2) | Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory. | 4.219627 | 4.391266 | 0.960914 |
relative = get_instance(path).relpath(path)
drive = path.rsplit(relative, 1)[0]
if drive and not drive[-2:] == '//':
# Keep "/" tail side
relative = '/' + relative
drive = drive.rstrip('/')
return drive, relative | def splitdrive(path) | Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.splitdrive".
Args:
path (p... | 8.652061 | 11.435637 | 0.756588 |
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
... | def handle_os_exceptions() | Handles pycosio exceptions and raise standard OS exceptions. | 4.366999 | 3.767001 | 1.159277 |
return [name.rstrip('/') for name, _ in
get_instance(path).list_objects(path, first_level=True)] | def listdir(path='.') | Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names. | 15.617628 | 18.705351 | 0.834928 |
system = get_instance(name)
# Checks if directory not already exists
if not exist_ok and system.isdir(system.ensure_dir_path(name)):
raise ObjectExistsError("File exists: '%s'" % name)
# Create directory
system.make_dir(name) | def makedirs(name, mode=0o777, exist_ok=False) | Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-like object): Path or URL.
mode (int): The mode param... | 6.870349 | 8.15693 | 0.842271 |
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0] + parent_dir + '/'
if not system.isdir(parent):
raise ObjectNotFoundError(
... | def mkdir(path, mode=0o777, dir_fd=None) | Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage o... | 4.947971 | 4.98396 | 0.992779 |
system = get_instance(path)
# Only support files
if system.is_locator(path) or path[-1] == '/':
raise is_a_directory_error("Is a directory: '%s'" % path)
# Remove
system.remove(path) | def remove(path, dir_fd=None) | Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects. | 8.260629 | 10.087586 | 0.818891 |
system = get_instance(path)
system.remove(system.ensure_dir_path(path)) | def rmdir(path, dir_fd=None) | Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects. | 14.824769 | 22.277746 | 0.665452 |
# Handles path-like objects
scandir_path = fsdecode(path).replace('\\', '/')
if not is_storage(scandir_path):
return os_scandir(scandir_path)
return _scandir_generator(
is_bytes=isinstance(fspath(path), (bytes, bytearray)),
scandir_path=scandir_path, system=get_instance(sc... | def scandir(path='.') | Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path... | 5.973777 | 6.739141 | 0.88643 |
with handle_os_exceptions():
for name, header in system.list_objects(scandir_path, first_level=True):
yield DirEntry(
scandir_path=scandir_path, system=system, name=name,
header=header, bytes_path=is_bytes) | def _scandir_generator(is_bytes, scandir_path, system) | scandir generator
Args:
is_bytes (bool): True if DirEntry must handle path as bytes.
scandir_path (str): Path.
system (pycosio._core.io_system.SystemBase subclass):
Storage system.
Yields:
DirEntry: Directory entries | 4.889042 | 5.231708 | 0.934502 |
name = self._name.rstrip('/')
if self._bytes_path:
name = fsencode(name)
return name | def name(self) | The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name. | 10.815281 | 11.061694 | 0.977724 |
path = self._path.rstrip('/')
if self._bytes_path:
path = fsencode(path)
return path | def path(self) | The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name. | 8.579382 | 10.224577 | 0.839094 |
try:
return (self._system.isdir(
path=self._path, client_kwargs=self._client_kwargs,
virtual_dir=False) or
# Some directories only exists virtually in object path and
# don't have headers.
bool(S_ISDIR(self.sta... | def is_dir(self, follow_symlinks=True) | Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlin... | 16.447796 | 16.38632 | 1.003752 |
return self._system.isfile(
path=self._path, client_kwargs=self._client_kwargs) | def is_file(self, follow_symlinks=True) | Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow sym... | 14.199368 | 16.620018 | 0.854353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.