code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def _update_spec_config(self, document_name, spec): self._spec_table.update_item( Key={'_id': '{}'.format(document_name)}, UpdateExpression="SET config = :v", ExpressionAttributeValues={':v': spec}, ReturnValues='ALL_NEW')
Dynamo implementation of project specific metadata spec
def interpolate_sysenv(line, defaults={}): map = ChainMap(os.environ, defaults) return line.format(**map)
Format line system environment variables + defaults
def deserialize(self, obj): if obj['immutable']: return obj['value'] else: guid = obj['value'] if not guid in object_registry: instance = JSObject(self, guid) object_registry[guid] = instance return object_registry[guid]
Deserialize an object from the front-end.
def load_patt(filename): with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') patt = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) lines.pop(0) for line in lines: lst = line.split(',') n = int(l...
Loads a file that was saved with the save_patt routine.
def setup_sensors(self): self._add_result = Sensor.float("add.result", "Last ?add result.", "", [-10000, 10000]) self._add_result.set_value(0, Sensor.UNREACHABLE) self._time_result = Sensor.timestamp("time.result", "Last ?time result.", "") self._time_result.set_v...
Setup some server sensors.
def key_field_name(self): name = 'resource_id' if self.resource: key_field = getmeta(self.resource).key_field if key_field: name = key_field.attname return name
Field identified as the key.
def pinyin(char, variant='mandarin', sep=' ', out='tones'): if len(char) > 1: return sep.join([pinyin(c, variant=variant, sep=sep, out=out) for c in char]) if not is_chinese(char): return char if char in _cd.GBK: char = gbk2big5(char) out_char = _cd.UNIHAN.get(char, {variant: '?...
Retrieve Pinyin of a character.
def _load_rules(self): for ruleset in self.active_rulesets: section_name = 'sweep_rules_' + ruleset.lower() try: ruledefs = getattr(self.config, section_name) except AttributeError: raise error.UserError("There is no [{}] section in your config...
Load rule definitions from config.
def create(gandi, name, value=None, filename=None): if not value and not filename: raise UsageError('You must set value OR filename.') if value and filename: raise UsageError('You must not set value AND filename.') if filename: value = filename.read() ret = gandi.sshkey.create(na...
Create a new SSH key.
def _prepare(self, serialized_obj): nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) encrypted = self.__safe.encrypt(serialized_obj, nonce) signed = self.__signing_key.sign(encrypted) return signed
Prepare the object to be sent over the untrusted channel.
async def teardown_conn(self, context): client_id = context.user_data self._logger.info("Tearing down client connection: %s", client_id) if client_id not in self.clients: self._logger.warning("client_id %s did not exist in teardown_conn", client_id) else: del self...
Teardown a connection from a client.
def _terminate_process_iou(self): if self._iou_process: log.info('Stopping IOU process for IOU VM "{}" PID={}'.format(self.name, self._iou_process.pid)) try: self._iou_process.terminate() except ProcessLookupError: pass self._started = ...
Terminate the IOU process if running
def run(self): connection = self.output().connect() query = ("select pg_terminate_backend(process) " "from STV_SESSIONS " "where db_name=%s " "and user_name != 'rdsdb' " "and process != pg_backend_pid()") cursor = connection.cur...
Kill any open Redshift sessions for the given database.
def small_phi_ces_distance(C1, C2): return sum(c.phi for c in C1) - sum(c.phi for c in C2)
Return the difference in |small_phi| between |CauseEffectStructure|.
def same_pyname(expected, pyname): if expected is None or pyname is None: return False if expected == pyname: return True if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) \ and type(pyname) not in \ (pynames.ImportedModule, pynames.ImportedName): ...
Check whether `expected` and `pyname` are the same
def close(self) -> None: self.cancel_pending_tasks() _LOGGER.debug("Disconnected") if self._transport: self._transport.close() self._is_connected = False
Closes connection to the LifeSOS ethernet interface.
def list(self): response = self._client.raw('disk.list', {}) result = response.get() if result.state != 'SUCCESS': raise RuntimeError('failed to list disks: %s' % result.stderr) if result.level != 20: raise RuntimeError('invalid response type from disk.list comman...
List available block devices
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 modify_path(): if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_...
Modify the module search path.
def RestoreTaskStoreFactory(store_class, chunk_size, restore_file, save_file): intm_results = np.load(restore_file) intm = intm_results[intm_results.files[0]] idx = np.isnan(intm).flatten().nonzero()[0] partitions = math.ceil(len(idx) / float(chunk_size)) task_store = store_class(partitions, idx.tol...
Restores a task store from file.
def local_run(): server_software = os.environ.get('SERVER_SOFTWARE') if server_software is None: return True if 'remote_api' in server_software: return False if server_software.startswith(('Development', 'testutil')): return True return False
Whether we should hit GCS dev appserver stub.
def deps_tree(self): dependencies = self.dependencies + [self.name] if self.repo == "sbo": for dep in dependencies: deps = Requires(flag="").sbo(dep) if dep not in self.deps_dict.values(): self.deps_dict[dep] = Utils().dimensional_list(deps...
Package dependencies image map file
def redef(obj, key, value, **kwargs): return Redef(obj, key, value=value, **kwargs)
A static constructor helper function
def push_supply(self, tokens): logger.debug("Pushing supply data: %s" % tokens) bus = self.case.buses[tokens["bus_no"] - 1] n_generators = len([g for g in self.case.generators if g.bus == bus]) if n_generators == 0: logger.error("No generator at bus [%s] for matching supply" ...
Adds OPF and CPF data to a Generator.
def mol(self): if self._mol is None: apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetRecordMol?csid=%s&calc3d=false&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) self._mol = tree.getroot().text return self._mol
Return record in MOL format
def tempnam(): stderr = sys.stderr try: sys.stderr = cStringIO.StringIO() return os.tempnam(None, 'tess_') finally: sys.stderr = stderr
returns a temporary file-name
def _construct_location_stack_entry(location, num_traverses): if not isinstance(num_traverses, int) or num_traverses < 0: raise AssertionError(u'Attempted to create a LocationStackEntry namedtuple with an invalid ' u'value for "num_traverses" {}. This is not allowed.' ...
Return a LocationStackEntry namedtuple with the specified parameters.
def _draw_lines(self, bg, colour, extent, line, xo, yo): coords = [self._scale_coords(x, y, extent, xo, yo) for x, y in line] self._draw_lines_internal(coords, colour, bg)
Draw a set of lines from a vector tile.
def close_application(self): self._debug('Closing application with session id %s' % self._current_application().session_id) self._cache.close()
Closes the current application and also close webdriver session.
def FaultFromFaultMessage(ps): pyobj = ps.Parse(FaultType.typecode) if pyobj.detail == None: detailany = None else: detailany = pyobj.detail.any return Fault(pyobj.faultcode, pyobj.faultstring, pyobj.faultactor, detailany)
Parse the message as a fault.
def __print(self, msg): self.announce(msg, level=distutils.log.INFO)
Shortcut for printing with the distutils logger.
def toggle_view(self, *args, **kwargs): group_to_display = self.views.popleft() self.cur_view.value = group_to_display for repo in self.tools_tc: for tool in self.tools_tc[repo]: t_groups = self.manifest.option(tool, 'groups')[1] if group_to_display no...
Toggles the view between different groups
async def fastStreamedQuery(self, url, *, headers=None, verify=True): response = await self.session.get(url, headers=self._buildHeaders(headers), timeout=HTTP_SHORT_TIMEOUT, ssl=verify) response.rai...
Send a GET request with short timeout, do not retry, and return streamed response.
def setdefault (self, key, *args): assert isinstance(key, basestring) return dict.setdefault(self, key.lower(), *args)
Set lowercase key value and return.
def match_patterns(pathname, patterns): for pattern in patterns: if fnmatch(pathname, pattern): return True return False
Returns ``True`` if the pathname matches any of the given patterns.
def convert_trig_to_hdf(workflow, hdfbank, xml_trigger_files, out_dir, tags=None): if tags is None: tags = [] logging.info('convert single inspiral trigger files to hdf5') make_analysis_dir(out_dir) trig_files = FileList() for ifo, insp_group in zip(*xml_trigger_files.categorize_by_attr('ifo...
Return the list of hdf5 trigger files outputs
def transform_outgoing(self, son, collection): if isinstance(son, dict): for (key, value) in son.items(): if self.replacement in key: k = self.revert_key(key) son[k] = self.transform_outgoing(son.pop(key), collection) elif isins...
Recursively restore all transformed keys.
def in_attack_range_of(self, unit: Unit, bonus_distance: Union[int, float] = 0) -> "Units": return self.filter(lambda x: unit.target_in_range(x, bonus_distance=bonus_distance))
Filters units that are in attack range of the unit in parameter
def rgb_reduce(r, g, b, mode=8): colours = ANSI_COLOURS[:mode] matches = [(rgb_distance(c, map(int, [r, g, b])), i) for i, c in enumerate(colours)] matches.sort() return sequence('m')(str(30 + matches[0][1]))
Convert an RGB colour to 8 or 16 colour ANSI graphics.
def to_python(self, value): "Normalize data to a list of strings." if not value: return [] return [v.strip() for v in value.splitlines() if v != ""]
Normalize data to a list of strings.
def _get_all_children(self,): res = '' if self.child_nodes: for c in self.child_nodes: res += ' child = ' + str(c) + '\n' if c.child_nodes: for grandchild in c.child_nodes: res += ' child = ' + str(grandchild) + '\...
return the list of children of a node
def queryables(self): return dict( [(a.cname, a) for a in self.index_axes] + [(self.storage_obj_type._AXIS_NAMES[axis], None) for axis, values in self.non_index_axes] + [(v.cname, v) for v in self.values_axes if v.name in set(self.data_columns)] ...
return a dict of the kinds allowable columns for this object
def find_interconnect_ports(self): phy_port_list = self.ext_br_obj.get_port_name_list() int_port_list = self.integ_br_obj.get_port_name_list() for port in phy_port_list: is_patch = ovs_lib.is_patch(self.root_helper, port) if is_patch: peer_port = ovs_lib.g...
Find the internal veth or patch ports.
def delete_thumbnails(relative_source_path, root=None, basedir=None, subdir=None, prefix=None): thumbs = thumbnails_for_file(relative_source_path, root, basedir, subdir, prefix) return _delete_using_thumbs_list(thumbs)
Delete all thumbnails for a source image.
def message(self, bot, comm): super(KarmaAdv, self).message(bot, comm) if not comm['directed'] and not comm['pm']: msg = comm['message'].strip().lower() words = self.regstr.findall(msg) karmas = self.modify_karma(words) if comm['user'] in karmas.keys(): ...
Check for strings ending with 2 or more '-' or '+'
def skip_connection_distance(a, b): if a[2] != b[2]: return 1.0 len_a = abs(a[1] - a[0]) len_b = abs(b[1] - b[0]) return (abs(a[0] - b[0]) + abs(len_a - len_b)) / (max(a[0], b[0]) + max(len_a, len_b))
The distance between two skip-connections.
def can_convert(x): if len(x.shape) < 2 or len(x.shape) > 3: return False dtype = x.dtype height = x.shape[0] width = x.shape[1] channels = 1 if len(x.shape) == 3: channels = x.shape[2] if channels > 4: return False retu...
Returns True if x can be converted to an image, False otherwise.
def round_corner(radius, fill): corner = Image.new('L', (radius, radius), 0) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill) return corner
Draw a round corner
def object_path(self, objhash): return os.path.join(self._path, self.OBJ_DIR, objhash)
Returns the path to an object file based on its hash.
def _prepare_target(ts, tables, buffer_size): for tablename in tables: table = ts[tablename] table[:] = [] if buffer_size is not None and table.is_attached(): table.write(append=False)
Clear tables affected by the processing.
def request(self, action): ev = threading.Event() first = False with self.__lock: if len(self.__events) == 0: first = True self.__events.append(ev) if first: action() return ev
Request an action to be performed, in case one.
def _save_file_and_pos(self): if not self._pos_changed: return with open(self.pos_storage_filename, 'w+') as f: _pos = '%s:%s' % (self._log_file, self._log_pos) _logger.debug('Saving position %s to file %s' % (_pos, self.pos_storage_filename)...
Save current position into file
def periodicity(freq_or_frame): if hasattr(freq_or_frame, 'rule_code'): rc = freq_or_frame.rule_code rc = rc.split('-')[0] factor = PER_YEAR_MAP.get(rc, None) if factor is not None: return factor / abs(freq_or_frame.n) else: raise Exception('Failed to ...
resolve the number of periods per year
def stat(self, filename, timeout=None): transport = StatFilesyncTransport(self.stream) transport.write_data('STAT', filename, timeout) stat_msg = transport.read_message(timeout) stat_msg.assert_command_is('STAT') return DeviceFileStat(filename, stat_msg.mode, stat_msg.size, stat_msg.time)
Return device file stat.
def device_connect(device_id): success = False if device_id in devices: devices[device_id].connect() success = True return jsonify(success=success)
Force a connection attempt via HTTP GET.
def _get_schema(name): item = datalab.utils.commands.get_notebook_item(name) if not item: item = _get_table(name) if isinstance(item, datalab.bigquery.Schema): return item if hasattr(item, 'schema') and isinstance(item.schema, datalab.bigquery._schema.Schema): return item.schema return None
Given a variable or table name, get the Schema if it exists.
def handle_code(code): "Handle a key or sequence of keys in braces" code_keys = [] if code in CODES: code_keys.append(VirtualKeyAction(CODES[code])) elif len(code) == 1: code_keys.append(KeyAction(code)) elif ' ' in code: to_repeat, count = code.rsplit(None, 1) if to_...
Handle a key or sequence of keys in braces
def _filterDictToStr(self, filterDict): values = [] for key, vals in filterDict.items(): if key not in ('contentRating', 'label'): raise BadRequest('Unknown filter key: %s', key) values.append('%s=%s' % (key, '%2C'.join(vals))) return '|'.join(values)
Converts friend filters to a string representation for transport.
def callback(newstate): print('callback: ', newstate) if newstate == modem.STATE_RING: if state == modem.STATE_IDLE: att = {"cid_time": modem.get_cidtime, "cid_number": modem.get_cidnumber, "cid_name": modem.get_cidname} print('Ringing', att)...
Callback from modem, process based on new state
def _parse_button(self, keypad, component_xml): button_xml = component_xml.find('Button') name = button_xml.get('Engraving') button_type = button_xml.get('ButtonType') direction = button_xml.get('Direction') if button_type == 'SingleSceneRaiseLower': name = 'Dimmer ' + direction if not nam...
Parses a button device that part of a keypad.
def _handler_http(self, result): monitor = result['monitor'] self.thread_debug("process_http", data=monitor, module='handler') self.stats.http_handled += 1 logargs = { 'type':"metric", 'endpoint': result['url'], 'pipeline': monitor['pipeline'], ...
Handle the result of an http monitor
def __json(self): if self.exclude_list is None: self.exclude_list = [] fields = {} for key, item in vars(self).items(): if hasattr(self, '_sa_instance_state'): if len(orm.attributes.instance_state(self).unloaded) > 0: mapper = in...
Using the exclude lists, convert fields to a string.
def _get_counts(self, f): self._consolidate_inplace() counts = dict() for b in self.blocks: v = f(b) counts[v] = counts.get(v, 0) + b.shape[0] return counts
return a dict of the counts of the function in BlockManager
def _fill(self): right_now = time.time() time_diff = right_now - self._last_fill if time_diff < 0: return self._count = min( self._count + self._fill_rate * time_diff, self._capacity, ) self._last_fill = right_now
Fills bucket with accrued tokens since last fill.
def save_proficiency(self, proficiency_form, *args, **kwargs): if proficiency_form.is_for_update(): return self.update_proficiency(proficiency_form, *args, **kwargs) else: return self.create_proficiency(proficiency_form, *args, **kwargs)
Pass through to provider ProficiencyAdminSession.update_proficiency
def parse(data, datafile): data._last_travel = [0, [0]] while True: section_number = int(datafile.readline()) if not section_number: break store = globals().get('section%d' % section_number) while True: fields = [ (int(field) if field.lstrip('-').isdigit()...
Read the Adventure data file and return a ``Data`` object.
def _tag_ec2(self, conn, role): tags = {'Role': role} conn.create_tags([self.instance_id], tags)
tag the current EC2 instance with a cluster role
def _player_step_tuple(self, envs_step_tuples): ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
Augment observation, return usual step tuple.
def main(dimension, iterations): objective_function = minimize(functions.sphere) stopping_condition = max_iterations(iterations) (solution, metrics) = optimize(objective_function=objective_function, domain=Domain(-5.12, 5.12, dimension), ...
Main function to execute gbest GC PSO algorithm.
def _dict_to_obj(self, d): if JsonEncoder.TYPE_ID not in d: return d type_name = d.pop(JsonEncoder.TYPE_ID) if type_name in _TYPE_NAME_TO_DECODER: decoder = _TYPE_NAME_TO_DECODER[type_name] return decoder(d) else: raise TypeError("Invalid type %s.", type_name)
Converts a dictionary of json object to a Python object.
def attrfindrows(self, groupname, attrname, value): values = self.attrgetcol(groupname, attrname) return [i for i in range(len(values)) if values[i] == value]
Get the row numbers of all rows where the attribute matches the given value.
async def _mogrify(conn, query, args): ps = await conn.prepare(query) paramtypes = [] for t in ps.get_parameters(): if t.name.endswith('[]'): pname = '_' + t.name[:-2] else: pname = t.name paramtypes.append('{}.{}'.format( _quote_ident(t.schema), _...
Safely inline arguments to query text.
def list_dynamodb(region, filter_by_kwargs): conn = boto.dynamodb.connect_to_region(region) tables = conn.list_tables() return lookup(tables, filter_by=filter_by_kwargs)
List all DynamoDB tables.
def md5(self): return hashlib.md5('_'.join([self.CHROM, str(self.POS), self.REF, self.ALT])).hexdigest()
Return a md5 key string based on position, ref and alt
def deep_run(self): self.get_period_LS(self.date, self.mag, self.n_threads, self.min_period) phase_folded_date = self.date % (self.period * 2.) sorted_index = np.argsort(phase_folded_date) folded_date = phase_folded_date[sorted_index] folded_mag = self.mag[sorted_index] s...
Derive period-based features.
def group_remove(name, **kwargs): ctx = Context(**kwargs) ctx.execute_action('group:remove', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, })
Remove routing group from the storage.
def send_point_data(events, additional): bodies = {} for (site, content_id), count in events.items(): if not len(site) or not len(content_id): continue bodies.setdefault(site, []) event, path = additional.get((site, content_id), (None, None)) bodies[site].append([cont...
creates data point payloads and sends them to influxdb
def _wraps(self, tokens): def _differ(tokens): inner, outer = tokens not_same_start = inner.get('start') != outer.get('start') not_same_end = inner.get('end') != outer.get('end') return not_same_start or not_same_end def _in_range(tokens): inne...
determine if a token is wrapped by another token
def read_records(file): records = [] for record_data in read_recordio(file): record = Record() record.ParseFromString(record_data) records.append(record) return records
Eagerly read a collection of amazon Record protobuf objects from file.
def _num_vowel_to_acc(vowel, tone): try: return VOWEL_MAP[vowel + str(tone)] except IndexError: raise ValueError("Vowel must be one of '{}' and tone must be a tone.".format(VOWELS))
Convert a numbered vowel to an accented vowel.
def getElementsByClassName(start_node: ParentNode, class_name: str ) -> NodeList: classes = set(class_name.split(' ')) return getElementsBy( start_node, lambda node: classes.issubset(set(node.classList)) )
Get child nodes which has ``class_name`` class attribute.
def read_pos_neg_data(path, folder, limit): training_pos_path = os.path.join(path, folder, 'pos') training_neg_path = os.path.join(path, folder, 'neg') X_pos = read_folder(training_pos_path) X_neg = read_folder(training_neg_path) if limit is None: X = X_pos + X_neg else: X = X_po...
returns array with positive and negative examples
def save_hierarchy(self, hierarchy_form, *args, **kwargs): if hierarchy_form.is_for_update(): return self.update_hierarchy(hierarchy_form, *args, **kwargs) else: return self.create_hierarchy(hierarchy_form, *args, **kwargs)
Pass through to provider HierarchyAdminSession.update_hierarchy
def _doc_rev(self, res): jstr = res.headers['X-Couchbase-Meta'] jobj = json.loads(jstr) return jobj['rev']
Returns the rev id from the header
def omnihash(obj): if isinstance(obj, set): return hash(frozenset(omnihash(e) for e in obj)) elif isinstance(obj, (tuple, list)): return hash(tuple(omnihash(e) for e in obj)) elif isinstance(obj, dict): return hash(frozenset((k, omnihash(v)) for k, v in obj.items())) else: ...
recursively hash unhashable objects
def scoreatpercentile(data,per,axis=0): 'like the function in scipy.stats but with an axis argument and works on arrays' a = np.sort(data,axis=axis) idx = per/100. * (data.shape[axis]-1) if (idx % 1 == 0): return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] else: l...
like the function in scipy.stats but with an axis argument and works on arrays
def _get_counter_reference(self): if (self.model is not None and self.base_factory is not None and self.base_factory._meta.model is not None and issubclass(self.model, self.base_factory._meta.model)): return self.base_factory._meta.counter_reference ...
Identify which factory should be used for a shared counter.
def list_action(**kwargs): def decorator(func): func.action = True func.detail = False func.kwargs = kwargs return func return decorator
Used to mark a method on a ResourceBinding that should be routed for list actions.
def _match_data_to_parameter(cls, data): in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
find the appropriate parameter for a parameter field
def query(self): if not self.b64_query: return None s = QSerializer(base64=True) return s.loads(self.b64_query)
De-serialize, decode and return an ORM query stored in b64_query.
def normalize_value(value): value = str(value) value = value.casefold() value = re.sub(r'\/\s*\d+', '', value) value = re.sub(r'^0+([0-9]+)', r'\1', value) value = re.sub(r'^(\d+)\.+', r'\1', value) value = re.sub(r'[^\w\s]', '', value) value = re.sub(r'^the\s+', '', value) value = re.sub(r'^\s+', '', value) v...
Normalize metadata value to improve match accuracy.
def _segment_normalized_cnvkit(cnr_file, work_dir, paired): cnvkit_base = os.path.join(utils.safe_makedir(os.path.join(work_dir, "cnvkit")), dd.get_sample_name(paired.tumor_data)) cnr_file = chromhacks.bed_to_standardonly(cnr_file, paired.tumor_data, headers="chromosome", ...
Segmentation of normalized inputs using CNVkit.
def _before_insert(mapper, connection, target): if target.position is None: func = sa.sql.func stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)]) target.position = connection.execute(stmt).scalar() + 1
Set item to last position if position not defined.
def _generic_signal_handler(self, signal_type): print("</pre>") message = "Got " + signal_type + ". Failing gracefully..." self.timestamp(message) self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True) sys.exit(1)
Function for handling both SIGTERM and SIGINT
def find_column(t): pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
Get cursor position, based on previous newline
def trim_trailing_silence(self): length = self.get_active_length() self.pianoroll = self.pianoroll[:length]
Trim the trailing silence of the pianoroll.
def in_tree(self, cmd_args): if not cmd_args: return True tree = self try: for datum in cmd_args: tree = tree.get_child(datum) except ValueError: return False return True
if a command is in the tree
def feed(self, cube, pair): self.cube = cube if pair not in ["FR", "RB", "BL", "LF"]: pair = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(pair)] self.pair = pair
Feed Cube to the solver.
def _at(self, t): rITRF, vITRF, error = self.ITRF_position_velocity_error(t) rGCRS, vGCRS = ITRF_to_GCRS2(t, rITRF, vITRF) return rGCRS, vGCRS, rGCRS, error
Compute this satellite's GCRS position and velocity at time `t`.
def _configure_logging(verbose=False, debug=False): overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {message}'), datefmt='%m%d %H:%M:%S', style='{', level...
Configure the log global, message format, and verbosity settings.