Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
379,700 | def compute_exit_code(config, exception=None):
code = 0
if exception is not None:
code = code | 1
if config.surviving_mutants > 0:
code = code | 2
if config.surviving_mutants_timeout > 0:
code = code | 4
if config.suspicious_mutants > 0:
code = code | 8
retur... | Compute an exit code for mutmut mutation testing
The following exit codes are available for mutmut:
* 0 if all mutants were killed (OK_KILLED)
* 1 if a fatal error occurred
* 2 if one or more mutants survived (BAD_SURVIVED)
* 4 if one or more mutants timed out (BAD_TIMEOUT)
* 8 if one or m... |
379,701 | def _get_nd_basic_indexing(self, key):
shape = self.shape
if isinstance(key, integer_types):
if key > shape[0] - 1:
raise IndexError(
.format(
key, shape[0]))
return self._at(key)
elif isinstance(key, py... | This function is called when key is a slice, or an integer,
or a tuple of slices or integers |
379,702 | def push_session(document, session_id=None, url=, io_loop=None):
s neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
... | Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and cha... |
379,703 | def repr_type(obj):
the_type = type(obj)
if (not py3compat.PY3) and the_type is InstanceType:
the_type = obj.__class__
msg = % (obj, the_type)
return msg | Return a string representation of a value and its type for readable
error messages. |
379,704 | def detect_types(
field_names,
field_values,
field_types=DEFAULT_TYPES,
skip_indexes=None,
type_detector=TypeDetector,
fallback_type=TextField,
*args,
**kwargs
):
detector = type_detector(
field_names,
field_types=field_types,
fallback_type=fal... | Detect column types (or "where the magic happens") |
379,705 | def main(args):
(args, opts) = _surface_to_ribbon_parser(args)
if opts[]:
print(info, file=sys.stdout)
return 1
verbose = opts[]
def note(s):
if verbose: print(s, file=sys.stdout)
return verbose
if in opts and opts[] is not None:
add_... | surface_to_rubbon.main(args) can be given a list of arguments, such as sys.argv[1:]; these
arguments may include any options and must include exactly one subject id and one output
filename. Additionally one or two surface input filenames must be given. The surface files are
projected into the ribbon and wri... |
379,706 | async def create_source_event_stream(
schema: GraphQLSchema,
document: DocumentNode,
root_value: Any = None,
context_value: Any = None,
variable_values: Dict[str, Any] = None,
operation_name: str = None,
field_resolver: GraphQLFieldResolver = None,
) -> Union[AsyncIterable[Any], ExecutionRes... | Create source even stream
Implements the "CreateSourceEventStream" algorithm described in the GraphQL
specification, resolving the subscription source event stream.
Returns a coroutine that yields an AsyncIterable.
If the client provided invalid arguments, the source stream could not be created,
... |
379,707 | def upload_slice_file(self, real_file_path, slice_size, file_name, offset=0, dir_name=None):
if dir_name is not None and dir_name[0] == :
dir_name = dir_name[1:len(dir_name)]
if dir_name is None:
dir_name = ""
self.url = + self.config.region + + str(
... | 此分片上传代码由GitHub用户a270443177(https://github.com/a270443177)友情提供
:param real_file_path:
:param slice_size:
:param file_name:
:param offset:
:param dir_name:
:return: |
379,708 | def do_loop(self, params):
repeat = params.repeat
if repeat < 0:
self.show_output("<repeat> must be >= 0.")
return
pause = params.pause
if pause < 0:
self.show_output("<pause> must be >= 0.")
return
cmds = params.cmds
... | \x1b[1mNAME\x1b[0m
loop - Runs commands in a loop
\x1b[1mSYNOPSIS\x1b[0m
loop <repeat> <pause> <cmd1> <cmd2> ... <cmdN>
\x1b[1mDESCRIPTION\x1b[0m
Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween
each <cmd> (0 means no pause).
\x1b[1mEXAMPLES\x1b[0m
... |
379,709 | def add_artwork_item(self, instance, item):
if in self.old_top[instance][item]:
pass
else:
(item_type, item_id) = item.split()
self.artwork[item_type][item_id] = {}
for s_item in sorted(self.old_top[instance][item]):
if self.old_t... | Add an artwork item e.g. Shapes, Notes and Pixmaps
:param instance: Hypervisor instance
:param item: Item to add |
379,710 | def load_user(user_email):
user_obj = store.user(user_email)
user_inst = LoginUser(user_obj) if user_obj else None
return user_inst | Returns the currently active user as an object. |
379,711 | def setEnabled(self, state):
super(XToolButton, self).setEnabled(state)
self.updateUi() | Updates the drop shadow effect for this widget on enable/disable
state change.
:param state | <bool> |
379,712 | def get_all_json_from_indexq(self):
files = self.get_all_as_list()
out = []
for efile in files:
out.extend(self._open_file(efile))
return out | Gets all data from the todo files in indexq and returns one huge list of all data. |
379,713 | def create_new_output_file(sampler, filename, force=False, injection_file=None,
**kwargs):
if os.path.exists(filename):
if force:
os.remove(filename)
else:
raise OSError("output-file already exists; use force if you "
... | Creates a new output file.
If the output file already exists, an ``OSError`` will be raised. This can
be overridden by setting ``force`` to ``True``.
Parameters
----------
sampler : sampler instance
Sampler
filename : str
Name of the file to create.
force : bool, optional
... |
379,714 | def _get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
if ssl_version not in (PROTOCOL_DTLS, PROTOCOL_DTLSv1, PROTOCOL_DTLSv1_2):
return _orig_get_server_certificate(addr, ssl_version, ca_certs)
if ca_certs is not None:
cert_reqs = ssl.CERT_REQUIRED
else:
... | Retrieve a server certificate
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt. |
379,715 | def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False):
assert len(gt_boxlists) == len(
pred_boxlists
), "Length of gt and pred lists need to be same."
prec, rec = calc_detection_voc_prec_rec(
pred_boxlists=pred_boxlists, gt_boxlists=gt_boxlists, iou_thr... | Evaluate on voc dataset.
Args:
pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields.
gt_boxlists(list[BoxList]): ground truth boxlist, has labels field.
iou_thresh: iou thresh
use_07_metric: boolean
Returns:
dict represents the results |
379,716 | def metarate(self, func, name=):
setattr(func, name, self.values)
return func | Set the values object to the function object's namespace |
379,717 | def get_snapshots(topology):
snapshots = []
snap_dir = os.path.join(topology_dirname(topology), )
if os.path.exists(snap_dir):
snaps = os.listdir(snap_dir)
for directory in snaps:
snap_top = os.path.join(snap_dir, directory, )
if os.path.exists(snap_top):
... | Return the paths of any snapshot topologies
:param str topology: topology file
:return: list of dicts containing snapshot topologies
:rtype: list |
379,718 | def find_version_by_string_lib(line):
if not line:
return None
simplified_line = simplify_line(line)
version = None
if simplified_line.startswith("version="):
if not in simplified_line:
pass
else:
if "=" in simplified_line:
... | No regex parsing. Or at least, mostly, not regex. |
379,719 | def on_delete(self, forced):
if not forced and self.handler is not None and not self.is_closed:
self.promote()
else:
self.close() | Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False. |
379,720 | def ReadPreprocessingInformation(self, knowledge_base):
generator = self._GetAttributeContainers(
self._CONTAINER_TYPE_SYSTEM_CONFIGURATION)
for stream_number, system_configuration in enumerate(generator):
knowledge_base.ReadSystemConfigurationArtifact(
system_configuration, ... | Reads preprocessing information.
The preprocessing information contains the system configuration which
contains information about various system specific configuration data,
for example the user accounts.
Args:
knowledge_base (KnowledgeBase): is used to store the preprocessing
informat... |
379,721 | def _item_to_metric(iterator, log_metric_pb):
resource = MessageToDict(log_metric_pb)
return Metric.from_api_repr(resource, iterator.client) | Convert a metric protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type log_metric_pb:
:class:`.logging_metrics_pb2.LogMetric`
:param log_metric_pb: Metric protobuf returned from the API.
... |
379,722 | def _checkDimensionsListLike(arrays):
dim1 = len(arrays)
dim2, dim3 = arrays[0].shape
for aa in range(1, dim1):
dim2_aa, dim3_aa = arrays[aa].shape
if (dim2_aa != dim2) or (dim3_aa != dim3):
raise _error.InvalidError(_MDPERR["obj_square"])
return dim1, dim2, dim3 | Check that each array in a list of arrays has the same size. |
379,723 | def get_import_stacklevel(import_hook):
py_version = sys.version_info[:2]
if py_version <= (3, 2):
return 4 if import_hook else 2
elif py_version == (3, 3):
return 8 if import_hook else 10
elif py_version == (3, 4):
return 10 if import_hook else 8
else:
... | Returns the stacklevel value for warnings.warn() for when the warning
gets emitted by an imported module, but the warning should point at the
code doing the import.
Pass import_hook=True if the warning gets generated by an import hook
(warn() gets called in load_module(), see PEP302) |
379,724 | def iniedited(self, *args, **kwargs):
self.inimodel.set_index_edited(self.files_lv.currentIndex(), True) | Set the current index of inimodel to modified
:returns: None
:rtype: None
:raises: None |
379,725 | def call_handlers(self, msg):
self.message_received.emit(msg)
msg_type = msg[][]
signal = getattr(self, msg_type + , None)
if signal:
signal.emit(msg)
elif msg_type in (, ):
self.stream_received.emit(msg) | Reimplemented to emit signals instead of making callbacks. |
379,726 | def check_ab(ab, verb):
r
try:
ab = int(ab)
except VariableCatch:
print()
raise
pab = [11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26,
31, 32, 33, 34, 35, 36, 41, 42, 43, 44, 45, 46,
51, 52, 53, 54, 55, 56, 61, 62, 63, 64, 65, 66]
if ab ... | r"""Check source-receiver configuration.
This check-function is called from one of the modelling routines in
:mod:`model`. Consult these modelling routines for a detailed description
of the input parameters.
Parameters
----------
ab : int
Source-receiver configuration.
verb : {0, ... |
379,727 | def system_monitor_mail_relay_domain_name(self, **kwargs):
config = ET.Element("config")
system_monitor_mail = ET.SubElement(config, "system-monitor-mail", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
relay = ET.SubElement(system_monitor_mail, "relay")
host_ip_key = ET.S... | Auto Generated Code |
379,728 | def initialize_tasks(self):
self.tasks = chain(self.iterable, [POISON_PILL] * self.num_processes)
for task in islice(self.tasks, Q_MAX_SIZE):
log.debug(, task)
self.task_queue.put(task) | Load the input queue to capacity.
Overfilling causes a deadlock when `queue.put` blocks when
full, so further tasks are enqueued as results are returned. |
379,729 | def _AssertDataIsList(key, lst):
if not isinstance(lst, list) and not isinstance(lst, tuple):
raise NotAListError( % key)
for element in lst:
if not isinstance(element, str):
raise ElementNotAStringError(,
(element, lst)) | Assert that lst contains list data and is not structured. |
379,730 | def get_config(repo):
files = get_files(repo)
config = DEFAULT_CONFIG
if "config.json" in files:
config_file = repo.get_file_contents(, ref="gh-pages")
try:
repo_config = json.loads(config_file.decoded_content.decode("utf-8"))
config.update(repo_config)
... | Get the config for the repo, merged with the default config. Returns the default config if
no config file is found. |
379,731 | def _generate_footer(notebook_object, notebook_type):
footer_aux = FOOTER
if "Main_Files" in notebook_type:
footer_aux = footer_aux.replace("../MainFiles/", "")
notebook_object["cells"].append(nb.v4.new_markdown_cell(footer_aux,
... | Internal function that is used for generation of the notebooks footer.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type : str
Notebook type: - "Main_Files_Signal_Samples"
... |
379,732 | def delete_external_link(self, id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_external_link_with_http_info(id, **kwargs)
else:
(data) = self.delete_external_link_with_http_info(id, **kwargs)
return data | Delete a specific external link # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_external_link(id, async_req=True)
>>> result = thread.get()
:pa... |
379,733 | def version(app, appbuilder):
_appbuilder = import_application(app, appbuilder)
click.echo(
click.style(
"F.A.B Version: {0}.".format(_appbuilder.version), bg="blue", fg="white"
)
) | Flask-AppBuilder package version |
379,734 | def listar_por_equip(self, equip_id):
if equip_id is None:
raise InvalidParameterError(
u)
url = + str(equip_id) +
code, xml = self.submit(None, , url)
return self.response(code, xml) | Lista todos os ambientes por equipamento especifico.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
'id_divisao': < id_divisao >,
'nome_divisao': < nome_divisao >,
'id_ambiente_logico'... |
379,735 | def stop(self, timeout=1.0):
if timeout:
self._running.wait(timeout)
return self._ioloop_manager.stop(callback=self._uninstall) | Stop a running server (from another thread).
Parameters
----------
timeout : float or None, optional
Seconds to wait for server to have *started*.
Returns
-------
stopped : thread-safe Future
Resolves when the server is stopped |
379,736 | def prepare_for_json_encoding(obj):
obj_type = type(obj)
if obj_type == list or obj_type == tuple:
return [prepare_for_json_encoding(item) for item in obj]
if obj_type == dict:
return OrderedDict(
(prepare_for_json_encoding(k),
prepare_for_json_... | Convert an arbitrary object into just JSON data types (list, dict, unicode str, int, bool, null). |
379,737 | def statement_after(self, i):
k = i + 1
o = len(self.body)
n = o + len(self.else_body)
if k > 0:
if k < o:
return self.body.statement(k)
if k > o and k < n:
return self.else_body.statement(k)
if k < 0:
i... | Return the statement after the *i*-th one, or `None`. |
379,738 | def platform_to_tags(platform, interpreter):
if platform.count() >= 3:
tags = platform.rsplit(, 3)
else:
tags = [platform, interpreter.identity.impl_ver,
interpreter.identity.abbr_impl, interpreter.identity.abi_tag]
tags[0] = tags[0].replace(, ).replace(, )
return tags | Splits a "platform" like linux_x86_64-36-cp-cp36m into its components.
If a simple platform without hyphens is specified, we will fall back to using
the current interpreter's tags. |
379,739 | def add_async_sender(
self, partition=None, operation=None, send_timeout=60,
keep_alive=30, auto_reconnect=True, loop=None):
target = "amqps://{}{}".format(self.address.hostname, self.address.path)
if operation:
target = target + operation
handler = A... | Add an async sender to the client to send ~azure.eventhub.common.EventData object
to an EventHub.
:param partition: Optionally specify a particular partition to send to.
If omitted, the events will be distributed to available partitions via
round-robin.
:type partition: str
... |
379,740 | def QA_data_day_resample(day_data, type_=):
try:
day_data = day_data.reset_index().set_index(, drop=False)
except:
day_data = day_data.set_index(, drop=False)
CONVERSION = {
: ,
: ,
: ,
: ,
: ,
: ,
:
} if in d... | 日线降采样
Arguments:
day_data {[type]} -- [description]
Keyword Arguments:
type_ {str} -- [description] (default: {'w'})
Returns:
[type] -- [description] |
379,741 | def switch_state(request):
if request.session.get(SESSION_KEY):
request.session[SESSION_KEY] = False
else:
request.session[SESSION_KEY] = True
return redirect(url) | Switch the default version state in
the session. |
379,742 | def list_repos(remote=False):
mgr = plugins_get_mgr()
if not remote:
repomgr = mgr.get(what=, name=)
repos = repomgr.get_repo_list()
repos.sort()
return repos
else:
raise Exception("Not supported yet") | List repos
Parameters
----------
remote: Flag |
379,743 | def get(context, request, resource=None, uid=None):
if uid and not resource:
return api.get_record(uid)
if api.is_uid(resource):
return api.get_record(resource)
portal_type = api.resource_to_portal_type(resource)
if portal_type is None:
raise APIError(404, "Not ... | GET |
379,744 | def iter_bases(bases):
sequences = ([list(inspect.getmro(base)) for base in bases] +
[list(bases)])
while True:
sequences = [seq for seq in sequences if seq]
if not sequences:
return
for seq in seq... | Performs MRO linearization of a set of base classes. Yields
each base class in turn. |
379,745 | def _loop_use_cache(self, helper_function, num, fragment):
self.log([u"Examining fragment %d (cache)...", num])
fragment_info = (fragment.language, fragment.filtered_text)
if self.cache.is_cached(fragment_info):
self.log(u"Fragment cached: retrieving audio data from cache")
... | Synthesize all fragments using the cache |
379,746 | def shortentext(text, minlength, placeholder=):
return textwrap.shorten(text, minlength, placeholder=str(placeholder)) | Shorten some text by replacing the last part with a placeholder (such as '...')
:type text: string
:param text: The text to shorten
:type minlength: integer
:param minlength: The minimum length before a shortening will occur
:type placeholder: string
:param placeholder: The text to append aft... |
379,747 | def form_query(self, columns, options={}):
from_cl =
direct = options.get(, self.direct)
if direct:
if columns != :
raise ProgrammingError("Column lists cannot be specified for a direct function call.")
columns =
from_cl =
... | :param str columns: literal sql string for list of columns
:param dict options: dict supporting a single key "direct" as in the constructor
:return: sql string |
379,748 | def __get_host(node, vm_):
node
if __get_ssh_interface(vm_) == or vm_[] is None:
ip_address = node.private_ips[0]
log.info(, ip_address)
else:
ip_address = node.public_ips[0]
log.info(, ip_address)
if ip_address:
return ip_address
return node.name | Return public IP, private IP, or hostname for the libcloud 'node' object |
379,749 | def shell():
if salt.utils.platform.is_windows():
env_var =
default = r
else:
env_var =
default =
return {: os.environ.get(env_var, default)} | Return the default shell to use on this system |
379,750 | def calculate_dependencies():
order = []
for g in toposort(merge_dicts(dependencies, soft_dependencies)):
for t in sorted(g, key=lambda x: (priorities[x], x)):
order.append(t)
return order | Calculate test dependencies
First do a topological sorting based on the dependencies.
Then sort the different dependency groups based on priorities. |
379,751 | def Enumerate():
hid_mgr = iokit.IOHIDManagerCreate(None, None)
if not hid_mgr:
raise errors.OsHidError()
iokit.IOHIDManagerSetDeviceMatching(hid_mgr, None)
device_set_ref = iokit.IOHIDManagerCopyDevices(hid_mgr)
if not device_set_ref:
raise errors.OsHidError()
num =... | See base class. |
379,752 | def delete_template(self, temp_id=None, params={}, callback=None, **kwargs):
url = self.mk_url(*[, , temp_id])
self.client.fetch(
self.mk_req(url, method=, **kwargs),
callback = callback
) | Delete a search template.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html>`_
:arg temp_id: Template ID |
379,753 | def text2lm(text, output_file, vocab_file=None, text2idngram_kwargs={}, idngram2lm_kwargs={}):
if vocab_file:
used_vocab_file = vocab_file
else:
with tempfile.NamedTemporaryFile(suffix=, delete=False) as f:
used_vocab_file = f.name
text2vocab(text, used_vocab_fi... | Convienience function to directly convert text (and vocabulary) into a language model. |
379,754 | def oneshot(self, query, **params):
if "exec_mode" in params:
raise TypeError("Cannot specify an exec_mode to oneshot.")
params[] = params.get(, )
return self.post(search=query,
exec_mode="oneshot",
**params).body | Run a oneshot search and returns a streaming handle to the results.
The ``InputStream`` object streams XML fragments from the server. To
parse this stream into usable Python objects,
pass the handle to :class:`splunklib.results.ResultsReader`::
import splunklib.client as client
... |
379,755 | def on(self, left_speed, right_speed):
(left_speed_native_units, right_speed_native_units) = self._unpack_speeds_to_native_units(left_speed, right_speed)
self.left_motor.speed_sp = int(round(left_speed_native_units))
self.right_motor.speed_sp = int(round(right_speed_native_uni... | Start rotating the motors according to ``left_speed`` and ``right_speed`` forever.
Speeds can be percentages or any SpeedValue implementation. |
379,756 | def get_nni_installation_path():
def try_installation_path_sequentially(*sitepackages):
def _generate_installation_path(sitepackages_path):
python_dir = get_python_dir(sitepackages_path)
entry_file = os.path.join(python_dir, , )
if os.path.isfile(entry_file)... | Find nni lib from the following locations in order
Return nni root directory if it exists |
379,757 | def unlock(self):
if self.queue:
function, argument = self.queue.popleft()
function(argument)
else:
self.locked = False | Unlock a mutex. If the queue is not empty, call the next
function with its argument. |
379,758 | def apply_args(job, inputs, optional_inputs=None):
_apply_args_loop(job, inputs, INPUT_FIELD)
_apply_args_loop(job, optional_inputs, OPTIONAL_FIELD)
return job | This function is error checking before the job gets
updated.
:param job: Must be a valid job
:param inputs: Must be a tuple type
:param optional_inputs: optional for OptionalInputs
:return: job |
379,759 | def get_resource_bin_session(self, proxy):
if not self.supports_resource_bin():
raise errors.Unimplemented()
return sessions.ResourceBinSession(proxy=proxy, runtime=self._runtime) | Gets the session for retrieving resource to bin mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.ResourceBinSession) - a
``ResourceBinSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
... |
379,760 | def _bin_op(instance, opnode, op, other, context, reverse=False):
if reverse:
method_name = protocols.REFLECTED_BIN_OP_METHOD[op]
else:
method_name = protocols.BIN_OP_METHOD[op]
return functools.partial(
_invoke_binop_inference,
instance=instance,
op=op,
... | Get an inference callable for a normal binary operation.
If *reverse* is True, then the reflected method will be used instead. |
379,761 | def bounded_by_sigmas(self, sigmas=3, square=False):
bounds = self.limits_sigma(sigmas=sigmas, square=square)
return SubspaceBounded(self, bounds) | Returns a bounded subspace (SubspaceBounded) with limits given by Subspace.limits_sigma()
:rtype: SubspaceBounded |
379,762 | def get_conn(self, urlparsed=None):
if not urlparsed:
urlparsed = self.dsc_parsed2
if urlparsed.scheme == :
return HTTPConnection(urlparsed.netloc)
else:
return HTTPSConnection(urlparsed.netloc) | Returns an HTTPConnection based on the urlparse result given or the
default Swift cluster (internal url) urlparse result.
:param urlparsed: The result from urlparse.urlparse or None to use the
default Swift cluster's value |
379,763 | def estimate(s1, s2):
s1bb = s1.get_bounding_box()
s2bb = s2.get_bounding_box()
total_area = ((s2bb[] - s2bb[]+1) *
(s2bb[] - s2bb[]+1))
total_area = float(total_area)
top_area = 0.0
superscript_area = 0.0
right_area = 0.0
subscript_area = 0.0
bottom_area = 0.0... | Estimate the spacial relationship by
examining the position of the bounding boxes.
Parameters
----------
s1 : HandwrittenData
s2 : HandwrittenData
Returns
-------
dict of probabilities
{'bottom': 0.1,
'subscript': 0.2,
'right': 0.3,
'superscript': 0.3... |
379,764 | def imbalance_metrics(data):
if not data:
return 0
imb = 0
num_classes=float(len(Counter(data)))
for x in Counter(data).values():
p_x = float(x)/len(data)
if p_x > 0:
imb += (p_x - 1/num_classes)*(p_x - 1/num_classes)
worst_case=(num_classes-1)*pow... | Computes imbalance metric for a given dataset.
Imbalance metric is equal to 0 when a dataset is perfectly balanced (i.e. number of in each class is exact).
:param data : pandas.DataFrame
A dataset in a panda's data frame
:returns int
A value of imbalance metric, where zero means that the ... |
379,765 | def get_indicator(self, resource):
path = resource.real_path
if os.name != and os.path.isdir(path):
return (os.path.getmtime(path),
len(os.listdir(path)),
os.path.getsize(path))
return (os.path.getmtime(path),
... | Return the modification time and size of a `Resource`. |
379,766 | def j0(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_j0,
(BigFloat._implicit_convert(x),),
context,
) | Return the value of the first kind Bessel function of order 0 at x. |
379,767 | async def data(
self, message: Union[str, bytes], timeout: DefaultNumType = _default
) -> SMTPResponse:
await self._ehlo_or_helo_if_needed()
self._raise_error_if_disconnected()
if timeout is _default:
timeout = self.timeout
if isinstance(mess... | Send an SMTP DATA command, followed by the message given.
This method transfers the actual email content to the server.
:raises SMTPDataError: on unexpected server response code
:raises SMTPServerDisconnected: connection lost |
379,768 | def cmd_slow_requests(self):
slow_requests = [
line.time_wait_response
for line in self._valid_lines
if line.time_wait_response > 1000
]
return slow_requests | List all requests that took a certain amount of time to be
processed.
.. warning::
By now hardcoded to 1 second (1000 milliseconds), improve the
command line interface to allow to send parameters to each command
or globally. |
379,769 | def objective_fun(theta, hamiltonian=None,
quantum_resource=QVMConnection(sync_endpoint=)):
if hamiltonian is None:
return 1.0
if isinstance(hamiltonian, PauliSum):
result = estimate_locally_commuting_operator(ucc_circuit(theta), hamiltonian,
... | Evaluate the Hamiltonian bny operator averaging
:param theta:
:param hamiltonian:
:return: |
379,770 | def _pos(self, idx):
if idx < 0:
last_len = len(self._lists[-1])
if (-idx) <= last_len:
return len(self._lists) - 1, last_len + idx
idx += self._len
if idx < 0:
raise IndexError()
elif idx >= self._len:
... | Convert an index into a pair (alpha, beta) that can be used to access
the corresponding _lists[alpha][beta] position.
Most queries require the index be built. Details of the index are
described in self._build_index.
Indexing requires traversing the tree to a leaf node. Each node has
... |
379,771 | def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode:
return InstanceNode(instance, xml_node, node_globals) | Wraps passed instance with InstanceNode |
379,772 | def get_items_for_config_file_output(self, source_to_settings,
parsed_namespace):
config_file_items = OrderedDict()
for source, settings in source_to_settings.items():
if source == _COMMAND_LINE_SOURCE_KEY:
_, existing_command... | Converts the given settings back to a dictionary that can be passed
to ConfigFormatParser.serialize(..).
Args:
source_to_settings: the dictionary described in parse_known_args()
parsed_namespace: namespace object created within parse_known_args()
Returns:
an ... |
379,773 | def decode_struct_fields(self, ins, fields, obj):
for name, field_data_type in fields:
if name in obj:
try:
v = self.json_compat_obj_decode_helper(field_data_type, obj[name])
setattr(ins, name, v)
except bv.ValidationEr... | Args:
ins: An instance of the class representing the data type being decoded.
The object will have its fields set.
fields: A tuple of (field_name: str, field_validator: Validator)
obj (dict): JSON-compatible dict that is being decoded.
strict (bool): See :... |
379,774 | def get_data_file_attachment(self, identifier, resource_id):
model_run = self.get_object(identifier)
if model_run is None:
return None, None
if not resource_id in model_run.attachments:
return None, None
attachment = model_run.a... | Get path to attached data file with given resource identifer. If no
data file with given id exists the result will be None.
Raise ValueError if an image archive with the given resource identifier
is attached to the model run instead of a data file.
Parameters
----------
... |
379,775 | def update(ctx, migrate=False):
msg =
if migrate:
msg +=
header(msg)
info()
lrun()
lrun()
info()
lrun()
if migrate:
info()
lrun() | Perform a development update |
379,776 | def regularpage(foldername=None, pagename=None):
if foldername is None and pagename is None:
raise ExperimentError()
if foldername is None and pagename is not None:
return render_template(pagename)
else:
return render_template(foldername+"/"+pagename) | Route not found by the other routes above. May point to a static template. |
379,777 | def db_putString(self, db_name, key, value):
warnings.warn(, DeprecationWarning)
return (yield from self.rpc_call(,
[db_name, key, value])) | https://github.com/ethereum/wiki/wiki/JSON-RPC#db_putstring
DEPRECATED |
379,778 | def find_editor() -> str:
editor = os.environ.get()
if not editor:
if sys.platform[:3] == :
editor =
else:
if which(editor):
break
return editor | Find a reasonable editor to use by default for the system that the cmd2 application is running on. |
379,779 | def load_genomic_CDR3_anchor_pos_and_functionality(anchor_pos_file_name):
anchor_pos_and_functionality = {}
anchor_pos_file = open(anchor_pos_file_name, )
first_line = True
for line in anchor_pos_file:
if first_line:
first_line = False
continue
... | Read anchor position and functionality from file.
Parameters
----------
anchor_pos_file_name : str
File name for the functionality and position of a conserved residue
that defines the CDR3 region for each V or J germline sequence.
Returns
-------
anchor_pos_and_functio... |
379,780 | def _process_file(self):
print
with open(self._rebase_file, ) as f:
raw = f.readlines()
names = [line.strip()[3:] for line in raw if line.startswith()]
seqs = [line.strip()[3:] for line in raw if line.startswith()]
if len(names) != len(seqs):
rai... | Process rebase file into dict with name and cut site information. |
379,781 | def add_additional_options(cls, parser):
group = OptionGroup(parser, "Target Engine Options",
"These options are not required, but may be "
"provided if a specific "
"BPMN application engine is targeted.")
group... | Override in subclass if required. |
379,782 | def read_stat():
data = []
with open("/proc/stat", "rb") as stat_file:
for line in stat_file:
cpu_stat = line.split()
if cpu_stat[0][:3] != b"cpu":
break
if len(cpu_stat[0]) == 3:
continue
data.append(
... | Returns the system stat information.
:returns: The system stat information.
:rtype: list |
379,783 | def project_closed(self, project):
yield from super().project_closed(project)
hdd_files_to_close = yield from self._find_inaccessible_hdd_files()
for hdd_file in hdd_files_to_close:
log.info("Closing VirtualBox VM disk file {}".format(os.path.basename(hdd_file)))
... | Called when a project is closed.
:param project: Project instance |
379,784 | def sha_github_file(cls, config, repo_file, repository_api, repository_branch):
repo_file_sha = None
cfg = config.get_conf()
github_token = cfg[][]
headers = {"Authorization": "token " + github_token}
url_dir = repository_api + "/git/trees/" + repository_branch
... | Return the GitHub SHA for a file in the repository |
379,785 | def parse_param_signature(sig):
match = PARAM_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError( + sig)
groups = match.groups()
modifiers = groups[0].split()
typ, name, _, default = groups[-4:]
return ParamTuple(name=name, typ=typ,
default=default, mod... | Parse a parameter signature of the form: type name (= default)? |
379,786 | def nz(value, none_value, strict=True):
if not DEBUG:
debug = False
else:
debug = False
if debug: print("START nz frameworkutilities.py ----------------------\n")
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val =... | This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
... |
379,787 | def get_imap_capabilities(server):
capabilities = list(map(str, list(server.capabilities())))
for i in range(len(capabilities)):
capabilities[i] = str(capabilities[i]).replace("b",
"")
logger.debug("IMAP server supports: {0}".f... | Returns a list of an IMAP server's capabilities
Args:
server (imapclient.IMAPClient): An instance of imapclient.IMAPClient
Returns (list): A list of capabilities |
379,788 | def quantile_for_single_value(self, **kwargs):
if self._is_transposed:
kwargs["axis"] = kwargs.get("axis", 0) ^ 1
return self.transpose().quantile_for_single_value(**kwargs)
axis = kwargs.get("axis", 0)
q = kwargs.get("q", 0.5)
assert type(q) is float
... | Returns quantile of each column or row.
Returns:
A new QueryCompiler object containing the quantile of each column or row. |
379,789 | def install_package(tar_url, folder, md5_url=,
on_download=lambda: None, on_complete=lambda: None):
data_file = join(folder, basename(tar_url))
md5_url = md5_url.format(tar_url=tar_url)
try:
remote_md5 = download(md5_url).decode().split()[0]
except (UnicodeDecodeError, ... | Install or update a tar package that has an md5
Args:
tar_url (str): URL of package to download
folder (str): Location to extract tar. Will be created if doesn't exist
md5_url (str): URL of md5 to use to check for updates
on_download (Callable): Function that gets called when downlo... |
379,790 | def get(self, reference, country, target=datetime.date.today()):
reference = self.reference if reference is None else reference
reference_value = self.data.get(reference, country).value
target_value = self.data.get(target, country).value
return sel... | Get the inflation/deflation value change for the target date based
on the reference date. Target defaults to today and the instance's
reference and country will be used if they are not provided as
parameters |
379,791 | def ext(self):
if self._filename:
return os.path.splitext(self._filename)[1].lstrip()
return {
CT.ASF: ,
CT.AVI: ,
CT.MOV: ,
CT.MP4: ,
CT.MPG: ,
CT.MS_VIDEO: ,
CT... | Return the file extension for this video, e.g. 'mp4'.
The extension is that from the actual filename if known. Otherwise
it is the lowercase canonical extension for the video's MIME type.
'vid' is used if the MIME type is 'video/unknown'. |
379,792 | def is_flapping(self, alert, window=1800, count=2):
pipeline = [
{: {
: alert.environment,
: alert.resource,
: alert.event,
: alert.customer
}},
{: },
{: {
: {: datetime.utcno... | Return true if alert severity has changed more than X times in Y seconds |
379,793 | def statistical_inefficiency(X, truncate_acf=True):
assert np.ndim(X[0]) == 1,
N = _maxlength(X)
xflat = np.concatenate(X)
Xmean = np.mean(xflat)
X0 = [x-Xmean for x in X]
x2m = np.mean(xflat ** 2)
corrsum = 0.0
for lag in range(N):
acf = 0.0
... | Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are
only :math:`I \cdot N` effective ... |
379,794 | def create_embedded_unclaimed_draft(self, test_mode=False, client_id=None, is_for_embedded_signing=False, requester_email_address=None, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, requesting_redirect_url=None, form_fields_per... | Creates a new Draft to be used for embedded requesting
Args:
test_mode (bool, optional): Whether this is a test, the signature request created from this draft will not be legally binding if set to True. Defaults to False.
client_id (str): Cli... |
379,795 | def save_namespace(self, filename):
from spyder_kernels.utils.nsview import get_remote_data
from spyder_kernels.utils.iofuncs import iofunctions
ns = self._get_current_namespace()
settings = self.namespace_view_settings
data = get_remote_data(ns, settings, mode=,
... | Save namespace into filename |
379,796 | def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None:
if not self.has_namespace(namespace):
raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name) | Raise an exception if the namespace is not defined. |
379,797 | def write(self, pack_uri, blob):
self._zipf.writestr(pack_uri.membername, blob) | Write *blob* to this zip package with the membername corresponding to
*pack_uri*. |
379,798 | def from_function(cls, function):
module_name = function.__module__
function_name = function.__name__
class_name = ""
function_source_hasher = hashlib.sha1()
try:
source = inspect.getsource(function)
if sys.version_info[... | Create a FunctionDescriptor from a function instance.
This function is used to create the function descriptor from
a python function. If a function is a class function, it should
not be used by this function.
Args:
cls: Current class which is required argument for classmeth... |
379,799 | def param_array(self):
if (self.__dict__.get(, None) is None) or (self._param_array_.size != self.size):
self._param_array_ = np.empty(self.size, dtype=np.float64)
return self._param_array_ | Array representing the parameters of this class.
There is only one copy of all parameters in memory, two during optimization.
!WARNING!: setting the parameter array MUST always be done in memory:
m.param_array[:] = m_copy.param_array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.