Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
339,600
def _render_timestep(self, t: int, s: Fluents, a: Fluents, f: Fluents, r: np.float32) -> None: print("============================") print("TIME = {}".format(t)) print("============================") fluent_variables = self._compiler.rddl.acti...
Prints fluents and rewards for the given timestep `t`. Args: t (int): timestep s (Sequence[Tuple[str], np.array]: State fluents. a (Sequence[Tuple[str], np.array]: Action fluents. f (Sequence[Tuple[str], np.array]: Interm state fluents. r (np.float32)...
339,601
def store(self, name, value, atype, new_name=None, multiplier=None, allowed_values=None): if value is not None: _bad_type = (not isinstance(value, atype)) if not _bad_type: _bad_type = (isinstance(value, bool) and atype == int) if _b...
store a config value in a dictionary, these values are used to populate a trasnfer spec validation -- check type, check allowed values and rename if required
339,602
def _header_message_type_update(obj, attr): old_enum = obj.message_type new_header = attr[1] new_enum = new_header.__class__.message_type.enum_ref if old_enum: msg_type_name = old_enum.name new_type = new_enum[msg_type_name] ...
Update the message type on the header. Set the message_type of the header according to the message_type of the parent class.
339,603
def _compile_update_columns(self, values): columns = [] for key, value in values.items(): columns.append("%s = %s" % (self.wrap(key), self.parameter(value))) return ", ".join(columns)
Compile the columns for the update statement :param values: The columns :type values: dict :return: The compiled columns :rtype: str
339,604
def format_repo_status(repo): commit = repo.commit() return { : os.path.basename(repo.working_dir), : commit.hexsha, : datetime.fromtimestamp( commit.committed_date).isoformat(), }
Return a dictionary representing the repository status It returns ``None`` for things we do not support or are not relevant. :param str repo_name: The name of the repository. :returns: dict
339,605
def update_radii(self, radii): self.radii = np.array(radii, dtype=) prim_radii = self._gen_radii(self.radii) self._radii_vbo.set_data(prim_radii) self.widget.update()
Update the radii inplace
339,606
def connect(self): self.connected_node = None for i, node in self.nodes.items(): host, port = i.split() port = int(port) redis_client = redis.Redis(host, port, **self.client_kw_args) try: ret = redis_client.execute_command() ...
Connect to one of the Disque nodes. You can get current connection with connected_node property :returns: nothing
339,607
def get_events(object_key: str) -> List[Event]: events_data = _get_events_data(object_key) return [Event.from_config(event_dict) for event_dict in events_data]
Get list of events for the object with the specified key.
339,608
def store(self, installed_stuff, metadata, interpreter, options): new_content = { : int(time.mktime(time.localtime())), : installed_stuff, : metadata, : interpreter, : options } logger.debug("Storing installed=%s metadata=%s in...
Store the virtualenv metadata for the indicated installed_stuff.
339,609
def _keepVol(self, vol): if vol is None: return if vol in self.extraVolumes: del self.extraVolumes[vol] return if vol not in self.paths: raise Exception("%s not in %s" % (vol, self)) paths = [os.path.basename(path) for path in s...
Mark this volume to be kept in path.
339,610
def accuracy_curve(self, delta_tau=0.01): orig_thresh = self.threshold sorted_labels, sorted_probs = self.sorted_values scores = [] taus = [] tau = 0 for k in range(len(sorted_labels)): self.threshold = tau scores.ap...
Computes the relationship between probability threshold and classification accuracy.
339,611
def databasesKEGG(organism,ens_ids): all_genes=urlopen("http://rest.kegg.jp/list/"+organism).read() all_genes=all_genes.split("\n") dbs=[] while len(dbs) == 0: for g in all_genes: if len(dbs) == 0: kid = g.split("\t")[0] gene=urlopen("http://rest....
Finds KEGG database identifiers for a respective organism given example ensembl ids. :param organism: an organism as listed in organismsKEGG() :param ens_ids: a list of ensenbl ids of the respective organism :returns: nothing if no database was found, or a string if a database was found
339,612
def get_vulnerability_functions_04(node, fname): logging.warning(, fname) imts = set() vf_ids = set() vmodel = scientific.VulnerabilityModel(**node.attrib) for vset in node: imt_str = vset.IML[] imls = ~vset.IML imts.add(imt_str) for vfun in vset.g...
:param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, vf_id -> vulnerability function
339,613
def _deleteCompletedMeasurement(self, measurementId): message, count, deleted = self.deleteFrom(measurementId, self.completeMeasurements) if count is 0: message, count, deleted = self.deleteFrom(measurementId, self.failedMeasurements) return message, count, deleted
Deletes the named measurement from the completed measurement store if it exists. :param measurementId: :return: String: error messages Integer: count of measurements deleted
339,614
def get_summary(self, dataset_number=None, use_dfsummary_made=False): dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return None test = self.get_dataset(dataset_number) ...
Retrieve summary returned as a pandas DataFrame.
339,615
def create_field(self, work_item_field, project=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) content = self._serialize.body(work_item_field, ) response = self._send(http_method=, loca...
CreateField. [Preview API] Create a new field. :param :class:`<WorkItemField> <azure.devops.v5_1.work_item_tracking.models.WorkItemField>` work_item_field: New field definition :param str project: Project ID or project name :rtype: :class:`<WorkItemField> <azure.devops.v5_1.work-item-tra...
339,616
def parse_wyckoff_csv(wyckoff_file): rowdata = [] points = [] hP_nums = [433, 436, 444, 450, 452, 458, 460] for i, line in enumerate(wyckoff_file): if line.strip() == : break rowdata.append(line.strip().split()) if rowdata[-1][0].isdigit(): ...
Parse Wyckoff.csv There are 530 data sets. For one example: 9:C 1 2 1::::::: ::4:c:1:(x,y,z):(-x,y,-z):: ::2:b:2:(0,y,1/2)::: ::2:a:2:(0,y,0):::
339,617
def get_platform(): _sys_map = {: , : , : , : , : } non_x86_linux_machines = {, , } sys_platform = _sys_map.get(sys.platform, ) bits = 8 * tuple.__itemsize__ if (sys_platform == and platform.machine() in non_x86_linux_machines): ...
Get platform of current system (system and bitness).
339,618
def should_compile_incrementally(self, vts, ctx): if not vts.is_incremental: return False if not self._clear_invalid_analysis: return True return os.path.exists(ctx.analysis_file)
Check to see if the compile should try to re-use the existing analysis. Returns true if we should try to compile the target incrementally.
339,619
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5): p_str = get_dim_name(p, (internal_names.PLEVEL_STR, )) p_vals = to_pascal(p.values.copy()) p_edges_interior = 0.5*(p_vals[:-1] + p_vals[1:]) p_edges = np.concatenate(([p_bot], p_edges_interior, [p_top])) p_edge_above = p_edges[1:] p_edge_be...
Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pressure is not changed by ps, since they don't in...
339,620
def opens(self, tag=None, fromdate=None, todate=None): return self.call("GET", "/stats/outbound/opens", tag=tag, fromdate=fromdate, todate=todate)
Gets total counts of recipients who opened your emails. This is only recorded when open tracking is enabled for that email.
339,621
def ssh(cls, vm_id, login, identity, args=None): cmd = [] if identity: cmd.extend((, identity,)) version, ip_addr = cls.vm_ip(vm_id) if version == 6: cmd.append() if not ip_addr: cls.echo( % vm_id) return cmd.app...
Spawn an ssh session to virtual machine.
339,622
def conv(name, x, output_channels, filter_size=None, stride=None, logscale_factor=3.0, apply_actnorm=True, conv_init="default", dilations=None): if conv_init == "zeros" and apply_actnorm: raise ValueError("apply_actnorm is unstable when init is set to zeros.") x_shape = common_layers.shape...
Convolutional layer with edge bias padding and optional actnorm. If x is 5-dimensional, actnorm is applied independently across every time-step. Args: name: variable scope. x: 4-D Tensor or 5-D Tensor of shape NHWC or NTHWC output_channels: Number of output channels. filter_size: list of ints, i...
339,623
def _use_last_dir_name(self, path, prefix=): matching_dirs = ( dir_name for dir_name in reversed(os.listdir(path)) if os.path.isdir(os.path.join(path, dir_name)) and dir_name.startswith(prefix) ) return next(matching_dirs, None) or
Return name of the last dir in path or '' if no dir found. Parameters ---------- path: str Use dirs in this path prefix: str Use only dirs startings by this prefix
339,624
def dstat_job_producer(provider, statuses, user_ids=None, job_ids=None, job_names=None, task_ids=None, task_attempts=None, labels=None, ...
Generate jobs as lists of task dicts ready for formatting/output. Args: provider: an instantiated dsub provider. statuses: a set of status strings that eligible jobs may match. user_ids: a set of user strings that eligible jobs may match. job_ids: a set of job-id strings eligible jobs may match. ...
339,625
def find_model_by_id(self, constructor, id_, *, columns=None): return self.find_model( constructor, get_id_constraints(constructor.primary_key_name, id_), columns=columns)
Searches for a model by id, according to its class' primary_key_name. If primary_key_name is a tuple, id_ must be a tuple with a matching length.
339,626
def set_target_n(self, value): if isinstance(value, int) is False: raise TypeError("The type of __target_n must be int.") self.__target_n = value
setter
339,627
def update_nexusport_binding(port_id, new_vlan_id): if not new_vlan_id: LOG.warning("update_nexusport_binding called with no vlan") return LOG.debug("update_nexusport_binding called") session = bc.get_writer_session() binding = _lookup_one_nexus_binding(session=session, port_id=port...
Updates nexusport binding.
339,628
def checkout(self, branch_name): try: find( self.repo.branches, lambda b: b.name == branch_name ).checkout() except OrigCheckoutError as e: raise CheckoutError(branch_name, details=e)
Checkout a branch by name.
339,629
def convert_into(input_path, output_path, output_format=, java_options=None, **kwargs): if output_path is None or len(output_path) is 0: raise AttributeError(" shoud not be None or empty") kwargs[] = output_path kwargs[] = _extract_format_for_conversion(output_format) if java_options is ...
Convert tables from PDF into a file. Args: input_path (file like obj): File like object of tareget PDF file. output_path (str): File path of output file. output_format (str, optional): Output format of this function (csv, json or tsv). Default: csv ...
339,630
def merge_context(self, src=None): if src is None: self._ctx.keys.extend(src.keys) self._ctx.preds.extend(src.preds)
Merges context from this instance with src.
339,631
def birth_and_death_date2marc(self, key, value): name_field = self.get(, {}) if in name_field: if int(name_field[].split()[0]) > int(value.split()[0]): dates_field = .join([value, name_field[]]) else: dates_field = .join([name_field[], value]) else: dat...
Populate the ``100__d`` MARC field, which includes the birth and the death date. By not using the decorator ```for_each_value```, the values of the fields ```birth_date``` and ```death_date``` are both added to ```values``` as a list.
339,632
def color_interp(data): from rasterio.enums import ColorInterp as ci modes = {: [ci.gray], : [ci.gray, ci.alpha], : [ci.Y, ci.Cb, ci.Cr], : [ci.Y, ci.Cb, ci.Cr, ci.alpha]} try: mode = .join(data[].values) return modes[mode] except KeyError: ...
Get the color interpretation for this image.
339,633
def delMargin(self, name): for index, margin in enumerate(self._margins): if margin.getName() == name: visible = margin.isVisible() margin.clear() margin.deleteLater() del self._margins[index] if visible: ...
Deletes a margin. Returns True if the margin was deleted and False otherwise.
339,634
def sendEmail(self, url, attempt, email, _sendEmail=_sendEmail): host = url.netloc.split(, 1)[0] from_ = + host body = file(sibpath(__file__, )).read() body %= {: from_, : email, : rfc822.formatdate(), : smtp.messageid(), ...
Send an email for the given L{_PasswordResetAttempt}. @type url: L{URL} @param url: The URL of the password reset page. @type attempt: L{_PasswordResetAttempt} @param attempt: An L{Item} representing a particular user's attempt to reset their password. @type email: C{s...
339,635
def _func_filters(self, filters): if not isinstance(filters, (list,tuple)): raise TypeError() for i, func in enumerate(filters) : if isinstance(func, str) and func == : filters[i] = elif isinstance(func, tuple) and func[0] in YQL.FUNC_FILTER...
Build post query filters
339,636
def get(self, identifier, default=None): split_label = (tuple(identifier.split()) if isinstance(identifier, str) else tuple(identifier)) if len(split_label) == 1: identifier = split_label[0] return self.__dict__.get(identifier, default) pat...
Get a node of the AttrTree using its path string. Args: identifier: Path string of the node to return default: Value to return if no node is found Returns: The indexed node of the AttrTree
339,637
def register_game(game_name, game_mode="NoFrameskip-v4"): if game_name not in ATARI_GAMES: raise ValueError("Game %s not in ATARI_GAMES" % game_name) if game_mode not in ATARI_GAME_MODES: raise ValueError("Unknown ATARI game mode: %s." % game_mode) camel_game_name = misc_utils.snakecase_to_camelcase(ga...
Create and register problems for the game. Args: game_name: str, one of the games in ATARI_GAMES, e.g. "bank_heist". game_mode: the frame skip and sticky keys config. Raises: ValueError: if game_name or game_mode are wrong.
339,638
def removeProductFrom(self, userstore): def uninstall(): i = userstore.findFirst(Installation, Installation.types == self.types) i.uninstall() i.deleteFromStore() userstore.transact(uninstall)
Uninstall all the powerups this product references and remove the Installation item from the user's store. Doesn't remove the actual powerups currently, but /should/ reactivate them if this product is reinstalled.
339,639
def imresize(img, size, return_scale=False, interpolation=): h, w = img.shape[:2] resized_img = cv2.resize( img, size, interpolation=interp_codes[interpolation]) if not return_scale: return resized_img else: w_scale = size[0] / w h_scale = size[1] / h return ...
Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanc...
339,640
def bivell (sx, sy, cxy): _bivcheck (sx, sy, cxy) from numpy import arctan2, sqrt sx2, sy2, cxy2 = sx**2, sy**2, cxy**2 pa = 0.5 * arctan2 (2 * cxy, sx2 - sy2) h = sqrt ((sx2 - sy2)**2 + 4*cxy2) t = 2 * (sx2 * sy2 - cxy2) / (sx2 + sy2 - h) if t < 0: raise ValueError ( ...
Given the parameters of a Gaussian bivariate distribution, compute the parameters for the equivalent 2D Gaussian in ellipse form (major, minor, pa). Inputs: * sx: standard deviation (not variance) of x var * sy: standard deviation (not variance) of y var * cxy: covariance (not correlation coef...
339,641
def _download(self, dstFile): for attempt in retry(predicate=lambda e: isinstance(e, HTTPError) and e.code == 400): with attempt: with closing(urlopen(self.url)) as content: buf = content.read() contentHash = hashlib.md5(buf) assert conten...
Download this resource from its URL to the given file object. :type dstFile: io.BytesIO|io.FileIO
339,642
def index_fields(self, vocab: Vocabulary) -> None: if not self.indexed: self.indexed = True for field in self.fields.values(): field.index(vocab)
Indexes all fields in this ``Instance`` using the provided ``Vocabulary``. This `mutates` the current object, it does not return a new ``Instance``. A ``DataIterator`` will call this on each pass through a dataset; we use the ``indexed`` flag to make sure that indexing only happens once. ...
339,643
def extendbed(args): from jcvi.formats.sizes import Sizes p = OptionParser(extendbed.__doc__) p.add_option("--nogaps", default=False, action="store_true", help="Do not print bed lines for gaps [default: %default]") p.add_option("--bed12", default=False, action="store_true", ...
%prog extend agpfile componentfasta Extend the components to fill the component range. For example, a bed/gff3 file that was converted from the agp will contain only the BAC sequence intervals that are 'represented' - sometimes leaving the 5` and 3` out (those that overlap with adjacent sequences. This...
339,644
def maybeReceiveAck(self, ackPacket): ackPredicate = self.ackPredicate self.ackPredicate = lambda packet: False if ackPacket.syn: self.synAck() return if ackPredicate(ackPacket): self.ack()
Receive an L{ack} or L{synAck} input from the given packet.
339,645
def create_response(headers, body, status): response = Response(body or ) for k, v in headers.items(): response.headers[str(k)] = v response.status_code = status return response
Create response class for Flask.
339,646
def _load_settings(self, info): modname, modsettings, architectures, targets, release_info = info self.settings = modsettings prepend = if in modsettings: prepend = modsettings[].lower() + key = prepend + modname.lower() self....
Load settings for a module.
339,647
def is_ipaddress(hostname): if six.PY3 and isinstance(hostname, bytes): hostname = hostname.decode() families = [socket.AF_INET] if hasattr(socket, ): families.append(socket.AF_INET6) for af in families: try: inet_pton(af, hostname) except (soc...
Detects whether the hostname given is an IP address. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise.
339,648
def point_segment_distance(point, segment): assert isinstance(point, Point), \ "point is not of type Point, but of %r" % type(point) dx = segment.p2.x - segment.p1.x dy = segment.p2.y - segment.p1.y if dx == dy == 0: p_below_p1 = point.y <= segment.p1.y and segment.p1.y <= segment...
>>> a = LineSegment(Point(1,0), Point(2,0)) >>> b = LineSegment(Point(2,0), Point(0,2)) >>> point_segment_distance(Point(0,0), a) 1.0 >>> "%0.2f" % point_segment_distance(Point(0,0), b) '1.41'
339,649
def get_activities_by_ids(self, activity_ids): collection = JSONClientValidated(, collection=, runtime=self._runtime) object_id_list = [] for i in activity_ids: objec...
Gets an ``ActivityList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the activities specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id`` in the supplied list is not found or inaccessi...
339,650
def __extractOntologies(self, exclude_BNodes = False, return_string=False): out = [] qres = self.queryHelper.getOntology() if qres: for candidate in qres: if isBlankNode(candidate[0]): if exclude_BNodes: ...
returns Ontology class instances [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ],
339,651
def _compile(self, module=None): mod = module or sys.modules[] self.mod = mod if hasattr(mod, ): version = "%(prog)s " + mod.__version__ self.ap_args.append( ap_arg(, , action=, version=version)) if module is Non...
Compile functions for argparsing.
339,652
def validate(self, dct): if not isinstance(dct, dict): self._raise_invalid_fields(, dct, ) txn_type = dct.get(TXN_TYPE) if txn_type is None: self._raise_missed_fields(TXN_TYPE) if txn_type in self.operations: op = sel...
Choose a schema for client request operation and validate the operation field. If the schema is not found skips validation. :param dct: an operation field from client request :return: raises exception if invalid request
339,653
def addr_info(addr): if isinstance(addr, basestring): return socket.AF_UNIX if not isinstance(addr, collections.Sequence): raise ValueError("address is not a tuple") if len(addr) < 2: raise ValueError("cannot understand address") if not (0 <= addr[1] ...
Interprets an address in standard tuple format to determine if it is valid, and, if so, which socket family it is. Returns the socket family.
339,654
def _get_directory(self, path, content, format): with self.engine.begin() as db: try: record = get_directory( db, self.user_id, path, content ) except NoSuchDirectory: if self.file_exists(path): ...
Get a directory from the database.
339,655
def get_program_details(self, request, program_uuid, enterprise_customer): try: course_catalog_api_client = CourseCatalogApiServiceClient(enterprise_customer.site) except ImproperlyConfigured: error_code = LOGGER.error( ...
Retrieve fundamental details used by both POST and GET versions of this view. Specifically: * Take the program UUID and get specific details about the program. * Determine whether the learner is enrolled in the program. * Determine whether the learner is certificate eligible for the pr...
339,656
def rename_key(self, old_key, new_key): if new_key in self.referenced_by: dbt.exceptions.raise_cache_inconsistent( .format(old_key, new_key) ) if old_key not in self.referenced_by: return value = self.referenced_by.po...
Rename a reference that may or may not exist. Only handles the reference itself, so this is the other half of what `rename` does. If old_key is not in referenced_by, this is a no-op. :param _ReferenceKey old_key: The old key to be renamed. :param _ReferenceKey new_key: The new key to r...
339,657
def sign_s3_upload(self): AWS_ACCESS_KEY = self.config_() AWS_SECRET_KEY = self.config_() S3_BUCKET = self.config_() object_name = request.args.get() mime_type = request.args.get() expires = long(time.time()+10) amz_headers = "x-amz-acl:public-read" ...
Allow to create Signed object to upload to S3 via JS
339,658
def moving_average(interval, windowsize, borders=None): half = int(math.floor(windowsize/2.0)) window = numpy.ones(int(windowsize))/float(windowsize) if borders == None: return numpy.convolve(interval, window, ) if borders == : return numpy.convolve(interval, window, ...
This is essentially a convolving operation. Several option exist for dealing with the border cases. * None: Here the returned signal will be smaller than the inputted interval. * zero_padding: Here the returned signal will be larger than the inputted interval and we will add zeros to the original inte...
339,659
def get_modification_date(brain_or_object): modified = getattr(brain_or_object, "modified", None) if modified is None: fail("Object {} has no modification date ".format( repr(brain_or_object))) if callable(modified): return modified() return modified
Get the modification date of the brain or object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Modification date :rtype: DateTime
339,660
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except: if not robust: s = + traceback.format_exc() logger = ...
Wraps a target with queues replacing stdout and stderr
339,661
def read(*paths): with open(os.path.join(os.path.dirname(__file__), *paths)) as fp: return fp.read()
read and return txt content of file
339,662
def add_distance_metric(self, distance_fun_name, distance_fun_module, with_x): if self.ampsq_is_diag: kls = covariance_wrapper_with_diag else: kls = covariance_wrapper new_fun = kls(self.cov_fun_name, self.cov_fun_module, self.extra_cov_params, distance_fun_name...
Takes a function that computes a distance matrix for points in some coordinate system and returns self's covariance function wrapped to use that distance function. Uses function apply_distance, which was used to produce self.euclidean and self.geographic and their docstrings. ...
339,663
def key_description(self): "Return a description of the key" vk, scan, flags = self._get_key_info() desc = if vk: if vk in CODE_NAMES: desc = CODE_NAMES[vk] else: desc = "VK %d"% vk else: desc = "%s"% self.key ...
Return a description of the key
339,664
def _validate_resource_desc(self): self._prof.prof(, uid=self._uid) self._logger.debug() expected_keys = [, , ] for key in expected_keys: if key not in self._resource_desc: raise MissingError(obj=, ...
**Purpose**: Validate the resource description provided to the ResourceManager
339,665
def optimize(self, x0, f=None, df=None, f_df=None): import scipy.optimize if f_df is None and df is not None: f_df = lambda x: float(f(x)), df(x) if f_df is not None: def _f_df(x): return f(x), f_df(x)[1][0] if f_df is None and df is None: ...
:param x0: initial point for a local optimizer. :param f: function to optimize. :param df: gradient of the function to optimize. :param f_df: returns both the function to optimize and its gradient.
339,666
def find_module(self, fullname, path=None): if path is None: return if fullname.startswith(self.module_prefix): return self else: return None
Find the appropriate loader for module ``name`` :param fullname: ``__name__`` of the module to import :type fullname: str :param path: ``__path__`` of the *parent* package already imported :type path: str or None
339,667
def join_(self, channel, key=None, process_only=False): with self.lock: topic = users = [] set_by = time_set = self.is_in_channel(channel, False) if not process_only: if key: self.send( % (ch...
Joins a channel. Returns a tuple of information regarding the channel. Channel Information: * [0] - A tuple containing /NAMES. * [1] - Channel topic. * [2] - Tuple containing information regarding of whom set the topic. * [3] - Time object about when the topic was set. ...
339,668
def live(self): session = self._session url = "{}/live".format(self._base_url) supported_params = frozenset([]) params = {k: v for k, v in iteritems(self._params) if k in supported_params} return session.live(url, self._datapoint_class, { : ...
Get a live stream of timeseries readings. This returns an Iterable over a live stream of readings. Note that the result will need to be closed since the system can not tell when you'll be done with it. You can either call ``close`` on the endpoint when you're or use the context...
339,669
def enable_gui(gui, kernel=None): if gui not in loop_map: raise ValueError("GUI %r not supported" % gui) if kernel is None: if Application.initialized(): kernel = getattr(Application.instance(), , None) if kernel is None: raise RuntimeError("You didn't specif...
Enable integration with a given GUI
339,670
def get_spherical_bounding_box(lons, lats): north, south = numpy.max(lats), numpy.min(lats) west, east = numpy.min(lons), numpy.max(lons) assert (-180 <= west <= 180) and (-180 <= east <= 180), (west, east) if get_longitudinal_extent(west, east) < 0: if hasattr(lo...
Given a collection of points find and return the bounding box, as a pair of longitudes and a pair of latitudes. Parameters define longitudes and latitudes of a point collection respectively in a form of lists or numpy arrays. :return: A tuple of four items. These items represent western, easte...
339,671
def merged_args_dicts(global_args, subcommand_args): t want False values for a flag in the subcommand to override True values if that flag was given at the top level. This function specifically handles that case.' merged = global_args.copy() for key, val in subcommand_args.items(): if key no...
We deal with docopt args from the toplevel peru parse and the subcommand parse. We don't want False values for a flag in the subcommand to override True values if that flag was given at the top level. This function specifically handles that case.
339,672
def update(self, friendly_name): data = values.of({: friendly_name, }) payload = self._version.update( , self._uri, data=data, ) return FunctionInstance( self._version, payload, service_sid=self._solution[...
Update the FunctionInstance :param unicode friendly_name: The friendly_name :returns: Updated FunctionInstance :rtype: twilio.rest.serverless.v1.service.function.FunctionInstance
339,673
def get_key_params_from_user(gpg_key_param_list): params = [[_(), ]] vals = [""] * len(params) while "" in vals: dlg = GPGParamsDialog(None, -1, "Enter GPG key parameters", params) dlg.CenterOnScreen() for val, textctrl in zip(vals, dlg.textctrls): textctrl.SetVa...
Displays parameter entry dialog and returns parameter dict Parameters ---------- gpg_key_param_list: List of 2-tuples \tContains GPG key generation parameters but not name_real
339,674
def get_B_factors(self, force = False): s B-factors. It returns a table of the mean and standard deviation per residue as well as the mean and standard deviation over all residues with each residue having equal weighting. Whether the atom is occupied or not is not taken into ac...
This reads in all ATOM lines and compute the mean and standard deviation of each residue's B-factors. It returns a table of the mean and standard deviation per residue as well as the mean and standard deviation over all residues with each residue having equal weighting. Whet...
339,675
def merge(self, indict): for key, val in list(indict.items()): if (key in self and isinstance(self[key], dict) and isinstance(val, dict)): self[key].merge(val) else: self[key] = val
A recursive update - useful for merging config files. >>> a = '''[section1] ... option1 = True ... [[subsection]] ... more_options = False ... # end of file'''.splitlines() >>> b = '''# File is user.ini ... [section1] ... option1 =...
339,676
def generate_net(df,tf_idf,dump_path=None): .wrnt if dump_path and dump_path[-4:] != __WRNT_FORMAT: raise Exception(__WRNG_FORMAT_MSG) start_t = datetime.now() print(TAG,) word_net = {} for word in df.keys(): word_net[word] = Word(word) print(TAG,,datetime.now()-star...
Generate WordNetwork dict of Word() instance, and dump as a file if asked to. @Args: -- df : IDF value generated by find_tf_idf() tf_idf : TF-IDF value generated by find_tf_idf() dump_path : file_path where to dump network entities, standart format is '.wrnt' (default=None) @returns:...
339,677
def apply_driver_hacks(self, app, sa_url, options): if sa_url.drivername.startswith(): sa_url.query.setdefault(, ) if sa_url.drivername != : options.setdefault(, 10) options.setdefault(, 7200) elif sa_url.drivername == : pool_s...
This method is called before engine creation and used to inject driver specific hacks into the options. The `options` parameter is a dictionary of keyword arguments that will then be used to call the :func:`sqlalchemy.create_engine` function. The default implementation provides some sa...
339,678
def has_table(self, table_name, **kwargs): with self.connection(kwargs.get(, None)) as connection: kwargs[] = connection tables = self.get_tables(table_name, **kwargs) return len(tables) > 0
check to see if a table is in the db table_name -- string -- the table to check return -- boolean -- True if the table exists, false otherwise
339,679
def tg_min(tas, freq=): r return tas.resample(time=freq).min(dim=, keep_attrs=True)
r"""Lowest mean temperature Minimum of daily mean temperature. Parameters ---------- tas : xarray.DataArray Mean daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Minimum of daily minimum temperature. Notes ...
339,680
def list_l3_agent_hosting_routers(self, router, **_params): return self.get((self.router_path + self.L3_AGENTS) % router, params=_params)
Fetches a list of L3 agents hosting a router.
339,681
def class_factory(name, base_class, class_dict): def __init__(self, tcex): base_class.__init__(self, tcex) for k, v in class_dict.items(): setattr(self, k, v) newclass = type(str(name), (base_class,), {: __init__}) return newclass
Internal method for dynamically building Custom Indicator classes.
339,682
def _WriteFlowResponsesAndExpectedUpdates(self, responses, cursor=None): self._WriteResponses(responses, cursor) query = for r in responses: if isinstance(r, rdf_flow_objects.FlowStatus): args = { "client_id": db_utils.ClientIDToInt(r.client_id), ...
Writes a flow responses and updates flow requests expected counts.
339,683
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]: rv = list() while len(rv) < max_jobs: try: job_json_string = self._get_queue(queue).get(block=False) except Empty: break job = Job.deserialize(job_json_str...
Get jobs from a queue.
339,684
def from_simple_str(cls, s): if not isinstance(s, str): raise TypeError("Expected an str instance, received %r" % (s,)) return cls(cls.bits_from_simple_str(s))
Accepts only the output of to_simple_str(). The output of __str__() is invalid as input.
339,685
def _user_headers(self, headers=None): h = self.copy() if headers is not None: keys = set(headers.keys()) if h.get(, False): keys -= {} for key in keys: h[key] = headers[key] return h
Make sure the user doesn't override the Authorization header
339,686
def get_region(cls, resource=None): if resource: resource_info = cls.parse_remote(resource) if resource_info.region: return resource_info.region return os.environ.get("AWS_DEFAULT_REGION", cls._DEFAULT_REGION)
Retrieve region from standard environmental variables or file name. More information of the following link: http://goo.gl/Vb9Jky
339,687
def named_any(name): assert name, names = name.split() topLevelPackage = None moduleNames = names[:] while not topLevelPackage: if moduleNames: trialname = .join(moduleNames) try: topLevelPackage = __import__(trialname) except Except...
Retrieve a Python object by its fully qualified name from the global Python module namespace. The first part of the name, that describes a module, will be discovered and imported. Each subsequent part of the name is treated as the name of an attribute of the object specified by all of the name which c...
339,688
def generate_default_profile(): data_format = {} for hazard in hazard_all: if exposure_population in hazard[]: continue data_format[hazard[]] = {} for classification in hazard[]: data_format[hazard[]][classification[]] = OrderedDict() for the_clas...
Helper to create data format from default definitions. Example: Flood: - Flood classification A - Flood class 1: affected, displacement_rate - Flood class 2: affected, displacement_rate - Flood classification B - Flood class 1: affecte...
339,689
def get_ticks_from_axis_limits(self, multiple=1): for k in [, , ]: self._ticks[k] = numpy.linspace( self._axis_limits[k][0], self._axis_limits[k][1], self._boundary_scale / float(multiple) + 1 ).tolist()
Taking self._axis_limits and self._boundary_scale get the scaled ticks for all three axes and store them in self._ticks under the keys 'b' for bottom, 'l' for left and 'r' for right axes.
339,690
def p_expression_derefseg(p): size = sizes[p[1]] address = p[6] seg = functions[](p[3]) base, limit, _ = functions[](seg) address = base + address char_list = functions[](address, size) value = Operators.CONCAT(8 * len(char_list), *reversed(map(Operators.ORD, char_list))) p[0] = val...
expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET
339,691
def bind(self, args, kwargs): spec = self._spec resolution = self.resolve(args, kwargs) params = dict(zip(spec.args, resolution.slots)) if spec.varargs: params[spec.varargs] = resolution.varargs if spec.varkw: params[spec.varkw] = resolution.varkw...
Bind arguments and keyword arguments to the encapsulated function. Returns a dictionary of parameters (named according to function parameters) with the values that were bound to each name.
339,692
def add_port_callback(self, port, cb): logger.debug(, port, cb) self.add_header_callback(cb, port, 0, 0xff, 0x0)
Add a callback for data that comes on a specific port
339,693
def translate_summary(data): headers = sorted(data.get("Headers", [])) summary = .replace(, data.get("Title", "table")) summary += n_cols = len(headers) col_str = "l" + "c" * n_cols summary += .replace("$NCOLS", col_str) spacer = * n_cols + r for header in headers: ...
Translates data where data["Type"]=="Summary"
339,694
def joint_positions_for_eef_command(self, dpos, rotation): self.ik_robot_target_pos += dpos * self.user_sensitivity rotation = rotation.dot( T.rotation_matrix(angle=-np.pi / 2, direction=[0., 0., 1.], point=None)[ :3, :3 ...
This function runs inverse kinematics to back out target joint positions from the provided end effector command. Same arguments as @get_control. Returns: A list of size @num_joints corresponding to the target joint angles.
339,695
def check_firmware_present(self, firmware_type, version): if not isinstance(firmware_type, FirmwareType): raise TypeError("firmware_type can only be an instance of type FirmwareType") if not isinstance(version, basestring): raise TypeError("version can only be an instanc...
Check if this VirtualBox installation has a firmware of the given type available, either system-wide or per-user. Optionally, this may return a hint where this firmware can be downloaded from. in firmware_type of type :class:`FirmwareType` Type of firmware to check. ...
339,696
def stop_job(self, job_id, array_id = None): self.lock() job, array_job = self._job_and_array(job_id, array_id) if job is not None: if job.status in (, , ): logger.info("Reset job (%s) in the database", job.name, self._format_log(job.id)) job.status = if array_job is not...
Resets the status of the given to 'submitted' when they are labeled as 'executing'.
339,697
def asVersion(self): return versions.Version(self.package, self.major, self.minor, self.micro)
Convert the version data in this item to a L{twisted.python.versions.Version}.
339,698
def get_celery_info(): import celery if not getattr(settings, , False): log.error("No celery config found. Set USE_CELERY in settings to enable.") return {"status": NO_CONFIG} start = datetime.now() try: app = celery.Celery() app.config_from_object(, namespa...
Check celery availability
339,699
def drawdowns(returns, geometric=True): wealth = 1. + returns_cumulative(returns, geometric=geometric, expanding=True) values = wealth.values if values.ndim == 2: ncols = values.shape[-1] values = np.vstack(([1.] * ncols, values)) maxwealth = pd.expanding_max(values)[1:] ...
compute the drawdown series for the period return series return: periodic return Series or DataFrame