Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,300
def remove_and_append(self, index): while index in self: self.remove(index) self.append(index)
Remove previous entrances of a tab, and add it as the latest.
349,301
def to_netjson(self): self.__backup_intermediate_data() self.config = OrderedDict() for converter_class in self.converters: if not converter_class.should_run_backward(self.intermediate_data): continue converter = converter_class(self) ...
Converts the intermediate data structure (self.intermediate_data) to the NetJSON configuration dictionary (self.config)
349,302
def applydiff(tokens,deltas): "tokens can be a string or a list of strings.\ deltas is [Delta,...]. Delta.text is actually a tokenlist of the same type as tokens (string or list of string).\ If tokens & tokenslist are strings, must be unicode for the offsets to match what JS produces.\ (If theyt matter; t...
tokens can be a string or a list of strings.\ deltas is [Delta,...]. Delta.text is actually a tokenlist of the same type as tokens (string or list of string).\ If tokens & tokenslist are strings, must be unicode for the offsets to match what JS produces.\ (If they're lists, it doesn't matter; the offsets are...
349,303
def load(self, file): if isfile(file): try: config = load_source("config", file) except Exception as e: raise ExceptionInConfigError(e) option_missing = False values = {} for option in self.options: if not option.validator(value): values[option.name] = option.defaul...
Returns the actual read- and editable config IN: file (type: str, hint: should be a valid path)
349,304
def readSegmentGT(gt_file): start positions - seg_end: a numpy array of segments f = open(gt_file, ) reader = csv.reader(f, delimiter=) seg_start = [] seg_end = [] seg_label = [] for row in reader: if len(row) == 3: seg_start.append(float(row[0])) ...
This function reads a segmentation ground truth file, following a simple CSV format with the following columns: <segment start>,<segment end>,<class label> ARGUMENTS: - gt_file: the path of the CSV segment file RETURNS: - seg_start: a numpy array of segments' start positions - seg_...
349,305
def set_USRdict(self,USRdict={}): self._check_inputs(USRdict=USRdict) self._USRdict = USRdict
Set the USRdict, containing user-defined info about the instance Useful for arbitrary info (e.g.: manufacturing date, material...) Parameters ---------- USRdict : dict A user-defined dictionary containing info about the instance
349,306
def getWindowRect(self, hwnd): rect = ctypes.wintypes.RECT() if ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)): x1 = rect.left y1 = rect.top x2 = rect.right y2 = rect.bottom return (x1, y1, x2-x1, y2-y1) return No...
Returns a rect (x,y,w,h) for the specified window's area
349,307
def run(): deps_dir = os.path.join(build_root, ) if os.path.exists(deps_dir): shutil.rmtree(deps_dir, ignore_errors=True) os.mkdir(deps_dir) try: print("Staging ci dependencies") _stage_requirements(deps_dir, os.path.join(package_root, , )) print("Checking out mod...
Installs required development dependencies. Uses git to checkout other modularcrypto repos for more accurate coverage data.
349,308
def dedup(l, suffix=, case_sensitive=True): new_l = [] seen = {} for s in l: s_fixed_case = s if case_sensitive else s.lower() if s_fixed_case in seen: seen[s_fixed_case] += 1 s += suffix + str(seen[s_fixed_case]) else: seen[s_fixed_case] = 0 ...
De-duplicates a list of string by suffixing a counter Always returns the same number of entries as provided, and always returns unique values. Case sensitive comparison by default. >>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar']))) foo,bar,bar__1,bar__2,Bar >>> print(','.join(dedup(['...
349,309
def _parse_file(cls, path, pickle=False): fname = path if fname.endswith(".gz"): fname = path[:-3] if fname.endswith(): cPickle.dump(data, fd) return data
parse a .chain file into a list of the type [(L{Chain}, arr, arr, arr) ...] :param fname: name of the file
349,310
def ReadFromPath(filepath): with io.open(filepath, mode="r", encoding="utf-8") as filedesc: return ReadFromFile(filedesc)
Reads a Python object stored in a specified YAML file. Args: filepath: A filepath to the YAML file. Returns: A Python data structure corresponding to the YAML in the given file.
349,311
def on_checked_changed(self, on): d = self.declaration with self.widget.setOn.suppressed(): d.checked = on
See https://stackoverflow.com/questions/19628310/
349,312
def get_applications(self): applications = [] for target_app in self.get_objects(None, self.uri()): applications.append({ : self.get_object(target_app, self.uri()), : self.get_object(target_app, ...
Return the list of supported applications.
349,313
def _get_role_arn(): role_arn = bottle.request.headers.get() if not role_arn: role_arn = _lookup_ip_role_arn(bottle.request.environ.get()) if not role_arn: role_arn = _role_arn return role_arn
Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default.
349,314
def devserver(port, admin_port, clear): admin_port = admin_port or (port + 1) args = [ .format(port), .format(admin_port) ] if clear: args += [] with conf.within_proj_dir(): shell.run(.format(args=.join(args)))
Run devserver. Args: port (int): Port on which the app will be served. admin_port (int): Port on which the admin interface is served. clear (bool): If set to **True**, clear the datastore on startup.
349,315
def get_fields(self): fields = super(DataSerializer, self).get_fields() if self.parent is not None: del fields[] del fields[] return fields
Dynamically adapt fields based on the current request.
349,316
def fetch_messages(self): if self._fetched: return start = time.time() loaded_messages = self.queue.lease_tasks_by_tag( self.duration, self.size, tag=self.tag, deadline=self.deadline) if (not loaded_messages and ...
Fetch messages from the specified pull-queue. This should only be called a single time by a given MessageIterator object. If the MessageIterator is iterated over again, it should return the originally leased messages.
349,317
def get_icon(keyword): filename = a99.get_path( "icons", keyword + ".png") if not os.path.isfile(filename): raise FileNotFoundError("File does not exist".format(filename)) return QIcon(filename)
Transforms a PNG file in a QIcon Looks for a file named <keyword>.png in the "icons" directory If file does not exist, returns None
349,318
def match(self, filename, line, codes): if ((not self.file_selectors or self.file_match_any(filename)) and (not self.environment_marker_selector or self.environment_marker_evaluate()) and (not self.code_selectors or self.codes_match_any(codes))): ...
Match rule.
349,319
def blurring(data, ground_truth, mask=None, normalized=False, smoothness_factor=None): r from scipy.ndimage.morphology import distance_transform_edt if not hasattr(data, ): data = odl.vector(data) space = data.space ground_truth = space.element(ground_truth) if smoothness...
r"""Return weighted L2 distance, emphasizing regions defined by ``mask``. .. note:: If the mask argument is omitted, this FOM is equivalent to the mean squared error. Parameters ---------- data : `Tensor` or `array-like` Input data to compare to the ground truth. If not a `Tens...
349,320
def add_contacts(self, indices, indices2=None, threshold=0.3, periodic=True, count_contacts=False): r from .distances import ContactFeature atom_pairs = _parse_pairwise_input( indices, indices2, self.logger, fname=) atom_pairs = self._check_indices(atom_pairs) f = Co...
r""" Adds the contacts to the feature list. Parameters ---------- indices : can be of two types: ndarray((n, 2), dtype=int): n x 2 array with the pairs of atoms between which the contacts shall be computed iterable of integers (eithe...
349,321
def get_string_from_rdf(src): res = src.split("/") return "".join([l.replace(, ) for l in res[len(res) - 1]])
extracts the real content from an RDF info object
349,322
def _new_controller(self, addr, port): for uid, controller in self.controllers.items(): if controller[0] == addr: self.sock.sendto(.format(uid).encode(), (addr, port)) return False uid = str(uuid4()) ...
Get an uid for your controller. :param addr: Address of the controller :param port: Port of the controller :type addr: str :type port: int :return: Unique id of the controller :rtype: str
349,323
def calc_hmin_qmin_hmax_qmax_v1(self): con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess if flu.qref <= der.qm: aid.hmin = 0. aid.qmin = 0. aid.hmax = con.hm ...
Determine an starting interval for iteration methods as the one implemented in method |calc_h_v1|. The resulting interval is determined in a manner, that on the one hand :math:`Qmin \\leq QRef \\leq Qmax` is fulfilled and on the other hand the results of method |calc_qg_v1| are continuous for :math...
349,324
def load(name, path=None, ext="dat", silent=False): filename = __get_filename(path, name, ext) if not os.path.exists(filename): if not silent: raise ValueException("Specified input filename doesn't exist.") return None with open(filename, "rb") as f: return pickle....
Loads an object from file with given name and extension. Optionally the path can be specified as well.
349,325
def get_domain_workgroup(): minion-id with salt.utils.winapi.Com(): conn = wmi.WMI() for computer in conn.Win32_ComputerSystem(): if computer.PartOfDomain: return {: computer.Domain} else: return {: computer.Workgroup}
Get the domain or workgroup the computer belongs to. .. versionadded:: 2015.5.7 .. versionadded:: 2015.8.2 Returns: str: The name of the domain or workgroup CLI Example: .. code-block:: bash salt 'minion-id' system.get_domain_workgroup
349,326
def get_bets(self, type=None, order_by=None, state=None, project_id=None, page=None, page_size=None): if page is None: page = 1 if page_size is None: page_size = 100 if state == : _states = [] elif state == : _st...
Return bets with given filters and ordering. :param type: return bets only with this type. Use None to include all (default). :param order_by: '-last_stake' or 'last_stake' to sort by stake's created date or None for default ordering. :param state: ...
349,327
def dlogprior(self, param): assert param in self.freeparams, "Invalid param: {0}".format(param) if param in self.distributionparams: return 0.0 else: return self._models[0].dlogprior(param)
Equal to value of `basemodel.dlogprior`.
349,328
def _cm_send_request( registration_ids, data, cloud_type="GCM", application_id=None, use_fcm_notifications=True, **kwargs ): payload = {"registration_ids": registration_ids} if registration_ids else {} data = data.copy() if cloud_type == "FCM" and use_fcm_notifications: notification_payload = {} if "m...
Sends a FCM or GCM notification to one or more registration_ids as json data. The registration_ids needs to be a list.
349,329
def mmInformation(NetworkName_presence=0, NetworkName_presence1=0, TimeZone_presence=0, TimeZoneAndTime_presence=0, LsaIdentifier_presence=0): a = TpPd(pd=0x5) b = MessageType(mesType=0x32) packet = a / b if NetworkName_presence is 1: c = NetworkNameHdr...
MM INFORMATION Section 9.2.15a
349,330
def generate_exact(self, model, vcpu_num, host_cpu): nested = {: , : } cpu = ET.Element(, match=) ET.SubElement(cpu, ).text = model cpu.append(self.generate_topology(vcpu_num)) vendor = host_cpu.findtext() if not nested.get(vendor): LOGGER.debug( ...
Generate exact CPU model with nested virtualization CPU feature. Args: model(str): libvirt supported CPU model vcpu_num(int): number of virtual cpus host_cpu(lxml.etree.Element): the host CPU model Returns: lxml.etree.Element: CPU XML node
349,331
def add(self, name, proc_cls, **kwargs): self.procedures[name] = proc_cls(display_name=name, **kwargs)
Add a function implementation fo the library. :param name: The name of the function as a string :param proc_cls: The implementation of the function as a SimProcedure _class_, not instance :param kwargs: Any additional parameters to the procedure class constructor may be passed as...
349,332
def automain(self, function): captured = self.main(function) if function.__module__ == : import inspect main_filename = inspect.getfile(function) if (main_filename == or (main_filename.startswith() and ma...
Decorator that defines *and runs* the main function of the experiment. The decorated function is marked as the default command for this experiment, and the command-line interface is automatically run when the file is executed. The method decorated by this should be last in the file bec...
349,333
def update_team_settings(self): self.blue_name_lineedit.setText(self.overall_config.get(TEAM_CONFIGURATION_HEADER, "Team Blue Name")) self.orange_name_lineedit.setText(self.overall_config.get(TEAM_CONFIGURATION_HEADER, "Team Orange Name")) self.blue_color_spinbox.setValue(self.overall_c...
Sets all team settings widgets to the value in the overall config :return:
349,334
def send(self, message, body_params=None): if not self.connected: self._LOG.debug("Trying to send message when not connected. (discarded)") else: if body_params and isinstance(message, MsgProto): proto_fill_from_dict(message.body, body_params) ...
.. versionchanged:: 0.8.4 Send a message to CM :param message: a message instance :type message: :class:`.Msg`, :class:`.MsgProto` :param body_params: a dict with params to the body (only :class:`.MsgProto`) :type body_params: dict
349,335
def gradient(self): r func = self class FunctionalQuotientGradient(Operator): def _call(self, x): dividendx = func.dividend(x) divisorx = func.divisor(x) return ((1 / divisorx) * func.dividend.gradient(x...
r"""Gradient operator of the functional. Notes ----- The derivative is computed using the quotient rule: .. math:: [\nabla (f / g)](p) = (g(p) [\nabla f](p) - f(p) [\nabla g](p)) / g(p)^2
349,336
def _destroy_image_acquirer(self, ia): id_ = None if ia.device: ia.stop_image_acquisition() ia._release_data_streams() id_ = ia._device.id_ if ia.device.node_map: ...
Releases all external resources including the controlling device.
349,337
def put(self, measurementId, deviceId): logger.info( + measurementId + + deviceId) if self._measurementController.startMeasurement(measurementId, deviceId): logger.info( + measurementId + + deviceId) return None, 200 else: logger.warning( + measurem...
Initialises the measurement session from the given device. :param measurementId: :param deviceId: :return:
349,338
def set_password(self, user, password): url = self._build_url(self.endpoint.set_password(id=user)) return self._post(url, payload=dict(password=password))
Sets the password for the passed user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/support/users#set-a-users-password>`__. :param user: User object or id :param password: new password
349,339
def getquery(self, default=None, encoding=, errors=): query = self.query if query is None: return default else: return uridecode(query, encoding, errors)
Return the decoded query string, or `default` if the original URI reference did not contain a query component.
349,340
def parse(self, handler): main_config_filename = os.path.abspath(self.parameters[]) config = load_json(main_config_filename) self.init_substitutes = {:%os.path.dirname(main_config_filename), :%os.path.dirname(os....
Main method to parse the Sonata files and call the appropriate methods in the handler
349,341
def get_log(request): query = d1_gmn.app.models.EventLog.objects.all().order_by(, ) if not d1_gmn.app.auth.is_trusted_subject(request): query = d1_gmn.app.db_filter.add_access_policy_filter( request, query, ) query = d1_gmn.app.db_filter.add_redact_annotation(request, q...
MNCore.getLogRecords(session[, fromDate][, toDate][, idFilter][, event] [, start=0][, count=1000]) → Log Sorted by timestamp, id.
349,342
def get_active_schedulings(self): blocks = EighthBlock.objects.get_blocks_this_year() scheduled_activities = EighthScheduledActivity.objects.filter(activity=self) scheduled_activities = scheduled_activities.filter(block__in=blocks) return scheduled_activities
Return EighthScheduledActivity's of this activity since the beginning of the year.
349,343
def patch(self, patch): self.engine.handle( , char=self.character.name, patch=patch, block=False ) for node, stats in patch.items(): nodeproxycache = self[node]._cache for k, v in stats.items(): if v...
Change a bunch of node stats at once. This works similarly to ``update``, but only accepts a dict-like argument, and it recurses one level. The patch is sent to the LiSE core all at once, so this is faster than using ``update``, too. :param patch: a dictionary. Keys are node n...
349,344
def unpack_version(version): minor_version = version % VERSION_MULTIPLIER major_version = (version - minor_version) / VERSION_MULTIPLIER return (major_version, minor_version)
Unpack a single version integer into the two major and minor components.
349,345
def cmp(op1, op2): op1 = BigFloat._implicit_convert(op1) op2 = BigFloat._implicit_convert(op2) if is_nan(op1) or is_nan(op2): raise ValueError("Cannot perform comparison with NaN.") return mpfr.mpfr_cmp(op1, op2)
Perform a three-way comparison of op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2. Both op1 and op2 are considered to their full own precision, which may differ. If one of the operands is NaN, raise ValueError. Note: This function may be usef...
349,346
def raw_sql(self, query, results=False): return self._execute(query, results=results)
Execute a given query string. Could have unexpected results if the query modifies the behavior of the session in a way unknown to Ibis; be careful. Parameters ---------- query : string DML or DDL statement results : boolean, default False Pass True if...
349,347
def main(self): self.status = self.parent.status self.modules = self.parent.executed_modules if hasattr(self, "extractor") and self.extractor.config.verbose: self.config.verbose = self.config.display.verbose = True if not self.config.file...
Responsible for calling self.init, initializing self.config.display, and calling self.run. Returns the value returned from self.run.
349,348
def pass_config(func=None, **config_kw): def decorate(func): def new_func(*args, **kw): config = load_config(**config_kw) func(config, *args, **kw) return functools.update_wrapper(new_func, func) if func is None: return decorate else: return de...
Decorator which passes the CCI config object as the first arg to a click command.
349,349
def _get_11paths_serialized_headers(x_headers): if x_headers: headers = to_key_val_list(x_headers, sort=True, insensitive=True) serialized_headers = "" for key, value in headers: if key.lower().startswith(X_11PATHS_HEADER_PREFIX.lower()) and \ key...
Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a...
349,350
def search_unique_identities(db, term, source=None): uidentities = [] pattern = + term + if term else None with db.connect() as session: query = session.query(UniqueIdentity).\ join(Identity).\ filter(UniqueIdentity.uuid == Identity.uuid) if source: ...
Look for unique identities. This function returns those unique identities which match with the given 'term'. The term will be compated with name, email, username and source values of each identity. When `source` is given, this search will be only performed on identities linked to this source. :par...
349,351
def get_record_collections(recid): try: from invenio.search_engine import ( get_all_collections_of_a_record, get_restricted_collections_for_recid) except ImportError: from invenio.legacy.search_engine import ( get_all_collections_of_a_record, ...
Get all collections the record belong to.
349,352
def timezone(zone): rUTCUS/EasternUS/EasternUS/Eastern%Y-%m-%d %H:%M:%S %Z (%z)2002-10-27 01:00:00 EST (-0500)2002-10-27 00:50:00 EST (-0500)2002-10-27 01:50:00 EDT (-0400)2002-10-27 01:10:00 EST (-0500)Asia/Shangri-LaUnknown\N{TRADE MARK SIGN}Unknown if zone.upper() == : return utc try: zo...
r''' Return a datetime.tzinfo implementation for the given timezone >>> from datetime import datetime, timedelta >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> timezone(unicode('US/Eastern')) is eastern True >>> utc_dt = datetime(2002, ...
349,353
def determineException(vm, m): if m.get_code().get_tries_size() <= 0: return [] h_off = {} handler_catch_list = m.get_code().get_handlers() for try_item in m.get_code().get_tries(): offset_handler = try_item.get_handler_off( ) + handler_catch_list.get_off() i...
Returns try-catch handler inside the method. :param vm: a :class:`~DalvikVMFormat` :param m: a :class:`~EncodedMethod` :return:
349,354
def _summarize_accessible_fields(field_descriptions, width=40, section_title=): key_str = "{:<{}}: {}" items = [] items.append(section_title) items.append("-" * len(section_title)) for field_name, field_desc in field_descriptions.items(): items.append(...
Create a summary string for the accessible fields in a model. Unlike `_toolkit_repr_print`, this function does not look up the values of the fields, it just formats the names and descriptions. Parameters ---------- field_descriptions : dict{str: str} Name of each field and its description, ...
349,355
def create_nouns(max=2): nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
Return a string of random nouns up to max number
349,356
def liked(self): if self.is_logged_in_user: return False classes = self._liked_xpb.one_(self.profile_tree).attrib[].split() return in classes
:returns: Whether or not the logged in user liked this profile
349,357
def get_column_listing(self, table): table = self._connection.get_table_prefix() + table results = self._connection.select(self._grammar.compile_column_exists(table)) return self._connection.get_post_processor().process_column_listing(results)
Get the column listing for a given table. :param table: The table :type table: str :rtype: list
349,358
def _find(self, key): key = self._real_key(key) val = self._override.get(key) if val is not None: log.debug("{0} found in override: {1}".format(key, val)) return val val = self._args.get(key) if val is not None: log...
Given a key, find the value Vyper will check in the following order: override, arg, env, config file, key/value store, default Vyper will check to see if an alias exists first.
349,359
def output(self, mode=, forced=False, context=None): output = .join(self.filter_input(forced, context=context)) if not output: return if settings.COMPRESS_ENABLED or forced: filtered_output = self.filter_output(output) return self.handle_output(mode, filtered_output, forced) ...
The general output method, override in subclass if you need to do any custom modification. Calls other mode specific methods or simply returns the content directly.
349,360
def write(self): with open(self.path, ) as file_: file_.write(self.content)
Write content back to file.
349,361
def add_experiment(experiment): redis = oz.redis.create_connection() oz.bandit.add_experiment(redis, experiment)
Adds a new experiment
349,362
def file_page_generator(my_file, max_page_size=2**28): page_start = " <page>\n" page_end = " </page>\n" chunk_size = max_page_size page_start = " <page>\n" page_end = " </page>\n" leftovers = "" while True: chunk = my_file.read(chunk_size) if not chunk: break chunk = leftovers + c...
Read wikipedia pages from a history dump. Since some pages can be terabytes in size (with all the revisions), we limit page size to max_page_size bytes. Args: my_file: an open file object. max_page_size: an integer Yields: strings
349,363
def dump(self, obj, file, protocol=0): pickle.dump((obj.__class__, obj.raw_data, obj.raw_headers), file, protocol)
Dumps (pickles) a PyGithub object to a file-like object. Some effort is made to not pickle sensitive informations like the Github credentials used in the :class:`Github` instance. But NO EFFORT is made to remove sensitive information from the object's attributes. :param obj: the object to pickl...
349,364
def reset_index(self): self.index = list(range(self.__len__())) self.index_name =
Resets the index of the Series to simple integer list and the index name to 'index'. :return: nothing
349,365
def pointer(self): return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p
349,366
def init_generic_serial_dut(contextlist, conf, index, args): port = conf[] baudrate = (args.baudrate if args.baudrate else conf.get( "application", {}).get("baudrate", 115200)) serial_config = {} if args.serial_rtscts: serial_config["serial_rtscts"] = args.serial_rtscts elif arg...
Initializes a local hardware dut
349,367
def get_host_uuid(self): xml = self._request_host() root = etree.fromstring(xml) data = self._elementtree_to_dict(root) return data[][][], data[][][]
Request host UUID of the server. :returns: the host UUID of the server :raises: IloConnectionError if failed connecting to the iLO.
349,368
def serialize_dict(self, value): if not isinstance(value, dict): return value return { dict_key: self.serialize_value(dict_value) for dict_key, dict_value in value.items() }
Ensure that all values of a dictionary are properly serialized :param value: :return:
349,369
def store_new(self, coll, path, mtime): obj = load_yaml_config(path) self.cache[coll] = (mtime, obj) return obj
Load a collections metadata file and store it :param str coll: The name of the collection the metadata is for :param str path: The path to the collections metadata file :param float mtime: The current mtime of the collections metadata file :return: The collections metadata :rtyp...
349,370
def uncompressed_size(filename): quoted_filename = shlex.quote(filename) if str(filename).lower().endswith(".xz"): output = execute_command(.format(quoted_filename)) compressed, uncompressed = regexp_sizes.findall(output) value, unit = uncompressed.split() value = flo...
Return the uncompressed size for a file by executing commands Note: due to a limitation in gzip format, uncompressed files greather than 4GiB will have a wrong value.
349,371
def comments(self) -> List[]: _lststr = self._lststr _type_to_spans = self._type_to_spans return [ Comment(_lststr, _type_to_spans, span, ) for span in self._subspans()]
Return a list of comment objects.
349,372
def dt2ts(dt, drop_micro=False): is_true(HAS_DATEUTIL, "`pip install python_dateutil` required") if is_empty(dt, except_=False): ts = None elif isinstance(dt, (int, long, float)): ts = float(dt) elif isinstance(dt, basestring): try: parsed_dt = float(dt) ...
convert datetime objects to timestamp seconds (float)
349,373
def prompt_file(prompt, default=None, must_exist=True, is_dir=False, show_default=True, prompt_suffix=, color=None): if must_exist: while True: r = prompt_autocomplete(prompt, path_complete(is_dir), default, show_default=show_default, pr...
Prompt a filename using using glob for autocompetion. If must_exist is True (default) then you can be sure that the value returned is an existing filename or directory name. If is_dir is True, this will show only the directories for the completion.
349,374
def main(argv=None): if argv is None: argv = sys.argv[1:] parser = build_args() args = parser.parse_args(args=argv) verbosity = args.verbose root = logging.getLogger() formatter = logging.Formatter() handler = logging.StreamHandler() handler.setFormatter(formatter) ...
Main script entry point. Args: argv (list): The command line arguments, defaults to sys.argv if not passed. Returns: int: The return value of the script.
349,375
def dock(window): if self._dock: print("Deleting existing dock...") parent = self._dock dialog = None stacked_widget = None main_windows = [] while parent: if isinstance(parent, QtWidgets.QDialog): dialog = parent ...
Expecting a window to parent into a Nuke panel, that is dockable.
349,376
def load(cls, config_paths, seed_values=None): @contextmanager def opener(f): with open(f, ) as fh: yield fh return cls._meta_load(opener, config_paths, seed_values)
Loads config from the given paths. A handful of seed values will be set to act as if specified in the loaded config file's DEFAULT section, and be available for use in substitutions. The caller may override some of these seed values. :param list config_paths: Load from these paths. Later instances ta...
349,377
def _resize_handler(self, *args, **kwarg): try: assert self.resize_lock except AssertionError: self.resize_lock = True term = self.term term.clear_cache() newHeight = term.height newWidth = term.width ...
Called when a window resize signal is detected Resets the scroll window
349,378
def _check_implied_parameters(self, parameters): for key, values, implied_keys in self.IMPLIED_PARAMETERS: self.log([u"Checking implied parameters by =", key, values]) if (key in parameters) and (parameters[key] in values): found = False for impli...
Check whether at least one of the keys in implied_keys is in ``parameters``, when a given ``key=value`` is present in ``parameters``, for some value in values. Log messages into ``self.result``. :param dict parameters: the given parameters
349,379
def delete(self, CorpNum, ItemCode, MgtKey, UserID=None): if MgtKey == None or MgtKey == "": raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.") if ItemCode == None or ItemCode == "": raise PopbillException(-99999999, "명세서 종류 코드가 입력되지 않았습니다.") return s...
삭제 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] MgtKey : 파트너 문서관리번호 UserID : 팝빌회원 아이디 return ...
349,380
def update_channels(self): logging.info("Updating channels") with switch_db(StreamDefinitionModel, ): for s in StreamDefinitionModel.objects(): try: stream_id = StreamId(name=s.stream_id.name, meta_data=s.stream_id.meta_data) excep...
Pulls out all of the stream definitions from the database, and populates the channels with stream references
349,381
def __create_weights_all_to_all(self, stimulus): for i in range(len(stimulus)): for j in range(i + 1, len(stimulus)): weight = self.__calculate_weight(stimulus[i], stimulus[j]) self.__weights[i][j] = weight se...
! @brief Create weight all-to-all structure between neurons in line with stimulus. @param[in] stimulus (list): External stimulus for the chaotic neural network.
349,382
def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ): for line in pixdump_iter( source, start, end, length, width, height, palette ): print( line )
Print the contents of a byte string as a 256 colour image. source The byte string to print. start Start offset to read from (default: start) end End offset to stop reading at (default: end) length Length to read in (optional replacement for end) width Wid...
349,383
def evaluate_bounding_box(ctrlpts): dimension = len(ctrlpts[0]) bbmin = [float() for _ in range(0, dimension)] bbmax = [float() for _ in range(0, dimension)] for cpt in ctrlpts: for i, arr in enumerate(zip(cpt, bbmin)): if arr[0] < arr[1]: bbmin[i] = a...
Computes the minimum bounding box of the point set. The (minimum) bounding box is the smallest enclosure in which all the input points lie. :param ctrlpts: points :type ctrlpts: list, tuple :return: bounding box in the format [min, max] :rtype: tuple
349,384
def get_description(self): return DisplayText( text=profile.DESCRIPTION, language_type=Type(**profile.LANGUAGETYPE), script_type=Type(**profile.SCRIPTTYPE), format_type=Type(**profile.FORMATTYPE))
Gets a description of this service implementation. return: (osid.locale.DisplayText) - a description *compliance: mandatory -- This method must be implemented.*
349,385
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): local_buffer = utils.BytearrayStream() if self._object_type: self._object_type.write(local_buffer, kmip_version=kmip_version) else: raise exceptions.InvalidField( "The Creat...
Write the data encoding the Create response payload to a buffer. Args: output_buffer (stream): A data buffer in which to encode object data, supporting a write method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the obj...
349,386
def get_config(self, view = None): path = self._path() + resp = self._get_resource_root().get(path, params = view and dict(view=view) or None) return self._parse_svc_config(resp, view)
Retrieve the service's configuration. Retrieves both the service configuration and role type configuration for each of the service's supported role types. The role type configurations are returned as a dictionary, whose keys are the role type name, and values are the respective configuration dictionari...
349,387
def initial_individual(self): ind = creator.Individual( [random.uniform(-1, 1) for _ in range(len(self._params[]))]) return ind
Generates an individual with random parameters within bounds.
349,388
def fcoe_get_login_output_fcoe_login_list_fcoe_login_connected_peer_type(self, **kwargs): config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login output = ET.SubElement(fcoe_get_login, "output") fcoe_login_list = ET.SubElement(...
Auto Generated Code
349,389
def start(self): if self._packet_pipeline_mode == Kinect2PacketPipelineMode.OPENGL: self._pipeline = lf2.OpenGLPacketPipeline() elif self._packet_pipeline_mode == Kinect2PacketPipelineMode.CPU: self._pipeline = lf2.CpuPacketPipeline() self._log...
Starts the Kinect v2 sensor stream. Raises ------ IOError If the Kinect v2 is not detected.
349,390
def confd_state_internal_callpoints_notification_stream_replay_replay_support(self, **kwargs): config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.SubElement(confd_state, "internal") call...
Auto Generated Code
349,391
def engage(self, height): if height > MAX_ENGAGE_HEIGHT or height < 0: raise ValueError(.format( MAX_ENGAGE_HEIGHT)) self._driver.move(height) self._engaged = True
Move the magnet to a specific height, in mm from home position
349,392
def eigvec_to_eigdispl(v, q, frac_coords, mass): c = np.exp(2j * np.pi * np.dot(frac_coords, q)) / np.sqrt(mass) return c*v
Converts a single eigenvector to an eigendisplacement in the primitive cell according to the formula:: exp(2*pi*i*(frac_coords \\dot q) / sqrt(mass) * v Compared to the modulation option in phonopy, here all the additional multiplicative and phase factors are set to 1. Args: ...
349,393
def find_elements_by_id(self, id_, update=False) -> Elements: t found. Usage: elements = driver.find_elements_by_id() ' return self.find_elements(by=By.ID, value=id_, update=update)
Finds multiple elements by id. Args: id_: The id of the elements to be found. update: If the interface has changed, this option should be True. Returns: A list with elements if any was found. An empty list if not. Raises: NoSuchElementException ...
349,394
def present(name, createdb=None, createroles=None, encrypted=None, superuser=None, replication=None, inherit=None, login=None, password=None, default_password=None, refresh_password=None, ...
Ensure that the named user is present with the specified privileges Please note that the user/group notion in postgresql is just abstract, we have roles, where users can be seens as roles with the LOGIN privilege and groups the others. name The name of the system user to manage. createdb ...
349,395
def build_report(job_ini, output_dir=None): calc_id = logs.init() oq = readinput.get_oqparam(job_ini) if oq.calculation_mode == : oq.calculation_mode = oq.ground_motion_fields = False output_dir = output_dir or os.path.dirname(job_ini) from openquake.calculators import base c...
Write a `report.csv` file with information about the calculation without running it :param job_ini: full pathname of the job.ini file :param output_dir: the directory where the report is written (default the input directory)
349,396
def get_vault_form(self, *args, **kwargs): if isinstance(args[-1], list) or in kwargs: return self.get_vault_form_for_create(*args, **kwargs) else: return self.get_vault_form_for_update(*args, **kwargs)
Pass through to provider VaultAdminSession.get_vault_form_for_update
349,397
def install(self, connection, partition, table_name=None, columns=None, materialize=False, logger=None): partition.localize() self._add_partition(connection, partition) fdw_table = partition.vid view_table = .format(fdw_table) if materialize: ...
Creates FDW or materialize view for given partition. Args: connection: connection to postgresql partition (orm.Partition): materialize (boolean): if True, create read-only table. If False create virtual table. Returns: str: name of the created table.
349,398
def get_cursor_position(self, file_path): try: map = json.loads(self._settings.value()) except TypeError: map = {} try: pos = map[file_path] except KeyError: pos = 0 if isinstance(pos, list): ...
Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0)
349,399
def _wal_name(cls): if cls._WAL_NAME is None: version = cls._dict_transform(psql_csv_run( "SELECT current_setting()")) if int(version[]) >= 100000: cls._WAL_NAME = else: cls._WAL_NAME = return cls._WAL_NAM...
Sets and returns _WAL_NAME to 'wal' or 'xlog' depending on version of postgres we are working with. It is used for handling xlog -> wal rename in postgres v10