code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_sym_eq_kpoints(self, kpoint, cartesian=False, tol=1e-2): if not self.structure: return None sg = SpacegroupAnalyzer(self.structure) symmops = sg.get_point_group_operations(cartesian=cartesian) points = np.dot(kpoint, [m.rotation_matrix for m in symmops]) rm_li...
Returns a list of unique symmetrically equivalent k-points. Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in cartesian or fractional coordinates tol (float): tolerance below which coordinates are considered equal Returns: ...
def CreateBlockDeviceMap(self, image_id, instance_type): image = self.ec2.get_image(image_id) block_device_map = image.block_device_mapping assert(block_device_map) ephemeral_device_names = ['/dev/sdb', '/dev/sdc', '/dev/sdd', '/dev/sde'] for i, device_name in enumerate(ephemeral_device_na...
If you launch without specifying a manual device block mapping, you may not get all the ephemeral devices available to the given instance type. This will build one that ensures all available ephemeral devices are mapped.
def _configure_ebs_volume(self, vol_type, name, size, delete_on_termination): root_dev = boto.ec2.blockdevicemapping.BlockDeviceType() root_dev.delete_on_termination = delete_on_termination root_dev.volume_type = vol_type if size != 'default': root_dev.size = size bdm...
Sets the desired root EBS size, otherwise the default EC2 value is used. :param vol_type: Type of EBS storage - gp2 (SSD), io1 or standard (magnetic) :type vol_type: str :param size: Desired root EBS size. :type size: int :param delete_on_termination: Toggle this flag to delete ...
def to_dict(self): session = self._get_session() snapshot = self._get_snapshot() return { "session_id": session._session_id, "transaction_id": snapshot._transaction_id, }
Return state as a dictionary. Result can be used to serialize the instance and reconstitute it later using :meth:`from_dict`. :rtype: dict
def getopt(self, p, default=None): for k, v in self.pairs: if k == p: return v return default
Returns the first option value stored that matches p or default.
def _fetch_dataframe(self): def reshape(training_summary): out = {} for k, v in training_summary['TunedHyperParameters'].items(): try: v = float(v) except (TypeError, ValueError): pass out[k] = v ...
Return a pandas dataframe with all the training jobs, along with their hyperparameters, results, and metadata. This also includes a column to indicate if a training job was the best seen so far.
def export_modifications(self): if self.__modified_data__ is not None: return self.export_data() result = {} for key, value in enumerate(self.__original_data__): try: if not value.is_modified(): continue modifications = ...
Returns list modifications.
def pop_fw_local(self, tenant_id, net_id, direc, node_ip): net = self.get_network(net_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.update_fw_local_cache(net_id, direc, node_ip) if net is not None: net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan, ...
Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache.
def set_pragmas(self, pragmas): self.pragmas = pragmas c = self.conn.cursor() c.executescript( ';\n'.join( ['PRAGMA %s=%s' % i for i in self.pragmas.items()] ) ) self.conn.commit()
Set pragmas for the current database connection. Parameters ---------- pragmas : dict Dictionary of pragmas; see constants.default_pragmas for a template and http://www.sqlite.org/pragma.html for a full list.
def _admin_metadata_from_uri(uri, config_path): uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) admin_metadata = storage_broker.get_admin_metadata() return admin_metadata
Helper function for getting admin metadata.
def declare_local_operator(self, type, raw_model=None): onnx_name = self.get_unique_operator_name(str(type)) operator = Operator(onnx_name, self.name, type, raw_model, self.target_opset) self.operators[onnx_name] = operator return operator
This function is used to declare new local operator.
def sort(self, columnId, order=Qt.AscendingOrder): self.layoutAboutToBeChanged.emit() self.sortingAboutToStart.emit() column = self._dataFrame.columns[columnId] self._dataFrame.sort_values(column, ascending=not bool(order), inplace=True) self.layoutChanged.emit() self.sor...
Sorts the model column After sorting the data in ascending or descending order, a signal `layoutChanged` is emitted. :param: columnId (int) the index of the column to sort on. :param: order (Qt::SortOrder, optional) descending(1) or ascending(0). defaults to Qt....
def metadata(dataset, node, entityids, extended=False, api_key=None): api_key = _get_api_key(api_key) url = '{}/metadata'.format(USGS_API) payload = { "jsonRequest": payloads.metadata(dataset, node, entityids, api_key=api_key) } r = requests.post(url, payload) response = r.json() _ch...
Request metadata for a given scene in a USGS dataset. :param dataset: :param node: :param entityids: :param extended: Send a second request to the metadata url to get extended metadata on the scene. :param api_key:
def get_project(username, project, machine_name=None): try: account = Account.objects.get( username=username, date_deleted__isnull=True) except Account.DoesNotExist: return "Account '%s' not found" % username if project is None: project = account.default_proje...
Used in the submit filter to make sure user is in project
def _update_indexes_for_deleted_object(collection, obj): for index in _db[collection].indexes.values(): _remove_from_index(index, obj)
If an object is deleted, it should no longer be indexed so this removes the object from all indexes on the given collection.
def get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool] = None, ) -> Optional[BaseEntity]: try: nodes, degrees = zip(*( (node, degree) for node, degree in sorted(graph.degree(), key=itemget...
Choose a node from the graph with probabilities based on their degrees. :type graph: networkx.Graph :param node_blacklist: Nodes to filter out :param invert_degrees: Should the degrees be inverted? Defaults to true.
def body_as_str(self, encoding='UTF-8'): data = self.body try: return "".join(b.decode(encoding) for b in data) except TypeError: return six.text_type(data) except: pass try: return data.decode(encoding) except Exception as ...
The body of the event data as a string if the data is of a compatible type. :param encoding: The encoding to use for decoding message data. Default is 'UTF-8' :rtype: str or unicode
def _restore_volume(self, fade): self.device.mute = self.mute if self.volume == 100: fixed_vol = self.device.renderingControl.GetOutputFixed( [('InstanceID', 0)])['CurrentFixed'] else: fixed_vol = False if not fixed_vol: self.device.bas...
Reinstate volume. Args: fade (bool): Whether volume should be faded up on restore.
def _ensure_extra_rows(self, term, N): attrs = self.graph.node[term] attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
Ensure that we're going to compute at least N extra rows of `term`.
def ingest(self, **kwargs): __name__ = '%s.ingest' % self.__class__.__name__ schema_dict = self.schema path_to_root = '.' valid_data = self._ingest_dict(kwargs, schema_dict, path_to_root) return valid_data
a core method to ingest and validate arbitrary keyword data **NOTE: data is always returned with this method** for each key in the model, a value is returned according to the following priority: 1. value in kwargs if field passes validation test 2....
def copy_neg(self): result = mpfr.Mpfr_t.__new__(BigFloat) mpfr.mpfr_init2(result, self.precision) new_sign = not self._sign() mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN) return result
Return a copy of self with the opposite sign bit. Unlike -self, this does not make use of the context: the result has the same precision as the original.
def get_property_value_for_brok(self, prop, tab): entry = tab[prop] value = getattr(self, prop, entry.default) pre_op = entry.brok_transformation if pre_op is not None: value = pre_op(self, value) return value
Get the property of an object and brok_transformation if needed and return the value :param prop: property name :type prop: str :param tab: object with all properties of an object :type tab: object :return: value of the property original or brok converted :rtype: str
def _init_dict(self, data, index=None, dtype=None): if data: keys, values = zip(*data.items()) values = list(values) elif index is not None: values = na_value_for_dtype(dtype) keys = index else: keys, values = [], [] s = Series(...
Derive the "_data" and "index" attributes of a new Series from a dictionary input. Parameters ---------- data : dict or dict-like Data used to populate the new Series index : Index or index-like, default None index for the new Series: if None, use dict ke...
def recall_score(y_true, y_pred, average='micro', suffix=False): true_entities = set(get_entities(y_true, suffix)) pred_entities = set(get_entities(y_pred, suffix)) nb_correct = len(true_entities & pred_entities) nb_true = len(true_entities) score = nb_correct / nb_true if nb_true > 0 else 0 ret...
Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. Args: ...
def _get_record(self, record_type): if not self.has_record_type(record_type): raise errors.Unsupported() if str(record_type) not in self._records: raise errors.Unimplemented() return self._records[str(record_type)]
Get the record string type value given the record_type.
def _is_string(thing): if _util._py3k: return isinstance(thing, str) else: return isinstance(thing, basestring)
Python character arrays are a mess. If Python2, check if **thing** is an :obj:`unicode` or a :obj:`str`. If Python3, check if **thing** is a :obj:`str`. :param thing: The thing to check. :returns: ``True`` if **thing** is a string according to whichever version of Python we're running in...
def read_index(self): if not isinstance(self.tree, dict): self.tree = dict() self.tree.clear() for path, metadata in self.read_index_iter(): self.tree[path] = metadata
Reads the index and populates the directory tree
def depth_february_average_ground_temperature(self, value=None): if value is not None: try: value = float(value) except ValueError: raise ValueError( 'value {} need to be of type float ' 'for field `depth_february_av...
Corresponds to IDD Field `depth_february_average_ground_temperature` Args: value (float): value for IDD Field `depth_february_average_ground_temperature` Unit: C if `value` is None it will not be checked against the specification and is assumed to be ...
def _repair_row(self): check_for_title = True for row_index in range(self.start[0], self.end[0]): table_row = self.table[row_index] row_start = table_row[self.start[1]] if check_for_title and is_empty_cell(row_start): self._stringify_row(row_index) ...
Searches for missing titles that can be inferred from the surrounding data and automatically repairs those titles.
def _log_msg(self, msg, ok): if self._config['color']: CGREEN, CRED, CEND = '\033[92m', '\033[91m', '\033[0m' else: CGREEN = CRED = CEND = '' LOG_LEVELS = {False: logging.ERROR, True: logging.INFO} L.log(LOG_LEVELS[ok], '%35s %s' + CEND, msg, CGREEN ...
Helper to log message to the right level
def update_url(self, url=None): if not url: raise ValueError("Neither a url or regex was provided to update_url.") post_url = "%s%s" % (self.BASE_URL, url) r = self.session.post(post_url) return int(r.status_code) < 500
Accepts a fully-qualified url. Returns True if successful, False if not successful.
def get_gpu_memory_usage(ctx: List[mx.context.Context]) -> Dict[int, Tuple[int, int]]: if isinstance(ctx, mx.context.Context): ctx = [ctx] ctx = [c for c in ctx if c.device_type == 'gpu'] if not ctx: return {} if shutil.which("nvidia-smi") is None: logger.warning("Couldn't find n...
Returns used and total memory for GPUs identified by the given context list. :param ctx: List of MXNet context devices. :return: Dictionary of device id mapping to a tuple of (memory used, memory total).
def save(self, filename): filename = pathlib.Path(filename) out = [] keys = sorted(list(self.keys())) for key in keys: out.append("[{}]".format(key)) section = self[key] ikeys = list(section.keys()) ikeys.sort() for ikey in ikey...
Save the configuration to a file
def zcr(data): data = np.mean(data, axis=1) count = len(data) countZ = np.sum(np.abs(np.diff(np.sign(data)))) / 2 return (np.float64(countZ) / np.float64(count - 1.0))
Computes zero crossing rate of segment
def adjust_attributes_on_object(self, collection, name, things, values, how): url = self._build_url("%s/%s" % (collection, name)) response = self._get(url) logger.debug("before modification: %s", response.content) build_json = response.json() how(build_json['metadata'], things, v...
adjust labels or annotations on object labels have to match RE: (([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])? and have at most 63 chars :param collection: str, object collection e.g. 'builds' :param name: str, name of object :param things: str, 'labels' or 'annotations' :...
def get_pixel_thresholds_from_calibration_array(gdacs, calibration_gdacs, threshold_calibration_array, bounds_error=True): if len(calibration_gdacs) != threshold_calibration_array.shape[2]: raise ValueError('Length of the provided pixel GDACs does not match the third dimension of the calibration array') ...
Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given. Parameters ---------- gdacs : array like The GDAC settings where the threshold should be determined from the calibr...
def store(self, addr, length=1, non_temporal=False): if non_temporal: raise ValueError("non_temporal stores are not yet supported") if addr is None: return elif not isinstance(addr, Iterable): self.first_level.store(addr, length=length) else: ...
Store one or more adresses. :param addr: byte address of store location :param length: All address from addr until addr+length (exclusive) are stored (default: 1) :param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed
def singleton(cls): import inspect instances = {} if cls.__init__ is not object.__init__: argspec = inspect.getfullargspec(cls.__init__) if len(argspec.args) != 1 or argspec.varargs or argspec.varkw: raise TypeError("Singleton classes cannot accept arguments to the constructor.")...
Decorator function that turns a class into a singleton.
def _plan_on_valid_line(self, at_line, final_line_count): if at_line == 1 or at_line == final_line_count: return True after_version = ( self._lines_seen["version"] and self._lines_seen["version"][0] == 1 and at_line == 2 ) if after_version:...
Check if a plan is on a valid line.
def all(self, customer_id, data={}, **kwargs): url = "{}/{}/tokens".format(self.base_url, customer_id) return self.get_url(url, data, **kwargs)
Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id
def fit(self, p, x, y): self.regression_model.fit(p, y) ml_pred = self.regression_model.predict(p) print('Finished learning regression model') self.krige.fit(x=x, y=y - ml_pred) print('Finished kriging residuals')
fit the regression method and also Krige the residual Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array correspo...
def proxy_model(self): if self.category != Category.MODEL: raise IllegalArgumentError("Part {} is not a model, therefore it cannot have a proxy model".format(self)) if 'proxy' in self._json_data and self._json_data.get('proxy'): catalog_model_id = self._json_data['proxy'].get('id...
Retrieve the proxy model of this proxied `Part` as a `Part`. Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy. :return: :class:`Part` with category `MODEL` and from whi...
def kalman_filter(points, noise): kalman = ikalman.filter(noise) for point in points: kalman.update_velocity2d(point.lat, point.lon, point.dt) (lat, lon) = kalman.get_lat_long() point.lat = lat point.lon = lon return points
Smooths points with kalman filter See https://github.com/open-city/ikalman Args: points (:obj:`list` of :obj:`Point`): points to smooth noise (float): expected noise
def sample_stats_prior_to_xarray(self): data = self.sample_stats_prior if not isinstance(data, dict): raise TypeError("DictConverter.sample_stats_prior is not a dictionary") return dict_to_dataset(data, library=None, coords=self.coords, dims=self.dims)
Convert sample_stats_prior samples to xarray.
def expand_short_options(self, argv): new_argv = [] for arg in argv: result = self.parse_multi_short_option(arg) new_argv.extend(result) return new_argv
Convert grouped short options like `-abc` to `-a, -b, -c`. This is necessary because we set ``allow_abbrev=False`` on the ``ArgumentParser`` in :prop:`self.arg_parser`. The argparse docs say ``allow_abbrev`` applies only to long options, but it also affects whether short options grouped...
def add_commands(self): self.parser.add_argument( '-d', action="count", **self.config.default.debug.get_arg_parse_arguments())
You can override this method in order to add your command line arguments to the argparse parser. The configuration file was reloaded at this time.
def set_state_options(self, left_add_options=None, left_remove_options=None, right_add_options=None, right_remove_options=None): s_right = self.project.factory.full_init_state( add_options=right_add_options, remove_options=right_remove_options, args=[], ) s_left = self.pr...
Checks that the specified state options result in the same states over the next `depth` states.
def key(self, frame): "Return the sort key for the given frame." def keytuple(primary): if frame.frameno is None: return (primary, 1) return (primary, 0, frame.frameno) if type(frame) in self.frame_keys: return keytuple(self.frame_keys[type(fra...
Return the sort key for the given frame.
def _validate_flushed(self) -> None: journal_diff = self._journal_storage.diff() if len(journal_diff) > 0: raise ValidationError( "StorageDB had a dirty journal when it needed to be clean: %r" % journal_diff )
Will raise an exception if there are some changes made since the last persist.
def get_covariance_table(self, chain=0, parameters=None, caption="Parameter Covariance", label="tab:parameter_covariance"): parameters, cov = self.get_covariance(chain=chain, parameters=parameters) return self._get_2d_latex_table(parameters, cov, caption, label)
Gets a LaTeX table of parameter covariance. Parameters ---------- chain : int|str, optional The chain index or name. Defaults to first chain. parameters : list[str], optional The list of parameters to compute correlations. Defaults to all parameters f...
def combine(self, other, name=None): return PhaseGroup( setup=self.setup + other.setup, main=self.main + other.main, teardown=self.teardown + other.teardown, name=name)
Combine with another PhaseGroup and return the result.
def reboot(self): token = self.get_token() self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PRIVATE, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE) url_suffix = "reboot?btoken={}".format(token) self.bbox_url.set_api_name(BboxConstant.API_DEVICE, url_suffix) api = BboxApiCa...
Reboot the device Useful when trying to get xDSL sync
def get_temp_export_dir(timestamped_export_dir): (dirname, basename) = os.path.split(timestamped_export_dir) temp_export_dir = os.path.join( tf.compat.as_bytes(dirname), tf.compat.as_bytes("temp-{}".format(basename))) return temp_export_dir
Builds a directory name based on the argument but starting with 'temp-'. This relies on the fact that TensorFlow Serving ignores subdirectories of the base directory that can't be parsed as integers. Args: timestamped_export_dir: the name of the eventual export directory, e.g. /foo/bar/<timestamp> ...
def setup(app): app.add_config_value('sphinxmark_enable', False, 'html') app.add_config_value('sphinxmark_div', 'default', 'html') app.add_config_value('sphinxmark_border', None, 'html') app.add_config_value('sphinxmark_repeat', True, 'html') app.add_config_value('sphinxmark_fixed', False, 'html') ...
Configure setup for Sphinx extension. :param app: Sphinx application context.
def _table_union(left, right, distinct=False): op = ops.Union(left, right, distinct=distinct) return op.to_expr()
Form the table set union of two table expressions having identical schemas. Parameters ---------- right : TableExpr distinct : boolean, default False Only union distinct rows not occurring in the calling table (this can be very expensive, be careful) Returns ------- uni...
def publish_message(self, message, expire=None): if expire is None: expire = self._expire if not isinstance(message, RedisMessage): raise ValueError('message object is not of type RedisMessage') for channel in self._publishers: self._connection.publish(channel...
Publish a ``message`` on the subscribed channel on the Redis datastore. ``expire`` sets the time in seconds, on how long the message shall additionally of being published, also be persisted in the Redis datastore. If unset, it defaults to the configuration settings ``WS4REDIS_EXPIRE``.
def fetch(opts): resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = ALL reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name)) if opts.verbose: backend.VERBOSE = True _fetch(resources, opts.resource_names, opts.mirror...
Create a local mirror of one or more resources.
def can_claim_fifty_moves(self) -> bool: if self.halfmove_clock >= 100: if any(self.generate_legal_moves()): return True return False
Draw by the fifty-move rule can be claimed once the clock of halfmoves since the last capture or pawn move becomes equal or greater to 100 and the side to move still has a legal move they can make.
def String(length=None, **kwargs): return Property( length=length, types=stringy_types, convert=to_string, **kwargs )
A string valued property with max. `length`.
def key(state, host, key=None, keyserver=None, keyid=None): if key: if urlparse(key).scheme: yield 'wget -O- {0} | apt-key add -'.format(key) else: yield 'apt-key add {0}'.format(key) if keyserver and keyid: yield 'apt-key adv --keyserver {0} --recv-keys {1}'.form...
Add apt gpg keys with ``apt-key``. + key: filename or URL + keyserver: URL of keyserver to fetch key from + keyid: key identifier when using keyserver Note: Always returns an add command, not state checking. keyserver/id: These must be provided together.
def _call_variants(example_dir, region_bed, data, out_file): tf_out_file = "%s-tfrecord.gz" % utils.splitext_plus(out_file)[0] if not utils.file_exists(tf_out_file): with file_transaction(data, tf_out_file) as tx_out_file: model = "wes" if strelka2.coverage_interval_from_bed(region_bed) == "...
Call variants from prepared pileup examples, creating tensorflow record file.
def peak_generation(self, mode): if mode == 'MV': return sum([_.capacity for _ in self.grid.generators()]) elif mode == 'MVLV': cum_mv_peak_generation = sum([_.capacity for _ in self.grid.generators()]) cum_lv_peak_generation = 0 for load_area in self.grid...
Calculates cumulative peak generation of generators connected to underlying grids This is done instantaneously using bottom-up approach. Parameters ---------- mode: str determines which generators are included:: 'MV': Only generation capacities of MV ...
def _untrack_tendril(self, tendril): try: del self.tendrils[tendril._tendril_key] except KeyError: pass try: del self._tendrils[tendril.proto][tendril._tendril_key] except KeyError: pass
Removes the tendril from the set of tracked tendrils.
def _get_predicton_csv_lines(data, headers, images): if images: data = copy.deepcopy(data) for img_col in images: for d, im in zip(data, images[img_col]): if im == '': continue im = im.copy() im.thumbnail((299, 299), Image.ANTIALIAS) buf = BytesIO() im.s...
Create CSV lines from list-of-dict data.
def decide(self, package): if self._backtracking: self._attempted_solutions += 1 self._backtracking = False self._decisions[package.name] = package self._assign( Assignment.decision(package, self.decision_level, len(self._assignments)) )
Adds an assignment of package as a decision and increments the decision level.
def _set_schedules(self): self.schedules = ['ReturnHeader990x', ] self.otherforms = [] for sked in self.raw_irs_dict['Return']['ReturnData'].keys(): if not sked.startswith("@"): if sked in KNOWN_SCHEDULES: self.schedules.append(sked) ...
Attach the known and unknown schedules
def chi_squareds(self, p=None): if len(self._set_xdata)==0 or len(self._set_ydata)==0: return None if p is None: p = self.results[0] rs = self.studentized_residuals(p) if rs == None: return None cs = [] for r in rs: cs.append(sum(r**2)) return cs
Returns a list of chi squared for each data set. Also uses ydata_massaged. p=None means use the fit results
def AddXrefFrom(self, ref_kind, classobj, methodobj, offset): self.xreffrom[classobj].add((ref_kind, methodobj, offset))
Creates a crossreference from this class. XrefFrom means, that the current class is called by another class. :param REF_TYPE ref_kind: type of call :param classobj: :class:`ClassAnalysis` object to link :param methodobj: :param offset: Offset in the methods bytecode, where the c...
def streaming_command(self, command, raw=False, timeout_ms=None): if raw: command = self._to_raw_command(command) return self.adb_connection.streaming_command('shell', command, timeout_ms)
Run the given command and yield the output as we receive it.
def g_step(self, gen_frames, fake_logits_stop): hparam_to_gen_loss = { "least_squares": gan_losses.least_squares_generator_loss, "cross_entropy": gan_losses.modified_generator_loss, "wasserstein": gan_losses.wasserstein_generator_loss } fake_logits = self.discriminator(gen_frames) ...
Performs the generator step in computing the GAN loss. Args: gen_frames: Generated frames fake_logits_stop: Logits corresponding to the generated frames as per the discriminator. Assumed to have a stop-gradient term. Returns: gan_g_loss_pos_d: Loss. gan_g_loss_ne...
def instagram_config(self, id, secret, scope=None, **_): scope = scope if scope else 'basic' token_params = dict(scope=scope) config = dict( access_token_url='/oauth/access_token/', authorize_url='/oauth/authorize/', base_url='https://api.instagram.com/', ...
Get config dictionary for instagram oauth
def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', bundle='quantopian-quandl', ...
Run a trading algorithm. Parameters ---------- start : datetime The start date of the backtest. end : datetime The end date of the backtest.. initialize : callable[context -> None] The initialize function to use for the algorithm. This is called once at the very begi...
def change_type(self, cls): target_type = cls._type target = self._embedded.createInstance(target_type) self._embedded.setDiagram(target) return cls(target)
Change type of diagram in this chart. Accepts one of classes which extend Diagram.
def join_channel(self, channel, key=None, tags=None): params = [channel] if key: params.append(key) self.send('JOIN', params=params, tags=tags)
Join the given channel.
def send(self, load, tries=None, timeout=None, raw=False): if 'cmd' not in load: log.error('Malformed request, no cmd: %s', load) return {} cmd = load['cmd'].lstrip('_') if cmd in self.cmd_stub: return self.cmd_stub[cmd] if not hasattr(self.fs, cmd): ...
Emulate the channel send method, the tries and timeout are not used
def construct_func_expr(n): op = n[0] if op.startswith('_') and op.endswith('_'): op = op.strip('_') if op == 'var': return Var(str(n[1])) elif op == 'literal': if isinstance(n[1], basestring): raise "not implemented" return Constant(n[...
construct the function expression
def wait(self, timeout=None): us = -1 if timeout is None else int(timeout * 1000000) return super(Reader, self).wait(us)
Wait for a change in the journal. `timeout` is the maximum time in seconds to wait, or None which means to wait forever. Returns one of NOP (no change), APPEND (new entries have been added to the end of the journal), or INVALIDATE (journal files have been added or removed).
def _get_symmetry(self): d = spglib.get_symmetry(self._cell, symprec=self._symprec, angle_tolerance=self._angle_tol) trans = [] for t in d["translations"]: trans.append([float(Fraction.from_float(c).limit_denominator(1000)) fo...
Get the symmetry operations associated with the structure. Returns: Symmetry operations as a tuple of two equal length sequences. (rotations, translations). "rotations" is the numpy integer array of the rotation matrices for scaled positions "translations" gives ...
def blit_2x( self, console: tcod.console.Console, dest_x: int, dest_y: int, img_x: int = 0, img_y: int = 0, img_width: int = -1, img_height: int = -1, ) -> None: lib.TCOD_image_blit_2x( self.image_c, _console(console), ...
Blit onto a Console with double resolution. Args: console (Console): Blit destination Console. dest_x (int): Console tile X position starting from the left at 0. dest_y (int): Console tile Y position starting from the top at 0. img_x (int): Left corner pixel of t...
def lookup(self, key): values = self.filter(lambda kv: kv[0] == key).values() if self.partitioner is not None: return self.ctx.runJob(values, lambda x: x, [self.partitioner(key)]) return values.collect()
Return the list of values in the RDD for key `key`. This operation is done efficiently if the RDD has a known partitioner by only searching the partition that the key maps to. >>> l = range(1000) >>> rdd = sc.parallelize(zip(l, l), 10) >>> rdd.lookup(42) # slow [42] ...
def anchor(self): anchor = self._subtotal_dict["anchor"] try: anchor = int(anchor) if anchor not in self.valid_elements.element_ids: return "bottom" return anchor except (TypeError, ValueError): return anchor.lower()
int or str indicating element under which to insert this subtotal. An int anchor is the id of the dimension element (category or subvariable) under which to place this subtotal. The return value can also be one of 'top' or 'bottom'. The return value defaults to 'bottom' for an anchor r...
def as_coeff_unit(self): coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ) return coeff, ret
Factor the coefficient multiplying a unit For units that are multiplied by a constant dimensionless coefficient, returns a tuple containing the coefficient and a new unit object for the unmultiplied unit. Example ------- >>> import unyt as u >>> unit = (u.m**2/...
def push(self, filename, data): self._queue.put(Chunk(filename, data))
Push a chunk of a file to the streaming endpoint. Args: filename: Name of file that this is a chunk of. chunk_id: TODO: change to 'offset' chunk: File data.
def set_terminal_width(self, command="", delay_factor=1): if not command: return "" delay_factor = self.select_delay_factor(delay_factor) command = self.normalize_cmd(command) self.write_channel(command) output = self.read_until_prompt() if self.ansi_escape_co...
CLI terminals try to automatically adjust the line based on the width of the terminal. This causes the output to get distorted when accessed programmatically. Set terminal width to 511 which works on a broad set of devices. :param command: Command string to send to the device :type com...
def generate_string(self, initial_logits, initial_state, sequence_length): current_logits = initial_logits current_state = initial_state generated_letters = [] for _ in range(sequence_length): char_index = tf.squeeze(tf.multinomial(current_logits, 1)) char_one_hot = tf.one_hot(char_index, se...
Builds sub-graph to generate a string, sampled from the model. Args: initial_logits: Starting logits to sample from. initial_state: Starting state for the RNN core. sequence_length: Number of characters to sample. Returns: A Tensor of characters, with dimensions `[sequence_length, batc...
def threeprime_plot(self): data = dict() dict_to_add = dict() for key in self.threepGtoAfreq_data: pos = list(range(1,len(self.threepGtoAfreq_data.get(key)))) tmp = [i * 100.0 for i in self.threepGtoAfreq_data.get(key)] tuples = list(zip(pos,tmp)) ...
Generate a 3' G>A linegraph plot
def set_constants(self, *constants, verbose=True): new = [] current = {c.expression: c for c in self._constants} for expression in constants: constant = current.get(expression, Constant(self, expression)) new.append(constant) self._constants = new for c in...
Set the constants associated with the data. Parameters ---------- constants : str Expressions for the new set of constants. verbose : boolean (optional) Toggle talkback. Default is True See Also -------- transform Similar meth...
def _execute(self, worker): self._assert_status_is(TaskStatus.RUNNING) operation = worker.look_up(self.operation) operation.invoke(self, [], worker=worker)
This method is ASSIGNED during the evaluation to control how to resume it once it has been paused
def _load_maps_by_type(map_type): seq_maps = COLOR_MAPS[map_type] loaded_maps = {} for map_name in seq_maps: loaded_maps[map_name] = {} for num in seq_maps[map_name]: inum = int(num) colors = seq_maps[map_name][num]['Colors'] bmap = BrewerMap(map_name, map...
Load all maps of a given type into a dictionary. Color maps are loaded as BrewerMap objects. Dictionary is keyed by map name and then integer numbers of defined colors. There is an additional 'max' key that points to the color map with the largest number of defined colors. Parameters ---------...
def apply_args(self, **kwargs): def apply_format(node): if isinstance(node, PathParam): return PathParam(node.name.format(**kwargs), node.type, node.type_args) else: return node return UrlPath(*(apply_format(n) for n in self._nodes))
Apply formatting to each path node. This is used to apply a name to nodes (used to apply key names) eg: >>> a = UrlPath("foo", PathParam('{key_field}'), "bar") >>> b = a.apply_args(id="item_id") >>> b.format() 'foo/{item_id}/bar'
def update_refobj(self, old, new, reftrack): if old: del self._parentsearchdict[old] if new: self._parentsearchdict[new] = reftrack
Update the parent search dict so that the reftrack can be found with the new refobj and delete the entry for the old refobj. Old or new can also be None. :param old: the old refobj of reftrack :param new: the new refobj of reftrack :param reftrack: The reftrack, which refobj wa...
def list_(name, add, match, stamp=False, prune=0): ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if not isinstance(add, list): add = add.split(',') if name not in __reg__: __reg__[name] = {} __reg__[name]['val'] = [] for event...
Add the specified values to the named list If ``stamp`` is True, then the timestamp from the event will also be added if ``prune`` is set to an integer higher than ``0``, then only the last ``prune`` values will be kept in the list. USAGE: .. code-block:: yaml foo: reg.list: ...
def replacePassword(self, currentPassword, newPassword): if unicode(currentPassword) != self.password: return fail(BadCredentials()) return self.setPassword(newPassword)
Set this account's password if the current password matches. @param currentPassword: The password to match against the current one. @param newPassword: The new password. @return: A deferred firing when the password has been changed. @raise BadCredentials: If the current password did no...
def splits(cls, exts, fields, root='.data', train='train', validation='val', test='test2016', **kwargs): if 'path' not in kwargs: expected_folder = os.path.join(root, cls.name) path = expected_folder if os.path.exists(expected_folder) else None else: pa...
Create dataset objects for splits of the Multi30k dataset. Arguments: exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data in each language. root: Root dataset storage directory. De...
def cmd_signing_key(self, args): if len(args) == 0: print("usage: signing setup passphrase") return if not self.master.mavlink20(): print("You must be using MAVLink2 for signing") return passphrase = args[0] key = self.passphrase_to_key(pas...
set signing key on connection
def extract_header_comment_key_value_tuples_from_file(file_descriptor): file_data = file_descriptor.read() findall_result = re.findall(HEADER_COMMENT_KEY_VALUE_TUPLES_REGEX, file_data, re.MULTILINE | re.DOTALL) returned_list = [] for header_comment, _ignored, raw_comments, key, value in findall_result: ...
Extracts tuples representing comments and localization entries from strings file. Args: file_descriptor (file): The file to read the tuples from Returns: list : List of tuples representing the headers and localization entries.
def export_batch(self): batch = self.batch_cls( model=self.model, history_model=self.history_model, using=self.using ) if batch.items: try: json_file = self.json_file_cls(batch=batch, path=self.path) json_file.write() except JSO...
Returns a batch instance after exporting a batch of txs.
def nhapDaiHan(self, cucSo, gioiTinh): for cung in self.thapNhiCung: khoangCach = khoangCachCung(cung.cungSo, self.cungMenh, gioiTinh) cung.daiHan(cucSo + khoangCach * 10) return self
Nhap dai han Args: cucSo (TYPE): Description gioiTinh (TYPE): Description Returns: TYPE: Description
def read(self) -> None: try: with netcdf4.Dataset(self.filepath, "r") as ncfile: timegrid = query_timegrid(ncfile) for variable in self.variables.values(): variable.read(ncfile, timegrid) except BaseException: objecttools.augmen...
Open an existing NetCDF file temporarily and call method |NetCDFVariableDeep.read| of all handled |NetCDFVariableBase| objects.
def _create_socket(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = ssl.wrap_socket(s) s.connect((self.host, self.__port)) s.settimeout(self.timeout) return s
Creates ssl socket, connects to stream api and sets timeout.