Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
385,000
def add_with_properties(self, model, name=None, update_dict=None, bulk=True, **kwargs): if self.category != Category.INSTANCE: raise APIError("Part should be of category INSTANCE") name = name or model.name action = properties_update_dict = dict() for prop_...
Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronte...
385,001
def get_event(self, client, check): data = self._request(, .format(client, check)) return data.json()
Returns an event for a given client & check name.
385,002
def stop_server(self): if self.rpc_server is not None: try: self.rpc_server.socket.shutdown(socket.SHUT_RDWR) except: log.warning("Failed to shut down server socket") self.rpc_server.shutdown()
Stop serving. Also stops the thread.
385,003
def _any_bound_condition_fails_criterion(agent, criterion): bc_agents = [bc.agent for bc in agent.bound_conditions] for b in bc_agents: if not criterion(b): return True return False
Returns True if any bound condition fails to meet the specified criterion. Parameters ---------- agent: Agent The agent whose bound conditions we evaluate criterion: function Evaluates criterion(a) for each a in a bound condition and returns True if any agents fail to meet t...
385,004
def delete(self, request, bot_id, hook_id, id, format=None): bot = self.get_bot(bot_id, request.user) hook = self.get_hook(hook_id, bot, request.user) recipient = self.get_recipient(id, hook, request.user) recipient.delete() return Response(status=status.HTTP_204_NO_CONT...
Delete an existing telegram recipient --- responseMessages: - code: 401 message: Not authenticated
385,005
def from_json(cls, service_dict): sd = service_dict.copy() service_endpoint = sd.get(cls.SERVICE_ENDPOINT) if not service_endpoint: logger.error( ) raise IndexError _type = sd.get() if not _type: logger.error() ...
Create a service object from a JSON string.
385,006
def clone(self, document): wrapped = document.wrap() if in wrapped: del wrapped[] return type(document).unwrap(wrapped, session=self)
Serialize a document, remove its _id, and deserialize as a new object
385,007
def tt_qr(X, left_to_right=True): X = X.round(eps=0) numDims = X.d coresX = tt.tensor.to_list(X) if left_to_right: for dim in xrange(0, numDims-1): coresX = cores_orthogonalization_step( coresX, dim, left_to_right=left_to_right) last_core =...
Orthogonalizes a TT tensor from left to right or from right to left. :param: X - thensor to orthogonalise :param: direction - direction. May be 'lr/LR' or 'rl/RL' for left/right orthogonalization :return: X_orth, R - orthogonal tensor and right (left) upper (lower) triangular mat...
385,008
def remove_breakpoint(self, event_type, bp=None, filter_func=None): if bp is None and filter_func is None: raise ValueError() try: if bp is not None: self._breakpoints[event_type].remove(bp) else: self._breakpoints[event_type...
Removes a breakpoint. :param bp: The breakpoint to remove. :param filter_func: A filter function to specify whether each breakpoint should be removed or not.
385,009
def add(self, album, objects, object_type=None, **kwds): return self._add_remove("add", album, objects, object_type, **kwds)
Endpoint: /album/<id>/<type>/add.json Add objects (eg. Photos) to an album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. Returns the updated album object.
385,010
def docs(root_url, path): root_url = root_url.rstrip() path = path.lstrip() if root_url == OLD_ROOT_URL: return .format(path) else: return .format(root_url, path)
Generate URL for path in the Taskcluster docs.
385,011
def normal(self): d = self.B - self.A return Line([-d.y, d.x], [d.y, -d.x])
:return: Line Returns a Line normal (perpendicular) to this Line.
385,012
def write(url, content, **args): with HTTPResource(url, **args) as resource: resource.write(content)
Put the object/collection into a file URL.
385,013
def resort_client_actions(portal): sorted_actions = [ "edit", "contacts", "view", "analysisrequests", "batches", "samplepoints", "profiles", "templates", "specs", "orders", "reports_listing" ] type_info = portal.po...
Resorts client action views
385,014
def multiCall(*commands, dependent=True, bundle=False, print_result=False, print_commands=False): results = [] dependent_failed = False for command in commands: if not dependent_failed: response = call(command, print_result=print_result, pr...
Calls the function 'call' multiple times, given sets of commands
385,015
def ensure_mingw_drive(win32_path): r win32_drive, _path = splitdrive(win32_path) mingw_drive = + win32_drive[:-1].lower() mingw_path = mingw_drive + _path return mingw_path
r""" replaces windows drives with mingw style drives Args: win32_path (str): CommandLine: python -m utool.util_path --test-ensure_mingw_drive Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> win32_path = r'C:/Program Files/Foobar' ...
385,016
def getFactors(self, aLocation, axisOnly=False, allFactors=False): deltas = [] aLocation.expand(self.getAxisNames()) limits = getLimits(self._allLocations(), aLocation) for deltaLocationTuple, (mathItem, deltaName) in sorted(self.items()): deltaLocation = Location(de...
Return a list of all factors and math items at aLocation. factor, mathItem, deltaName all = True: include factors that are zero or near-zero
385,017
def reprString(self, string, length): if isinstance(string, int): length = min(length, self.length - string) string = self.string[string:string + length] voc = self.voc res = self.tokSep.join((voc[id] for id in string[:length])) if self.unit == UNIT_WORD...
Output a string of length tokens in the original form. If string is an integer, it is considered as an offset in the text. Otherwise string is considered as a sequence of ids (see voc and tokId). >>> SA=SuffixArray('mississippi', UNIT_BYTE) >>> SA.reprString(0, 3) 'mis' ...
385,018
def clear_caches(delete_all=False): global _time_caches if delete_all: _time_caches = [] _parser = { "default": CodeParser() } else: for tc in _time_caches: for key, (t, value) in list(tc.items()): if t < time.time(): ...
Fortpy caches many things, that should be completed after each completion finishes. :param delete_all: Deletes also the cache that is normally not deleted, like parser cache, which is important for faster parsing.
385,019
def save_model(self, request, obj, form, change): obj.save() if notification: if obj.parent_msg is None: sender_label = recipients_label = else: sender_label = recipients_label = ...
Saves the message for the recipient and looks in the form instance for other possible recipients. Prevents duplication by excludin the original recipient from the list of optional recipients. When changing an existing message and choosing optional recipients, the message is effectively ...
385,020
def add_requirements(self, metadata_path): additional = list(self.setupcfg_requirements()) if not additional: return pkg_info = read_pkg_info(metadata_path) if in pkg_info or in pkg_info: warnings.warn() del pkg_info[] del pkg_info[] ...
Add additional requirements from setup.cfg to file metadata_path
385,021
def copy(self): new_digest = Digest(self.digest_type) libcrypto.EVP_MD_CTX_copy(new_digest.ctx, self.ctx) return new_digest
Creates copy of the digest CTX to allow to compute digest while being able to hash more data
385,022
def fill_triangle(setter, x0, y0, x1, y1, x2, y2, color=None, aa=False): a = b = y = last = 0 if y0 > y1: y0, y1 = y1, y0 x0, x1 = x1, x0 if y1 > y2: y2, y1 = y1, y2 x2, x1 = x1, x2 if y0 > y1: y0, y1 = y1, y0 x0, x1 = x1, x0 if y0 == y2: ...
Draw solid triangle with points x0,y0 - x1,y1 - x2,y2
385,023
def is_all_field_none(self): if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._type_ is not None: return False if self._cvc2 is not No...
:rtype: bool
385,024
def key_81_CosSin_2009(): r dlf = DigitalFilter(, ) dlf.base = np.array([ 3.354626279025119e-04, 4.097349789797864e-04, 5.004514334406104e-04, 6.112527611295723e-04, 7.465858083766792e-04, 9.118819655545162e-04, 1.113775147844802e-03, 1.360368037547893e-03, 1.661557273173934e-03...
r"""Key 81 pt CosSin filter, as published in [Key09]_. Taken from file ``FilterModules.f90`` provided with 1DCSEM_. License: `Apache License, Version 2.0, <http://www.apache.org/licenses/LICENSE-2.0>`_.
385,025
def _close(self, args): reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._x_close_ok() raise error_for_code(reply_code, reply_text, (class_id, method_id...
Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender pro...
385,026
def add_line(self, line=, *, empty=False): max_page_size = self.max_size - self._prefix_len - 2 if len(line) > max_page_size: raise RuntimeError( % (max_page_size)) if self._count + len(line) + 1 > self.max_size: self.close_page() self._count += len(lin...
Adds a line to the current page. If the line exceeds the :attr:`max_size` then an exception is raised. Parameters ----------- line: :class:`str` The line to add. empty: :class:`bool` Indicates if another empty line should be added. Raise...
385,027
def _create_arg_dict(self, tenant_id, data, in_sub, out_sub): in_seg, in_vlan = self.get_in_seg_vlan(tenant_id) out_seg, out_vlan = self.get_out_seg_vlan(tenant_id) in_ip_dict = self.get_in_ip_addr(tenant_id) out_ip_dict = self.get_out_ip_addr(tenant_id) excl_list = [in_...
Create the argument dictionary.
385,028
def fetch_json(self, uri_path, http_method=, query_params=None, body=None, headers=None): query_params = query_params or {} headers = headers or {} query_params = self.add_authorisation(query_params) uri = self.build_uri(uri_path, query_params) allow...
Make a call to Trello API and capture JSON response. Raises an error when it fails. Returns: dict: Dictionary with the JSON data
385,029
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): was_imported = in sys.modules or in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) ...
Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is n...
385,030
def infer_format(filename:str) -> str: _, ext = os.path.splitext(filename) return ext
Return extension identifying format of given filename
385,031
def client_for(service, service_module, thrift_service_name=None): assert service_module, service = service or if not thrift_service_name: thrift_service_name = service_module.__name__.rsplit(, 1)[-1] method_names = get_service_methods(service_module.Iface) def init( sel...
Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registered with Hyperbahn under the name "comment", here's how this might be ...
385,032
def _bse_cli_list_ref_formats(args): all_refformats = api.get_reference_formats() if args.no_description: liststr = all_refformats.keys() else: liststr = format_columns(all_refformats.items()) return .join(liststr)
Handles the list-ref-formats subcommand
385,033
async def notifications(dev: Device, notification: str, listen_all: bool): notifications = await dev.get_notifications() async def handle_notification(x): click.echo("got notification: %s" % x) if listen_all: if notification is not None: await dev.services[notification].li...
List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are requested.
385,034
def get(self, request): sections_list = self.generate_sections() p = Paginator(sections_list, 25) page = request.GET.get() try: sections = p.page(page) except PageNotAnInteger: sections = p.page(1) except EmptyPage: ...
Handle HTTP GET request. Returns template and context from generate_page_title and generate_sections to populate template.
385,035
def __check_prefix_conflict(self, existing_ni_or_ns_uri, incoming_prefix): if incoming_prefix not in self.__prefix_map: return prefix_check_ni = self.__prefix_map[incoming_prefix] if isinstance(existing_ni_or_ns_uri, _NamespaceInfo): existing_ni = exis...
If existing_ni_or_ns_uri is a _NamespaceInfo object (which must be in this set), then caller wants to map incoming_prefix to that namespace. This function verifies that the prefix isn't already mapped to a different namespace URI. If it is, an exception is raised. Otherwise, existing_...
385,036
def encode(self, payload): token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm) return token.decode()
Returns an encoded token for the given payload dictionary.
385,037
def pkg(pkg_path, pkg_sum, hash_type, test=None, **kwargs): * popts = salt.utils.state.get_sls_opts(__opts__, **kwargs) if not os.path.isfile(pkg_path): return {} if not salt.utils.hashutils.get_hash(pkg_path, hash_type) == pkg_sum: return {} root...
Execute a packaged state run, the packaged state run will exist in a tarball available locally. This packaged state can be generated using salt-ssh. CLI Example: .. code-block:: bash salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5
385,038
def exclude(prop): t replicate property that is normally replicated: ordering column, many-to-one relation that is marked for replication from other side.' if isinstance(prop, QueryableAttribute): prop = prop.property assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty)) _e...
Don't replicate property that is normally replicated: ordering column, many-to-one relation that is marked for replication from other side.
385,039
def apply_dict_of_variables_vfunc( func, *args, signature, join=, fill_value=None ): args = [_as_variables_or_variable(arg) for arg in args] names = join_dict_keys(args, how=join) grouped_by_name = collect_dict_values(args, names, fill_value) result_vars = OrderedDict() for name, variable_...
Apply a variable level function over dicts of DataArray, DataArray, Variable and ndarray objects.
385,040
def create_transient(self, input_stream, original_name, length=None): ext = os.path.splitext(original_name)[1] transient = self.new_transient(ext) if not os.path.isdir(self.transient_root): os.makedirs(self.transient_root) self._copy_file(input_stream, transient.pat...
Create TransientFile and file on FS from given input stream and original file name.
385,041
def LEA(cpu, dest, src): dest.write(Operators.EXTRACT(src.address(), 0, dest.size))
Loads effective address. Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors addressing modes; the destination operand is a g...
385,042
def analyze_beam_spot(scan_base, combine_n_readouts=1000, chunk_size=10000000, plot_occupancy_hists=False, output_pdf=None, output_file=None): combine_n_readouts//data//SCC_50_fei4_self_trigger_scan_390 time_stamp = [] x = [] y = [] for data_file in scan_base: with tb.open_file(data_file + ...
Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The occupancy is determined for the given combined events and stored into a pdf file. At the end the beam x and y is plotted into a scatter plot with absolute ...
385,043
def update_project(id, **kwargs): content = update_project_raw(id, **kwargs) if content: return utils.format_json(content)
Update an existing Project with new information
385,044
def clean(args): p = OptionParser(clean.__doc__) opts, args = p.parse_args(args) for link_name in os.listdir(os.getcwd()): if not op.islink(link_name): continue logging.debug("remove symlink `{0}`".format(link_name)) os.unlink(link_name)
%prog clean Removes all symlinks from current folder
385,045
def mailto_to_envelope(mailto_str): from alot.db.envelope import Envelope headers, body = parse_mailto(mailto_str) return Envelope(bodytext=body, headers=headers)
Interpret mailto-string into a :class:`alot.db.envelope.Envelope`
385,046
def procrustes(anchors, X, scale=True, print_out=False): def centralize(X): n = X.shape[0] ones = np.ones((n, 1)) return X - np.multiply(1 / n * np.dot(ones.T, X), ones) m = anchors.shape[0] N, d = X.shape assert m >= d, X_m = X[N - m:, :] ones = np.ones((m, 1)) ...
Fit X to anchors by applying optimal translation, rotation and reflection. Given m >= d anchor nodes (anchors in R^(m x d)), return transformation of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense. :param anchors: Matrix of shape m x d, where m is number of ancho...
385,047
def infer_type(self, in_type): return in_type, [in_type[0]]*len(self.list_outputs()), \ [in_type[0]]*len(self.list_auxiliary_states())
infer_type interface. override to create new operators Parameters ---------- in_type : list of np.dtype list of argument types in the same order as declared in list_arguments. Returns ------- in_type : list list of argument types. Can...
385,048
def animate(self, **kwargs): super(VisSurface, self).render(**kwargs) surf_cmaps = kwargs.get(, None) tri_idxs = [] vert_coords = [] trisurf_params = [] frames = [] frames_tris = [] num_vertices = 0 f...
Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps are a visualization feature of Matplotlib....
385,049
def get_failed_jobs(self, fail_running=False, fail_pending=False): failed_jobs = {} for job_key, job_details in self.jobs.items(): if job_details.status == JobStatus.failed: failed_jobs[job_key] = job_details elif job_details.status == JobStatus.partial_f...
Return a dictionary with the subset of jobs that are marked as failed Parameters ---------- fail_running : `bool` If True, consider running jobs as failed fail_pending : `bool` If True, consider pending jobs as failed Returns ------- fai...
385,050
def set_subcommands(func, parser): if hasattr(func, ) and func.__subcommands__: sub_parser = parser.add_subparsers( title=SUBCOMMANDS_LIST_TITLE, dest=, description=SUBCOMMANDS_LIST_DESCRIPTION.format( func.__cmd_name__), help=func.__doc__) fo...
Set subcommands.
385,051
def set_memory(self, total=None, static=None): if total: self.params["rem"]["mem_total"] = total if static: self.params["rem"]["mem_static"] = static
Set the maxium allowed memory. Args: total: The total memory. Integer. Unit: MBytes. If set to None, this parameter will be neglected. static: The static memory. Integer. Unit MBytes. If set to None, this parameterwill be neglected.
385,052
def download_sysdig_capture(self, capture_id): url = .format( url=self.url, id=capture_id, product=self.product) res = requests.get(url, headers=self.hdrs, verify=self.ssl_verify) if not self._checkResponse(res): return False, self.lasterr return True, r...
**Description** Download a sysdig capture by id. **Arguments** - **capture_id**: the capture id to download. **Success Return Value** The bytes of the scap
385,053
def gaussian_prior_model_for_arguments(self, arguments): return CollectionPriorModel( { key: value.gaussian_prior_model_for_arguments(arguments) if isinstance(value, AbstractPriorModel) else value for key, value in self.__dict_...
Parameters ---------- arguments: {Prior: float} A dictionary of arguments Returns ------- prior_models: [PriorModel] A new list of prior models with gaussian priors
385,054
def _check_seismogenic_depths(self, upper_depth, lower_depth): if upper_depth: if upper_depth < 0.: raise ValueError( ) else: self.upper_depth = upper_depth else: self.upper_depth = 0.0...
Checks the seismic depths for physical consistency :param float upper_depth: Upper seismogenic depth (km) :param float lower_depth: Lower seismogenic depth (km)
385,055
def directionaldiff(f, x0, vec, **options): x0 = np.asarray(x0) vec = np.asarray(vec) if x0.size != vec.size: raise ValueError() vec = np.reshape(vec/np.linalg.norm(vec.ravel()), x0.shape) return Derivative(lambda t: f(x0+t*vec), **options)(0)
Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: ar...
385,056
def write_chisq(page, injList, grbtag): if injList: th = []+injList + [] else: th= [,] injList = [] td = [] plots = [,,, ] for test in plots: pTag = test.replace(,).title() d = [pTag] for inj in injList + []: plot = markup.page() ...
Write injection chisq plots to markup.page object page
385,057
def make_url(*args, **kwargs): base = "/".join(args) if kwargs: return "%s?%s" % (base, urlencode(kwargs)) else: return base
Makes a URL from component parts
385,058
def _check_for_answers(self, pk): longest_match = () if len(self._answer_patterns) > 0: data = (pk.header,) + tuple(pk.data) for p in list(self._answer_patterns.keys()): logger.debug(, p, data) if len(p) <= len(data): i...
Callback called for every packet received to check if we are waiting for an answer on this port. If so, then cancel the retry timer.
385,059
def _pnorm_default(x, p): return np.linalg.norm(x.data.ravel(), ord=p)
Default p-norm implementation.
385,060
def calculate_md5(filename, length): assert length >= 0 if length == 0: return md5_summer = hashlib.md5() f = open(filename, ) try: bytes_read = 0 while bytes_read < length: chunk_size = min(MD5_CHUNK_SIZE, length - bytes_read) ch...
Calculate the MD5 hash of a file, up to length bytes. Returns the MD5 in its binary form, as an 8-byte string. Raises IOError or OSError in case of error.
385,061
def get_docker_tag(platform: str, registry: str) -> str: platform = platform if any(x in platform for x in [, ]) else .format(platform) if not registry: registry = "mxnet_local" return "{0}/{1}".format(registry, platform)
:return: docker tag to be used for the container
385,062
async def _get_popular_people_page(self, page=1): return await self.get_data(self.url_builder( , url_params=OrderedDict(page=page), ))
Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data.
385,063
def to_bytes(self, frame, state): frame = six.binary_type(frame) return self.encode_length(frame, state) + frame
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
385,064
def get_search_result(self, ddoc_id, index_name, **query_params): ddoc = DesignDocument(self, ddoc_id) return self._get_search_result( .join((ddoc.document_url, , index_name)), **query_params )
Retrieves the raw JSON content from the remote database based on the search index on the server, using the query_params provided as query parameters. A ``query`` parameter containing the Lucene query syntax is mandatory. Example for search queries: .. code-block:: python ...
385,065
def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs): def func_wrapper(ds): return grid_attrs_to_aospy_names(func(ds, **kwargs), grid_attrs) return func_wrapper
Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess function is called on the loaded Dataset before aospy's is applied. An example fo...
385,066
def update(self, instance): assert isinstance(instance, UnitOfWork) if instance.db_id: query = {: ObjectId(instance.db_id)} else: query = {unit_of_work.PROCESS_NAME: instance.process_name, unit_of_work.TIMEPERIOD: instance.timeperiod, ...
method finds unit_of_work record and change its status
385,067
def inverse(self): inv = np.empty(self.size, np.int) inv[self.sorter] = self.sorted_group_rank_per_key return inv
return index array that maps unique values back to original space. unique[inverse]==keys
385,068
def _check_subject_identifier_matches_requested(self, authentication_request, sub): if in authentication_request: requested_id_token_sub = authentication_request[].get(, {}).get() requested_userinfo_sub = authentication_request[].get(, {}).get() if requeste...
Verifies the subject identifier against any requested subject identifier using the claims request parameter. :param authentication_request: authentication request :param sub: subject identifier :raise AuthorizationError: if the subject identifier does not match the requested one
385,069
def setupTable_VORG(self): if "VORG" not in self.tables: return self.otf["VORG"] = vorg = newTable("VORG") vorg.majorVersion = 1 vorg.minorVersion = 0 vorg.VOriginRecords = {} vorg_count = Counter(_getVerticalOrigin(self.otf, glyph) ...
Make the VORG table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
385,070
def logs(self, prefix=): logs = [] logs += [(, np.mean(self.success_history))] if self.compute_Q: logs += [(, np.mean(self.Q_history))] logs += [(, self.n_episodes)] if prefix != and not prefix.endswith(): return [(prefix + + key, val) for key,...
Generates a dictionary that contains all collected statistics.
385,071
def get_path(self, dir=None): if not dir: dir = self.fs.getcwd() if self == dir: return path_elems = self.get_path_elements() pathname = try: i = path_elems.index(dir) except ValueError: for p in path_elems[:-1]: ...
Return path relative to the current working directory of the Node.FS.Base object that owns us.
385,072
def documentation(self): newclient = self.__class__(self.session, self.root_url) return newclient.get_raw()
Get the documentation that the server sends for the API.
385,073
def bbduk_trim(forward_in, forward_out, reverse_in=, reverse_out=, trimq=20, k=25, minlength=50, forcetrimleft=15, hdist=1, returncmd=False, **kwargs): options = kwargs_to_string(kwargs) cmd = try: subprocess.check_output(cmd.split()).decode() except subprocess.CalledProcess...
Wrapper for using bbduk to quality trim reads. Contains arguments used in OLC Assembly Pipeline, but these can be overwritten by using keyword parameters. :param forward_in: Forward reads you want to quality trim. :param returncmd: If set to true, function will return the cmd string passed to subprocess as ...
385,074
def find_application(app_id=None, app_name=None): LOGGER.debug("ApplicationService.find_application") if (app_id is None or not app_id) and (app_name is None or not app_name): raise exceptions.ArianeCallParametersError() if (app_id is not None and app_id) and (app_name is n...
find the application according application id (prioritary) or application name :param app_id: the application id :param app_name: the application name :return: found application or None if not found
385,075
def parse_definition_expr(expr, default_value=None): try: define, value = expr.split(, 1) try: value = parse_number_token(value) except ValueError: value = parse_bool_token(value) except ValueError: if expr: define, value = expr, default_v...
Parses a definition expression and returns a key-value pair as a tuple. Each definition expression should be in one of these two formats: * <variable>=<value> * <variable> :param expr: String expression to be parsed. :param default_value: (Default None) When a definiti...
385,076
def _calculate(self): self.logpriors = np.zeros_like(self.rad) for i in range(self.N-1): o = np.arange(i+1, self.N) dist = ((self.zscale*(self.pos[i] - self.pos[o]))**2).sum(axis=-1) dist0 = (self.rad[i] + self.rad[o])**2 update = self.prior_func(dist -...
# This is equivalent for i in range(self.N-1): for j in range(i+1, self.N): d = ((self.zscale*(self.pos[i] - self.pos[j]))**2).sum(axis=-1) r = (self.rad[i] + self.rad[j])**2 cost = self.prior_func(d - r) self.logpriors[i] += cost ...
385,077
def nonoverlap(item_a, time_a, item_b, time_b, max_value): return np.minimum(1 - item_a.count_overlap(time_a, item_b, time_b), max_value) / float(max_value)
Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value:...
385,078
def _compute_anelastic_attenuation_term(self, C, rrup, mag): r = (rrup**2. + (C[] * np.exp(C[] * mag + C[] * (8.5 - mag)**2.5))**2.)**.5 f3 = ((C[] + C[] * mag) * np.log(r) + (C[] + C[] * mag) * r) return f3
Compute magnitude-distance scaling term as defined in equation 21, page 2291 (Tavakoli and Pezeshk, 2005)
385,079
def query_fetch_all(self, query, values): self.cursor.execute(query, values) retval = self.cursor.fetchall() self.__close_db() return retval
Executes a db query, gets all the values, and closes the connection.
385,080
def info(self): hosts = .join(x[] for x in self.members()) mongodb_uri = + hosts + + self.repl_id result = {"id": self.repl_id, "auth_key": self.auth_key, "members": self.members(), "mongodb_uri": mongodb_uri, "or...
return information about replica set
385,081
def _parse_routes(iface, opts): opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if not in opts: _raise_error_routes(iface, , ) for opt in opts: result[opt] = opts[opt] return result
Filters given options and outputs valid settings for the route settings file.
385,082
def discover_settings(conf_base=None): settings = { : , : False, : False, : False, : {}, : {}, } if sys.platform.startswith(): settings[] = False if conf_base: merge(settings, load_config(, conf_base)) merge(settings,...
Discover custom settings for ZMQ path
385,083
def Load(self): for record in super(EventFileLoader, self).Load(): yield event_pb2.Event.FromString(record)
Loads all new events from disk. Calling Load multiple times in a row will not 'drop' events as long as the return value is not iterated over. Yields: All events in the file that have not been yielded yet.
385,084
def setup_panel_params(self, scale_x, scale_y): def train(scale, limits, trans, name): if limits is None: rangee = scale.dimension() else: rangee = scale.transform(limits) out = scale.break_info(rangee) ...
Compute the range and break information for the panel
385,085
def to_capabilities(self): capabilities = ChromeOptions.to_capabilities(self) capabilities.update(self._caps) opera_options = capabilities[self.KEY] if self.android_package_name: opera_options["androidPackage"] = self.android_package_name if self.android_dev...
Creates a capabilities with all the options that have been set and returns a dictionary with everything
385,086
def acquire(self, key): if _debug: DeviceInfoCache._debug("acquire %r", key) if isinstance(key, int): device_info = self.cache.get(key, None) elif not isinstance(key, Address): raise TypeError("key must be integer or an address") elif key.addrType not ...
Return the known information about the device and mark the record as being used by a segmenation state machine.
385,087
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.stats_iters == 0: self.gen_stats_updated, self.crit_sta...
Callback function that writes backward end appropriate data to Tensorboard.
385,088
def _find_all_versions(self, project_name): index_locations = self._get_index_urls_locations(project_name) index_file_loc, index_url_loc = self._sort_locations(index_locations) fl_file_loc, fl_url_loc = self._sort_locations( self.find_links, expand_dir=True) dep_file...
Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted
385,089
def _check_stations_csv(self, usr, root): if path.exists(path.join(usr, )): return else: copyfile(root, path.join(usr, ))
Reclocate a stations.csv copy in user home for easy manage. E.g. not need sudo when you add new station, etc
385,090
def resize_image(fullfile,fullfile_resized,_megapixels): logger.debug("%s - Resizing to %s MP"%(fullfile,_megapixels)) img = Image.open(fullfile) width,height=img.size current_megapixels=width*height/(2.0**20) new_width,new_height=resize_compute_width_height(\ fullfile,_...
Resizes image (fullfile), saves to fullfile_resized. Image aspect ratio is conserved, will be scaled to be close to _megapixels in size. Eg if _megapixels=2, will resize 2560x1920 so each dimension is scaled by ((2**(20+1*MP))/float(2560*1920))**2
385,091
def _convert_to_ndarray(self, data): if data.__class__.__name__ != "DataFrame": raise Exception(f"data is not a DataFrame but {data.__class__.__name__}.") shape_ndarray = (self._height, self._width, data.shape[1]) data_ndarray = data.values.reshape(shape_ndarray) ret...
Converts data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)
385,092
def process_bytecode(link_refs: Dict[str, Any], bytecode: bytes) -> str: all_offsets = [y for x in link_refs.values() for y in x.values()] validate_link_ref_fns = ( validate_link_ref(ref["start"] * 2, ref["length"] * 2) for ref in concat(all_offsets) ) pipe(bytecode, *validate_...
Replace link_refs in bytecode with 0's.
385,093
def delete_chat_sticker_set(self, chat_id): result = apihelper.delete_chat_sticker_set(self.token, chat_id) return result
Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on su...
385,094
def get(self): if self.bucket.get() < 1: return None now = time.time() self.mutex.acquire() try: task = self.priority_queue.get_nowait() self.bucket.desc() except Queue.Empty: self.mutex.release() return None ...
Get a task from queue when bucket available
385,095
def format_option(self, ohi): lines = [] choices = .format(ohi.choices) if ohi.choices else arg_line = ( .format(args=self._maybe_cyan(.join(ohi.display_args)), dflt=self._maybe_green(.format(choices, ohi.default)))) lines.append(arg_line) indent = ...
Format the help output for a single option. :param OptionHelpInfo ohi: Extracted information for option to print :return: Formatted help text for this option :rtype: list of string
385,096
def make_clean_visible_file(i_chunk, clean_visible_path): _clean = open(clean_visible_path, ) _clean.write() _clean.write() for idx, si in enumerate(i_chunk): if si.stream_id is None: stream_id = else: stream_id = si.stream_id ...
make a temp file of clean_visible text
385,097
def add(self, pattern, method=None, call=None, name=None): if not pattern.endswith(): pattern += parts = tuple(pattern.split()[1:]) node = self._routes for part in parts: node = node.setdefault(part, {}) if method is None: node[] = ca...
Add a url pattern. Args: pattern (:obj:`str`): URL pattern to add. This is usually '/' separated path. Parts of the URL can be parameterised using curly braces. Examples: "/", "/path/to/resource", "/resoures/{param}" method (:obj:`str`, :o...
385,098
def start_sctp_server(self, ip, port, name=None, timeout=None, protocol=None, family=): self._start_server(SCTPServer, ip, port, name, timeout, protocol, family)
Starts a new STCP server to given `ip` and `port`. `family` can be either ipv4 (default) or ipv6. pysctp (https://github.com/philpraxis/pysctp) need to be installed your system. Server can be given a `name`, default `timeout` and a `protocol`. Notice that you have to use `Accept Connec...
385,099
def _GetDirectory(self): if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return CPIODirectory(self._file_system, self.path_spec)
Retrieves a directory. Returns: CPIODirectory: a directory or None if not available.