_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8700 | render_cvmfs_pvc | train | def render_cvmfs_pvc(cvmfs_volume):
"""Render REANA_CVMFS_PVC_TEMPLATE."""
name = CVMFS_REPOSITORIES[cvmfs_volume]
rendered_template = dict(REANA_CVMFS_PVC_TEMPLATE)
rendered_template['metadata']['name'] = 'csi-cvmfs-{}-pvc'.format(name) | python | {
"resource": ""
} |
q8701 | render_cvmfs_sc | train | def render_cvmfs_sc(cvmfs_volume):
"""Render REANA_CVMFS_SC_TEMPLATE."""
name = CVMFS_REPOSITORIES[cvmfs_volume]
rendered_template | python | {
"resource": ""
} |
q8702 | create_cvmfs_storage_class | train | def create_cvmfs_storage_class(cvmfs_volume):
"""Create CVMFS storage class."""
from kubernetes.client.rest import ApiException
from reana_commons.k8s.api_client import current_k8s_storagev1_api_client
| python | {
"resource": ""
} |
q8703 | create_cvmfs_persistent_volume_claim | train | def create_cvmfs_persistent_volume_claim(cvmfs_volume):
"""Create CVMFS persistent volume claim."""
from kubernetes.client.rest import ApiException
from reana_commons.k8s.api_client import current_k8s_corev1_api_client
try:
current_k8s_corev1_api_client.\
create_namespaced_persistent_volume_claim(
| python | {
"resource": ""
} |
q8704 | create_api_client | train | def create_api_client(api='BatchV1'):
"""Create Kubernetes API client using config.
:param api: String which represents which Kubernetes API to spawn. By
default BatchV1.
:returns: Kubernetes python client object for a specific API i.e. BatchV1.
"""
k8s_config.load_incluster_config()
| python | {
"resource": ""
} |
q8705 | BasePublisher.__error_callback | train | def __error_callback(self, exception, interval):
"""Execute when there is an error while sending a message.
:param exception: Exception which has been thrown while trying to send
the message.
:param interval: Interval in which the message delivery will be
| python | {
"resource": ""
} |
q8706 | BasePublisher._publish | train | def _publish(self, msg):
"""Publish, handling retries, a message in the queue.
:param msg: Object which represents the message to be sent in
the queue. Note that this object should be serializable in the
configured format (by default JSON).
"""
connection = self._connection.clone()
publish = connection.ensure(self.producer, self.producer.publish,
errback=self.__error_callback,
| python | {
"resource": ""
} |
q8707 | WorkflowStatusPublisher.publish_workflow_status | train | def publish_workflow_status(self, workflow_uuid, status,
logs='', message=None):
"""Publish workflow status using the configured.
:param workflow_uudid: String which represents the workflow UUID.
:param status: Integer which represents the status of the workflow,
this is defined in the | python | {
"resource": ""
} |
q8708 | WorkflowSubmissionPublisher.publish_workflow_submission | train | def publish_workflow_submission(self,
user_id,
workflow_id_or_name,
parameters):
"""Publish workflow submission parameters."""
msg = {
| python | {
"resource": ""
} |
q8709 | serial_load | train | def serial_load(workflow_file, specification, parameters=None, original=None):
"""Validate and return a expanded REANA Serial workflow specification.
:param workflow_file: A specification file compliant with
REANA Serial workflow specification.
:returns: A dictionary which represents the valid Serial workflow with all
| python | {
"resource": ""
} |
q8710 | _expand_parameters | train | def _expand_parameters(specification, parameters, original=None):
"""Expand parameters inside comands for Serial workflow specifications.
:param specification: Full valid Serial workflow specification.
:param parameters: Parameters to be extended on a Serial specification.
:param original: Flag which, determins type of specifications to return.
:returns: If 'original' parameter is set, a copy of the specification
whithout expanded parametrers will be returned. If 'original' is not
set, a copy of the specification with expanded parameters (all $varname
and ${varname} will be expanded with their value). Otherwise an error
| python | {
"resource": ""
} |
q8711 | reana_ready | train | def reana_ready():
"""Check if reana can start new workflows."""
from reana_commons.config import REANA_READY_CONDITIONS
for module_name, condition_list in REANA_READY_CONDITIONS.items():
for condition_name in condition_list:
module = importlib.import_module(module_name)
| python | {
"resource": ""
} |
q8712 | check_predefined_conditions | train | def check_predefined_conditions():
"""Check k8s predefined conditions for the nodes."""
try:
node_info = current_k8s_corev1_api_client.list_node()
for node in node_info.items:
# check based on the predefined conditions about the
# node status: MemoryPressure, OutOfDisk, KubeletReady
# DiskPressure, PIDPressure,
for condition in node.status.conditions:
| python | {
"resource": ""
} |
q8713 | check_running_job_count | train | def check_running_job_count():
"""Check upper limit on running jobs."""
try:
job_list = current_k8s_batchv1_api_client.\
list_job_for_all_namespaces()
if len(job_list.items) > K8S_MAXIMUM_CONCURRENT_JOBS:
return False
except ApiException as e:
| python | {
"resource": ""
} |
q8714 | BaseAPIClient._get_spec | train | def _get_spec(self, spec_file):
"""Get json specification from package data."""
spec_file_path = os.path.join(
pkg_resources.
resource_filename(
'reana_commons',
| python | {
"resource": ""
} |
q8715 | JobControllerAPIClient.submit | train | def submit(self,
workflow_uuid='',
experiment='',
image='',
cmd='',
prettified_cmd='',
workflow_workspace='',
job_name='',
cvmfs_mounts='false'):
"""Submit a job to RJC API.
:param name: Name of the job.
:param experiment: Experiment the job belongs to.
:param image: Identifier of the Docker image which will run the job.
:param cmd: String which represents the command to execute. It can be
modified by the workflow engine i.e. prepending ``cd /some/dir/``.
:prettified_cmd: Original command submitted by the user.
:workflow_workspace: Path to the workspace of the workflow.
:cvmfs_mounts: String with CVMFS volumes to mount in job pods.
:return: Returns a dict with the ``job_id``.
"""
job_spec = {
'experiment': experiment,
'docker_img': image,
'cmd': cmd,
'prettified_cmd': prettified_cmd,
'env_vars': {},
'workflow_workspace': workflow_workspace,
| python | {
"resource": ""
} |
q8716 | JobControllerAPIClient.check_status | train | def check_status(self, job_id):
"""Check status of a job."""
response, http_response = self._client.jobs.get_job(job_id=job_id).\
result()
if http_response.status_code == 404:
raise HTTPNotFound('The | python | {
"resource": ""
} |
q8717 | JobControllerAPIClient.get_logs | train | def get_logs(self, job_id):
"""Get logs of a job."""
response, http_response = self._client.jobs.get_logs(job_id=job_id).\
result() | python | {
"resource": ""
} |
q8718 | JobControllerAPIClient.check_if_cached | train | def check_if_cached(self, job_spec, step, workflow_workspace):
"""Check if job result is in cache."""
response, http_response = self._client.job_cache.check_if_cached(
job_spec=json.dumps(job_spec),
workflow_json=json.dumps(step),
workflow_workspace=workflow_workspace).\
result()
if http_response.status_code == 400:
raise HTTPBadRequest('Bad request to check cache. Error: {}'.
| python | {
"resource": ""
} |
q8719 | _logging_callback | train | def _logging_callback(level, domain, message, data):
""" Callback that outputs libgphoto2's logging message via
Python's standard logging facilities.
:param level: libgphoto2 logging level
:param domain: component the message originates from
:param message: logging message
:param data: Other data in the logging record (unused)
"""
| python | {
"resource": ""
} |
q8720 | Transfer.run | train | def run(self, name, cache_key,
local_path, remote_path,
local_options, remote_options, **kwargs):
"""
The main work horse of the transfer task. Calls the transfer
method with the local and remote storage backends as given
with the parameters.
:param name: name of the file to transfer
:type name: str
:param local_path: local storage class to transfer from
:type local_path: str
:param local_options: options of the local storage class
:type local_options: dict
:param remote_path: remote storage class to transfer to
:type remote_path: str
| python | {
"resource": ""
} |
q8721 | Transfer.transfer | train | def transfer(self, name, local, remote, **kwargs):
"""
Transfers the file with the given name from the local to the remote
storage backend.
:param name: The name of the file to transfer
:param local: The local storage backend instance
:param remote: The remote storage backend instance
:returns: `True` when the transfer succeeded, `False` if not. Retries
the task when returning `False`
:rtype: bool
"""
try:
| python | {
"resource": ""
} |
q8722 | get_string | train | def get_string(cfunc, *args):
""" Call a C function and return its return value as a Python string.
:param cfunc: C function to call
:param args: Arguments to call function with
:rtype: str
"""
| python | {
"resource": ""
} |
q8723 | get_ctype | train | def get_ctype(rtype, cfunc, *args):
""" Call a C function that takes a pointer as its last argument and
return the C object that it contains after the function has finished.
:param rtype: C data type is filled by the function
:param cfunc: C function to call
:param args: Arguments to call function with | python | {
"resource": ""
} |
q8724 | new_gp_object | train | def new_gp_object(typename):
""" Create an indirect pointer to a GPhoto2 type, call its matching
constructor function and return the pointer to it.
:param typename: Name of the type to create.
:return: A pointer to the | python | {
"resource": ""
} |
q8725 | get_library_version | train | def get_library_version():
""" Get the version number of the underlying gphoto2 library.
:return: The version
:rtype: tuple of (major, minor, patch) version numbers
"""
version_str | python | {
"resource": ""
} |
q8726 | list_cameras | train | def list_cameras():
""" List all attached USB cameras that are supported by libgphoto2.
:return: All recognized cameras
:rtype: list of :py:class:`Camera`
"""
ctx = lib.gp_context_new()
camlist_p = new_gp_object("CameraList")
port_list_p = new_gp_object("GPPortInfoList")
lib.gp_port_info_list_load(port_list_p)
abilities_list_p = new_gp_object("CameraAbilitiesList")
lib.gp_abilities_list_load(abilities_list_p, ctx)
lib.gp_abilities_list_detect(abilities_list_p, port_list_p,
camlist_p, ctx)
out = []
for idx in range(lib.gp_list_count(camlist_p)):
| python | {
"resource": ""
} |
q8727 | supported_cameras | train | def supported_cameras():
""" List the names of all cameras supported by libgphoto2, grouped by the
name of their driver.
"""
ctx = lib.gp_context_new()
abilities_list_p = new_gp_object("CameraAbilitiesList")
lib.gp_abilities_list_load(abilities_list_p, ctx)
abilities = ffi.new("CameraAbilities*")
out = []
for idx in range(lib.gp_abilities_list_count(abilities_list_p)):
lib.gp_abilities_list_get_abilities(abilities_list_p, idx, abilities)
if abilities.device_type == lib.GP_DEVICE_STILL_CAMERA:
libname = os.path.basename(ffi.string(abilities.library)
| python | {
"resource": ""
} |
q8728 | VideoCaptureContext.stop | train | def stop(self):
""" Stop the capture. """
self.camera._get_config()['actions']['movie'].set(False)
self.videofile = self.camera._wait_for_event(
event_type=lib.GP_EVENT_FILE_ADDED)
| python | {
"resource": ""
} |
q8729 | Directory.path | train | def path(self):
""" Absolute path to the directory on the camera's filesystem. """
| python | {
"resource": ""
} |
q8730 | Directory.supported_operations | train | def supported_operations(self):
""" All directory operations supported by the camera. """
| python | {
"resource": ""
} |
q8731 | Directory.exists | train | def exists(self):
""" Check whether the directory exists on the camera. """
if self.name in ("", "/") and self.parent is None:
| python | {
"resource": ""
} |
q8732 | Directory.files | train | def files(self):
""" Get a generator that yields all files in the directory. """
filelist_p = new_gp_object("CameraList")
lib.gp_camera_folder_list_files(self._cam._cam, self.path.encode(),
| python | {
"resource": ""
} |
q8733 | Directory.directories | train | def directories(self):
""" Get a generator that yields all subdirectories in the directory.
"""
dirlist_p = new_gp_object("CameraList")
lib.gp_camera_folder_list_folders(self._cam._cam, self.path.encode(),
dirlist_p, self._cam._ctx)
for idx in range(lib.gp_list_count(dirlist_p)):
name = os.path.join(
| python | {
"resource": ""
} |
q8734 | Directory.create | train | def create(self):
""" Create the directory. """
lib.gp_camera_folder_make_dir(
| python | {
"resource": ""
} |
q8735 | Directory.remove | train | def remove(self):
""" Remove the directory. """
lib.gp_camera_folder_remove_dir(
| python | {
"resource": ""
} |
q8736 | Directory.upload | train | def upload(self, local_path):
""" Upload a file to the camera's permanent storage.
:param local_path: Path to file to copy
:type local_path: str/unicode
"""
camerafile_p = ffi.new("CameraFile**")
with open(local_path, 'rb') as fp:
lib.gp_file_new_from_fd(camerafile_p, fp.fileno())
| python | {
"resource": ""
} |
q8737 | File.supported_operations | train | def supported_operations(self):
""" All file operations supported by the camera. """
| python | {
"resource": ""
} |
q8738 | File.dimensions | train | def dimensions(self):
""" Dimensions of the image.
:rtype: :py:class:`ImageDimensions`
"""
return | python | {
"resource": ""
} |
q8739 | File.permissions | train | def permissions(self):
""" Permissions of the file.
Can be "r-" (read-only), "-w" (write-only), "rw" (read-write)
or "--" (no rights).
:rtype: str
| python | {
"resource": ""
} |
q8740 | File.save | train | def save(self, target_path, ftype='normal'):
""" Save file content to a local file.
:param target_path: Path to save remote file as.
:type target_path: str/unicode
:param ftype: Select 'view' on file.
:type ftype: | python | {
"resource": ""
} |
q8741 | File.get_data | train | def get_data(self, ftype='normal'):
""" Get file content as a bytestring.
:param ftype: Select 'view' on file.
:type ftype: str
:return: File content
:rtype: bytes
"""
camfile_p = ffi.new("CameraFile**")
lib.gp_file_new(camfile_p)
lib.gp_camera_file_get(
self._cam._cam, self.directory.path.encode(), self.name.encode(),
backend.FILE_TYPES[ftype], camfile_p[0], self._cam._ctx)
| python | {
"resource": ""
} |
q8742 | File.iter_data | train | def iter_data(self, chunk_size=2**16, ftype='normal'):
""" Get an iterator that yields chunks of the file content.
:param chunk_size: Size of yielded chunks in bytes
:type chunk_size: int
:param ftype: Select 'view' on file.
:type ftype: str
:return: Iterator
"""
self._check_type_supported(ftype)
buf_p = ffi.new("char[{0}]".format(chunk_size))
size_p = ffi.new("uint64_t*")
offset_p = ffi.new("uint64_t*")
| python | {
"resource": ""
} |
q8743 | File.remove | train | def remove(self):
""" Remove file from device. """
lib.gp_camera_file_delete(self._cam._cam, | python | {
"resource": ""
} |
q8744 | ConfigItem.set | train | def set(self, value):
""" Update value of the option.
Only possible for options with :py:attr:`readonly` set to `False`.
If :py:attr:`type` is `choice`, the value must be one of the
:py:attr:`choices`.
If :py:attr:`type` is `range`, the value must be in the range
described by :py:attr:`range`.
:param value: Value to set
"""
if self.readonly:
raise ValueError("Option is read-only.")
val_p = None
if self.type == 'selection':
if value not in self.choices:
raise ValueError("Invalid choice (valid: {0})".format(
repr(self.choices)))
val_p = ffi.new("const char[]", value.encode())
elif self.type == 'text':
if not isinstance(value, basestring):
raise ValueError("Value must be a string.")
val_p = ffi.new("char**")
val_p[0] = ffi.new("char[]", value.encode())
elif self.type == 'range':
if value < self.range.min or value > self.range.max:
raise ValueError("Value exceeds valid range ({0}-{1}."
| python | {
"resource": ""
} |
q8745 | Camera.supported_operations | train | def supported_operations(self):
""" All operations supported by the camera. """
| python | {
"resource": ""
} |
q8746 | Camera.usb_info | train | def usb_info(self):
""" The camera's USB information. """
return UsbInformation(self._abilities.usb_vendor,
self._abilities.usb_product,
| python | {
"resource": ""
} |
q8747 | Camera.config | train | def config(self):
""" Writeable configuration parameters.
:rtype: dict
"""
config = self._get_config()
return {section: {itm.name: itm for itm in config[section].values()
| python | {
"resource": ""
} |
q8748 | Camera.storage_info | train | def storage_info(self):
""" Information about the camera's storage. """
info_p = ffi.new("CameraStorageInformation**")
num_info_p = ffi.new("int*")
lib.gp_camera_get_storageinfo(self._cam, info_p, num_info_p, self._ctx)
infos = []
for idx in range(num_info_p[0]):
out = SimpleNamespace()
struc = (info_p[0] + idx)
fields = struc.fields
if lib.GP_STORAGEINFO_BASE & fields:
out.directory = next(
(d for d in self.list_all_directories()
if d.path == ffi.string(struc.basedir).decode()),
None)
if lib.GP_STORAGEINFO_LABEL & fields:
out.label = ffi.string(struc.label).decode()
if lib.GP_STORAGEINFO_DESCRIPTION & fields:
out.description = ffi.string(struc.description).decode()
if lib.GP_STORAGEINFO_STORAGETYPE & fields:
| python | {
"resource": ""
} |
q8749 | Camera.list_all_files | train | def list_all_files(self):
""" Utility method that yields all files on the device's file
systems.
"""
def list_files_recursively(directory):
| python | {
"resource": ""
} |
q8750 | Camera.list_all_directories | train | def list_all_directories(self):
""" Utility method that yields all directories on the device's file
systems.
"""
def list_dirs_recursively(directory):
if directory == self.filesystem:
| python | {
"resource": ""
} |
q8751 | Camera.capture | train | def capture(self, to_camera_storage=False):
""" Capture an image.
Some cameras (mostly Canon and Nikon) support capturing to internal
RAM. On these devices, you have to specify `to_camera_storage` if
you want to save the images to the memory card. On devices that
do not support saving to RAM, the only difference is that the file
is automatically downloaded and deleted when set to `False`.
:param to_camera_storage: Save image to the camera's internal storage
:type to_camera_storage: bool
:return: A :py:class:`File` if `to_camera_storage` was `True`,
| python | {
"resource": ""
} |
q8752 | Camera.capture_video | train | def capture_video(self, length):
""" Capture a video.
This always writes to the memory card, since internal RAM is likely
to run out of space very quickly.
Currently this only works with Nikon cameras.
| python | {
"resource": ""
} |
q8753 | Camera.get_preview | train | def get_preview(self):
""" Get a preview from the camera's viewport.
This will usually be a JPEG image with the dimensions depending on
the camera. You will need to call the exit() method manually after
you are done capturing a live preview.
:return: The preview image as a bytestring
:rtype: | python | {
"resource": ""
} |
q8754 | QueuedStorage.transfer | train | def transfer(self, name, cache_key=None):
"""
Transfers the file with the given name to the remote storage
backend by queuing the task.
:param name: file name
:type name: str
:param cache_key: the cache key to set after | python | {
"resource": ""
} |
q8755 | QueuedStorage.get_available_name | train | def get_available_name(self, name):
"""
Returns a filename that's free on both the local and remote storage
systems, and available for new content to be written to.
:param name: file name
:type name: str
:rtype: str
"""
| python | {
"resource": ""
} |
q8756 | QueryAnalyzer.generate_query_report | train | def generate_query_report(self, db_uri, parsed_query, db_name, collection_name):
"""Generates a comprehensive report on the raw query"""
index_analysis = None
recommendation = None
namespace = parsed_query['ns']
indexStatus = "unknown"
index_cache_entry = self._ensure_index_cache(db_uri,
db_name,
collection_name)
query_analysis = self._generate_query_analysis(parsed_query,
db_name,
collection_name)
if ((query_analysis['analyzedFields'] != []) and
query_analysis['supported']):
index_analysis = self._generate_index_analysis(query_analysis,
| python | {
"resource": ""
} |
q8757 | QueryAnalyzer._ensure_index_cache | train | def _ensure_index_cache(self, db_uri, db_name, collection_name):
"""Adds a collections index entries to the cache if not present"""
if not self._check_indexes or db_uri is None:
return {'indexes': None}
if db_name not in self.get_cache():
self._internal_map[db_name] = {}
if collection_name not in self._internal_map[db_name]:
indexes = []
try:
if self._index_cache_connection is None:
self._index_cache_connection = pymongo.MongoClient(db_uri,
document_class=OrderedDict,
| python | {
"resource": ""
} |
q8758 | QueryAnalyzer._generate_query_analysis | train | def _generate_query_analysis(self, parsed_query, db_name, collection_name):
"""Translates a raw query object into a Dex query analysis"""
analyzed_fields = []
field_count = 0
supported = True
sort_fields = []
query_mask = None
if 'command' in parsed_query and parsed_query['command'] not in SUPPORTED_COMMANDS:
supported = False
else:
#if 'orderby' in parsed_query:
sort_component = parsed_query['orderby'] if 'orderby' in parsed_query else []
sort_seq = 0
for key in sort_component:
sort_field = {'fieldName': key,
'fieldType': SORT_TYPE,
'seq': sort_seq}
sort_fields.append(key)
analyzed_fields.append(sort_field)
field_count += 1
sort_seq += 1
query_component = parsed_query['query'] if 'query' in parsed_query else {}
for key in query_component:
if key not in sort_fields:
field_type = UNSUPPORTED_TYPE
if ((key not in UNSUPPORTED_QUERY_OPERATORS) and
(key not in COMPOSITE_QUERY_OPERATORS)):
try:
if query_component[key] == {}:
raise
nested_field_list = query_component[key].keys()
except:
field_type = EQUIV_TYPE
else:
| python | {
"resource": ""
} |
q8759 | QueryAnalyzer._generate_index_analysis | train | def _generate_index_analysis(self, query_analysis, indexes):
"""Compares a query signature to the index cache to identify complete
and partial indexes available to the query"""
needs_recommendation = True
full_indexes = []
partial_indexes = []
coverage = "unknown"
if indexes is not None:
for index_key in indexes.keys():
index = indexes[index_key]
index_report = self._generate_index_report(index,
query_analysis)
if index_report['supported'] is True:
if index_report['coverage'] == 'full':
full_indexes.append(index_report)
if index_report['idealOrder']:
needs_recommendation = False
| python | {
"resource": ""
} |
q8760 | QueryAnalyzer._generate_index_report | train | def _generate_index_report(self, index, query_analysis):
"""Analyzes an existing index against the results of query analysis"""
all_fields = []
equiv_fields = []
sort_fields = []
range_fields = []
for query_field in query_analysis['analyzedFields']:
all_fields.append(query_field['fieldName'])
if query_field['fieldType'] is EQUIV_TYPE:
equiv_fields.append(query_field['fieldName'])
elif query_field['fieldType'] is SORT_TYPE:
sort_fields.append(query_field['fieldName'])
elif query_field['fieldType'] is RANGE_TYPE:
range_fields.append(query_field['fieldName'])
max_equiv_seq = len(equiv_fields)
max_sort_seq = max_equiv_seq + len(sort_fields)
max_range_seq = max_sort_seq + len(range_fields)
coverage = 'none'
| python | {
"resource": ""
} |
q8761 | QueryAnalyzer._generate_recommendation | train | def _generate_recommendation(self,
query_analysis,
db_name,
collection_name):
"""Generates an ideal query recommendation"""
index_rec = '{'
for query_field in query_analysis['analyzedFields']:
if query_field['fieldType'] is EQUIV_TYPE:
if len(index_rec) is not 1:
index_rec += ', '
index_rec += '"' + query_field['fieldName'] + '": 1'
for query_field in query_analysis['analyzedFields']:
if query_field['fieldType'] is SORT_TYPE:
if len(index_rec) is not 1:
index_rec | python | {
"resource": ""
} |
q8762 | ReportAggregation.add_query_occurrence | train | def add_query_occurrence(self, report):
"""Adds a report to the report aggregation"""
initial_millis = int(report['parsed']['stats']['millis'])
mask = report['queryMask']
existing_report = self._get_existing_report(mask, report)
if existing_report is not None:
self._merge_report(existing_report, report)
else:
time = None
if 'ts' in report['parsed']:
time = report['parsed']['ts']
self._reports.append(OrderedDict([
('namespace', report['namespace']),
('lastSeenDate', time),
| python | {
"resource": ""
} |
q8763 | ReportAggregation.get_reports | train | def get_reports(self):
"""Returns a minimized version of the aggregation"""
return sorted(self._reports,
| python | {
"resource": ""
} |
q8764 | ReportAggregation._get_existing_report | train | def _get_existing_report(self, mask, report):
"""Returns the aggregated report that matches report"""
for existing_report in self._reports: | python | {
"resource": ""
} |
q8765 | ReportAggregation._merge_report | train | def _merge_report(self, target, new):
"""Merges a new report into the target report"""
time = None
if 'ts' in new['parsed']:
time = new['parsed']['ts']
if (target.get('lastSeenDate', None) and
| python | {
"resource": ""
} |
q8766 | Parser.parse | train | def parse(self, input):
"""Passes input to each QueryLineHandler in use"""
query = None
for handler in self._line_handlers:
try:
query = handler.handle(input)
| python | {
"resource": ""
} |
q8767 | Dex.generate_query_report | train | def generate_query_report(self, db_uri, query, db_name, collection_name):
"""Analyzes a single query"""
return self._query_analyzer.generate_query_report(db_uri,
query,
| python | {
"resource": ""
} |
q8768 | Dex.watch_logfile | train | def watch_logfile(self, logfile_path):
"""Analyzes queries from the tail of a given log file"""
self._run_stats['logSource'] = logfile_path
log_parser = LogParser()
# For each new line in the logfile ...
output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
try:
firstLine = True
for line in self._tail_file(open(logfile_path),
WATCH_INTERVAL_SECONDS):
if firstLine:
self._run_stats['timeRange']['start'] = get_line_time(line)
| python | {
"resource": ""
} |
q8769 | Dex._tail_file | train | def _tail_file(self, file, interval):
"""Tails a file"""
file.seek(0,2)
while True:
where = file.tell()
line = file.readline()
if not line:
| python | {
"resource": ""
} |
q8770 | Dex._tail_profile | train | def _tail_profile(self, db, interval):
"""Tails the system.profile collection"""
latest_doc = None
while latest_doc is None:
time.sleep(interval)
latest_doc = db['system.profile'].find_one()
current_time = latest_doc['ts']
while True:
time.sleep(interval) | python | {
"resource": ""
} |
q8771 | Dex._tuplefy_namespace | train | def _tuplefy_namespace(self, namespace):
"""Converts a mongodb namespace to a db, collection tuple"""
namespace_split = namespace.split('.', 1)
if len(namespace_split) is 1:
# we treat a single element as a collection name.
# this also properly tuplefies '*'
| python | {
"resource": ""
} |
q8772 | Dex._validate_namespaces | train | def _validate_namespaces(self, input_namespaces):
"""Converts a list of db namespaces to a list of namespace tuples,
supporting basic commandline wildcards"""
output_namespaces = []
if input_namespaces == []:
return output_namespaces
elif '*' in input_namespaces:
if len(input_namespaces) > 1:
warning = 'Warning: Multiple namespaces are '
warning += 'ignored when one namespace is "*"\n'
sys.stderr.write(warning)
return output_namespaces
else:
for namespace in input_namespaces:
if not isinstance(namespace, unicode):
namespace = unicode(namespace)
namespace_tuple = self._tuplefy_namespace(namespace)
if namespace_tuple is None:
warning = 'Warning: Invalid namespace ' + namespace
| python | {
"resource": ""
} |
q8773 | Dex._namespace_requested | train | def _namespace_requested(self, namespace):
"""Checks whether the requested_namespaces contain the provided
namespace"""
if namespace is None:
return False
namespace_tuple = self._tuplefy_namespace(namespace)
if namespace_tuple[0] in IGNORE_DBS:
return | python | {
"resource": ""
} |
q8774 | Dex._tuple_requested | train | def _tuple_requested(self, namespace_tuple):
"""Helper for _namespace_requested. Supports limited wildcards"""
if not isinstance(namespace_tuple[0], unicode):
encoded_db = unicode(namespace_tuple[0])
else:
encoded_db = namespace_tuple[0]
if not isinstance(namespace_tuple[1], unicode):
encoded_coll = unicode(namespace_tuple[1])
else:
encoded_coll = namespace_tuple[1]
if namespace_tuple is None:
return False
elif len(self._requested_namespaces) is 0:
| python | {
"resource": ""
} |
q8775 | Dex._get_requested_databases | train | def _get_requested_databases(self):
"""Returns a list of databases requested, not including ignored dbs"""
requested_databases = []
if ((self._requested_namespaces is not None) and
(self._requested_namespaces != [])):
for requested_namespace in self._requested_namespaces:
if requested_namespace[0] | python | {
"resource": ""
} |
q8776 | FortiOSDriver.get_config | train | def get_config(self, retrieve="all"):
"""get_config implementation for FortiOS."""
get_startup = retrieve == "all" or retrieve == "startup"
get_running = retrieve == "all" or retrieve == "running"
get_candidate = retrieve == "all" or retrieve == "candidate"
if retrieve == "all" or get_running:
result = self._execute_command_with_vdom('show')
text_result = '\n'.join(result)
return {
'startup': u"",
| python | {
"resource": ""
} |
q8777 | DelugeRPCClient.connect | train | def connect(self):
"""
Connects to the Deluge instance
"""
self._connect()
logger.debug('Connected to Deluge, detecting daemon version')
self._detect_deluge_version()
logger.debug('Daemon version {} detected, | python | {
"resource": ""
} |
q8778 | DelugeRPCClient.disconnect | train | def disconnect(self):
"""
Disconnect from deluge
"""
if self.connected:
self._socket.close() | python | {
"resource": ""
} |
q8779 | DelugeRPCClient.call | train | def call(self, method, *args, **kwargs):
"""
Calls an RPC function
"""
tried_reconnect = False
for _ in range(2):
try:
self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs)
return self._receive_response(self.deluge_version, self.deluge_protocol_version)
except | python | {
"resource": ""
} |
q8780 | StickerSet.to_array | train | def to_array(self):
"""
Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(StickerSet, self).to_array()
array['name'] = u(self.name) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, | python | {
"resource": ""
} |
q8781 | StickerSet.from_array | train | def from_array(array):
"""
Deserialize a new StickerSet from a given dictionary.
:return: new StickerSet instance.
:rtype: StickerSet
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import Sticker
data = {}
| python | {
"resource": ""
} |
q8782 | MaskPosition.to_array | train | def to_array(self):
"""
Serializes this MaskPosition to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(MaskPosition, self).to_array()
| python | {
"resource": ""
} |
q8783 | MaskPosition.from_array | train | def from_array(array):
"""
Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
| python | {
"resource": ""
} |
q8784 | compile | train | def compile(cfg_path, out_path, executable=None, env=None, log=None):
"""
Use ACE to compile a grammar.
Args:
cfg_path (str): the path to the ACE config file
out_path (str): the path where the compiled grammar will be
written
executable (str, optional): the path to the ACE binary; if
`None`, the `ace` command will be used
env (dict, optional): environment variables to pass to the ACE
subprocess
log (file, optional): if given, the file, opened for writing,
or stream to write ACE's stdout and stderr compile messages
"""
try:
| python | {
"resource": ""
} |
q8785 | AceProcess.close | train | def close(self):
"""
Close the ACE process and return the process's exit code.
"""
self.run_info['end'] = datetime.now()
self._p.stdin.close()
for line in self._p.stdout:
if line.startswith('NOTE: tsdb run:'):
| python | {
"resource": ""
} |
q8786 | loads | train | def loads(s, single=False):
"""
Deserialize DMRX string representations
Args:
s (str): a DMRX string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)
"""
corpus = etree.fromstring(s)
| python | {
"resource": ""
} |
q8787 | ParseResult.derivation | train | def derivation(self):
"""
Deserialize and return a Derivation object for UDF- or
JSON-formatted derivation data; otherwise return the original
string.
| python | {
"resource": ""
} |
q8788 | ParseResult.tree | train | def tree(self):
"""
Deserialize and return a labeled syntax tree. The tree data
may be a standalone datum, or embedded in the derivation.
"""
tree = self.get('tree')
if isinstance(tree, stringtypes):
tree = SExpr.parse(tree).data
elif tree is None:
drv = self.get('derivation')
if isinstance(drv, dict) and 'label' in drv:
def _extract_tree(d):
t = [d.get('label', '')]
| python | {
"resource": ""
} |
q8789 | ParseResult.mrs | train | def mrs(self):
"""
Deserialize and return an Mrs object for simplemrs or
JSON-formatted MRS data; otherwise return the original string.
"""
mrs = self.get('mrs')
if mrs is not None:
| python | {
"resource": ""
} |
q8790 | ParseResult.eds | train | def eds(self):
"""
Deserialize and return an Eds object for native- or
JSON-formatted EDS data; otherwise return the original string.
"""
_eds = self.get('eds')
if _eds is not None:
if | python | {
"resource": ""
} |
q8791 | ParseResult.dmrs | train | def dmrs(self):
"""
Deserialize and return a Dmrs object for JSON-formatted DMRS
data; otherwise return the original string.
"""
dmrs = self.get('dmrs')
if dmrs is not None:
| python | {
"resource": ""
} |
q8792 | ParseResponse.tokens | train | def tokens(self, tokenset='internal'):
"""
Deserialize and return a YyTokenLattice object for the
initial or internal token set, if provided, from the YY
format or the JSON-formatted data; otherwise return the
original string.
Args:
tokenset (str): return `'initial'` or `'internal'` tokens
(default: `'internal'`)
Returns:
:class:`YyTokenLattice`
"""
toks = self.get('tokens', {}).get(tokenset)
| python | {
"resource": ""
} |
q8793 | GameHighScore.to_array | train | def to_array(self):
"""
Serializes this GameHighScore to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(GameHighScore, self).to_array()
array['position'] = int(self.position) # type int
| python | {
"resource": ""
} |
q8794 | GameHighScore.from_array | train | def from_array(array):
"""
Deserialize a new GameHighScore from a given dictionary.
:return: new GameHighScore instance.
:rtype: GameHighScore
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.peer import User
| python | {
"resource": ""
} |
q8795 | valuemap | train | def valuemap(f):
"""
Decorator to help PEG functions handle value conversions.
"""
@wraps(f)
def wrapper(*args, **kwargs):
if 'value' in kwargs:
val = kwargs['value']
del kwargs['value']
_f = f(*args, **kwargs)
def valued_f(*args, **kwargs):
result = _f(*args, **kwargs)
s, obj, span = result
if | python | {
"resource": ""
} |
q8796 | literal | train | def literal(x):
"""
Create a PEG function to consume a literal.
"""
xlen = len(x)
msg = 'Expected: "{}"'.format(x)
| python | {
"resource": ""
} |
q8797 | regex | train | def regex(r):
"""
Create a PEG function to match a regular expression.
"""
if isinstance(r, stringtypes):
p = re.compile(r)
else:
p = r
msg = 'Expected to match: {}'.format(p.pattern)
def match_regex(s, grm=None, pos=0):
m = p.match(s)
if m is not None:
| python | {
"resource": ""
} |
q8798 | nonterminal | train | def nonterminal(n):
"""
Create a PEG function to match a nonterminal.
"""
def match_nonterminal(s, grm=None, pos=0):
if grm is None: grm = {}
| python | {
"resource": ""
} |
q8799 | and_next | train | def and_next(e):
"""
Create a PEG function for positive lookahead.
"""
def match_and_next(s, grm=None, pos=0):
try:
e(s, grm, pos)
except PegreError as ex:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.