Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
340,300
def _get_branch(self, remotes=False): return self.m( , cmdd=dict( cmd= % ( if remotes else ), cwd=self.local ), verbose=False )
Helper function to determine current branch :param remotes: List the remote-tracking branches
340,301
def add_mpl_dendrogram(dfr, fig, heatmap_gs, orientation="col"): if orientation == "row": dists = distance.squareform(distance.pdist(dfr)) spec = heatmap_gs[1, 0] orient = "left" nrows, ncols = 1, 2 height_ratios = [1] else: dists = distance.squareform...
Return a dendrogram and corresponding gridspec, attached to the fig Modifies the fig in-place. Orientation is either 'row' or 'col' and determines location and orientation of the rendered dendrogram.
340,302
def calc_signal_color1(self, distance_modulus, mass_steps=10000): mag_1, mag_2 = self.catalog.mag_1,self.catalog.mag_2 mag_err_1, mag_err_2 = self.catalog.mag_err_1,self.catalog.mag_err_2 u_density = self.isochrone.pdf(mag_1,mag_2,mag_err_1,mag_err_2,distance_modulus,self.delta_mag,mass...
Compute signal color probability (u_color) for each catalog object on the fly.
340,303
def copy(self): context = CLIContext() for item in dir(self): if item[0] != and item not in (, ): setattr(context, item, getattr(self, item)) return context
Returns a new CLIContext instance that is a shallow copy of the original, much like dict's copy method.
340,304
def deferred_call(self, callback, *args, **kwargs): loop = self.loop r = loop.callLater(0, callback, *args, **kwargs) loop.wakeUp() return r
We have to wake up the reactor after every call because it may calculate a long delay where it can sleep which causes events that happen during this period to seem really slow as they do not get processed until after the reactor "wakes up"
340,305
def _check_paired(files, force_single, separators): full_name = _check_stems(files) if files[0].endswith(".bam"): return files elif is_gsm(files[0]): return files return combine_pairs(files, force_single, full_name, separators)
check if files are fastq(.gz) and paired
340,306
def get_root_objective_banks(self): if self._catalog_session is not None: return self._catalog_session.get_root_catalogs() return ObjectiveBankLookupSession( self._proxy, self._runtime).get_objective_banks_by_ids(list(self.get_root_objective...
Gets the root objective banks in this objective bank hierarchy. return: (osid.learning.ObjectiveBankList) - the root objective banks raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This metho...
340,307
def print_vcf(data): id_name = "." qual = "." chrom = data[] pos = data[] nt_ref = data[][1] nt_snp = data[][0] flt = "PASS" info = "ID=%s" % data[] frmt = "GT:NR:NS" gntp = "%s:%s:%s" % (_genotype(data), data["counts"], data["diff"]) print("\t".join(map(str, [chrom, pos...
Print vcf line following rules.
340,308
def set_client_cmds(self): self.task_data[] = self.input.get() self.task_data[] = self.input.get() filters = self.input.get(, {}) try: if isinstance(filters, dict): self.task_data[] = filters.get()[][0] elif filters[0][...
This is method automatically called on each request and updates "object_id", "cmd" and "flow" client variables from current.input. "flow" and "object_id" variables will always exists in the task_data so app developers can safely check for their values in workflows. Thei...
340,309
def check_originating_identity(): from flask import request, json if "X-Broker-API-Originating-Identity" in request.headers: try: platform, value = request.headers["X-Broker-API-Originating-Identity"].split(None, 1) request.originating_identity = { : platform...
Check and decode the "X-Broker-API-Originating-Identity" header https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity
340,310
def send_compound(self, messages, sid, tid, related=False): send_data = b"" session = self.session_table[sid] tree = session.tree_connect_table[tid] requests = [] total_requests = len(messages) for i, message in enumerate(messages): if i == total_req...
Sends multiple messages within 1 TCP request, will fail if the size of the total length exceeds the maximum of the transport max. :param messages: A list of messages to send to the server :param sid: The session_id that the request is sent for :param tid: A tree_id object that the messa...
340,311
def get_logout_uri(self, id_token_hint=None, post_logout_redirect_uri=None, state=None, session_state=None): params = {"oxd_id": self.oxd_id} if id_token_hint: params["id_token_hint"] = id_token_hint if post_logout_redirect_uri: params["po...
Function to logout the user. Parameters: * **id_token_hint (string, optional):** oxd server will use last used ID Token, if not provided * **post_logout_redirect_uri (string, optional):** URI to redirect, this uri would override the value given in the site-config * **state (...
340,312
def load_tempo(filename, delimiter=r): r t1, t2, weight = load_delimited(filename, [float, float, float], delimiter) weight = weight[0] tempi = np.concatenate([t1, t2]) if len(t1) != 1: raise ValueError() try: tempo.validate_tempi(tempi) except ValueError as erro...
r"""Load tempo estimates from an annotation file in MIREX format. The file should consist of three numeric columns: the first two correspond to tempo estimates (in beats-per-minute), and the third denotes the relative confidence of the first value compared to the second (in the range [0, 1]). The file s...
340,313
def po_to_csv_merge(languages, locale_root, po_files_path, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv): msgids = [] trans_reader = UnicodeReader(gdocs_trans_csv) meta_reader = UnicodeReader(gdocs_meta_csv) try: trans_title = tr...
Converts po file to csv GDocs spreadsheet readable format. Merges them if some msgid aren't in the spreadsheet. :param languages: list of language codes :param locale_root: path to locale root folder containing directories with languages :param po_files_path: path from lang direc...
340,314
def cli(yamlfile, inline, format): print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
Generate JSON Schema representation of a biolink model
340,315
def transfer_attributes_to_instrument(self, inst, strict_names=False): banned = inst._base_attr base_attrb = self._base_attr this_attrb = dir(self) adict = {} transfer_key = [] for key in this_attrb: if key not in banned: ...
Transfer non-standard attributes in Meta to Instrument object. Pysat's load_netCDF and similar routines are only able to attach netCDF4 attributes to a Meta object. This routine identifies these attributes and removes them from the Meta object. Intent is to support simple transfers to ...
340,316
def pbm(self): if not self.disable_rpyc: from plumbum import SshMachine return SshMachine(host=self.private_hostname, user=self.username, keyfile=self.key_filename, ssh_opts=["-o", "UserKnownHostsFile=/dev/null", ...
Plumbum lazy property
340,317
def mirror_pull(self, **kwargs): path = % self.get_id() self.manager.gitlab.http_post(path, **kwargs)
Start the pull mirroring process for the project. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server failed to perform the request
340,318
def create_submission_parameter(self, name, default=None, type_=None): if name in self._submission_parameters: raise ValueError("Submission parameter {} already defined.".format(name)) sp = streamsx.topology.runtime._SubmissionParam(name, default, type_) self._submi...
Create a submission parameter. A submission parameter is a handle for a value that is not defined until topology submission time. Submission parameters enable the creation of reusable topology bundles. A submission parameter has a `name`. The name must be unique within the to...
340,319
def format_title(text): text = text.strip() if len(text) == 0: return text else: text = text.lower() words = [word for word in text.strip().split(" ") if len(word) >= 1] words_new = list() for word in words: if word not in F...
Capitalize first letter for each words except function words. Example:: title = "Beautiful is Better than Ugly" **中文文档** 将文本 "标题化", 即除了虚词, 每一个英文单词的第一个字母大写。
340,320
def classify(self, dataset, missing_value_action=): return super(SVMClassifier, self).classify(dataset, missing_value_action=missing_value_action)
Return a classification, for each example in the ``dataset``, using the trained SVM model. The output SFrame contains predictions as class labels (0 or 1) associated with the the example. Parameters ---------- dataset : SFrame Dataset of new observations. Must includ...
340,321
def djfrontend_jqueryui(version=None): if version is None: version = getattr(settings, , DJFRONTEND_JQUERYUI_DEFAULT) if getattr(settings, , False): return format_html( , settings.STATIC_URL, version) else: return format_html( <s...
Returns the jQuery UI plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
340,322
def timout(et, pictur, lenout=_default_len_out): pictur = stypes.stringToCharP(pictur) output = stypes.stringToCharP(lenout) lenout = ctypes.c_int(lenout) if hasattr(et, "__iter__"): times = [] for t in et: libspice.timout_c(ctypes.c_double(t), pictur, lenout, output) ...
This vectorized routine converts an input epoch represented in TDB seconds past the TDB epoch of J2000 to a character string formatted to the specifications of a user's format picture. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/timout_c.html :param et: An epoch in seconds past the ephemer...
340,323
def get_endpoints_using_raw_json_emission(domain): uri = "http://{0}/data.json".format(domain) r = requests.get(uri) r.raise_for_status() return r.json()
Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the first of the two ways of getting this information, the raw JSON endpoint. Parameters ---------- domain: str A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" fo...
340,324
def clear_search_defaults(self, args=None): if args is None: self._search_defaults.clear() else: for arg in args: if arg in self._search_defaults: del self._search_defaults[arg]
Clear all search defaults specified by the list of parameter names given as ``args``. If ``args`` is not given, then clear all existing search defaults. Examples:: conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs=['cn']) conn.clear_search_defaults(['scope']) ...
340,325
def _set_ma_name(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("ma_name",ma_name.ma_name, yang_name="ma-name", rest_name="ma-name", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u...
Setter method for ma_name, mapped from YANG variable /protocol/cfm/domain_name/ma_name (list) If this variable is read-only (config: false) in the source YANG file, then _set_ma_name is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ma_na...
340,326
def get_profile_model(): if (not hasattr(settings, ) or not settings.AUTH_PROFILE_MODULE): raise SiteProfileNotAvailable profile_mod = get_model(*settings.AUTH_PROFILE_MODULE.split()) if profile_mod is None: raise SiteProfileNotAvailable return profile_mod
Return the model class for the currently-active user profile model, as defined by the ``AUTH_PROFILE_MODULE`` setting. :return: The model that is used as profile.
340,327
def permute(num): "Permutation for randomizing data order." if permute_data: return np.random.permutation(num) else: logging.warning("Warning not permuting data") return np.arange(num)
Permutation for randomizing data order.
340,328
def run(self, message): self.zmq_socket.send_pyobj(message, copy=True) reply = self.zmq_socket.recv_pyobj() return reply
This function needs to be fast at the same time aware of the possibility of ZMQ pipes overflowing. The timeout increases slowly if contention is detected on ZMQ pipes. We could set copy=False and get slightly better latency but this results in ZMQ sockets reaching a broken state once th...
340,329
def _build_url(url, _params): scheme, netloc, path, params, query, fragment = urlparse(url) netloc = netloc.encode().decode() if not path: path = if six.PY2: if isinstance(scheme, six.text_type): scheme = scheme.encode() if isinstance(netloc, six.text_typ...
Build the actual URL to use.
340,330
def ajax_login_required(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) else: ...
Handle non-authenticated users differently if it is an AJAX request.
340,331
def getFileKeys(self): files = self.getFileObjects() files_list = [] for key, value in files.iteritems(): if value: files_list.append(key) return files_list
Retrieve a list of file keys that have been read into the database. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys in conjunction with the dictionary returned by the getFileObjects method. Returns: list: List of keys re...
340,332
def section(self): if self.api and self.section_id: return self.api._get_section(self.section_id)
| Comment: The id of the section to which this article belongs
340,333
def update_variogram_model(self, variogram_model, variogram_parameters=None, variogram_function=None, nlags=6, weight=False, anisotropy_scaling=1., anisotropy_angle=0.): if anisotropy_scaling != self.anisotropy_scaling or \ ...
Allows user to update variogram type and/or variogram model parameters. Parameters ---------- variogram_model : str May be any of the variogram models listed above. May also be 'custom', in which case variogram_parameters and variogram_functio...
340,334
def knx2_to_float(knxdata): if len(knxdata) != 2: raise KNXException("Can only convert a 2 Byte object to float") data = knxdata[0] * 256 + knxdata[1] sign = data >> 15 exponent = (data >> 11) & 0x0f mantisse = float(data & 0x7ff) if sign == 1: mantisse = -2048 + mantisse ...
Convert a KNX 2 byte float object to a float
340,335
def add_fixer(self, fixer): self.fixers.append(fixer) tree = reduce_tree(fixer.pattern_tree) linear = tree.get_linear_subpattern() match_nodes = self.add(linear, start=self.root) for match_node in match_nodes: match_node.fixers.append(fixer)
Reduces a fixer's pattern tree to a linear path and adds it to the matcher(a common Aho-Corasick automaton). The fixer is appended on the matching states and called when they are reached
340,336
def get_qpimage_raw(self, idx): with self._qpseries() as qps: qpi = qps.get_qpimage(index=idx).copy() qpi.set_bg_data(None) for key in self.meta_data: qpi[key] = self.meta_data[key] qpi["identifier"] = self.get_identifier(idx) ...
Return QPImage without background correction
340,337
def context(self): plugin_context_name = str(type(self)) if plugin_context_name not in self.manticore.context: self.manticore.context[plugin_context_name] = {} return self.manticore.context[plugin_context_name]
Convenient access to shared context
340,338
def _initialize(self, funs_to_tally, length): dir = os.path.join(self._directory, CHAIN_NAME % self.chains) os.mkdir(dir) base.Database._initialize(self, funs_to_tally, length)
Create folder to store simulation results.
340,339
def explorev2(self, datasource_type, datasource_id): return redirect(url_for( , datasource_type=datasource_type, datasource_id=datasource_id, **request.args))
Deprecated endpoint, here for backward compatibility of urls
340,340
def graph_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, save_weights_to=None, dropout_br...
graph attention. Args: q: a Tensor with shape [batch, heads, length_q, depth_k] k: a Tensor with shape [batch, heads, length_kv, depth_k] v: a Tensor with shape [batch, heads, length_kv, depth_v] bias: bias Tensor (see attention_bias()) dropout_rate: a floating point number image_shapes: opti...
340,341
def send_image(self, sender, receiver_type, receiver_id, media_id): data = { : { : receiver_type, : receiver_id, }, : sender, : , : { : media_id, } } return self._post...
发送图片消息 详情请参考 https://qydev.weixin.qq.com/wiki/index.php?title=企业会话接口说明 :param sender: 发送人 :param receiver_type: 接收人类型:single|group,分别表示:单聊|群聊 :param receiver_id: 接收人的值,为userid|chatid,分别表示:成员id|会话id :param media_id: 图片媒体文件id,可以调用上传素材文件接口获取 :return: 返回的 JSON 数据包
340,342
def sort_arrival_times(self, x_mins, y_mins, kwargs_lens): if hasattr(self.lensModel, ): raise Exception( ) if len(x_mins) <= 1: return x_mins, y_mins x_source, y_source = self.lensModel.ray_shooting(x_mins, y_mins, kwargs_lens) ...
sort arrival times (fermat potential) of image positions in increasing order of light travel time :param x_mins: ra position of images :param y_mins: dec position of images :param kwargs_lens: keyword arguments of lens model :return: sorted lists of x_mins and y_mins
340,343
def CheckIfUserIsAdmin(self, username): user_obj = data_store.REL_DB.ReadGRRUser(username) if user_obj.user_type != user_obj.UserType.USER_TYPE_ADMIN: raise access_control.UnauthorizedAccess("User %s is not an admin." % username)
Checks whether the user is an admin.
340,344
def parse_property_array(self, tup_tree): self.check_node(tup_tree, , (, ), (, , , , , ), (, )) values = self.unpack_value(tup_tree) attrl = attrs(tup_tree) qualifiers = self.list_of_matching(t...
:: <!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)> <!ATTLIST PROPERTY.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize; %ClassOrigin; %Propagated; %EmbeddedObject; xml...
340,345
def revoke_admin(): build = g.build form = forms.RemoveAdminForm() if form.validate_on_submit(): user = models.User.query.get(form.user_id.data) if not user: logging.debug( , form.user_id.data, build.id) abort(400) if user == cu...
Form submission handler for revoking admin access to a build.
340,346
def delete_attr(self, name: str, axis: int = 0) -> None: deprecated(" is deprecated. Use or instead") if axis == 0: del self.ra[name] else: del self.ca[name]
**DEPRECATED** - Use `del ds.ra.key` or `del ds.ca.key` instead, where `key` is replaced with the attribute name
340,347
def new_sender(project_id): project = get_data_or_404(, project_id) if project[] != get_current_user_id(): return jsonify(message=), 403 form = NewSenderForm() if not form.validate_on_submit(): return jsonify(errors=form.errors), 400 data = form.data data[] = project_id ...
Add sender.
340,348
def get_postalcodes_around_radius(self, pc, radius): postalcodes = self.get(pc) if postalcodes is None: raise PostalCodeNotFoundException("Could not find postal code you Bounding box calculations updated from pyzipcode ' earth_radius = 6371 dlat = rad...
Bounding box calculations updated from pyzipcode
340,349
def from_url(cls, url, db=None, skip_full_coverage_check=False, **kwargs): connection_pool = ClusterConnectionPool.from_url(url, db=db, **kwargs) return cls(connection_pool=connection_pool, skip_full_coverage_check=skip_full_coverage_check)
Return a Redis client object configured from the given URL, which must use either `the ``redis://`` scheme <http://www.iana.org/assignments/uri-schemes/prov/redis>`_ for RESP connections or the ``unix://`` scheme for Unix domain sockets. For example:: redis://[:password]@localhos...
340,350
def set_authorizer_option( self, authorizer_appid, option_name, option_value): return self.post( , data={ : self.component_appid, : authorizer_appid, : option_name, : option_value } )
设置授权方的选项信息 :params authorizer_appid: 授权公众号appid :params option_name: 选项名称 :params option_value: 设置的选项值
340,351
def _create_mock(self, endpoint_desc, session, request_params, mock_desc, loop): try: mock_def = mock_manager.next_mock(self.service_client.name, endpoint_desc[]) if isinstance(mock_def, PatchMockDescDefinition): moc...
The class imported should have the __call__ function defined to be an object directly callable
340,352
def _startDriver(self): framework = addict.Dict() framework.user = getpass.getuser() framework.name = "toil" framework.principal = framework.name self.driver = MesosSchedulerDriver(self, framework, self._resol...
The Mesos driver thread which handles the scheduler's communication with the Mesos master
340,353
def update(self, id, dashboard_data): return self._put( url=.format(self.URL, id), headers=self.headers, data=dashboard_data, )
This API endpoint updates a dashboard and all defined widgets. :type id: int :param id: Dashboard ID :type dashboard: dict :param dashboard: Dashboard Dictionary :rtype dict :return: The JSON response of the API :: { "dashboard": { ...
340,354
def get_orders(self, product_id=None, status=None, **kwargs): params = kwargs if product_id is not None: params[] = product_id if status is not None: params[] = status return self._send_paginated_message(, params=params)
List your current open orders. This method returns a generator which may make multiple HTTP requests while iterating through it. Only open or un-settled orders are returned. As soon as an order is no longer open and settled, it will no longer appear in the default request. ...
340,355
def serialize(self, tag): handler = getattr(self, f, None) if handler is None: raise TypeError(ft serialize {type(tag)!r} instance') return handler(tag)
Return the literal representation of a tag.
340,356
def ExtractEventsFromSources(self): self._CheckStorageFile(self._storage_file_path, warn_about_existing=True) scan_context = self.ScanSource(self._source_path) self._source_type = scan_context.source_type self._status_view.SetMode(self._status_view_mode) self._status_view.SetSourceInformation...
Processes the sources and extracts events. Raises: BadConfigOption: if the storage file path is invalid or the storage format not supported or an invalid filter was specified. SourceScannerError: if the source scanner could not find a supported file system. UserAbort: if the u...
340,357
def _emit_element(self, element, level, declared_prefixes): declarations = {} declared_prefixes = dict(declared_prefixes) name = element.tag prefixed = self._make_prefixed(name, True, declared_prefixes, declarations...
Recursive XML element serializer. :Parameters: - `element`: the element to serialize - `level`: nest level (0 - root element, 1 - stanzas, etc.) - `declared_prefixes`: namespace to prefix mapping of already declared prefixes. :Types: - `elem...
340,358
def _send_string_selection(self, string: str): backup = self.clipboard.selection if backup is None: logger.warning("Tried to backup the X PRIMARY selection content, but got None instead of a string.") self.clipboard.selection = string self.__enqueue(self._paste_usi...
Use the mouse selection clipboard to send a string.
340,359
def GetMerger(self, cls): for merger in self._mergers: if isinstance(merger, cls): return merger raise LookupError()
Looks for an added DataSetMerger derived from the given class. Args: cls: A class derived from DataSetMerger. Returns: The matching DataSetMerger instance. Raises: LookupError: No matching DataSetMerger has been added.
340,360
def generate(env): env[] = env[] = SCons.Util.CLVar() env[] = env[][] = midl_builder
Add Builders and construction variables for midl to an Environment.
340,361
def map(self, func): return TList([func(k, v) for k, v in self.items()])
:param func: :type func: (K, T) -> U :rtype: TList[U] Usage: >>> sorted(TDict(k1=1, k2=2, k3=3).map(lambda k, v: v*2)) [2, 4, 6]
340,362
def auto_detect(self, value): if isinstance(value, bool): if self.autodetect is not value: self._verify_proxy_type_compatibility(ProxyType.AUTODETECT) self.proxyType = ProxyType.AUTODETECT self.autodetect = value else: rais...
Sets autodetect setting. :Args: - value: The autodetect value.
340,363
def publish_for_collection(self, collection_name): self.revisions = BaseAsyncMotorDocument("%s_revisions" % collection_name, self.settings) changes = yield self.__get_pending_revisions() if len(changes) > 0: self.logger.info("%s revisions will be actioned" % len(changes))...
Run the publishing operations for a given collection :param str collection_name:
340,364
def upload_template_and_reload(name): template = get_templates()[name] local_path = template["local_path"] if not os.path.exists(local_path): project_root = os.path.dirname(os.path.abspath(__file__)) local_path = os.path.join(project_root, local_path) remote_path = template["remote_...
Uploads a template only if it has changed, and if so, reload the related service.
340,365
def build_help_html(): remove_from_help = ["not-in-help", "copyright"] if sys.platform in ["win32", "cygwin"]: remove_from_help.extend(["osx", "linux"]) elif sys.platform == "darwin": remove_from_help.extend(["linux", "windows", "linux-windows"]) else: remove_from_help.exten...
Build the help HTML using the shared resources.
340,366
def is_export_interface(instrument_interface): if IInstrumentExportInterface.providedBy(instrument_interface): return True if hasattr(instrument_interface, ): obj_name = instrument_interface.__name__.replace(__name__, "") if obj_name[1:] in __all__ and hasattr(instrument_inter...
Returns whether the instrument interface passed in is for results export
340,367
def parse(self, file_name): self.object = self.parsed_class() with open(file_name, encoding=) as f: self.parse_str(f.read()) return self.object
Parse entire file and return relevant object. :param file_name: File path :type file_name: str :return: Parsed object
340,368
def clone_version(self, service_id, version_number): content = self._fetch("/service/%s/version/%d/clone" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
Clone the current configuration into a new version.
340,369
def define( name: str, default: Any = None, type: type = None, help: str = None, metavar: str = None, multiple: bool = False, group: str = None, callback: Callable[[Any], None] = None, ) -> None: return options.define( name, default=default, type=type, ...
Defines an option in the global namespace. See `OptionParser.define`.
340,370
def _split_input_from_namespace(cls, app, namespace, entity_kind, shard_count): raw_entity_kind = cls._get_raw_entity_kind(entity_kind) if shard_count == 1: random_keys = cls._choose_split_points(random_keys, shard_count) key_ranges = [] key_ra...
Helper for _split_input_from_params. If there are not enough Entities to make all of the given shards, the returned list of KeyRanges will include Nones. The returned list will contain KeyRanges ordered lexographically with any Nones appearing at the end. Args: app: the app. namespace:...
340,371
def normalized(self): return Rect(pos=(min(self.left, self.right), min(self.top, self.bottom)), size=(abs(self.width), abs(self.height)))
Return a Rect covering the same area, but with height and width guaranteed to be positive.
340,372
def do_import(self, name, default): try: option = getattr(self.options, name) if option: klass = import_class(option) else: klass = default setattr(self.options, name, klass) except Exception as e: self....
Import the given option (use default values if not defined on command line)
340,373
def load_slice(self, state, start, end): items = [ ] if start > self._page_addr + self._page_size or end < self._page_addr: l.warning("Calling load_slice on the wrong page.") return items for addr in range(max(start, self._page_addr), min(end, self._page_addr + ...
Return the memory objects overlapping with the provided slice. :param start: the start address :param end: the end address (non-inclusive) :returns: tuples of (starting_addr, memory_object)
340,374
def weld_str_startswith(array, pat): obj_id, weld_obj = create_weld_object(array) pat_id = get_weld_obj_id(weld_obj, pat) weld_template = weld_obj.weld_code = weld_template.format(array=obj_id, pat=pat_id) return weld_obj
Check which elements start with pattern. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To check for. Returns ------- WeldObject Representation of this computation.
340,375
def get_setting(connection, key): if key in connection.settings_dict: return connection.settings_dict[key] else: return getattr(settings, key)
Get key from connection or default to settings.
340,376
def flick_element(self, on_element, xoffset, yoffset, speed): self._actions.append(lambda: self._driver.execute( Command.FLICK, { : on_element.id, : int(xoffset), : int(yoffset), : int(speed)})) return self
Flick starting at on_element, and moving by the xoffset and yoffset with specified speed. :Args: - on_element: Flick will start at center of element. - xoffset: X offset to flick to. - yoffset: Y offset to flick to. - speed: Pixels per second to flick.
340,377
def factorgraph_viz(d): m = defaultdict(list) for node in d[]: m[].append(dict( id=node[], type= )) for factor in d[]: m[].append(dict( id=factor[], type= )) fo...
Map the dictionary into factorgraph-viz format. See https://github.com/mbforbes/factorgraph-viz :param d: The dictionary :return: The formatted dictionary
340,378
def scale_and_crop_with_subject_location(im, size, subject_location=False, zoom=None, crop=False, upscale=False, **kwargs): subject_location = normalize_subject_location(subject_location) if not (subject_location and crop): ...
Like ``easy_thumbnails.processors.scale_and_crop``, but will use the coordinates in ``subject_location`` to make sure that that part of the image is in the center or at least somewhere on the cropped image. Please not that this does *not* work correctly if the image has been resized by a previous proces...
340,379
def import_lane_set_element(process_attributes, lane_set_element, plane_element): lane_set_id = lane_set_element.getAttribute(consts.Consts.id) lanes_attr = {} for element in utils.BpmnImportUtils.iterate_elements(lane_set_element): if element.nodeType != element.TEXT_NODE: ...
Method for importing 'laneSet' element from diagram file. :param process_attributes: dictionary that holds attribute values of 'process' element, which is parent of imported flow node, :param lane_set_element: XML document element, :param plane_element: object representing a BPMN XM...
340,380
def kwargs(self): keywords = self.keywords or [] return [keyword for keyword in keywords if keyword.arg is None]
The keyword arguments that unpack something. :type: list(Keyword)
340,381
def identical_blocks(self): identical_blocks = [] for (func_a, func_b) in self.function_matches: identical_blocks.extend(self.get_function_diff(func_a, func_b).identical_blocks) return identical_blocks
:return A list of all block matches that appear to be identical
340,382
def send_messages(self, messages, timeout): data = { : self.assignment.endpoint, : messages, : self.args.submit } address = self.API_ENDPOINT address_params = { : , : client.__version__, } log.info(, add...
Send messages to server, along with user authentication.
340,383
def modify_key_parity(key): validated_key = b for byte in key: if parityOf(int(byte)) == -1: byte_candidate = int(byte) + 1 while parityOf(byte_candidate) == -1: byte_candidate = divmod(byte_candidate + 1, 256)[1] validated_key += bytes([byte_can...
The prior use of the function is to return the parity-validated key. The incoming key is expected to be hex data binary representation, e.g. b'E7A3C8B1'
340,384
def override_env_variables(): env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME") old = [os.environ[v] if v in os.environ else None for v in env_vars] for v in env_vars: os.environ[v] = "test" yield for i, v in enumerate(env_vars): if old[i]: os.environ[v] = old[i]
Override user environmental variables with custom one.
340,385
def main(): import argparse from kazoo.client import KazooClient parser = argparse.ArgumentParser( description="Crawler config file pusher to Zookeeper") parser.add_argument(, , action=, required=True, help="The yaml file to use") parser.add_argument(, , act...
A manual configuration file pusher for the crawlers. This will update Zookeeper with the contents of the file specified in the args.
340,386
def get_relevant_nodes(network_id, query_nodes): url = ndex_relevance + kernel_id = get_heat_kernel(network_id) if kernel_id is None: return None if isinstance(query_nodes, basestring): query_nodes = [query_nodes] params = {: query_nodes, : kernel_id} res = nd...
Return a set of network nodes relevant to a given query set. A heat diffusion algorithm is used on a pre-computed heat kernel for the given network which starts from the given query nodes. The nodes in the network are ranked according to heat score which is a measure of relevance with respect to the qu...
340,387
def bind_socket(address, port): assert address assert port bindsocket = socket.socket() try: bindsocket.bind((address, port)) except socket.error: logger.error("CouldnListening on %s:%s', address, port) bindsocket.listen(0) return bindsocket
Returns a socket bound on (address:port).
340,388
def _families_and_addresses(self, hostname, port): guess = True addrinfos = socket.getaddrinfo( hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM ) for (family, socktype, proto, canonname, sockaddr) in addrinfos: if socktype == socket.SOCK_STREAM: ...
Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to connect to :param int port: the server port to connect to :returns: Yields an iterable of ``(family, address)`` tuples
340,389
def _build_weight_from_kernel(self, kernel): weight = kernel.copy() self._diagonal = weight.diagonal().copy() weight = utils.set_diagonal(weight, 0) return weight
Private method to build an adjacency matrix from a kernel matrix Just puts zeroes down the diagonal in-place, since the kernel matrix is ultimately not stored. Parameters ---------- kernel : array-like, shape=[n_samples, n_samples] Kernel matrix. Re...
340,390
def CheckBraces(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] if Match(r, line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r, prevline) and not Match(r, prevline)): error(filename, linenum,...
Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
340,391
def parse_directory_response(s): seq_quotes = 0 start = False directory = "" for ch in s: if not start: if ch == "\"": start = True else: if ch == "\"": seq_quotes += 1 ...
Parsing directory server response. :param s: response line :type s: :py:class:`str` :rtype: :py:class:`pathlib.PurePosixPath`
340,392
def insertOrderedList(self): cursor = self.editor().textCursor() currlist = cursor.currentList() new_style = QTextListFormat.ListDecimal indent = 1 if currlist: format = currlist.format() indent = format.indent() + 1 ...
Inserts an ordered list into the editor.
340,393
def _load_image_set_index(self, shuffle): assert os.path.exists(self.list_file), .format(self.list_file) with open(self.list_file, ) as f: image_set_index = [x.strip() for x in f.readlines()] if shuffle: np.random.shuffle(image_set_index) return image_set...
find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting
340,394
def get_assets_by_search(self, asset_query, asset_search): if not self._can(): raise PermissionDenied() return self._provider_session.get_assets_by_search(asset_query, asset_search)
Pass through to provider AssetSearchSession.get_assets_by_search
340,395
def power_on(self, interval=200): if self.__power_on_port is None: cij.err("cij.usb.relay: Invalid USB_RELAY_POWER_ON") return 1 return self.__press(self.__power_on_port, interval=interval)
230v power on
340,396
def start(self, nodes=None): if not self.is_connected(): return None nodes = nodes or self.nodes result = [] for node in nodes: if node.state == : logging.warning(, node.name) continue try: sta...
Start one or many nodes. :param nodes: Nodes to be started. :type nodes: ``list``
340,397
def setup_exchange(self, exchange_name): self._logger.debug( % exchange_name) try: self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self._exchange_type) except Exce...
Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC command. When it is complete, the on_exchange_declareok method will be invoked by pika. :param str|unicode exchange_name: The name of the exchange to declare
340,398
def _agent_registration(self): for attempts in range(MAX_REGISTRATION_ATTEMPTS): context = bc.context.get_admin_context_without_session() self.send_agent_report(self.agent_state, context) try: res = self.devmgr_rpc.register_for_duty(context) ...
Register this agent with the server. This method registers the cfg agent with the neutron server so hosting devices can be assigned to it. In case the server is not ready to accept registration (it sends a False) then we retry registration for `MAX_REGISTRATION_ATTEMPTS` with a delay of...
340,399
def sys_names(self): names = [] for sample in self.samples: names.extend(sample.sys_names()) return list(set(names))
Return a list of unique systematic names from OverallSys and HistoSys