positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _transform(comps, trans): """ Transform the given string with transform type trans """ logging.debug("== In _transform(%s, %s) ==", comps, trans) components = list(comps) action, parameter = _get_action(trans) if action == _Action.ADD_MARK and \ components[2] == "" and \ mark.strip(components[1]).lower() in ['oe', 'oa'] and trans == "o^": action, parameter = _Action.ADD_CHAR, trans[0] if action == _Action.ADD_ACCENT: logging.debug("add_accent(%s, %s)", components, parameter) components = accent.add_accent(components, parameter) elif action == _Action.ADD_MARK and mark.is_valid_mark(components, trans): logging.debug("add_mark(%s, %s)", components, parameter) components = mark.add_mark(components, parameter) # Handle uơ in "huơ", "thuở", "quở" # If the current word has no last consonant and the first consonant # is one of "h", "th" and the vowel is "ươ" then change the vowel into # "uơ", keeping case and accent. If an alphabet character is then added # into the word then change back to "ươ". # # NOTE: In the dictionary, these are the only words having this strange # vowel so we don't need to worry about other cases. if accent.remove_accent_string(components[1]).lower() == "ươ" and \ not components[2] and components[0].lower() in ["", "h", "th", "kh"]: # Backup accents ac = accent.get_accent_string(components[1]) components[1] = ("u", "U")[components[1][0].isupper()] + components[1][1] components = accent.add_accent(components, ac) elif action == _Action.ADD_CHAR: if trans[0] == "<": if not components[2]: # Only allow ư, ơ or ươ sitting alone in the middle part # and ['g', 'i', '']. If we want to type giowf = 'giờ', separate() # will create ['g', 'i', '']. Therefore we have to allow # components[1] == 'i'. if (components[0].lower(), components[1].lower()) == ('g', 'i'): components[0] += components[1] components[1] = '' if not components[1] or \ (components[1].lower(), trans[1].lower()) == ('ư', 'ơ'): components[1] += trans[1] else: components = utils.append_comps(components, parameter) if parameter.isalpha() and \ accent.remove_accent_string(components[1]).lower().startswith("uơ"): ac = accent.get_accent_string(components[1]) components[1] = ('ư', 'Ư')[components[1][0].isupper()] + \ ('ơ', 'Ơ')[components[1][1].isupper()] + components[1][2:] components = accent.add_accent(components, ac) elif action == _Action.UNDO: components = _reverse(components, trans[1:]) if action == _Action.ADD_MARK or (action == _Action.ADD_CHAR and parameter.isalpha()): # If there is any accent, remove and reapply it # because it is likely to be misplaced in previous transformations ac = accent.get_accent_string(components[1]) if ac != accent.Accent.NONE: components = accent.add_accent(components, Accent.NONE) components = accent.add_accent(components, ac) logging.debug("After transform: %s", components) return components
Transform the given string with transform type trans
def upgrade(): """Upgrade database.""" op.create_index(op.f('ix_access_actionsroles_role_id'), 'access_actionsroles', ['role_id'], unique=False) op.drop_constraint(u'fk_access_actionsroles_role_id_accounts_role', 'access_actionsroles', type_='foreignkey') op.create_foreign_key(op.f('fk_access_actionsroles_role_id_accounts_role'), 'access_actionsroles', 'accounts_role', ['role_id'], ['id'], ondelete='CASCADE') op.create_index(op.f('ix_access_actionsusers_user_id'), 'access_actionsusers', ['user_id'], unique=False) op.drop_constraint(u'fk_access_actionsusers_user_id_accounts_user', 'access_actionsusers', type_='foreignkey') op.create_foreign_key(op.f('fk_access_actionsusers_user_id_accounts_user'), 'access_actionsusers', 'accounts_user', ['user_id'], ['id'], ondelete='CASCADE')
Upgrade database.
def features(self, expand=False): """Return the list of feature-value pairs in the conjunction.""" featvals = [] for term in self._terms: if isinstance(term, AVM): featvals.extend(term.features(expand=expand)) return featvals
Return the list of feature-value pairs in the conjunction.
def search_user(self, user_name, quiet=False, limit=9): """Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object. """ result = self.search(user_name, search_type=1002, limit=limit) if result['result']['userprofileCount'] <= 0: LOG.warning('User %s not existed!', user_name) raise SearchNotFound('user {} not existed'.format(user_name)) else: users = result['result']['userprofiles'] if quiet: user_id, user_name = users[0]['userId'], users[0]['nickname'] user = User(user_id, user_name) return user else: return self.display.select_one_user(users)
Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object.
def cmd_alt(self, args): '''show altitude''' print("Altitude: %.1f" % self.status.altitude) qnh_pressure = self.get_mav_param('AFS_QNH_PRESSURE', None) if qnh_pressure is not None and qnh_pressure > 0: ground_temp = self.get_mav_param('GND_TEMP', 21) pressure = self.master.field('SCALED_PRESSURE', 'press_abs', 0) qnh_alt = self.altitude_difference(qnh_pressure, pressure, ground_temp) print("QNH Alt: %u meters %u feet for QNH pressure %.1f" % (qnh_alt, qnh_alt*3.2808, qnh_pressure)) print("QNH Estimate: %.1f millibars" % self.qnh_estimate())
show altitude
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = data.get('options'), data.get('sql_raw') if options == 'format': sql_formmated = sqlparse.format(sql_raw, keyword_case='upper', reindent=True) return build_response(dict(data=sql_formmated, code=200)) elif options in ('all', 'selected'): conn = SQL(config.sql_host, config.sql_port, config.sql_user, config.sql_pwd, config.sql_db) result = conn.run(sql_raw) return build_response(dict(data=result, code=200)) else: pass pass
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
def iscsi_settings(self): """Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset. """ return ISCSISettings( self._conn, utils.get_subresource_path_by( self, ["@Redfish.Settings", "SettingsObject"]), redfish_version=self.redfish_version)
Property to provide reference to iSCSI settings instance It is calculated once when the first time it is queried. On refresh, this property gets reset.
def assert_is_instance(value, types, message=None, extra=None): """Raises an AssertionError if value is not an instance of type(s).""" assert isinstance(value, types), _assert_fail_message( message, value, types, "is not an instance of", extra )
Raises an AssertionError if value is not an instance of type(s).
def auth(self): """Performs an authentication. Uses either the private token, or the email/password pair. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success. """ if self.private_token or self.oauth_token: self._token_auth() else: self._credentials_auth()
Performs an authentication. Uses either the private token, or the email/password pair. The `user` attribute will hold a `gitlab.objects.CurrentUser` object on success.
def get_line_in_facet(self, facet): """ Returns the sorted pts in a facet used to draw a line """ lines = list(facet.outer_lines) pt = [] prev = None while len(lines) > 0: if prev is None: l = lines.pop(0) else: for i, l in enumerate(lines): if prev in l: l = lines.pop(i) if l[1] == prev: l.reverse() break # make sure the lines are connected one by one. # find the way covering all pts and facets pt.append(self.wulff_pt_list[l[0]].tolist()) pt.append(self.wulff_pt_list[l[1]].tolist()) prev = l[1] return pt
Returns the sorted pts in a facet used to draw a line
def __split_genomic_interval_filename(fn): """ Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom). :return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not present in the filename. """ if fn is None or fn == "": raise ValueError("invalid filename: " + str(fn)) fn = ".".join(fn.split(".")[:-1]) parts = fn.split(":") if len(parts) == 1: return (parts[0].strip(), None, None) else: r_parts = parts[1].split("-") if len(r_parts) != 2: raise ValueError("Invalid filename: " + str(fn)) return (parts[0].strip(), int(r_parts[0]), int(r_parts[1]))
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom). :return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not present in the filename.
async def hincrbyfloat(self, name, key, amount=1.0): """ Increment the value of ``key`` in hash ``name`` by floating ``amount`` """ return await self.execute_command('HINCRBYFLOAT', name, key, amount)
Increment the value of ``key`` in hash ``name`` by floating ``amount``
def transformer_wikitext103_l4k_v0(): """HParams for training languagemodel_wikitext103_l4k.""" hparams = transformer_big() # Adafactor uses less memory than Adam. # switch to Adafactor with its recommended learning rate scheme. hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 hparams.num_heads = 4 hparams.max_length = 4096 hparams.batch_size = 4096 hparams.shared_embedding_and_softmax_weights = False hparams.num_hidden_layers = 8 hparams.attention_dropout = 0.1 hparams.layer_prepostprocess_dropout = 0.2 hparams.relu_dropout = 0.1 hparams.label_smoothing = 0.0 # Using noise broadcast in the dropout layers saves memory during training. hparams.attention_dropout_broadcast_dims = "0,1" # batch, heads hparams.relu_dropout_broadcast_dims = "1" # length hparams.layer_prepostprocess_dropout_broadcast_dims = "1" # length # Avoid an expensive concat on TPU. # >1 shards helps with faster parameter distribution on multi-GPU machines hparams.symbol_modality_num_shards = 1 return hparams
HParams for training languagemodel_wikitext103_l4k.
def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current): """Process a REIL instruction. Args: instr (ReilInstruction): Instruction to process. avoid (list): List of addresses to avoid while executing the code. next_addr (int): Address of the following instruction. initial_state (State): Initial execution state. execution_state (Queue): Queue of execution states. trace_current (list): Current trace. Returns: int: Returns the next address to execute. """ # Process branch (JCC oprnd0, empty, oprnd2). if instr.mnemonic == ReilMnemonic.JCC: not_taken_addr = next_addr address, index = split_address(instr.address) logger.debug("[+] Processing branch: {:#08x}:{:02x} : {}".format(address, index, instr)) # Process conditional branch (oprnd0 is a REGISTER). if isinstance(instr.operands[0], ReilRegisterOperand): next_ip = self.__process_branch_cond(instr, avoid, initial_state, execution_state, trace_current, not_taken_addr) # Process unconditional branch (oprnd0 is an INTEGER). else: next_ip = self.__process_branch_uncond(instr, trace_current, not_taken_addr) # Process the rest of the instructions. else: trace_current += [(instr, None)] self.__cpu.execute(instr) next_ip = next_addr return next_ip
Process a REIL instruction. Args: instr (ReilInstruction): Instruction to process. avoid (list): List of addresses to avoid while executing the code. next_addr (int): Address of the following instruction. initial_state (State): Initial execution state. execution_state (Queue): Queue of execution states. trace_current (list): Current trace. Returns: int: Returns the next address to execute.
def transcript_names(self, contig=None, strand=None): """ What are all the transcript names in the database (optionally, restrict to a given chromosome and/or strand) """ return self._all_feature_values( column="transcript_name", feature="transcript", contig=contig, strand=strand)
What are all the transcript names in the database (optionally, restrict to a given chromosome and/or strand)
def fetch_access_token(self): """ 获取 access token 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list\ &t=resource/res_list&verify=1&id=open1419318587&token=&lang=zh_CN 这是内部刷新机制。请不要完全依赖! 因为有可能在缓存期间没有对此公众号的操作,造成refresh_token失效。 :return: 返回的 JSON 数据包 """ expires_in = 7200 result = self.component.refresh_authorizer_token( self.appid, self.refresh_token) if 'expires_in' in result: expires_in = result['expires_in'] self.session.set( self.access_token_key, result['authorizer_access_token'], expires_in ) self.expires_at = int(time.time()) + expires_in return result
获取 access token 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list\ &t=resource/res_list&verify=1&id=open1419318587&token=&lang=zh_CN 这是内部刷新机制。请不要完全依赖! 因为有可能在缓存期间没有对此公众号的操作,造成refresh_token失效。 :return: 返回的 JSON 数据包
def __vciFormatError(library_instance, function, HRESULT): """ Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :return: Formatted string """ buf = ctypes.create_string_buffer(constants.VCI_MAX_ERRSTRLEN) ctypes.memset(buf, 0, constants.VCI_MAX_ERRSTRLEN) library_instance.vciFormatError(HRESULT, buf, constants.VCI_MAX_ERRSTRLEN) return "function {} failed ({})".format(function._name, buf.value.decode('utf-8', 'replace'))
Format a VCI error and attach failed function and decoded HRESULT :param CLibrary library_instance: Mapped instance of IXXAT vcinpl library :param callable function: Failed function :param HRESULT HRESULT: HRESULT returned by vcinpl call :return: Formatted string
def _division(divisor, dividend, remainder, base): """ Get the quotient and remainder :param int divisor: the divisor :param dividend: the divident :type dividend: sequence of int :param int remainder: initial remainder :param int base: the base :returns: quotient and remainder :rtype: tuple of (list of int) * int Complexity: O(log_{divisor}(quotient)) """ quotient = [] for value in dividend: remainder = remainder * base + value (quot, rem) = divmod(remainder, divisor) quotient.append(quot) if quot > 0: remainder = rem return (quotient, remainder)
Get the quotient and remainder :param int divisor: the divisor :param dividend: the divident :type dividend: sequence of int :param int remainder: initial remainder :param int base: the base :returns: quotient and remainder :rtype: tuple of (list of int) * int Complexity: O(log_{divisor}(quotient))
def disconnect_entry_signals(): """ Disconnect all the signals on Entry model. """ post_save.disconnect( sender=Entry, dispatch_uid=ENTRY_PS_PING_DIRECTORIES) post_save.disconnect( sender=Entry, dispatch_uid=ENTRY_PS_PING_EXTERNAL_URLS) post_save.disconnect( sender=Entry, dispatch_uid=ENTRY_PS_FLUSH_SIMILAR_CACHE) post_delete.disconnect( sender=Entry, dispatch_uid=ENTRY_PD_FLUSH_SIMILAR_CACHE)
Disconnect all the signals on Entry model.
def _extract_program_from_pyquil_executable_response(response: PyQuilExecutableResponse) -> Program: """ Unpacks a rpcq PyQuilExecutableResponse object into a pyQuil Program object. :param response: PyQuilExecutableResponse object to be unpacked. :return: Resulting pyQuil Program object. """ p = Program(response.program) for attr, val in response.attributes.items(): setattr(p, attr, val) return p
Unpacks a rpcq PyQuilExecutableResponse object into a pyQuil Program object. :param response: PyQuilExecutableResponse object to be unpacked. :return: Resulting pyQuil Program object.
def parse_args(args=None): """Parse command-line arguments""" parser = argparse.ArgumentParser(description='afraid.org dyndns client') ## positional arguments parser.add_argument('user') parser.add_argument('password') parser.add_argument('hosts', nargs='*', help='(deafult: all associated hosts)', default=None ) ## optional arguments # should we fork? parser.add_argument('--daemonize', '-d', action='store_true', default=False, help='run in background (default: no)', ) # log to a file or stdout parser.add_argument('--log', help='log to file (default: log to stdout)', type=argparse.FileType('w'), default=sys.stdout, metavar='file' ) # how long to sleep between updates parser.add_argument('--interval', help='update interval, in seconds (default: 21600)', metavar='seconds', default=6 * 60 * 60, # 6 hours type=int ) return parser.parse_args(args)
Parse command-line arguments
def set_bool(self, location, value): """Set a boolean value. Casper booleans in XML are string literals of "true" or "false". This method sets the text value of "location" to the correct string representation of a boolean. Args: location: Element or a string path argument to find() value: Boolean or string value to set. (Accepts "true"/"True"/"TRUE"; all other strings are False). """ element = self._handle_location(location) if isinstance(value, basestring): value = True if value.upper() == "TRUE" else False elif not isinstance(value, bool): raise ValueError if value is True: element.text = "true" else: element.text = "false"
Set a boolean value. Casper booleans in XML are string literals of "true" or "false". This method sets the text value of "location" to the correct string representation of a boolean. Args: location: Element or a string path argument to find() value: Boolean or string value to set. (Accepts "true"/"True"/"TRUE"; all other strings are False).
def hoist_event(self, e): """ Hoist an xcb_generic_event_t to the right xcffib structure. """ if e.response_type == 0: return self._process_error(ffi.cast("xcb_generic_error_t *", e)) # We mask off the high bit here because events sent with SendEvent have # this bit set. We don't actually care where the event came from, so we # just throw this away. Maybe we could expose this, if anyone actually # cares about it. event = self._event_offsets[e.response_type & 0x7f] buf = CffiUnpacker(e) return event(buf)
Hoist an xcb_generic_event_t to the right xcffib structure.
def approximating_model_reg(self, beta, T, Z, R, Q, h_approx, data, X, state_no): """ Creates approximating Gaussian state space model for Skewt measurement density Parameters ---------- beta : np.array Contains untransformed starting values for latent variables T, Z, R, Q : np.array State space matrices used in KFS algorithm h_approx : float The variance of the measurement density data: np.array The univariate time series data X: np.array The regressors state_no : int Number of states Returns ---------- H : np.array Approximating measurement variance matrix mu : np.array Approximating measurement constants """ H = np.ones(data.shape[0])*h_approx mu = np.zeros(data.shape[0]) return H, mu
Creates approximating Gaussian state space model for Skewt measurement density Parameters ---------- beta : np.array Contains untransformed starting values for latent variables T, Z, R, Q : np.array State space matrices used in KFS algorithm h_approx : float The variance of the measurement density data: np.array The univariate time series data X: np.array The regressors state_no : int Number of states Returns ---------- H : np.array Approximating measurement variance matrix mu : np.array Approximating measurement constants
def emit_node(self, node): """Emit a single node.""" emit = getattr(self, "%s_emit" % node.kind, self.default_emit) return emit(node)
Emit a single node.
def read_vest_pickle(gname, score_dir): """Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns None if not found. """ vest_path = os.path.join(score_dir, gname+".vest.pickle") if os.path.exists(vest_path): if sys.version_info < (3,): with open(vest_path) as handle: gene_vest = pickle.load(handle) else: with open(vest_path, 'rb') as handle: gene_vest = pickle.load(handle, encoding='latin-1') return gene_vest else: return None
Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns None if not found.
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset. """ trans = _LazyTransformDataset(self, fn) if lazy: return trans return SimpleDataset([i for i in trans])
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False, transforms all samples at once. Otherwise, transforms each sample on demand. Note that if `fn` is stochastic, you must set lazy to True or you will get the same result on all epochs. Returns ------- Dataset The transformed dataset.
def stop(self, free_resource=False): ''' send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id ''' if not self.is_stopped(): self._is_stopping = True try: if free_resource or self.is_running(False): if not free_resource: logger.info("StopTransfer called - %s" % self.get_transfer_id()) self._is_stopped = faspmanager2.stopTransfer(self.get_transfer_id()) if not free_resource: logger.info("StopTransfer returned %s - %s" % ( self._is_stopped, self.get_transfer_id())) except Exception as ex: self.notify_exception(ex) self._is_stopping = False return self.is_stopped(False)
send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id
def get_order_book(self, code): """ 获取实时摆盘数据 :param code: 股票代码 :return: (ret, data) ret == RET_OK 返回字典,数据格式如下 ret != RET_OK 返回错误字符串 {‘code’: 股票代码 ‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, order_num),…] ‘Bid’: [ (bid_price1, bid_volume1, order_num), (bid_price2, bid_volume2, order_num),…] } 'Ask':卖盘, 'Bid'买盘。每个元组的含义是(委托价格,委托数量,委托订单数) """ if code is None or is_str(code) is False: error_str = ERROR_STR_PREFIX + "the type of code param is wrong" return RET_ERROR, error_str query_processor = self._get_sync_query_processor( OrderBookQuery.pack_req, OrderBookQuery.unpack_rsp, ) kargs = { "code": code, "conn_id": self.get_sync_conn_id() } ret_code, msg, orderbook = query_processor(**kargs) if ret_code == RET_ERROR: return ret_code, msg return RET_OK, orderbook
获取实时摆盘数据 :param code: 股票代码 :return: (ret, data) ret == RET_OK 返回字典,数据格式如下 ret != RET_OK 返回错误字符串 {‘code’: 股票代码 ‘Ask’:[ (ask_price1, ask_volume1,order_num), (ask_price2, ask_volume2, order_num),…] ‘Bid’: [ (bid_price1, bid_volume1, order_num), (bid_price2, bid_volume2, order_num),…] } 'Ask':卖盘, 'Bid'买盘。每个元组的含义是(委托价格,委托数量,委托订单数)
def _modifyInternal(self, *, sort=None, purge=False, done=None): """Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments. """ sortAll, sortLevels = sort is not None and sort or ([], {}) doneAll, doneLevels = done is not None and done or ([], {}) def _mark(v, i): if done is None: return v[:4] def _mark_(index, regexp, du): if du is None: return v[:4] if index is None: for v_ in v[:3]: if regexp is None or re.match(regexp, str(v_)): return v[:3] + [du] return v[:4] if regexp is None or re.match(regexp, str(v[index])): return v[:3] + [du] try: for doneLevel in doneLevels[i]: result = _mark_(*doneLevel) if result is not None: return result except KeyError: pass for doneAll_ in doneAll: result = _mark_(*doneAll_) if result is None: return v[:4] return result def _modify(submodel, i): _new = list() for v in submodel: if purge: if not v[3]: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) else: _new.append(_mark(v, i) + [_modify(v[4], i + 1)]) levels = sortLevels.get(i) or sortLevels.get(str(i)) for index, reverse in levels or sortAll: _new = sorted(_new, key=lambda e: e[index], reverse=reverse) return _new return _modify(self.data, 1)
Creates a whole new database from existing one, based on given modifiers. :sort: pattern should look like this: ([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}), where True|False indicate whether to reverse or not, <index> are one of Model.indexes and <level_index> indicate a number of level to sort. Of course, the lists above may contain multiple items. :done: patterns looks similar to :sort:, except that it has additional <regexp> values and that True|False means to mark as done|undone. @note: Should not be used directly. It was defined here, because :save: decorator needs undecorated version of Model.modify. :sort: Pattern on which to sort the database. :purge: Whether to purge done items. :done: Pattern on which to mark items as done/undone. :returns: New database, modified according to supplied arguments.
def calculate_rate(country_code, subdivision, city, address_country_code=None, address_exception=None): """ Calculates the VAT rate from the data returned by a GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param city: The city name :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :param address_exception: The user's exception name, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :raises: ValueError - if country code is not two characers, or subdivision or city are not strings UndefinitiveError - when no address_country_code and address_exception are provided and the geoip2 information is not specific enough :return: A tuple of (Decimal percentage rate, country code, exception name [or None]) """ if not country_code or not isinstance(country_code, str_cls) or len(country_code) != 2: raise ValueError('Invalidly formatted country code') if not isinstance(subdivision, str_cls): raise ValueError('Subdivision is not a string') if not isinstance(city, str_cls): raise ValueError('City is not a string') country_code = country_code.upper() subdivision = subdivision.lower() city = city.lower() if country_code not in rates.BY_COUNTRY: return (Decimal('0.0'), country_code, None) country_default = rates.BY_COUNTRY[country_code]['rate'] if country_code not in GEOIP2_EXCEPTIONS: return (country_default, country_code, None) exceptions = GEOIP2_EXCEPTIONS[country_code] for matcher in exceptions: # Subdivision-only match if isinstance(matcher, str_cls): sub_match = matcher city_match = None else: sub_match, city_match = matcher if sub_match != subdivision: continue if city_match and city_match != city: continue info = exceptions[matcher] exception_name = info['name'] if not info['definitive']: if address_country_code is None: raise UndefinitiveError('It is not possible to determine the users VAT rates based on the information provided') if address_country_code != country_code: continue if address_exception != exception_name: continue rate = rates.BY_COUNTRY[country_code]['exceptions'][exception_name] return (rate, country_code, exception_name) return (country_default, country_code, None)
Calculates the VAT rate from the data returned by a GeoLite2 database :param country_code: Two-character country code :param subdivision: The first subdivision name :param city: The city name :param address_country_code: The user's country_code, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :param address_exception: The user's exception name, as detected from billing_address or declared_residence. This prevents an UndefinitiveError from being raised. :raises: ValueError - if country code is not two characers, or subdivision or city are not strings UndefinitiveError - when no address_country_code and address_exception are provided and the geoip2 information is not specific enough :return: A tuple of (Decimal percentage rate, country code, exception name [or None])
def scrobble( self, artist, title, timestamp, album=None, album_artist=None, track_number=None, duration=None, stream_id=None, context=None, mbid=None, ): """Used to add a track-play to a user's profile. Parameters: artist (Required) : The artist name. title (Required) : The track name. timestamp (Required) : The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, January 1st 1970 UTC). This must be in the UTC time zone. album (Optional) : The album name. album_artist (Optional) : The album artist - if this differs from the track artist. context (Optional) : Sub-client version (not public, only enabled for certain API keys) stream_id (Optional) : The stream id for this track received from the radio.getPlaylist service. track_number (Optional) : The track number of the track on the album. mbid (Optional) : The MusicBrainz Track ID. duration (Optional) : The length of the track in seconds. """ return self.scrobble_many( ( { "artist": artist, "title": title, "timestamp": timestamp, "album": album, "album_artist": album_artist, "track_number": track_number, "duration": duration, "stream_id": stream_id, "context": context, "mbid": mbid, }, ) )
Used to add a track-play to a user's profile. Parameters: artist (Required) : The artist name. title (Required) : The track name. timestamp (Required) : The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, January 1st 1970 UTC). This must be in the UTC time zone. album (Optional) : The album name. album_artist (Optional) : The album artist - if this differs from the track artist. context (Optional) : Sub-client version (not public, only enabled for certain API keys) stream_id (Optional) : The stream id for this track received from the radio.getPlaylist service. track_number (Optional) : The track number of the track on the album. mbid (Optional) : The MusicBrainz Track ID. duration (Optional) : The length of the track in seconds.
def get_png_data_url(blob: Optional[bytes]) -> str: """ Converts a PNG blob into a local URL encapsulating the PNG. """ return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii')
Converts a PNG blob into a local URL encapsulating the PNG.
def CheckEmail(self, email, checkTypo=False): '''Checks a Single email if it is correct''' contents = email.split('@') if len(contents) == 2: if contents[1] in self.valid: return True return False
Checks a Single email if it is correct
def _get_parameter_intervals(self): """Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxValue, minIntervalClosed, maxIntervalClosed] - minValue Minimal value for the parameter - maxValue Maximal value for the parameter - minIntervalClosed :py:const:`True`, if minValue represents a valid value for the parameter. :py:const:`False` otherwise. - maxIntervalClosed: :py:const:`True`, if maxValue represents a valid value for the parameter. :py:const:`False` otherwise. :rtype: dictionary """ parameterIntervals = {} parameterIntervals["smoothingFactor"] = [0.0, 1.0, False, False] parameterIntervals["trendSmoothingFactor"] = [0.0, 1.0, False, False] return parameterIntervals
Returns the intervals for the methods parameter. Only parameters with defined intervals can be used for optimization! :return: Returns a dictionary containing the parameter intervals, using the parameter name as key, while the value hast the following format: [minValue, maxValue, minIntervalClosed, maxIntervalClosed] - minValue Minimal value for the parameter - maxValue Maximal value for the parameter - minIntervalClosed :py:const:`True`, if minValue represents a valid value for the parameter. :py:const:`False` otherwise. - maxIntervalClosed: :py:const:`True`, if maxValue represents a valid value for the parameter. :py:const:`False` otherwise. :rtype: dictionary
def setup_catalogs( portal, catalogs_definition={}, force_reindex=False, catalogs_extension={}, force_no_reindex=False): """ Setup the given catalogs. Redefines the map between content types and catalogs and then checks the indexes and metacolumns, if one index/column doesn't exist in the catalog_definition any more it will be removed, otherwise, if a new index/column is found, it will be created. :param portal: The Plone's Portal object :param catalogs_definition: a dictionary with the following structure { CATALOG_ID: { 'types': ['ContentType', ...], 'indexes': { 'UID': 'FieldIndex', ... }, 'columns': [ 'Title', ... ] } } :type catalogs_definition: dict :param force_reindex: Force to reindex the catalogs even if there's no need :type force_reindex: bool :param force_no_reindex: Force reindexing NOT to happen. :param catalog_extensions: An extension for the primary catalogs definition Same dict structure as param catalogs_definition. Allows to add columns and indexes required by Bika-specific add-ons. :type catalog_extensions: dict """ # If not given catalogs_definition, use the LIMS one if not catalogs_definition: catalogs_definition = getCatalogDefinitions() # Merge the catalogs definition of the extension with the primary # catalog definition definition = _merge_catalog_definitions(catalogs_definition, catalogs_extension) # Mapping content types in catalogs # This variable will be used to clean reindex the catalog. Saves the # catalogs ids archetype_tool = getToolByName(portal, 'archetype_tool') clean_and_rebuild = _map_content_types(archetype_tool, definition) # Indexing for cat_id in definition.keys(): reindex = False reindex = _setup_catalog( portal, cat_id, definition.get(cat_id, {})) if (reindex or force_reindex) and (cat_id not in clean_and_rebuild): # add the catalog if it has not been added before clean_and_rebuild.append(cat_id) # Reindex the catalogs which needs it if not force_no_reindex: _cleanAndRebuildIfNeeded(portal, clean_and_rebuild) return clean_and_rebuild
Setup the given catalogs. Redefines the map between content types and catalogs and then checks the indexes and metacolumns, if one index/column doesn't exist in the catalog_definition any more it will be removed, otherwise, if a new index/column is found, it will be created. :param portal: The Plone's Portal object :param catalogs_definition: a dictionary with the following structure { CATALOG_ID: { 'types': ['ContentType', ...], 'indexes': { 'UID': 'FieldIndex', ... }, 'columns': [ 'Title', ... ] } } :type catalogs_definition: dict :param force_reindex: Force to reindex the catalogs even if there's no need :type force_reindex: bool :param force_no_reindex: Force reindexing NOT to happen. :param catalog_extensions: An extension for the primary catalogs definition Same dict structure as param catalogs_definition. Allows to add columns and indexes required by Bika-specific add-ons. :type catalog_extensions: dict
def get_timestats_str(unixtime_list, newlines=1, full=True, isutc=True): r""" Args: unixtime_list (list): newlines (bool): Returns: str: timestat_str CommandLine: python -m utool.util_time --test-get_timestats_str Example: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >>> unixtime_list = [0, 0 + 60 * 60 * 5 , 10 + 60 * 60 * 5, 100 + 60 * 60 * 5, 1000 + 60 * 60 * 5] >>> newlines = 1 >>> full = False >>> timestat_str = get_timestats_str(unixtime_list, newlines, full=full, isutc=True) >>> result = ut.align(str(timestat_str), ':') >>> print(result) { 'max' : '1970/01/01 05:16:40', 'mean' : '1970/01/01 04:03:42', 'min' : '1970/01/01 00:00:00', 'range': '5:16:40', 'std' : '2:02:01', } Example2: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >>> unixtime_list = [0, 0 + 60 * 60 * 5 , 10 + 60 * 60 * 5, 100 + 60 * 60 * 5, 1000 + 60 * 60 * 5, float('nan'), 0] >>> newlines = 1 >>> timestat_str = get_timestats_str(unixtime_list, newlines, isutc=True) >>> result = ut.align(str(timestat_str), ':') >>> print(result) { 'max' : '1970/01/01 05:16:40', 'mean' : '1970/01/01 03:23:05', 'min' : '1970/01/01 00:00:00', 'nMax' : 1, 'nMin' : 2, 'num_nan': 1, 'range' : '5:16:40', 'shape' : (7,), 'std' : '2:23:43', } """ import utool as ut datetime_stats = get_timestats_dict(unixtime_list, full=full, isutc=isutc) timestat_str = ut.repr4(datetime_stats, newlines=newlines) return timestat_str
r""" Args: unixtime_list (list): newlines (bool): Returns: str: timestat_str CommandLine: python -m utool.util_time --test-get_timestats_str Example: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >>> unixtime_list = [0, 0 + 60 * 60 * 5 , 10 + 60 * 60 * 5, 100 + 60 * 60 * 5, 1000 + 60 * 60 * 5] >>> newlines = 1 >>> full = False >>> timestat_str = get_timestats_str(unixtime_list, newlines, full=full, isutc=True) >>> result = ut.align(str(timestat_str), ':') >>> print(result) { 'max' : '1970/01/01 05:16:40', 'mean' : '1970/01/01 04:03:42', 'min' : '1970/01/01 00:00:00', 'range': '5:16:40', 'std' : '2:02:01', } Example2: >>> # ENABLE_DOCTEST >>> from utool.util_time import * # NOQA >>> import utool as ut >>> unixtime_list = [0, 0 + 60 * 60 * 5 , 10 + 60 * 60 * 5, 100 + 60 * 60 * 5, 1000 + 60 * 60 * 5, float('nan'), 0] >>> newlines = 1 >>> timestat_str = get_timestats_str(unixtime_list, newlines, isutc=True) >>> result = ut.align(str(timestat_str), ':') >>> print(result) { 'max' : '1970/01/01 05:16:40', 'mean' : '1970/01/01 03:23:05', 'min' : '1970/01/01 00:00:00', 'nMax' : 1, 'nMin' : 2, 'num_nan': 1, 'range' : '5:16:40', 'shape' : (7,), 'std' : '2:23:43', }
def checkPos(self): """check all positions""" soup = BeautifulSoup(self.css1(path['movs-table']).html, 'html.parser') poss = [] for label in soup.find_all("tr"): pos_id = label['id'] # init an empty list # check if it already exist pos_list = [x for x in self.positions if x.id == pos_id] if pos_list: # and update it pos = pos_list[0] pos.update(label) else: pos = self.new_pos(label) pos.get_gain() poss.append(pos) # remove old positions self.positions.clear() self.positions.extend(poss) logger.debug("%d positions update" % len(poss)) return self.positions
check all positions
def receivetime_delay(self, tid, days, session): '''taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间''' request = TOPRequest('taobao.trade.receivetime.delay') request['tid'] = tid request['days'] = days self.create(self.execute(request, session)['trade']) return self
taobao.trade.receivetime.delay 延长交易收货时间 延长交易收货时间
def do_raise(self, arg): """Raise the last exception caught.""" self.do_continue(arg) # Annotating the exception for a continual re-raise _, exc_value, _ = self.exc_info exc_value._ipdbugger_let_raise = True raise_(*self.exc_info)
Raise the last exception caught.
def CreateApproval(self, reason=None, notified_users=None, email_cc_addresses=None): """Create a new approval for the current user to access this hunt.""" if not reason: raise ValueError("reason can't be empty") if not notified_users: raise ValueError("notified_users list can't be empty.") approval = user_pb2.ApiHuntApproval( reason=reason, notified_users=notified_users, email_cc_addresses=email_cc_addresses or []) args = user_pb2.ApiCreateHuntApprovalArgs( hunt_id=self.hunt_id, approval=approval) data = self._context.SendRequest("CreateHuntApproval", args) return HuntApproval( data=data, username=self._context.username, context=self._context)
Create a new approval for the current user to access this hunt.
def addRNAQuantification(self, datafields): """ Adds an RNAQuantification to the db. Datafields is a tuple in the order: id, feature_set_ids, description, name, read_group_ids, programs, biosample_id """ self._rnaValueList.append(datafields) if len(self._rnaValueList) >= self._batchSize: self.batchaddRNAQuantification()
Adds an RNAQuantification to the db. Datafields is a tuple in the order: id, feature_set_ids, description, name, read_group_ids, programs, biosample_id
def reverse_format(format_string, resolved_string): """ Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str String with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form {field_name: value} such that ``format_string.(**args) == resolved_string`` Examples -------- >>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv') {'year': '2014', 'month': '01', 'day': '03'} >>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv') {'year': 2014, 'month': 1, 'day': 3} >>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv') {'date': datetime.datetime(2016, 10, 1, 0, 0)} >>> reverse_format('{state:2}{zip:5}', 'PA19104') {'state': 'PA', 'zip': '19104'} See also -------- str.format : method that this reverses reverse_formats : method for reversing a list of strings using one pattern """ from string import Formatter from datetime import datetime fmt = Formatter() args = {} # ensure that format_string is in posix format format_string = make_path_posix(format_string) # split the string into bits literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string)) if not any(field_names): return {} for i, conversion in enumerate(conversions): if conversion: raise ValueError(('Conversion not allowed. Found on {}.' .format(field_names[i]))) # ensure that resolved string is in posix format resolved_string = make_path_posix(resolved_string) # get a list of the parts that matter bits = _get_parts_of_format_string(resolved_string, literal_texts, format_specs) for i, (field_name, format_spec) in enumerate(zip(field_names, format_specs)): if field_name: try: if format_spec.startswith('%'): args[field_name] = datetime.strptime(bits[i], format_spec) elif format_spec[-1] in list('bcdoxX'): args[field_name] = int(bits[i]) elif format_spec[-1] in list('eEfFgGn'): args[field_name] = float(bits[i]) elif format_spec[-1] == '%': args[field_name] = float(bits[i][:-1])/100 else: args[field_name] = fmt.format_field(bits[i], format_spec) except: args[field_name] = bits[i] return args
Reverse the string method format. Given format_string and resolved_string, find arguments that would give ``format_string.format(**arguments) == resolved_string`` Parameters ---------- format_string : str Format template string as used with str.format method resolved_string : str String with same pattern as format_string but with fields filled out. Returns ------- args : dict Dict of the form {field_name: value} such that ``format_string.(**args) == resolved_string`` Examples -------- >>> reverse_format('data_{year}_{month}_{day}.csv', 'data_2014_01_03.csv') {'year': '2014', 'month': '01', 'day': '03'} >>> reverse_format('data_{year:d}_{month:d}_{day:d}.csv', 'data_2014_01_03.csv') {'year': 2014, 'month': 1, 'day': 3} >>> reverse_format('data_{date:%Y_%m_%d}.csv', 'data_2016_10_01.csv') {'date': datetime.datetime(2016, 10, 1, 0, 0)} >>> reverse_format('{state:2}{zip:5}', 'PA19104') {'state': 'PA', 'zip': '19104'} See also -------- str.format : method that this reverses reverse_formats : method for reversing a list of strings using one pattern
def mxmt(m1, m2): """ Multiply a 3x3 matrix and the transpose of another 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of floats :return: The product m1 times m2 transpose. :rtype: float """ m1 = stypes.toDoubleMatrix(m1) m2 = stypes.toDoubleMatrix(m2) mout = stypes.emptyDoubleMatrix() libspice.mxmt_c(m1, m2, mout) return stypes.cMatrixToNumpy(mout)
Multiply a 3x3 matrix and the transpose of another 3x3 matrix. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mxmt_c.html :param m1: 3x3 double precision matrix. :type m1: 3x3-Element Array of floats :param m2: 3x3 double precision matrix. :type m2: 3x3-Element Array of floats :return: The product m1 times m2 transpose. :rtype: float
def is_callable_tag(tag): """ Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag. """ return (isinstance(tag, six.string_types) and tag.strip().startswith('{{') and tag.strip().endswith('}}'))
Determine whether :tag: is a valid callable string tag. String is assumed to be valid callable if it starts with '{{' and ends with '}}'. :param tag: String name of tag.
def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database""" cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cachefile)) return df = pd.read_csv(cachefile, compression='infer', header=0, infer_datetime_format=True) df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time']) df = df.set_index('Datetime') df = df.drop(['Date', 'Time'], axis=1) try: self.dfdb.write_points(df, ticker) except InfluxDBClientError as err: log.error('Write to database failed: %s' % err)
Write Pandas Dataframe to InfluxDB database
def get_nve_vni_switch_bindings(vni, switch_ip): """Return the nexus nve binding(s) per switch.""" LOG.debug("get_nve_vni_switch_bindings() called") session = bc.get_reader_session() try: return (session.query(nexus_models_v2.NexusNVEBinding). filter_by(vni=vni, switch_ip=switch_ip).all()) except sa_exc.NoResultFound: return None
Return the nexus nve binding(s) per switch.
def retry(self): """ Retry payment on this invoice if it isn't paid, closed, or forgiven.""" if not self.paid and not self.forgiven and not self.closed: stripe_invoice = self.api_retrieve() updated_stripe_invoice = ( stripe_invoice.pay() ) # pay() throws an exception if the charge is not successful. type(self).sync_from_stripe_data(updated_stripe_invoice) return True return False
Retry payment on this invoice if it isn't paid, closed, or forgiven.
def add(self, key, val, minutes): """ Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|datetime :rtype: bool """ if not self.has(key): self.put(key, val, minutes) return True return False
Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|datetime :rtype: bool
def compile_bundle_entry(self, spec, entry): """ Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory. """ modname, source, target, modpath = entry bundled_modpath = {modname: modpath} bundled_target = {modname: target} export_module_name = [] if isfile(source): export_module_name.append(modname) copy_target = join(spec[BUILD_DIR], target) if not exists(dirname(copy_target)): makedirs(dirname(copy_target)) shutil.copy(source, copy_target) elif isdir(source): copy_target = join(spec[BUILD_DIR], modname) shutil.copytree(source, copy_target) return bundled_modpath, bundled_target, export_module_name
Handler for each entry for the bundle method of the compile process. This copies the source file or directory into the build directory.
def remove_group_roles(request, group, domain=None, project=None): """Removes all roles from a group on a domain or project.""" client = keystoneclient(request, admin=True) roles = client.roles.list(group=group, domain=domain, project=project) for role in roles: remove_group_role(request, role=role.id, group=group, domain=domain, project=project)
Removes all roles from a group on a domain or project.
def normalize(self, mag=1.): """Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1. """ def f(dataset, s, null, mag): dataset[s] -= null dataset[s] /= mag if self.signed: mag = self.mag() / mag else: mag = self.max() / mag self.chunkwise(f, null=self.null, mag=mag) self._null = 0
Normalize a Channel, set `null` to 0 and the mag to given value. Parameters ---------- mag : float (optional) New value of mag. Default is 1.
def load_many(self, keys): # type: (Iterable[Hashable]) -> Promise """ Loads multiple keys, promising an array of values >>> a, b = await my_loader.load_many([ 'a', 'b' ]) This is equivalent to the more verbose: >>> a, b = await Promise.all([ >>> my_loader.load('a'), >>> my_loader.load('b') >>> ]) """ if not isinstance(keys, Iterable): raise TypeError( ( "The loader.loadMany() function must be called with Array<key> " + "but got: {}." ).format(keys) ) return Promise.all([self.load(key) for key in keys])
Loads multiple keys, promising an array of values >>> a, b = await my_loader.load_many([ 'a', 'b' ]) This is equivalent to the more verbose: >>> a, b = await Promise.all([ >>> my_loader.load('a'), >>> my_loader.load('b') >>> ])
def resource_show(resource_id, extra_args=None, cibfile=None): ''' Show a resource via pcs command resource_id name of the resource extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib' ''' return item_show(item='resource', item_id=resource_id, extra_args=extra_args, cibfile=cibfile)
Show a resource via pcs command resource_id name of the resource extra_args additional options for the pcs command cibfile use cibfile instead of the live CIB CLI Example: .. code-block:: bash salt '*' pcs.resource_show resource_id='galera' cibfile='/tmp/cib_for_galera.cib'
def _tokenize_wordpiece(self, text): """Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] Args: text: A single token or whitespace separated tokens. This should have already been passed through `BERTBasicTokenizer. Returns: A list of wordpiece tokens. """ output_tokens = [] for token in self.basic_tokenizer._whitespace_tokenize(text): chars = list(token) if len(chars) > self.max_input_chars_per_word: output_tokens.append(self.vocab.unknown_token) continue is_bad = False start = 0 sub_tokens = [] while start < len(chars): end = len(chars) cur_substr = None while start < end: substr = ''.join(chars[start:end]) if start > 0: substr = '##' + substr if substr in self.vocab: cur_substr = substr break end -= 1 if cur_substr is None: is_bad = True break sub_tokens.append(cur_substr) start = end if is_bad: output_tokens.append(self.vocab.unknown_token) else: output_tokens.extend(sub_tokens) return output_tokens
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example: input = "unaffable" output = ["un", "##aff", "##able"] Args: text: A single token or whitespace separated tokens. This should have already been passed through `BERTBasicTokenizer. Returns: A list of wordpiece tokens.
def get_model(self): """ Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model() """ if self.probnet.get('type') == "BayesianNetwork": model = BayesianModel() model.add_nodes_from(self.probnet['Variables'].keys()) model.add_edges_from(self.probnet['edges'].keys()) tabular_cpds = [] cpds = self.probnet['Potentials'] for cpd in cpds: var = list(cpd['Variables'].keys())[0] states = self.probnet['Variables'][var]['States'] evidence = cpd['Variables'][var] evidence_card = [len(self.probnet['Variables'][evidence_var]['States']) for evidence_var in evidence] arr = list(map(float, cpd['Values'].split())) values = np.array(arr) values = values.reshape((len(states), values.size//len(states))) tabular_cpds.append(TabularCPD(var, len(states), values, evidence, evidence_card)) model.add_cpds(*tabular_cpds) variables = model.nodes() for var in variables: for prop_name, prop_value in self.probnet['Variables'][var].items(): model.node[var][prop_name] = prop_value edges = model.edges() if nx.__version__.startswith('1'): for edge in edges: for prop_name, prop_value in self.probnet['edges'][edge].items(): model.edge[edge[0]][edge[1]][prop_name] = prop_value else: for edge in edges: for prop_name, prop_value in self.probnet['edges'][edge].items(): model.adj[edge[0]][edge[1]][prop_name] = prop_value return model else: raise ValueError("Please specify only Bayesian Network.")
Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model()
def print_preview(self, print_area, print_data): """Launch print preview""" if cairo is None: return print_info = \ self.main_window.interfaces.get_cairo_export_info("Print") if print_info is None: # Dialog has been canceled return printout_preview = Printout(self.grid, print_data, print_info) printout_printing = Printout(self.grid, print_data, print_info) preview = wx.PrintPreview(printout_preview, printout_printing, print_data) if not preview.Ok(): # Printout preview failed return pfrm = wx.PreviewFrame(preview, self.main_window, _("Print preview")) pfrm.Initialize() pfrm.SetPosition(self.main_window.GetPosition()) pfrm.SetSize(self.main_window.GetSize()) pfrm.Show(True)
Launch print preview
def bin_remove(self): """Remove Slackware packages """ packages = self.args[1:] options = [ "-r", "--removepkg" ] additional_options = [ "--deps", "--check-deps", "--tag", "--checklist" ] flag, extra = "", [] flags = [ "-warn", "-preserve", "-copy", "-keep" ] # merge --check-deps and --deps options if (additional_options[1] in self.args and additional_options[0] not in self.args): self.args.append(additional_options[0]) if len(self.args) > 1 and self.args[0] in options: for additional in additional_options: if additional in self.args: extra.append(additional) self.args.remove(additional) packages = self.args[1:] for fl in flags: if fl in self.args: flag = self.args[1] packages = self.args[2:] PackageManager(packages).remove(flag, extra) else: usage("")
Remove Slackware packages
def get_key_field(ui, ui_option_name, default_val=0, default_is_number=True): """ parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is a boolean value that indicates whether the value is a column name or a column number (numbers start at 0). """ key = default_val key_is_field_number = default_is_number if ui.optionIsSet(ui_option_name): key = ui.getValue(ui_option_name) try: key = int(key) - 1 key_is_field_number = True except ValueError: key_is_field_number = False return key, key_is_field_number
parse an option from a UI object as the name of a key field. If the named option is not set, return the default values for the tuple. :return: a tuple of two items, first is the value of the option, second is a boolean value that indicates whether the value is a column name or a column number (numbers start at 0).
def to_trajectory(self, show_ports=False, chains=None, residues=None, box=None): """Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajectory. chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be used when converting to a `Trajectory`. If 'None', a bounding box is used with a 0.5nm buffer in each dimension. to avoid overlapping atoms, unless `self.periodicity` is not None, in which case those values are used for the box lengths. Returns ------- trajectory : md.Trajectory See also -------- _to_topology """ atom_list = [particle for particle in self.particles(show_ports)] top = self._to_topology(atom_list, chains, residues) # Coordinates. xyz = np.ndarray(shape=(1, top.n_atoms, 3), dtype='float') for idx, atom in enumerate(atom_list): xyz[0, idx] = atom.pos # Unitcell information. unitcell_angles = [90.0, 90.0, 90.0] if box is None: unitcell_lengths = np.empty(3) for dim, val in enumerate(self.periodicity): if val: unitcell_lengths[dim] = val else: unitcell_lengths[dim] = self.boundingbox.lengths[dim] + 0.5 else: unitcell_lengths = box.lengths unitcell_angles = box.angles return md.Trajectory(xyz, top, unitcell_lengths=unitcell_lengths, unitcell_angles=unitcell_angles)
Convert to an md.Trajectory and flatten the compound. Parameters ---------- show_ports : bool, optional, default=False Include all port atoms when converting to trajectory. chains : mb.Compound or list of mb.Compound Chain types to add to the topology residues : str of list of str Labels of residues in the Compound. Residues are assigned by checking against Compound.name. box : mb.Box, optional, default=self.boundingbox (with buffer) Box information to be used when converting to a `Trajectory`. If 'None', a bounding box is used with a 0.5nm buffer in each dimension. to avoid overlapping atoms, unless `self.periodicity` is not None, in which case those values are used for the box lengths. Returns ------- trajectory : md.Trajectory See also -------- _to_topology
def _get_entity_id(field_name, attrs): """Find the ID for a one to one relationship. The server may return JSON data in the following forms for a :class:`nailgun.entity_fields.OneToOneField`:: 'user': None 'user': {'name': 'Alice Hayes', 'login': 'ahayes', 'id': 1} 'user_id': 1 'user_id': None Search ``attrs`` for a one to one ``field_name`` and return its ID. :param field_name: A string. The name of a field. :param attrs: A dict. A JSON payload as returned from a server. :returns: Either an entity ID or None. """ field_name_id = field_name + '_id' if field_name in attrs: if attrs[field_name] is None: return None elif 'id' in attrs[field_name]: return attrs[field_name]['id'] if field_name_id in attrs: return attrs[field_name_id] else: raise MissingValueError( 'Cannot find a value for the "{0}" field. Searched for keys named ' '{1}, but available keys are {2}.' .format(field_name, (field_name, field_name_id), attrs.keys()) )
Find the ID for a one to one relationship. The server may return JSON data in the following forms for a :class:`nailgun.entity_fields.OneToOneField`:: 'user': None 'user': {'name': 'Alice Hayes', 'login': 'ahayes', 'id': 1} 'user_id': 1 'user_id': None Search ``attrs`` for a one to one ``field_name`` and return its ID. :param field_name: A string. The name of a field. :param attrs: A dict. A JSON payload as returned from a server. :returns: Either an entity ID or None.
def favorite_remove(self, post_id): """Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id. """ return self._get('favorites/{0}.json'.format(post_id), method='DELETE', auth=True)
Remove a post from favorites (Requires login). Parameters: post_id (int): Where post_id is the post id.
def highlightBlock(self, text): """ Actually highlight the block""" # Note that an undefined blockstate is equal to -1, so the first block # will have the correct behaviour of starting at 0. if self._allow_highlight: start = self.previousBlockState() + 1 end = start + len(text) for i, (fmt, letter) in enumerate(self._charlist[start:end]): self.setFormat(i, 1, fmt) self.setCurrentBlockState(end) self.highlight_spaces(text)
Actually highlight the block
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ self.add_attributes(( (PROV['type'], self.type), (NIDM_GROUP_NAME, self.group_name), (NIDM_NUMBER_OF_SUBJECTS, self.num_subjects), (PROV['label'], self.label)))
Create prov entities and activities.
def folderitems(self): """Returns an array of dictionaries, each dictionary represents an analysis row to be rendered in the list. The array returned is sorted in accordance with the layout positions set for the analyses this worksheet contains when the analyses were added in the worksheet. :returns: list of dicts with the items to be rendered in the list """ items = BaseView.folderitems(self) # Fill empty positions from the layout with fake rows. The worksheet # can be generated by making use of a WorksheetTemplate, so there is # the chance that some slots of this worksheet being empty. We need to # render a row still, at lest to display the slot number (Pos) self.fill_empty_slots(items) # Sort the items in accordance with the layout items = sorted(items, key=itemgetter("pos_sortkey")) # Fill the slot header cells (first cell of each row). Each slot # contains the analyses that belong to the same parent # (AnalysisRequest, ReferenceSample), so the information about the # parent must be displayed in the first cell of each slot. self.fill_slots_headers(items) return items
Returns an array of dictionaries, each dictionary represents an analysis row to be rendered in the list. The array returned is sorted in accordance with the layout positions set for the analyses this worksheet contains when the analyses were added in the worksheet. :returns: list of dicts with the items to be rendered in the list
def get_interpolated_value(self, x): """ Returns an interpolated y value for a particular x value. Args: x: x value to return the y value for Returns: Value of y at x """ if len(self.ydim) == 1: return get_linear_interpolated_value(self.x, self.y, x) else: return [get_linear_interpolated_value(self.x, self.y[:, k], x) for k in range(self.ydim[1])]
Returns an interpolated y value for a particular x value. Args: x: x value to return the y value for Returns: Value of y at x
def from_env(key: str, default: T = None) -> Union[str, Optional[T]]: """Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None`` """ return os.getenv(key, default)
Shortcut for safely reading environment variable. :param key: Environment var key. :param default: Return default value if environment var not found by given key. By default: ``None``
def stop(self): """Gracefully shutdown a server that is serving forever.""" self.ready = False if self._start_time is not None: self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if not isinstance(self.bind_addr, six.string_types): # Touch our own socket to make accept() return immediately. try: host, port = sock.getsockname()[:2] except socket.error as ex: if ex.args[0] not in errors.socket_errors_to_ignore: # Changed to use error code and not message # See # https://github.com/cherrypy/cherrypy/issues/860. raise else: # Note that we're explicitly NOT using AI_PASSIVE, # here, because we want an actual IP to touch. # localhost won't work if we've bound to a public IP, # but it will if we bound to '0.0.0.0' (INADDR_ANY). for res in socket.getaddrinfo( host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, ): af, socktype, proto, canonname, sa = res s = None try: s = socket.socket(af, socktype, proto) # See # https://groups.google.com/group/cherrypy-users/ # browse_frm/thread/bbfe5eb39c904fe0 s.settimeout(1.0) s.connect((host, port)) s.close() except socket.error: if s: s.close() if hasattr(sock, 'close'): sock.close() self.socket = None self.requests.stop(self.shutdown_timeout)
Gracefully shutdown a server that is serving forever.
def _load_parameters(self): """ Load the .mlaunch_startup file that exists in each datadir. Handles different protocol versions. """ datapath = self.dir startup_file = os.path.join(datapath, '.mlaunch_startup') if not os.path.exists(startup_file): return False in_dict = json.load(open(startup_file, 'rb')) # handle legacy version without versioned protocol if 'protocol_version' not in in_dict: in_dict['protocol_version'] = 1 self.loaded_args = in_dict self.startup_info = {} # hostname was added recently self.loaded_args['hostname'] = socket.gethostname() elif in_dict['protocol_version'] == 2: self.startup_info = in_dict['startup_info'] self.loaded_unknown_args = in_dict['unknown_args'] self.loaded_args = in_dict['parsed_args'] # changed 'authentication' to 'auth', if present (from old env) rename if 'authentication' in self.loaded_args: self.loaded_args['auth'] = self.loaded_args['authentication'] del self.loaded_args['authentication'] return True
Load the .mlaunch_startup file that exists in each datadir. Handles different protocol versions.
def _handle_files(self, data): """Handle new files being uploaded""" initial = data.get("set", False) files = data["files"] for f in files: try: fobj = File( self.room, self.conn, f[0], f[1], type=f[2], size=f[3], expire_time=int(f[4]) / 1000, uploader=f[6].get("nick") or f[6].get("user"), ) self.room.filedict = fobj.fid, fobj if not initial: self.conn.enqueue_data("file", fobj) except Exception: import pprint LOGGER.exception("bad file") pprint.pprint(f) if initial: self.conn.enqueue_data("initial_files", self.room.files)
Handle new files being uploaded
def get_provides(self, ignored=tuple()): """ a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map""" if self._provides is None: self._collect_requires_provides() d = self._provides if ignored: d = dict((k, v) for k, v in d.items() if not fnmatches(k, *ignored)) return d
a map of provided classes and class members, and what provides them. ignored is an optional list of globbed patterns indicating packages, classes, etc that shouldn't be included in the provides map
def get_certificate_issuer(self, certificate_issuer_id, **kwargs): # noqa: E501 """Get certificate issuer by ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer(certificate_issuer_id, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str certificate_issuer_id: Certificate issuer ID. The ID of the certificate issuer. (required) :return: CertificateIssuerInfo If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous'): return self.get_certificate_issuer_with_http_info(certificate_issuer_id, **kwargs) # noqa: E501 else: (data) = self.get_certificate_issuer_with_http_info(certificate_issuer_id, **kwargs) # noqa: E501 return data
Get certificate issuer by ID. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.get_certificate_issuer(certificate_issuer_id, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str certificate_issuer_id: Certificate issuer ID. The ID of the certificate issuer. (required) :return: CertificateIssuerInfo If the method is called asynchronously, returns the request thread.
def times(self, query): """ Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa. Args: query (str): Termo para utilizar na busca. Returns: Uma lista de instâncias de cartolafc.TimeInfo, uma para cada time contento o termo utilizado na busca. """ url = '{api_url}/times'.format(api_url=self._api_url) data = self._request(url, params=dict(q=query)) return [TimeInfo.from_dict(time_info) for time_info in data]
Retorna o resultado da busca ao Cartola por um determinado termo de pesquisa. Args: query (str): Termo para utilizar na busca. Returns: Uma lista de instâncias de cartolafc.TimeInfo, uma para cada time contento o termo utilizado na busca.
def transfer(self, payment_id, data={}, **kwargs): """" Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered """ url = "{}/{}/transfers".format(self.base_url, payment_id) return self.post_url(url, data, **kwargs)
Create Transfer for given Payment Id Args: payment_id : Id for which payment object has to be transfered Returns: Payment dict after getting transfered
def createImageObjectList(files,instrpars,group=None, undistort=True, inmemory=False): """ Returns a list of imageObject instances, 1 for each input image in the list of input filenames. """ imageObjList = [] mtflag = False mt_refimg = None for img in files: image = _getInputImage(img,group=group) image.setInstrumentParameters(instrpars) image.compute_wcslin(undistort=undistort) if 'MTFLAG' in image._image['PRIMARY'].header: # check to see whether we are dealing with moving target observations... _keyval = image._image['PRIMARY'].header['MTFLAG'] if not util.is_blank(_keyval): if isinstance(_keyval,bool): mtflag = _keyval else: if 'T' in _keyval: mtflag = True else: mtflag = False else: mtflag = False if mtflag: print("#####\nProcessing Moving Target Observations using reference image as WCS for all inputs!\n#####\n") if mt_refimg is None: mt_refimg = image else: image.set_mt_wcs(mt_refimg) image.inmemory = inmemory # set flag for inmemory processing # Now add (possibly updated) image object to list imageObjList.append(image) return imageObjList
Returns a list of imageObject instances, 1 for each input image in the list of input filenames.
def set_filesystems( name, device, vfstype, opts='-', mount='true', config='/etc/filesystems', test=False, match_on='auto', **kwargs): ''' .. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2 ''' # Fix the opts type if it is a list if isinstance(opts, list): opts = ','.join(opts) # preserve arguments for updating entry_args = { 'name': name, 'dev': device.replace('\\ ', '\\040'), 'vfstype': vfstype, 'opts': opts, 'mount': mount, } view_lines = [] ret = None if 'AIX' not in __grains__['kernel']: return ret # Transform match_on into list--items will be checked later if isinstance(match_on, list): pass elif not isinstance(match_on, six.string_types): raise CommandExecutionError('match_on must be a string or list of strings') elif match_on == 'auto': # Try to guess right criteria for auto.... # added IBM types from sys/vmount.h after btrfs # NOTE: missing some special fstypes here specialFSes = frozenset([ 'none', 'tmpfs', 'sysfs', 'proc', 'fusectl', 'debugfs', 'securityfs', 'devtmpfs', 'cgroup', 'btrfs', 'cdrfs', 'procfs', 'jfs', 'jfs2', 'nfs', 'sfs', 'nfs3', 'cachefs', 'udfs', 'cifs', 'namefs', 'pmemfs', 'ahafs', 'nfs4', 'autofs', 'stnfs']) if vfstype in specialFSes: match_on = ['name'] else: match_on = ['dev'] else: match_on = [match_on] # generate entry and criteria objects, handle invalid keys in match_on entry_ip = _FileSystemsEntry.from_line(entry_args, kwargs) try: criteria = entry_ip.pick(match_on) except KeyError: filterFn = lambda key: key not in _FileSystemsEntry.compatibility_keys invalid_keys = filter(filterFn, match_on) raise CommandExecutionError('Unrecognized keys in match_on: "{0}"'.format(invalid_keys)) # parse file, use ret to cache status if not os.path.isfile(config): raise CommandExecutionError('Bad config file "{0}"'.format(config)) # read in block of filesystem, block starts with '/' till empty line try: fsys_filedict = _filesystems(config, False) for fsys_view in six.viewitems(fsys_filedict): if criteria.match(fsys_view): ret = 'present' if entry_ip.match(fsys_view): view_lines.append(fsys_view) else: ret = 'change' kv = entry_ip['name'] view_lines.append((kv, entry_ip)) else: view_lines.append(fsys_view) except (IOError, OSError) as exc: raise CommandExecutionError('Couldn\'t read from {0}: {1}'.format(config, exc)) # add line if not present or changed if ret is None: for dict_view in six.viewitems(entry_ip.dict_from_entry()): view_lines.append(dict_view) ret = 'new' if ret != 'present': # ret in ['new', 'change']: try: with salt.utils.files.fopen(config, 'wb') as ofile: # The line was changed, commit it! for fsys_view in view_lines: entry = fsys_view[1] mystrg = _FileSystemsEntry.dict_to_lines(entry) ofile.writelines(salt.utils.data.encode(mystrg)) except (IOError, OSError): raise CommandExecutionError('File not writable {0}'.format(config)) return ret
.. versionadded:: 2018.3.3 Verify that this mount is represented in the filesystems, change the mount to match the data passed, or add the mount if it is not present on AIX Provide information if the path is mounted :param name: The name of the mount point where the device is mounted. :param device: The device that is being mounted. :param vfstype: The file system that is used (AIX has two fstypes, fstype and vfstype - similar to Linux fstype) :param opts: Additional options used when mounting the device. :param mount: Mount if not mounted, default True. :param config: Configuration file, default /etc/filesystems. :param match: File systems type to match on, default auto CLI Example: .. code-block:: bash salt '*' mount.set_filesystems /mnt/foo /dev/sdz1 jfs2
def batchInsert(self, itemType, itemAttributes, dataRows): """ Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), (28, u"Jim", u"Fresno"), (43, u"Betty", u"Dubuque")] myStore.batchInsert(FooItem, [FooItem.age, FooItem.name, FooItem.city], myData) @param itemType: an Item subclass to create instances of. @param itemAttributes: an iterable of attributes on the Item subclass. @param dataRows: an iterable of iterables, each the same length as C{itemAttributes} and containing data corresponding to each attribute in it. @return: None. """ class FakeItem: pass _NEEDS_DEFAULT = object() # token for lookup failure fakeOSelf = FakeItem() fakeOSelf.store = self sql = itemType._baseInsertSQL(self) indices = {} schema = [attr for (name, attr) in itemType.getSchema()] for i, attr in enumerate(itemAttributes): indices[attr] = i for row in dataRows: oid = self.store.executeSchemaSQL( _schema.CREATE_OBJECT, [self.store.getTypeID(itemType)]) insertArgs = [oid] for attr in schema: i = indices.get(attr, _NEEDS_DEFAULT) if i is _NEEDS_DEFAULT: pyval = attr.default else: pyval = row[i] dbval = attr._convertPyval(fakeOSelf, pyval) insertArgs.append(dbval) self.executeSQL(sql, insertArgs)
Create multiple items in the store without loading corresponding Python objects into memory. the items' C{stored} callback will not be called. Example:: myData = [(37, u"Fred", u"Wichita"), (28, u"Jim", u"Fresno"), (43, u"Betty", u"Dubuque")] myStore.batchInsert(FooItem, [FooItem.age, FooItem.name, FooItem.city], myData) @param itemType: an Item subclass to create instances of. @param itemAttributes: an iterable of attributes on the Item subclass. @param dataRows: an iterable of iterables, each the same length as C{itemAttributes} and containing data corresponding to each attribute in it. @return: None.
def recursive_directory_listing( log, baseFolderPath, whatToList="all" ): """*list directory contents recursively.* Options to list only files or only directories. **Key Arguments:** - ``log`` -- logger - ``baseFolderPath`` -- path to the base folder to list contained files and folders recursively - ``whatToList`` -- list files only, durectories only or all [ "files" | "dirs" | "all" ] **Return:** - ``matchedPathList`` -- the matched paths **Usage:** .. code-block:: python from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp" ) # OR JUST FILE from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp", whatToList="files" ) # OR JUST FOLDERS from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp", whatToList="dirs" ) print theseFiles """ log.debug('starting the ``recursive_directory_listing`` function') ## VARIABLES ## matchedPathList = [] parentDirectoryList = [baseFolderPath, ] count = 0 while os.listdir(baseFolderPath) and count < 20: count += 1 while len(parentDirectoryList) != 0: childDirList = [] for parentDir in parentDirectoryList: try: thisDirList = os.listdir(parentDir) except Exception, e: log.error(e) continue for d in thisDirList: fullPath = os.path.join(parentDir, d) if whatToList is "all": matched = True elif whatToList is "dirs": matched = os.path.isdir(fullPath) elif whatToList is "files": matched = os.path.isfile(fullPath) else: log.error( 'cound not list files in %s, `whatToList` variable incorrect: [ "files" | "dirs" | "all" ]' % (baseFolderPath,)) sys.exit(0) if matched: matchedPathList.append(fullPath) # UPDATE DIRECTORY LISTING if os.path.isdir(fullPath): childDirList.append(fullPath) parentDirectoryList = childDirList log.debug('completed the ``recursive_directory_listing`` function') return matchedPathList
*list directory contents recursively.* Options to list only files or only directories. **Key Arguments:** - ``log`` -- logger - ``baseFolderPath`` -- path to the base folder to list contained files and folders recursively - ``whatToList`` -- list files only, durectories only or all [ "files" | "dirs" | "all" ] **Return:** - ``matchedPathList`` -- the matched paths **Usage:** .. code-block:: python from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp" ) # OR JUST FILE from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp", whatToList="files" ) # OR JUST FOLDERS from fundamentals.files import recursive_directory_listing theseFiles = recursive_directory_listing( log, baseFolderPath="/tmp", whatToList="dirs" ) print theseFiles
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True, errors='replace', separator='&', cls=None): """Parse a querystring and return it as :class:`MultiDict`. Per default only values are decoded into unicode strings. If `decode_keys` is set to `True` the same will happen for keys. Per default a missing value for a key will default to an empty key. If you don't want that behavior you can set `include_empty` to `False`. Per default encoding errors are ignored. If you want a different behavior you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a `HTTPUnicodeError` is raised. .. versionchanged:: 0.5 In previous versions ";" and "&" could be used for url decoding. This changed in 0.5 where only "&" is supported. If you want to use ";" instead a different `separator` can be provided. The `cls` parameter was added. :param s: a string with the query string to decode. :param charset: the charset of the query string. :param decode_keys: set to `True` if you want the keys to be decoded as well. :param include_empty: Set to `False` if you don't want empty values to appear in the dict. :param errors: the decoding error behavior. :param separator: the pair separator to be used, defaults to ``&`` :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used. """ if cls is None: cls = MultiDict return cls(_url_decode_impl(str(s).split(separator), charset, decode_keys, include_empty, errors))
Parse a querystring and return it as :class:`MultiDict`. Per default only values are decoded into unicode strings. If `decode_keys` is set to `True` the same will happen for keys. Per default a missing value for a key will default to an empty key. If you don't want that behavior you can set `include_empty` to `False`. Per default encoding errors are ignored. If you want a different behavior you can set `errors` to ``'replace'`` or ``'strict'``. In strict mode a `HTTPUnicodeError` is raised. .. versionchanged:: 0.5 In previous versions ";" and "&" could be used for url decoding. This changed in 0.5 where only "&" is supported. If you want to use ";" instead a different `separator` can be provided. The `cls` parameter was added. :param s: a string with the query string to decode. :param charset: the charset of the query string. :param decode_keys: set to `True` if you want the keys to be decoded as well. :param include_empty: Set to `False` if you don't want empty values to appear in the dict. :param errors: the decoding error behavior. :param separator: the pair separator to be used, defaults to ``&`` :param cls: an optional dict class to use. If this is not specified or `None` the default :class:`MultiDict` is used.
def ecc_correct_intra(ecc_manager_intra, ecc_params_intra, field, ecc, enable_erasures=False, erasures_char="\x00", only_erasures=False): """ Correct an intra-field with its corresponding intra-ecc if necessary """ fentry_fields = {"ecc_field": ecc} field_correct = [] # will store each block of the corrected (or already correct) filepath fcorrupted = False # check if field was corrupted fcorrected = True # check if field was corrected (if it was corrupted) errmsg = '' # Decode each block of the filepath for e in entry_assemble(fentry_fields, ecc_params_intra, len(field), '', field): # Check if this block of the filepath is OK, if yes then we just copy it over if ecc_manager_intra.check(e["message"], e["ecc"]): field_correct.append(e["message"]) else: # Else this block is corrupted, we will try to fix it using the ecc fcorrupted = True # Repair the message block and the ecc try: repaired_block, repaired_ecc = ecc_manager_intra.decode(e["message"], e["ecc"], enable_erasures=enable_erasures, erasures_char=erasures_char, only_erasures=only_erasures) except (ReedSolomonError, RSCodecError), exc: # the reedsolo lib may raise an exception when it can't decode. We ensure that we can still continue to decode the rest of the file, and the other files. repaired_block = None repaired_ecc = None errmsg += "- Error: metadata field at offset %i: %s\n" % (entry_pos[0], exc) # Check if the block was successfully repaired: if yes then we copy the repaired block... if repaired_block is not None and ecc_manager_intra.check(repaired_block, repaired_ecc): field_correct.append(repaired_block) else: # ... else it failed, then we copy the original corrupted block and report an error later field_correct.append(e["message"]) fcorrected = False # Join all the blocks into one string to build the final filepath if isinstance(field_correct[0], bytearray): field_correct = [str(x) for x in field_correct] # workaround when using --ecc_algo 3 or 4, because we get a list of bytearrays instead of str field = ''.join(field_correct) # Report errors return (field, fcorrupted, fcorrected, errmsg)
Correct an intra-field with its corresponding intra-ecc if necessary
def download_and_uncompress(self, fileobj, dst_path): """Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unknown object encountered inside the TAR file. """ try: with tarfile.open(mode="r|*", fileobj=fileobj) as tgz: for tarinfo in tgz: abs_target_path = _merge_relative_path(dst_path, tarinfo.name) if tarinfo.isfile(): self._extract_file(tgz, tarinfo, abs_target_path) elif tarinfo.isdir(): tf_v1.gfile.MakeDirs(abs_target_path) else: # We do not support symlinks and other uncommon objects. raise ValueError( "Unexpected object type in tar archive: %s" % tarinfo.type) total_size_str = tf_utils.bytes_to_readable_str( self._total_bytes_downloaded, True) self._print_download_progress_msg( "Downloaded %s, Total size: %s" % (self._url, total_size_str), flush=True) except tarfile.ReadError: raise IOError("%s does not appear to be a valid module." % self._url)
Streams the content for the 'fileobj' and stores the result in dst_path. Args: fileobj: File handle pointing to .tar/.tar.gz content. dst_path: Absolute path where to store uncompressed data from 'fileobj'. Raises: ValueError: Unknown object encountered inside the TAR file.
def _remove_unicode_keys(dictobj): """Convert keys from 'unicode' to 'str' type. workaround for <http://bugs.python.org/issue2646> """ if sys.version_info[:2] >= (3, 0): return dictobj assert isinstance(dictobj, dict) newdict = {} for key, value in dictobj.items(): if type(key) is unicode: key = key.encode('utf-8') newdict[key] = value return newdict
Convert keys from 'unicode' to 'str' type. workaround for <http://bugs.python.org/issue2646>
def _get_numbering(document, numid, ilvl): """Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error. """ try: abs_num = document.numbering[numid] return document.abstruct_numbering[abs_num][ilvl]['numFmt'] except: return 'bullet'
Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error.
def writeTicks(self, ticks): ''' read quotes ''' self.__writeData(self.targetPath(ExcelDAM.TICK), TICK_FIELDS, [[getattr(tick, field) for field in TICK_FIELDS] for tick in ticks])
read quotes
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'sentence_id') and self.sentence_id is not None: _dict['sentence_id'] = self.sentence_id if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] if hasattr(self, 'tone_categories') and self.tone_categories is not None: _dict['tone_categories'] = [ x._to_dict() for x in self.tone_categories ] if hasattr(self, 'input_from') and self.input_from is not None: _dict['input_from'] = self.input_from if hasattr(self, 'input_to') and self.input_to is not None: _dict['input_to'] = self.input_to return _dict
Return a json dictionary representing this model.
def clear_copyright_registration(self): """Removes the copyright registration. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.repository.AssetContentForm.clear_url_template if (self.get_copyright_registration_metadata().is_read_only() or self.get_copyright_registration_metadata().is_required()): raise errors.NoAccess() self._my_map['copyrightRegistration'] = self._copyright_registration_default
Removes the copyright registration. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
async def post_subscribe(request): """ --- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: exchange: type: string routing: type: string """ args = await request.json() get_listener(request.app).subscribe( args['exchange'], args['routing'] ) return web.Response()
--- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: exchange: type: string routing: type: string
def run(self, collector, image, available_actions, tasks, **extras): """Run this task""" task_func = available_actions[self.action] configuration = collector.configuration.wrapped() if self.options: if image: configuration.update({"images": {image: self.options}}) else: configuration.update(self.options) # args like --port and the like should override what's in the options # But themselves be overridden by the overrides configuration.update(configuration["args_dict"].as_dict(), source="<args_dict>") if self.overrides: overrides = {} for key, val in self.overrides.items(): overrides[key] = val if isinstance(val, MergedOptions): overrides[key] = dict(val.items()) configuration.update(overrides) if task_func.needs_image: self.find_image(image, configuration) image = configuration["images"][image] image.find_missing_env() from harpoon.collector import Collector new_collector = Collector() new_collector.configuration = configuration new_collector.configuration_file = collector.configuration_file artifact = configuration["harpoon"].artifact return task_func(new_collector, image=image, tasks=tasks, artifact=artifact, **extras)
Run this task
def destroy(self): """Recursively destroy all Controllers The method remove all controllers, which calls the destroy method of the child controllers. Then, all registered models are relieved and and the widget hand by the initial view argument is destroyed. """ self.disconnect_all_signals() controller_names = [key for key in self.__child_controllers] for controller_name in controller_names: self.remove_controller(controller_name) self.relieve_all_models() if self.parent: self.__parent = None if self._view_initialized: # print(self.__class__.__name__, "destroy view", self.view, self) self.view.get_top_widget().destroy() self.view = None self._Observer__PROP_TO_METHS.clear() # prop name --> set of observing methods self._Observer__METH_TO_PROPS.clear() # method --> set of observed properties self._Observer__PAT_TO_METHS.clear() # like __PROP_TO_METHS but only for pattern names (to optimize search) self._Observer__METH_TO_PAT.clear() # method --> pattern self._Observer__PAT_METH_TO_KWARGS.clear() # (pattern, method) --> info self.observe = None else: logger.warning("The controller {0} seems to be destroyed before the view was fully initialized. {1} " "Check if you maybe do not call {2} or there exist most likely threading problems." "".format(self.__class__.__name__, self.model, ExtendedController.register_view))
Recursively destroy all Controllers The method remove all controllers, which calls the destroy method of the child controllers. Then, all registered models are relieved and and the widget hand by the initial view argument is destroyed.
def symlink_exists(self, symlink): """Checks whether a symbolic link exists in the guest. in symlink of type str Path to the alleged symbolic link. Guest path style. return exists of type bool Returns @c true if the symbolic link exists. Returns @c false if it does not exist, if the file system object identified by the path is not a symbolic link, or if the object type is inaccessible to the user, or if the @a symlink argument is empty. raises :class:`OleErrorNotimpl` The method is not implemented yet. """ if not isinstance(symlink, basestring): raise TypeError("symlink can only be an instance of type basestring") exists = self._call("symlinkExists", in_p=[symlink]) return exists
Checks whether a symbolic link exists in the guest. in symlink of type str Path to the alleged symbolic link. Guest path style. return exists of type bool Returns @c true if the symbolic link exists. Returns @c false if it does not exist, if the file system object identified by the path is not a symbolic link, or if the object type is inaccessible to the user, or if the @a symlink argument is empty. raises :class:`OleErrorNotimpl` The method is not implemented yet.
def add_to_message(data, indent_level=0) -> list: """Adds data to the message object""" message = [] if isinstance(data, str): message.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return message for line in data: offset = 0 if isinstance(line, str) else 1 message += add_to_message(line, indent_level + offset) return message
Adds data to the message object
def rss_create(channel, articles): """Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which will \ result to `<dict_key>dict_value</dict_key>` :type articles: list(dict(str,str)) :return: root element :rtype: ElementTree.Element """ channel = channel.copy() # TODO use deepcopy # list will not clone the dictionaries in the list and `elemen_from_dict` # pops items from them articles = list(articles) rss = ET.Element('rss') rss.set('version', '2.0') channel_node = ET.SubElement(rss, 'channel') element_from_dict(channel_node, channel, 'title') element_from_dict(channel_node, channel, 'link') element_from_dict(channel_node, channel, 'description') element_from_dict(channel_node, channel, 'language') for article in articles: item = ET.SubElement(channel_node, 'item') element_from_dict(item, article, 'title') element_from_dict(item, article, 'description') element_from_dict(item, article, 'link') for key in article: complex_el_from_dict(item, article, key) return ET.ElementTree(rss)
Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which will \ result to `<dict_key>dict_value</dict_key>` :type articles: list(dict(str,str)) :return: root element :rtype: ElementTree.Element
def confirm(self, tid, out_sid, session): '''taobao.logistics.online.confirm 确认发货通知接口 确认发货的目的是让交易流程继承走下去,确认发货后交易状态会由【买家已付款】变为【卖家已发货】,然后买家才可以确认收货,货款打入卖家账号。货到付款的订单除外''' request = TOPRequest('taobao.logistics.online.confirm') request['tid'] = tid request['out_sid'] = out_sid self.create(self.execute(request, session), fields = ['shipping',], models = {'shipping':Shipping}) return self.shipping
taobao.logistics.online.confirm 确认发货通知接口 确认发货的目的是让交易流程继承走下去,确认发货后交易状态会由【买家已付款】变为【卖家已发货】,然后买家才可以确认收货,货款打入卖家账号。货到付款的订单除外
def datacenters(gandi, id): """List available datacenters.""" output_keys = ['iso', 'name', 'country', 'dc_code', 'status'] if id: output_keys.append('id') result = gandi.datacenter.list() for num, dc in enumerate(result): if num: gandi.separator_line() output_datacenter(gandi, dc, output_keys, justify=10) return result
List available datacenters.
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except TypeError: map = {} map[path] = encoding self._settings.setValue('cachedFileEncodings', json.dumps(map))
Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache
def set_permutation_symmetry(force_constants): """Enforce permutation symmetry to force cosntants by Phi_ij_ab = Phi_ji_ba i, j: atom index a, b: Cartesian axis index This is not necessary for harmonic phonon calculation because this condition is imposed when making dynamical matrix Hermite in dynamical_matrix.py. """ fc_copy = force_constants.copy() for i in range(force_constants.shape[0]): for j in range(force_constants.shape[1]): force_constants[i, j] = (force_constants[i, j] + fc_copy[j, i].T) / 2
Enforce permutation symmetry to force cosntants by Phi_ij_ab = Phi_ji_ba i, j: atom index a, b: Cartesian axis index This is not necessary for harmonic phonon calculation because this condition is imposed when making dynamical matrix Hermite in dynamical_matrix.py.
def _file_read(path): ''' Read a file and return content ''' content = False if os.path.exists(path): with salt.utils.files.fopen(path, 'r+') as fp_: content = salt.utils.stringutils.to_unicode(fp_.read()) fp_.close() return content
Read a file and return content
def process_raw(self, raw: dict) -> None: """Pre-process raw dict. Prepare parameters to work with APIItems. """ raw_ports = {} for param in raw: port_index = REGEX_PORT_INDEX.search(param).group(0) if port_index not in raw_ports: raw_ports[port_index] = {} name = param.replace(IOPORT + '.I' + port_index + '.', '') raw_ports[port_index][name] = raw[param] super().process_raw(raw_ports)
Pre-process raw dict. Prepare parameters to work with APIItems.
def _definition_from_example(example): """Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json """ assert isinstance(example, dict) def _has_simple_type(value): accepted = (str, int, float, bool) return isinstance(value, accepted) definition = { 'type': 'object', 'properties': {}, } for key, value in example.items(): if not _has_simple_type(value): raise Exception("Not implemented yet") ret_value = None if isinstance(value, str): ret_value = {'type': 'string'} elif isinstance(value, int): ret_value = {'type': 'integer', 'format': 'int64'} elif isinstance(value, float): ret_value = {'type': 'number', 'format': 'double'} elif isinstance(value, bool): ret_value = {'type': 'boolean'} else: raise Exception("Not implemented yet") definition['properties'][key] = ret_value return definition
Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json
def _save_current(self, settings, axes_active=True): ''' Sets the current in Amperes (A) by axis. Currents are limited to be between 0.0-2.0 amps per axis motor. Note: this method does not send gcode commands, but instead stores the desired current setting. A seperate call to _generate_current_command() will return a gcode command that can be used to set Smoothie's current settings Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C') and floating point number for current (generally between 0.1 and 2) ''' self._active_axes.update({ ax: axes_active for ax in settings.keys() }) self._current_settings['now'].update(settings) log.debug("_save_current: {}".format(self.current))
Sets the current in Amperes (A) by axis. Currents are limited to be between 0.0-2.0 amps per axis motor. Note: this method does not send gcode commands, but instead stores the desired current setting. A seperate call to _generate_current_command() will return a gcode command that can be used to set Smoothie's current settings Dict with axes as valies (e.g.: 'X', 'Y', 'Z', 'A', 'B', or 'C') and floating point number for current (generally between 0.1 and 2)