code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_cam_bounds(self): world_pos = self.get_world_pos() screen_res = Ragnarok.get_world().get_backbuffer_size() * .5 return (self.pan.X - screen_res.X), (self.pan.Y - screen_res.Y), (self.pan.X + screen_res.X), ( self.pan.Y + screen_res.Y)
Return the bounds of the camera in x, y, xMax, and yMax format.
def _empty_cache(self, termlist=None): if termlist is None: for term in six.itervalues(self.terms): term._empty_cache() else: for term in termlist: try: self.terms[term.id]._empty_cache() except AttributeError: ...
Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for...
def findExtname(fimg, extname, extver=None): i = 0 extnum = None for chip in fimg: hdr = chip.header if 'EXTNAME' in hdr: if hdr['EXTNAME'].strip() == extname.upper(): if extver is None or hdr['EXTVER'] == extver: extnum = i ...
Returns the list number of the extension corresponding to EXTNAME given.
def set_param(self, key, value): self.__dict__[key] = value self._parameters[key] = value
Set the value of a parameter.
def setLog(self, fileName, writeName=False): self.log = 1 self.logFile = fileName self._logPtr = open(fileName, "w") if writeName: self._namePtr = open(fileName + ".name", "w")
Opens a log file with name fileName.
def paragraphs(self, index = None): if index is None: return self.select(Paragraph) else: if index < 0: index = sum(t.count(Paragraph) for t in self.data) + index for t in self.data: for i,e in enumerate(t.select(Paragraph)) : ...
Return a generator of all paragraphs found in the document. If an index is specified, return the n'th paragraph only (starting at 0)
def add(self, event, pk, ts=None, ttl=None): key = self._keygen(event, ts) try: self._zadd(key, pk, ts, ttl) return True except redis.ConnectionError as e: self.logger.error( "redis event store failed with connection error %r" % e) ...
Add an event to event store. All events were stored in a sorted set in redis with timestamp as rank score. :param event: the event to be added, format should be ``table_action`` :param pk: the primary key of event :param ts: timestamp of the event, default to redis_server's ...
def QA_SU_save_stock_info(engine, client=DATABASE): engine = select_save_engine(engine) engine.QA_SU_save_stock_info(client=client)
save stock info Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
def _get_last_entries(db, qty): doc_ids = [post.doc_id for post in db.posts.all()] doc_ids = sorted(doc_ids, reverse=True) entries = [Entry(os.path.join(CONFIG['content_root'], db.posts.get(doc_id=doc_id)['filename']), doc_id) for doc_id in doc_ids] entries.sort(key=o...
get all entries and the last qty entries
def create(self): self.consul.create_bucket("%s-%s" % (self.stack.name, self.name))
Creates a new bucket
def _declarations_as_string(self, declarations): return ''.join('%s:%s%s;' % ( d.name, d.value.as_css(), ' !' + d.priority if d.priority else '') for d in declarations)
Returns a list of declarations as a formatted CSS string :param declarations: The list of tinycss Declarations to format :type declarations: list of tinycss.css21.Declaration :returns: The CSS string for the declarations list :rtype: str
def send_feature_report(self, data, report_id=0x0): self._check_device_status() bufp = ffi.new("unsigned char[]", len(data)+1) buf = ffi.buffer(bufp, len(data)+1) buf[0] = report_id buf[1:] = data rv = hidapi.hid_send_feature_report(self._device, bufp, len(bufp)) ...
Send a Feature report to the device. Feature reports are sent over the Control endpoint as a Set_Report transfer. :param data: The data to send :type data: str/bytes :param report_id: The Report ID to send to :type report_id: int
def add_prefix(self, name, *args, **kwargs): if os.path.exists(self.join(name)): raise LagoPrefixAlreadyExistsError(name, self.path) self.prefixes[name] = self.prefix_class( self.join(name), *args, **kwargs ) self.prefixes[name].initialize() if self.curren...
Adds a new prefix to the workdir. Args: name(str): Name of the new prefix to add *args: args to pass along to the prefix constructor *kwargs: kwargs to pass along to the prefix constructor Returns: The newly created prefix Raises: La...
def code(item): _res = [] i = 0 for attr in ATTR: val = getattr(item, attr) if val: _res.append("%d=%s" % (i, quote(val))) i += 1 return ",".join(_res)
Turn a NameID class instance into a quoted string of comma separated attribute,value pairs. The attribute names are replaced with digits. Depends on knowledge on the specific order of the attributes for the class that is used. :param item: The class instance :return: A quoted string
def calc_smoothpar_logistic2(metapar): if metapar <= 0.: return 0. return optimize.newton(_error_smoothpar_logistic2, .3 * metapar**.84, _smooth_logistic2_derivative, args=(metapar,))
Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the smoothing parameter value corresponding the meta parameter value 2.5: >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2 >>> smoothpar = calc_smoothpar_logistic2(2.5) ...
def on_click(self, button, **kwargs): if button in (4, 5): return super().on_click(button, **kwargs) else: activemodule = self.get_active_module() if not activemodule: return return activemodule.on_click(button, **kwargs)
Capture scrollup and scorlldown to move in groups Pass everthing else to the module itself
def nonzero(self): return [i for i in xrange(self.size()) if self.test(i)]
Get all non-zero bits
def filter(self, filter_fn): op = Operator( _generate_uuid(), OpType.Filter, "Filter", filter_fn, num_instances=self.env.config.parallelism) return self.__register(op)
Applies a filter to the stream. Attributes: filter_fn (function): The user-defined filter function.
def repeat(self, rid, count, index=0): elems = None if rid in self.__repeat_ids: elems = self.__repeat_ids[rid] elif rid in self.__element_ids: elems = self.__element_ids if elems and index < len(elems): elem = elems[index] self.__repeat(el...
Repeat an xml element marked with the matching rid.
def is_probably_packed( pe ): total_pe_data_length = len( pe.trim() ) if not total_pe_data_length: return True has_significant_amount_of_compressed_data = False total_compressed_data = 0 for section in pe.sections: s_entropy = section.get_entropy() s_length = len( section.get...
Returns True is there is a high likelihood that a file is packed or contains compressed data. The sections of the PE file will be analyzed, if enough sections look like containing compressed data and the data makes up for more than 20% of the total file size, the function will return True.
def is_elaborated(type_): nake_type = remove_alias(type_) if isinstance(nake_type, cpptypes.elaborated_t): return True elif isinstance(nake_type, cpptypes.reference_t): return is_elaborated(nake_type.base) elif isinstance(nake_type, cpptypes.pointer_t): return is_elaborated(nake_...
returns True, if type represents C++ elaborated type, False otherwise
def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity): try: dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name) return False, dynamodb_table except botocore.exceptions.ClientError: dynamodb_table = self.dynamodb_client...
Create the DynamoDB table for async task return values
def on_transmit(self, broker): _vv and IOLOG.debug('%r.on_transmit()', self) if self._output_buf: buf = self._output_buf.popleft() written = self.transmit_side.write(buf) if not written: _v and LOG.debug('%r.on_transmit(): disconnection detected', self...
Transmit buffered messages.
def set_position(self, position): if position < 0: position += len(self.checkdefs) while position >= len(self.checkdefs): self.checkdefs.append(([], [])) self.position = position
Sets the if-statement position.
def compute_output(t0, t1): if t0 is None or t1 is None: return -1.0 else: response = 1.1 - 0.1 * abs(t0 - t1) return max(0.0, min(1.0, response))
Compute the network's output based on the "time to first spike" of the two output neurons.
def _load(self, dataset_spec): for idx, ds in enumerate(dataset_spec): self.append(ds, idx)
Actual loading of datasets
def param_request_list_send(self, target_system, target_component, force_mavlink1=False): return self.send(self.param_request_list_encode(target_system, target_component), force_mavlink1=force_mavlink1)
Request all parameters of this component. After this request, all parameters are emitted. target_system : System ID (uint8_t) target_component : Component ID (uint8_t)
def _set_random_data(self): rdata = self._load_response('random') rdata = rdata['query']['random'][0] pageid = rdata.get('id') title = rdata.get('title') self.data.update({'pageid': pageid, 'title': title})
sets page data from random request
def transform(self): ax = self.ax return {'axes': ax.transAxes, 'fig': ax.get_figure().transFigure, 'data': ax.transData}
Dictionary containing the relevant transformations
def enable_parallel(processnum=None): global pool, dt, cut, cut_for_search from multiprocessing import cpu_count if os.name == 'nt': raise NotImplementedError( "jieba: parallel mode only supports posix system") else: from multiprocessing import Pool dt.check_initialized()...
Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported.
def _ensure_value_is_in_objects(self,val): if not (val in self.objects): self.objects.append(val)
Make sure that the provided value is present on the objects list. Subclasses can override if they support multiple items on a list, to check each item instead.
def operate_multi(self, points): points = np.array(points) affine_points = np.concatenate( [points, np.ones(points.shape[:-1] + (1,))], axis=-1) return np.inner(affine_points, self.affine_matrix)[..., :-1]
Apply the operation on a list of points. Args: points: List of Cartesian coordinates Returns: Numpy array of coordinates after operation
def AddPerformanceOptions(self, argument_group): argument_group.add_argument( '--buffer_size', '--buffer-size', '--bs', dest='buffer_size', action='store', default=0, help=( 'The buffer size for the output (defaults to 196MiB).')) argument_group.add_argument( '--queue_size', ...
Adds the performance options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def check_1d(inp): if isinstance(inp, list): return check_1d(np.array(inp)) if isinstance(inp, np.ndarray): if inp.ndim == 1: return inp
Check input to be a vector. Converts lists to np.ndarray. Parameters ---------- inp : obj Input vector Returns ------- numpy.ndarray or None Input vector or None Examples -------- >>> check_1d([0, 1, 2, 3]) [0, 1, 2, 3] >>> check_1d('test') None
def Convert(self, metadata, config, token=None): result = ExportedDNSClientConfiguration( metadata=metadata, dns_servers=" ".join(config.dns_server), dns_suffixes=" ".join(config.dns_suffix)) yield result
Converts DNSClientConfiguration to ExportedDNSClientConfiguration.
def delete_file(f): fp = f.get_fullpath() log.info("Deleting file %s", fp) os.remove(fp)
Delete the given file :param f: the file to delete :type f: :class:`JB_File` :returns: None :rtype: None :raises: :class:`OSError`
def boundary_cell_fractions(self): frac_list = [] for ax, (cvec, bmin, bmax) in enumerate(zip( self.grid.coord_vectors, self.set.min_pt, self.set.max_pt)): if len(cvec) == 1: frac_list.append((1.0, 1.0)) else: left_frac = 0.5 + (cve...
Return a tuple of contained fractions of boundary cells. Since the outermost grid points can have any distance to the boundary of the partitioned set, the "natural" outermost cell around these points can either be cropped or extended. This property is a tuple of (float, float) tuples, o...
def need_record_permission(factory_name): def need_record_permission_builder(f): @wraps(f) def need_record_permission_decorator(self, record=None, *args, **kwargs): permission_factory = ( getattr(self, factory_name) or ...
Decorator checking that the user has the required permissions on record. :param factory_name: name of the permission factory.
def get_all(self, references, field_paths=None, transaction=None): document_paths, reference_map = _reference_info(references) mask = _get_doc_mask(field_paths) response_iterator = self._firestore_api.batch_get_documents( self._database_string, document_paths, ...
Retrieve a batch of documents. .. note:: Documents returned by this method are not guaranteed to be returned in the same order that they are given in ``references``. .. note:: If multiple ``references`` refer to the same document, the server will only retu...
def load_key(self, key): self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance
def is_distributed(partition_column, lower_bound, upper_bound): if ( (partition_column is not None) and (lower_bound is not None) and (upper_bound is not None) ): if upper_bound > lower_bound: return True else: raise InvalidArguments("upper_bound m...
Check if is possible distribute a query given that args Args: partition_column: column used to share the data between the workers lower_bound: the minimum value to be requested from the partition_column upper_bound: the maximum value to be requested from the partition_column Returns: ...
def color_msg(msg, color): " Return colored message " return ''.join((COLORS.get(color, COLORS['endc']), msg, COLORS['endc']))
Return colored message
def get_archive(self, archive_name, default_version=None): auth, archive_name = self._normalize_archive_name(archive_name) res = self.manager.get_archive(archive_name) if default_version is None: default_version = self._default_versions.get(archive_name, None) if (auth is not...
Retrieve a data archive Parameters ---------- archive_name: str Name of the archive to retrieve default_version: version str or :py:class:`~distutils.StrictVersion` giving the default version number to be used on read operations Returns ...
def build_available_time_string(availabilities): prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, bu...
Build a string eliciting for a possible time slot among at least two availabilities.
def apply_settings(settings): for key, value in settings.items(): ConfigManager.SETTINGS[key] = value
Allows new settings to be added without users having to lose all their configuration
def xpath(self, xpath, dom=None): if dom is None: dom = self.browser return expect(dom.find_by_xpath, args=[xpath])
xpath find function abbreviation
def kcore_bd(CIJ, k, peel=False): if peel: peelorder, peellevel = ([], []) iter = 0 CIJkcore = CIJ.copy() while True: id, od, deg = degrees_dir(CIJkcore) ff, = np.where(np.logical_and(deg < k, deg > 0)) if ff.size == 0: break iter += 1 CIJkcore...
The k-core is the largest subnetwork comprising nodes of degree at least k. This function computes the k-core for a given binary directed connection matrix by recursively peeling off nodes with degree lower than k, until no such nodes remain. Parameters ---------- CIJ : NxN np.ndarray b...
def _domain_event_block_threshold_cb(conn, domain, dev, path, threshold, excess, opaque): _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'dev': dev, 'path': path, 'threshold': threshold, 'excess': excess })
Domain block threshold events handler
def delete_network_postcommit(self, context): network = context.current log_context("delete_network_postcommit: network", network) segments = context.network_segments tenant_id = network['project_id'] self.delete_segments(segments) self.delete_network(network) sel...
Delete the network from CVX
def getCoeff(self, name, light=None, date=None): d = self.coeffs[name] try: c = d[light] except KeyError: try: k, i = next(iter(d.items())) if light is not None: print( 'no calibration fo...
try to get calibration for right light source, but use another if they is none existent
def get_assignable_bin_ids(self, bin_id): mgr = self._get_provider_manager('RESOURCE', local=True) lookup_session = mgr.get_bin_lookup_session(proxy=self._proxy) bins = lookup_session.get_bins() id_list = [] for bin in bins: id_list.append(bin.get_id()) return...
Gets a list of bins including and under the given bin node in which any resource can be assigned. arg: bin_id (osid.id.Id): the ``Id`` of the ``Bin`` return: (osid.id.IdList) - list of assignable bin ``Ids`` raise: NullArgument - ``bin_id`` is ``null`` raise: OperationFailed - unab...
def comment(self, text): url = self._imgur._base_url + "/3/comment" payload = {'image_id': self.id, 'comment': text} resp = self._imgur._send_request(url, params=payload, needs_auth=True, method='POST') return Comment(resp, imgur=self._imgur, has_...
Make a top-level comment to this. :param text: The comment text.
def __remove_trailing_zeros(self, collection): index = len(collection) - 1 while index >= 0 and collection[index] == 0: index -= 1 return collection[:index + 1]
Removes trailing zeroes from indexable collection of numbers
def button_pressed(self, key_code, prefix=None): if prefix is not None: state = self.buttons_by_code.get(prefix + str(key_code)) else: state = self.buttons_by_code.get(key_code) if state is not None: for handler in state.button_handlers: handle...
Called from the controller classes to update the state of this button manager when a button is pressed. :internal: :param key_code: The code specified when populating Button instances :param prefix: Applied to key code if present
def event_html_page_context(app, pagename, templatename, context, doctree): assert app or pagename or templatename if 'script_files' in context and doctree and any(hasattr(n, 'disqus_shortname') for n in doctree.traverse()): context['script_files'] = context['script_files'][:] + ['_static/disqus.js']
Called when the HTML builder has created a context dictionary to render a template with. Conditionally adding disqus.js to <head /> if the directive is used in a page. :param sphinx.application.Sphinx app: Sphinx application object. :param str pagename: Name of the page being rendered (without .html or an...
def unregisterHandler(self, fh): try: self.fds.remove(fh) except KeyError: pass self.lock.acquire() try: self.data.rollover() finally: self.lock.release() if self.closing and not self.fds: self.data.close()
Unregister a file descriptor. Clean data, if such operation has been scheduled. Parameters ---------- fh : int File descriptor.
def getValidReff(self, urn, inventory=None, level=None): return self.call({ "inv": inventory, "urn": urn, "level": level, "request": "GetValidReff" })
Retrieve valid urn-references for a text :param urn: URN identifying the text :type urn: text :param inventory: Name of the inventory :type inventory: text :param level: Depth of references expected :type level: int :return: XML Response from the API as string ...
def validate(self, _portfolio, account, algo_datetime, _algo_current_data): if (algo_datetime > self.deadline and account.leverage < self.min_leverage): self.fail()
Make validation checks if we are after the deadline. Fail if the leverage is less than the min leverage.
def remove(self, path): entry = self.find(path) if not entry: raise ValueError("%s does not exists" % path) if entry.type == 'root storage': raise ValueError("can no remove root entry") if entry.type == "storage" and not entry.child_id is None: raise V...
Removes both streams and storage DirEntry types from file. storage type entries need to be empty dirs.
def size(self, type=None, failed=False): return len(self.nodes(type=type, failed=failed))
How many nodes in a network. type specifies the class of node, failed can be True/False/all.
def undefine(self): if lib.EnvUndefrule(self._env, self._rule) != 1: raise CLIPSError(self._env) self._env = None
Undefine the Rule. Python equivalent of the CLIPS undefrule command. The object becomes unusable after this method has been called.
def with_translations(self, **kwargs): force = kwargs.pop("force", False) if self._prefetch_translations_done and force is False: return self self._prefetched_translations_cache = utils.get_grouped_translations( self, **kwargs ) self._prefetch_translations...
Prefetches translations. Takes three optional keyword arguments: * ``field_names``: ``field_name`` values for SELECT IN * ``languages``: ``language`` values for SELECT IN * ``chunks_length``: fetches IDs by chunk
def _format_volume_string(self, volume_string): return '[' + volume_string[volume_string.find(self.volume_string):].replace(' %','%').replace('ume', '')+'] '
format mplayer's volume
def get_object_key(self, key, using_name=True): try: if using_name: return self.o_name[key].key else: return self.o[key].key except KeyError: raise ValueError("'%s' are not found!" % key)
Given a object key or name, return it's object key.
def authenticate_peer(self, auth_data, peer_id, message): logger.debug('message: {}'.format(dump(message))) signed_octets = message + self.Ni + prf(self.SK_pr, peer_id._data) auth_type = const.AuthenticationType(struct.unpack(const.AUTH_HEADER, auth_data[:4])[0]) assert auth_type == cons...
Verifies the peers authentication.
def create(self, service_name, json, **kwargs): return self._send(requests.post, service_name, json, **kwargs)
Create a new AppNexus object
def user_fields(self, user): return self._query_zendesk(self.endpoint.user_fields, 'user_field', id=user)
Retrieve the user fields for this user. :param user: User object or id
def __get_labels(self): labels = [] try: with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'r') as file_desc: for line in file_desc.readlines(): line = line.strip() (label_name, label_color) = l...
Read the label file of the documents and extract all the labels Returns: An array of labels.Label objects
def is_transition_metal(self): ns = list(range(21, 31)) ns.extend(list(range(39, 49))) ns.append(57) ns.extend(list(range(72, 81))) ns.append(89) ns.extend(list(range(104, 113))) return self.Z in ns
True if element is a transition metal.
def global_lppooling(attrs, inputs, proto_obj): p_value = attrs.get('p', 2) new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), 'pool_typ...
Performs global lp pooling on the input.
def show_wait_cursor(object): @functools.wraps(object) def show_wait_cursorWrapper(*args, **kwargs): QApplication.setOverrideCursor(Qt.WaitCursor) value = None try: value = object(*args, **kwargs) finally: QApplication.restoreOverrideCursor() r...
Shows a wait cursor while processing. :param object: Object to decorate. :type object: object :return: Object. :rtype: object
def extract_along_line(self, pid, xy0, xy1, N=10): assert N >= 2 xy0 = np.array(xy0).squeeze() xy1 = np.array(xy1).squeeze() assert xy0.size == 2 assert xy1.size == 2 points = [(x, y) for x, y in zip( np.linspace(xy0[0], xy1[0], N), np.linspace(xy0[1], xy1[1],...
Extract parameter values along a given line. Parameters ---------- pid: int The parameter id to extract values from xy0: tuple A tupe with (x,y) start point coordinates xy1: tuple A tupe with (x,y) end point coordinates N: integer, opt...
def encode_coin_link(copper, silver=0, gold=0): return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
Encode a chat link for an amount of coins.
def get_tx(tx_id, api_code=None): resource = 'rawtx/' + tx_id if api_code is not None: resource += '?api_code=' + api_code response = util.call_api(resource) json_response = json.loads(response) return Transaction(json_response)
Get a single transaction based on a transaction hash. :param str tx_id: transaction hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Transaction` class
def _inject_dist(distname, kwargs={}, ns=locals()): dist_logp, dist_random, grad_logp = name_to_funcs(distname, ns) classname = capitalize(distname) ns[classname] = stochastic_from_dist(distname, dist_logp, dist_random, grad_l...
Reusable function to inject Stochastic subclasses into module namespace
def cores(self): for (x, y), chip_info in iteritems(self): for p, state in enumerate(chip_info.core_states): yield (x, y, p, state)
Generate the set of all cores in the system. Yields ------ (x, y, p, :py:class:`~rig.machine_control.consts.AppState`) A core in the machine, and its state. Cores related to a specific chip are yielded consecutively in ascending order of core number.
def get_comments_of_invoice_per_page(self, invoice_id, per_page=1000, page=1): return self._get_resource_per_page( resource=INVOICE_COMMENTS, per_page=per_page, page=page, params={'invoice_id': invoice_id}, )
Get comments of invoice per page :param invoice_id: the invoice id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def _repr__base(self, rich_output=False): repr_dict = collections.OrderedDict() key = '%s (point source)' % self.name repr_dict[key] = collections.OrderedDict() repr_dict[key]['position'] = self._sky_position.to_dict(minimal=True) repr_dict[key]['spectrum'] = collections.OrderedD...
Representation of the object :param rich_output: if True, generates HTML, otherwise text :return: the representation
def split_taf(txt: str) -> [str]: lines = [] split = txt.split() last_index = 0 for i, item in enumerate(split): if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'): lines.append(' '.join(split[last_index:i])) last_index = i lines.append(' '.jo...
Splits a TAF report into each distinct time period
def triangles(self): triangles = collections.deque() triangles_node = collections.deque() for node_name in self.graph.nodes_geometry: transform, geometry_name = self.graph[node_name] geometry = self.geometry[geometry_name] if not hasattr(geometry, 'triangles')...
Return a correctly transformed polygon soup of the current scene. Returns ---------- triangles: (n,3,3) float, triangles in space
def create_dir(self, jbfile): try: jbfile.create_directory() except os.error: self.statusbar.showMessage('Could not create path: %s' % jbfile.get_path())
Create a dir for the given dirfile and display an error message, if it fails. :param jbfile: the jb file to make the directory for :type jbfile: class:`JB_File` :returns: None :rtype: None :raises: None
def list_(self): with self.lock: self.send('LIST') list_ = {} while self.readable(): msg = self._recv(expected_replies=('322', '321', '323')) if msg[0] == '322': channel, usercount, modes, topic = msg[2].split(' ', 3) ...
Gets a list of channels on the server.
def parse_template(self): self.templ_dict = {'actions': {'definition': {}}} self.templ_dict['name'] = self._get_template_name() self._add_cli_scripts() self._add_sections() self._add_attrs() return self.templ_dict
Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template
def _begin_request(self): headers = self.m2req.headers self._request = HTTPRequest(connection=self, method=headers.get("METHOD"), uri=self.m2req.path, version=headers.get("VERSION"), headers=headers, remote_ip=headers.get("x-forwarded-for")) ...
Actually start executing this request.
def _publish_replset(self, data, base_prefix): prefix = base_prefix + ['replset'] self._publish_dict_with_prefix(data, prefix) total_nodes = len(data['members']) healthy_nodes = reduce(lambda value, node: value + node['health'], data['members'], 0) ...
Given a response to replSetGetStatus, publishes all numeric values of the instance, aggregate stats of healthy nodes vs total nodes, and the observed statuses of all nodes in the replica set.
def branch_out(self, limb=None): if not limb: limbs = self._cfg.sections() else: limb = limb if isinstance(limb, list) else [limb] limbs = ['general'] limbs.extend(limb) for leaf in limbs: leaf = leaf if leaf in self._cfg.sections() els...
Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into the os environment. Parameters: limb (str/list): The ...
def build_sample_ace_problem_breiman85(N=200): x_cubed = numpy.random.standard_normal(N) x = scipy.special.cbrt(x_cubed) noise = numpy.random.standard_normal(N) y = numpy.exp((x ** 3.0) + noise) return [x], y
Sample problem from Breiman 1985.
def read_command(self): reader = self.reader line = yield from reader.readline() if line == b'': raise ConnectionResetError() try: codeobj = self.attempt_compile(line.rstrip(b'\n')) except SyntaxError: yield from self.send_exception() ...
Read a command from the user line by line. Returns a code object suitable for execution.
def _create_in_progress(self): instance = self.service.service.get_instance(self.service.name) if (instance['last_operation']['state'] == 'in progress' and instance['last_operation']['type'] == 'create'): return True return False
Creating this service is handled asynchronously so this method will simply check if the create is in progress. If it is not in progress, we could probably infer it either failed or succeeded.
def filter_pipeline(effects, filters): for filter_fn in filters: filtered_effects = filter_fn(effects) if len(effects) == 1: return effects elif len(filtered_effects) > 1: effects = filtered_effects return effects
Apply each filter to the effect list sequentially. If any filter returns zero values then ignore it. As soon as only one effect is left, return it. Parameters ---------- effects : list of MutationEffect subclass instances filters : list of functions Each function takes a list of effect...
def _build_gan_trainer(self, input, model): self.tower_func = TowerFuncWrapper(model.build_graph, model.get_input_signature()) with TowerContext('', is_training=True): self.tower_func(*input.get_input_tensors()) opt = model.get_optimizer() with tf.name_scope('optimize'): ...
We need to set tower_func because it's a TowerTrainer, and only TowerTrainer supports automatic graph creation for inference during training. If we don't care about inference during training, using tower_func is not needed. Just calling model.build_graph directly is OK.
def pretty_xml(string_input, add_ns=False): if add_ns: elem = "<foo " for key, value in DOC_CONTENT_ATTRIB.items(): elem += ' %s="%s"' % (key, value) string_input = elem + ">" + string_input + "</foo>" doc = minidom.parseString(string_input) if add_ns: s1 = doc.ch...
pretty indent string_input
def runSearchRnaQuantifications(self, request): return self.runSearchRequest( request, protocol.SearchRnaQuantificationsRequest, protocol.SearchRnaQuantificationsResponse, self.rnaQuantificationsGenerator)
Returns a SearchRnaQuantificationResponse for the specified SearchRnaQuantificationRequest object.
def resample_singlechan(x, ann, fs, fs_target): resampled_x, resampled_t = resample_sig(x, fs, fs_target) new_sample = resample_ann(resampled_t, ann.sample) assert ann.sample.shape == new_sample.shape resampled_ann = Annotation(record_name=ann.record_name, extension=ann.ex...
Resample a single-channel signal with its annotations Parameters ---------- x: numpy array The signal array ann : wfdb Annotation The wfdb annotation object fs : int, or float The original frequency fs_target : int, or float The target frequency Returns ...
def list_users(self, envs=[], query="/users/"): juicer.utils.Log.log_debug( "List Users In: %s", ", ".join(envs)) for env in envs: juicer.utils.Log.log_info("%s:" % (env)) _r = self.connectors[env].get(query) if _r.status_code == Constants.PULP_GET_OK:...
List users in specified environments
def clear_cache(): fsb_cachedir = os.path.join(__opts__['cachedir'], 'svnfs') list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/svnfs') errors = [] for rdir in (fsb_cachedir, list_cachedir): if os.path.exists(rdir): try: shutil.rmtree(rdir) ex...
Completely clear svnfs cache
def export(self): data = {} for key, value in self.items(): data[key] = value return data
Exports as dictionary
def function_end(self): self.newline_label(self.shared.function_name + "_exit", True, True) self.move("%14", "%15") self.pop("%14") self.newline_text("RET", True)
Inserts an exit label and function return instructions
def populate_jobset(job, jobset, depth): jobset.add(job) if len(job.dependencies) == 0: return jobset for j in job.dependencies: jobset = populate_jobset(j, jobset, depth+1) return jobset
Creates a set of jobs, containing jobs at difference depths of the dependency tree, retaining dependencies as strings, not Jobs.
async def _pinger(self): async def _do_ping(): try: await pinger_facade.Ping() await asyncio.sleep(10, loop=self.loop) except CancelledError: pass pinger_facade = client.PingerFacade.from_connection(self) try: wh...
A Controller can time us out if we are silent for too long. This is especially true in JaaS, which has a fairly strict timeout. To prevent timing out, we send a ping every ten seconds.