code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@server.route('/getTasks', methods=['GET']) <NEW_LINE> def get_task(): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> global waiting_list <NEW_LINE> global success_list <NEW_LINE> global app_list <NEW_LINE> last = len(waiting_list) <NEW_LINE> if last == 0: <NEW_LINE> <INDENT> ret["success"] = True <NEW_LINE> ret["last"] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> needTaskNum = request.args.get('taskNum', '0') <NEW_LINE> returnNum = int(needTaskNum) <NEW_LINE> if returnNum > last: <NEW_LINE> <INDENT> returnNum = last <NEW_LINE> <DEDENT> applist = waiting_list[:returnNum] <NEW_LINE> waiting_list = waiting_list[returnNum:] <NEW_LINE> crawling_list.extend(applist) <NEW_LINE> for i in range(returnNum): <NEW_LINE> <INDENT> applist[i].status = App_Status.CRAWLING <NEW_LINE> applist[i] = applist[i].json_obj() <NEW_LINE> <DEDENT> ret["applist"] = applist <NEW_LINE> ret["success"] = True <NEW_LINE> ret["last"] = last - returnNum <NEW_LINE> print(applist) <NEW_LINE> <DEDENT> print("下发任务, 当前剩余任务数量 : %d" % (last)) <NEW_LINE> return jsonify(ret) | 获取 任务, 由爬虫自己控制数量, 我们暂时这里只处理下发任务和收集数据。 格式为 {last:1,success:true,app:{...}} | 625941bec432627299f04b6e |
def __build_tuples(self): <NEW_LINE> <INDENT> if self.num_words < self.length: <NEW_LINE> <INDENT> Exception("Input file size too small.") <NEW_LINE> <DEDENT> for i in range(self.num_words - (self.length - 1)): <NEW_LINE> <INDENT> yield tuple(self.words[i+j] for j in range(self.length)) | Build the tuples from the word list for the database | 625941be3c8af77a43ae36c8 |
def makeColoredRect(corner, width, height, color, win): <NEW_LINE> <INDENT> corner2 = corner.clone() <NEW_LINE> corner2.move(width, -height) <NEW_LINE> rect = Rectangle(corner, corner2) <NEW_LINE> rect.setFill(color) <NEW_LINE> rect.draw(win) <NEW_LINE> return rect | Return a Rectangle drawn in win with the upper left corner
and color specified. | 625941befff4ab517eb2f364 |
def make_sure(name,password,address): <NEW_LINE> <INDENT> f1 = open(address,'r') <NEW_LINE> f = f1.readlines() <NEW_LINE> f1.close() <NEW_LINE> for line in f: <NEW_LINE> <INDENT> out_list = [] <NEW_LINE> line = line.split() <NEW_LINE> if len(line)==0 : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if line[0] == name and line[1] == password: <NEW_LINE> <INDENT> out_list.append(True) <NEW_LINE> try: <NEW_LINE> <INDENT> salary = line[2] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> salary = None <NEW_LINE> <DEDENT> if salary is None: <NEW_LINE> <INDENT> out_list.append(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> salary = int(salary) <NEW_LINE> out_list.append(salary) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> out_list.append('wrong') <NEW_LINE> <DEDENT> <DEDENT> return out_list <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_list.append(None) <NEW_LINE> <DEDENT> return out_list | :param name: 账户的名字
:param password: 账户密码
:param address: 账户密码存放地址
:return: 该账户是否正确 是否存在salary,如有则返回,第一项为账户是否真确,第二为是否有工资,有则返回 | 625941bed58c6744b4257b8a |
def validate_data(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> res_pid = self.validate_data_product_id() <NEW_LINE> if not res_pid: <NEW_LINE> <INDENT> args.append("Product ID") <NEW_LINE> <DEDENT> res_cnd = self.validate_data_condition() <NEW_LINE> if not res_cnd: <NEW_LINE> <INDENT> args.append("Condition") <NEW_LINE> <DEDENT> res_qty = self.validate_data_quantity() <NEW_LINE> if not res_qty: <NEW_LINE> <INDENT> args.append("Quantity") <NEW_LINE> <DEDENT> res_lvl = self.validate_data_restock_level() <NEW_LINE> if not res_lvl: <NEW_LINE> <INDENT> args.append("Restock Level") <NEW_LINE> <DEDENT> res_avl = self.validate_data_available() <NEW_LINE> if not res_avl: <NEW_LINE> <INDENT> args.append("Available") <NEW_LINE> <DEDENT> if not (res_pid and res_cnd and res_qty and res_lvl and res_avl): <NEW_LINE> <INDENT> msg = "Error in data: {}".format(args) <NEW_LINE> raise DataValidationError(msg) <NEW_LINE> <DEDENT> return True | VALIDATING DATA FORMATS | 625941be8da39b475bd64e9a |
def procura_sul(): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for palavra in palavras: <NEW_LINE> <INDENT> for coluna in range(grelha_nr_colunas(grelha)): <NEW_LINE> <INDENT> coord = coordenada(0, coluna, 'S') <NEW_LINE> frase = grelha_linha(grelha, coord) <NEW_LINE> linha = palavra_em_frase(frase, palavra) <NEW_LINE> if linha != -1: <NEW_LINE> <INDENT> res = res + [(palavra, coordenada(linha, coluna, 'S'))] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return resposta(res) | procura_sul: sub-funcao responsavel pela procura das palavras da
sopa de letras na direcao Sul, devolvendo uma resposta com as palavras
escritas nessa direcao | 625941bea79ad161976cc06f |
@hook.command("killers", autohelp=False) <NEW_LINE> def killers(text, chan, conn, db): <NEW_LINE> <INDENT> if chan in opt_out: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> killers = defaultdict(int) <NEW_LINE> out = "" <NEW_LINE> if text.lower() == 'global': <NEW_LINE> <INDENT> out = "Duck killer scores across the network: " <NEW_LINE> scores = db.execute(select([table.c.name, table.c.shot]) .where(table.c.network == conn.name) .order_by(desc(table.c.shot))) <NEW_LINE> if scores: <NEW_LINE> <INDENT> for row in scores: <NEW_LINE> <INDENT> if row[1] == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> killers[row[0]] += row[1] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return "it appears no one has killed any ducks yet." <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> out = "Duck killer scores in {}: ".format(chan) <NEW_LINE> scores = db.execute(select([table.c.name, table.c.shot]) .where(table.c.network == conn.name) .where(table.c.chan == chan.lower()) .order_by(desc(table.c.shot))) <NEW_LINE> if scores: <NEW_LINE> <INDENT> for row in scores: <NEW_LINE> <INDENT> if row[1] == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> killers[row[0]] += row[1] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return "it appears no one has killed any ducks yet." <NEW_LINE> <DEDENT> <DEDENT> topkillers = sorted(killers.items(), key=operator.itemgetter(1), reverse = True) <NEW_LINE> out += ' • '.join(["{}: {}".format('\x02' + k[:1] + u'\u200b' + k[1:] + '\x02', str(v)) for k, v in topkillers]) <NEW_LINE> out = smart_truncate(out) <NEW_LINE> return out | Prints a list of the top duck killers in the channel, if 'global' is specified all channels in the database are included. | 625941be442bda511e8be346 |
def download_data(): <NEW_LINE> <INDENT> urls = get_urls() <NEW_LINE> if LIMIT: <NEW_LINE> <INDENT> urls = urls[:LIMIT] <NEW_LINE> <DEDENT> if not isdir(PATH_SEQ): <NEW_LINE> <INDENT> mkpath(PATH_SEQ) <NEW_LINE> <DEDENT> f_error = open(PATH_DATA + "/error_log.txt", "w") <NEW_LINE> thread_pool = ThreadPool(processes=NB_THREADS) <NEW_LINE> res = thread_pool.map(_download, urls) <NEW_LINE> print("######## errors founds:") <NEW_LINE> for err in res: <NEW_LINE> <INDENT> if err: <NEW_LINE> <INDENT> print(err) <NEW_LINE> f_error.write('{0}\n'.format(err)) | download dataset from ncbi | 625941be5f7d997b871749bf |
def __init__(self, name, description : str = None, version : str = None, author : str = None, defaults : MessageDefaults = None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.version = version <NEW_LINE> self.author = author <NEW_LINE> self.current_room = None <NEW_LINE> self.previous_room = None <NEW_LINE> self.starting_room = None <NEW_LINE> self.inventory = [] <NEW_LINE> self._start_time = time.time() <NEW_LINE> self.defaults = defaults or MessageDefaults() <NEW_LINE> if not presence.is_in_world("amber"): <NEW_LINE> <INDENT> presence.add_to_world(self, "amber") | The main class of the Amber engine.
:param name: Game name
:param description: Game description
:param version: Version of your game
:param author: You, the author
:param defaults: MessageDefaults instance | 625941bee1aae11d1e749bdf |
def _restart_openstack_service(self): <NEW_LINE> <INDENT> self.client.run('service cinder-volume restart') <NEW_LINE> time.sleep(3) <NEW_LINE> return self._is_cinder_running() | Restart service on openstack | 625941be76d4e153a657ea5a |
def fget_object(self, bucket_name, object_name, file_path): <NEW_LINE> <INDENT> is_valid_bucket_name(bucket_name) <NEW_LINE> is_non_empty_string(object_name) <NEW_LINE> stat = self.stat_object(bucket_name, object_name) <NEW_LINE> file_is_dir = os.path.isdir(file_path) <NEW_LINE> if file_is_dir: <NEW_LINE> <INDENT> raise OSError("file is a directory.") <NEW_LINE> <DEDENT> top_level_dir = os.path.dirname(file_path) <NEW_LINE> if top_level_dir: <NEW_LINE> <INDENT> mkdir_p(top_level_dir) <NEW_LINE> <DEDENT> file_part_path = file_path + stat.etag + '.part.minio' <NEW_LINE> with open(file_part_path, 'ab') as file_part_data: <NEW_LINE> <INDENT> file_statinfo = os.stat(file_part_path) <NEW_LINE> response = self._get_partial_object(bucket_name, object_name, offset=file_statinfo.st_size, length=0) <NEW_LINE> content_size = int(response.headers['content-length']) <NEW_LINE> total_written = 0 <NEW_LINE> for data in response.stream(amt=1024*1024): <NEW_LINE> <INDENT> file_part_data.write(data) <NEW_LINE> total_written += len(data) <NEW_LINE> <DEDENT> if total_written < content_size: <NEW_LINE> <INDENT> msg = 'Data written {0} bytes is smaller than the' 'specified size {1} bytes'.format(total_written, content_size) <NEW_LINE> raise InvalidSizeError(msg) <NEW_LINE> <DEDENT> if total_written > content_size: <NEW_LINE> <INDENT> msg = 'Data written {0} bytes is in excess than the' 'specified size {1} bytes'.format(total_written, content_size) <NEW_LINE> raise InvalidSizeError(msg) <NEW_LINE> <DEDENT> <DEDENT> file_part_data.close() <NEW_LINE> os.rename(file_part_path, file_path) | Retrieves an object from a bucket and writes at file_path.
Examples:
minio.fget_object('foo', 'bar', 'localfile')
:param bucket_name: Bucket to read object from.
:param object_name: Name of the object to read.
:param file_path: Local file path to save the object. | 625941be6aa9bd52df036ccd |
def __init__(self, lit): <NEW_LINE> <INDENT> self.__lit = lit | Creates a new L() instance.
:param lit: Literal to match
:type lit: object | 625941bea8ecb033257d2ff8 |
def define_components(m): <NEW_LINE> <INDENT> m.FUEL_BANS = Set(dimen=2, initialize=[('LSFO', 2017)]) <NEW_LINE> m.BANNED_FUEL_DISPATCH_POINTS = Set(dimen=3, initialize=lambda m: [(g, tp, f) for (f, y) in m.FUEL_BANS for g in m.GENERATION_PROJECTS_BY_FUEL[f] for pe in m.PERIODS if m.period_end[pe] >= y for tp in m.TPS_IN_PERIOD[pe] if (g, tp) in m.GEN_TPS ] ) <NEW_LINE> m.ENFORCE_FUEL_BANS = Constraint(m.BANNED_FUEL_DISPATCH_POINTS, rule = lambda m, g, tp, f: m.DispatchGenByFuel[g, tp, f] == 0 ) | prevent non-cogen plants from burning pure LSFO after 2017 due to MATS emission restrictions | 625941be956e5f7376d70d99 |
def del_item(self, jid: OptJid, node: Optional[str], ifrom: OptJid, data: Dict[str, str]): <NEW_LINE> <INDENT> if self.node_exists(jid, node): <NEW_LINE> <INDENT> self.get_node(jid, node)['items'].del_item( data.get('ijid', ''), node=data.get('inode', None)) | Remove an item from a JID/node combination.
The data parameter may include:
:param ijid: JID of the item to remove.
:param inode: Optional extra identifying information. | 625941be2eb69b55b151c7d6 |
def reachability_helper(G, cur, chain, visited, mermap, path_d, debug=False): <NEW_LINE> <INDENT> if cur in visited: <NEW_LINE> <INDENT> if len(chain) >= 2: <NEW_LINE> <INDENT> if debug: pdb.set_trace() <NEW_LINE> log.debug("chain found! {0}".format(chain + [cur])) <NEW_LINE> collapse_chain(G, chain+[cur], mermap, path_d) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> visited[cur] = 1 <NEW_LINE> indeg = G.in_degree(cur) <NEW_LINE> outdeg = G.out_degree(cur) <NEW_LINE> if indeg == 1: <NEW_LINE> <INDENT> if outdeg == 0 or outdeg > 1: <NEW_LINE> <INDENT> if len(chain) >= 2: <NEW_LINE> <INDENT> if debug: pdb.set_trace() <NEW_LINE> log.debug("chain found! {0}".format(chain + [cur])) <NEW_LINE> collapse_chain(G, chain+[cur], mermap, path_d) <NEW_LINE> <DEDENT> for n in G.successors(cur): <NEW_LINE> <INDENT> reachability_helper(G, n, [], visited, mermap, path_d, debug) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> reachability_helper(G, next(G.successors(cur)), chain + [cur], visited, mermap, path_d, debug) <NEW_LINE> <DEDENT> <DEDENT> elif outdeg == 1: <NEW_LINE> <INDENT> if indeg >= 1 and len(chain) >= 2: <NEW_LINE> <INDENT> if debug: pdb.set_trace() <NEW_LINE> log.debug("chain found! {0}".format(chain + [cur])) <NEW_LINE> collapse_chain(G, chain+[cur], mermap, path_d) <NEW_LINE> <DEDENT> reachability_helper(G, next(G.successors(cur)), [cur], visited, mermap, path_d, debug) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for n in G.successors(cur): <NEW_LINE> <INDENT> reachability_helper(G, n, [], visited, mermap, path_d, debug) | a chain started must have outdeg = 1 (indeg does not matter)
a chain ender must have indeg = 1 (outdeg does not matter)
a chain member (neither start/end) must have indeg = 1 and outdeg = 1 | 625941be76e4537e8c35159b |
def test_resource_domain_type_resource_get_domain_type_get(self): <NEW_LINE> <INDENT> pass | Test case for resource_domain_type_resource_get_domain_type_get
Returns domain type identified by given id. # noqa: E501 | 625941be8c0ade5d55d3e8e5 |
def removeNthFromEnd(self, head, n): <NEW_LINE> <INDENT> preNode = head <NEW_LINE> nextNode = head.next <NEW_LINE> tmp = None <NEW_LINE> while not nextNode == None: <NEW_LINE> <INDENT> preNode.next = tmp <NEW_LINE> tmp = preNode <NEW_LINE> preNode = nextNode <NEW_LINE> nextNode = nextNode.next <NEW_LINE> <DEDENT> preNode.next = tmp <NEW_LINE> head = preNode <NEW_LINE> if n==1: <NEW_LINE> <INDENT> return head.next <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = 1 <NEW_LINE> while i < n-1: <NEW_LINE> <INDENT> nextNode = nextNode.next <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> nextNode.next = nextNode.next.next <NEW_LINE> return head | :type head: ListNode
:type n: int
:rtype: ListNode | 625941be56ac1b37e62640fe |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(KubernetesCustomizationParameters, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result | Returns the model properties as a dict | 625941be2c8b7c6e89b356ec |
def pc_nproduced(self): <NEW_LINE> <INDENT> return _blocks_swig1.stream_to_tagged_stream_sptr_pc_nproduced(self) | pc_nproduced(stream_to_tagged_stream_sptr self) -> float | 625941beb7558d58953c4e43 |
def send_password_reset_notice(user): <NEW_LINE> <INDENT> if config_value("SEND_PASSWORD_RESET_NOTICE_EMAIL"): <NEW_LINE> <INDENT> _security._send_mail( config_value("EMAIL_SUBJECT_PASSWORD_NOTICE"), user.email, "reset_notice", user=user, ) | Sends the password reset notice email for the specified user.
:param user: The user to send the notice to | 625941be711fe17d8254229b |
def __init__(self, bytes = None, timestamp = None, **kv): <NEW_LINE> <INDENT> if bytes is None: <NEW_LINE> <INDENT> request = pcs.StringField("request", 65535*8) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = pcs.StringField("request", len(bytes)*8) <NEW_LINE> <DEDENT> pcs.Packet.__init__(self, [request], bytes = bytes, **kv) <NEW_LINE> self.description = "initialize a TCP packet" <NEW_LINE> if timestamp is None: <NEW_LINE> <INDENT> self.timestamp = time.time() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.timestamp = timestamp <NEW_LINE> <DEDENT> self.data = None | initialize a TCP packet | 625941be71ff763f4b5495b1 |
def merge_head_prediction(start_idx, output_dict, keys): <NEW_LINE> <INDENT> for key in keys: <NEW_LINE> <INDENT> cur_output = output_dict[key][start_idx:] <NEW_LINE> if len(cur_output) == 0: continue <NEW_LINE> merged_output = tf.concat(cur_output, axis=1) <NEW_LINE> output_dict[key].append(merged_output) <NEW_LINE> <DEDENT> return | Merge items in output dict from start_idx to -1, and add the merged result to output_dict
for each item in output_dict, it has a shape of [bs, npoint, ...]
merge them on npoint dimension | 625941bebf627c535bc130f9 |
def isMatch(self, s, pattern): <NEW_LINE> <INDENT> memo = {} <NEW_LINE> def isMatchHelper(sStart, patternStart): <NEW_LINE> <INDENT> if (sStart, patternStart) in memo: <NEW_LINE> <INDENT> return memo[(sStart, patternStart)] <NEW_LINE> <DEDENT> elif len(pattern) == patternStart: <NEW_LINE> <INDENT> ans = (len(s) == sStart) <NEW_LINE> <DEDENT> elif len(s) - sStart >= 1 and (s[sStart] == pattern[patternStart] or pattern[patternStart] == '.'): <NEW_LINE> <INDENT> if len(pattern) - patternStart >= 2 and pattern[patternStart + 1] == '*': <NEW_LINE> <INDENT> ans = isMatchHelper(sStart, patternStart + 2) or isMatchHelper(sStart + 1, patternStart) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ans = isMatchHelper(sStart + 1, patternStart + 1) <NEW_LINE> <DEDENT> <DEDENT> elif len(pattern) - patternStart >= 2 and pattern[patternStart + 1] == '*': <NEW_LINE> <INDENT> ans = isMatchHelper(sStart, patternStart + 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ans = False <NEW_LINE> <DEDENT> memo[(sStart, patternStart)] = ans <NEW_LINE> return ans <NEW_LINE> <DEDENT> return isMatchHelper(0, 0) | :type s: str
:type p: str
:rtype: bool
>>> sol = Solution().isMatch
>>> sol("aa", "a")
False
>>> sol("aa", "a*")
True
>>> sol("ab", ".*")
True
>>> sol("aab", "c*a*b")
True
>>> sol("mississippi", "mis*is*p*")
False
>>> sol("aaaaab", "a*aab")
True
>>> sol("aaaaab", "a.*ab")
True
>>> sol("abcdabcdabcd", "a.*dab.*d")
True
>>> sol("ab", ".*c")
False | 625941be4428ac0f6e5ba71c |
def hashablize(obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hash(obj) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> if isinstance(obj, dict): <NEW_LINE> <INDENT> return tuple( (k, hashablize(v)) for (k, v) in sorted(obj.items())) <NEW_LINE> <DEDENT> elif hasattr(obj, '__iter__'): <NEW_LINE> <INDENT> return tuple(hashablize(o) for o in obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError( "Can't hashablize object of type %r" % type(obj)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return obj | Convert a container hierarchy into one that can be hashed.
Don't use this with recursive structures!
Also, this won't be useful if you pass dictionaries with
keys that don't have a total order.
Actually, maybe you're best off not using this function at all.
http://stackoverflow.com/a/985369/4117209 | 625941be94891a1f4081b9d2 |
def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.setDaemon(True) <NEW_LINE> self.buffer = '' <NEW_LINE> self.read_len = 0 <NEW_LINE> self.timer = 0 <NEW_LINE> self.closed = False <NEW_LINE> self.acc_lock = allocate_lock() <NEW_LINE> print('EP Debug: Creating a threaded logger...') | Mock Logger. | 625941be4c3428357757c254 |
@click.command() <NEW_LINE> @click.option( "--default-editor", "-e", default=None, type=str, help="try to use this editor instead (e.g. notepad.exe)", ) <NEW_LINE> def edit(default_editor): <NEW_LINE> <INDENT> config_file = _configloc() <NEW_LINE> if config_file: <NEW_LINE> <INDENT> config_file_str = str(config_file.resolve()) <NEW_LINE> if default_editor is not None: <NEW_LINE> <INDENT> args = [default_editor, config_file_str] <NEW_LINE> click.echo(f"[cellpy] (edit) Calling '{default_editor}'") <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.call(args) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> click.echo(f"[cellpy] (edit) Failed!") <NEW_LINE> click.echo( "[cellpy] (edit) Try 'cellpy edit -e notepad.exe' if you are on Windows" ) <NEW_LINE> <DEDENT> <DEDENT> if default_editor is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import editor <NEW_LINE> editor.edit(filename=config_file_str) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> click.echo(f"[cellpy] (edit) Failed!") <NEW_LINE> click.echo( f"[cellpy] (edit) Searching for editors uses the python-editor package" ) <NEW_LINE> click.echo(f"[cellpy] (edit) Possible fixes:") <NEW_LINE> click.echo( f"[cellpy] (edit) - provide a default editor " f"using the -e option (e.g. cellpy edit -e notepad.exe)" ) <NEW_LINE> click.echo( f"[cellpy] (edit) - install teh python-editor package " f"(pip install python-editor)" ) | Edit your cellpy config file. | 625941bed164cc6175782c78 |
def getPowerTransformerInfo(self): <NEW_LINE> <INDENT> return self._PowerTransformerInfo | Power transformer data.
| 625941be5fcc89381b1e15e7 |
def parsed_version(version): <NEW_LINE> <INDENT> return tuple(map(int, (version.split(".")[:3]))) | Converts string X.X.X.Y to int tuple (X, X, X) | 625941be01c39578d7e74d65 |
def hasItem(self): <NEW_LINE> <INDENT> return self._item is not None | Checks if the container item is not None
:returns: Depending on success or failure of the method it returns True
or False
:rtype: bool | 625941beb57a9660fec337ac |
def _check_match_del(self, data): <NEW_LINE> <INDENT> return self._check_match_simple_tag("del", data) | Check if a possible tag match is a valid "del" tag.
:param data: Data starting with the possible tag
:return: (bool) True if valid
:since: v1.0.0
| 625941be796e427e537b04ee |
def scrape_list_of_topics(): <NEW_LINE> <INDENT> g = glob.glob('archive/*/*/*') <NEW_LINE> g = [x.split('/')[3] for x in g] <NEW_LINE> s = set(g) <NEW_LINE> g = list(s) <NEW_LINE> g.sort() <NEW_LINE> return g | Glob the archive to figure out what topics we have available | 625941be2ae34c7f2600d05c |
def _generate_svg(self, dot_format, dot_string): <NEW_LINE> <INDENT> command = [ 'dot', '-K', dot_format, '-T' 'svg', '-Nfontname=Schoolbook', '-Nfontsize=11'] <NEW_LINE> file_in = dot_string.encode('utf-8') <NEW_LINE> file_out = subprocess.run( command, stdout=subprocess.PIPE, input=file_in ) <NEW_LINE> result = file_out.stdout.decode('utf-8') <NEW_LINE> parts = result.split('<svg', 1) <NEW_LINE> if len(parts) == 2: <NEW_LINE> <INDENT> img_tag = "<img src='data:image/svg+xml;utf8,<svg%s' />" <NEW_LINE> html = img_tag % parts[1] <NEW_LINE> return html <NEW_LINE> <DEDENT> return alert("Error generating SVG.") | Perform the DOT system call, trimming first 6 lines; graphviz MUST be
installed; see requirements_apt.txt; ONLY tested on *NIX. | 625941be29b78933be1e55db |
def __init__(self, *args): <NEW_LINE> <INDENT> this = _osgAnimation.new_VertexList(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this | __init__(std::vector<(VertexIndexWeight)> self) -> VertexList
__init__(std::vector<(VertexIndexWeight)> self, VertexList arg2) -> VertexList
__init__(std::vector<(VertexIndexWeight)> self, std::vector< std::pair< int,float > >::size_type size) -> VertexList
__init__(std::vector<(VertexIndexWeight)> self, std::vector< std::pair< int,float > >::size_type size, VertexIndexWeight value) -> VertexList | 625941be9f2886367277a7ba |
def logServerData(self, line): <NEW_LINE> <INDENT> l = irc_line() <NEW_LINE> try: <NEW_LINE> <INDENT> l.parseLine(line) <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if l.messageType == "QUIT" or l.messageType == "NICK": <NEW_LINE> <INDENT> if l.nickname in self.channelsByNickname: <NEW_LINE> <INDENT> for c in self.channelsByNickname[l.nickname]: <NEW_LINE> <INDENT> l.channel = c <NEW_LINE> self.db.logIrcLine(l) <NEW_LINE> <DEDENT> del self.channelsByNickname[l.nickname] <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> if l.channel == self.logConfig.get('nickname'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.logConfig.get('debug'): <NEW_LINE> <INDENT> print("[Server] %s" % l) <NEW_LINE> <DEDENT> self.db.logIrcLine(l) | Receive server logs for messages sent from the IRC server that aren't channel messages (e.g QUIT notices). | 625941bed6c5a10208143f73 |
def test_area_only_size(self): <NEW_LINE> <INDENT> Square_test = Square(9) <NEW_LINE> Square_test.area() <NEW_LINE> self.assertEqual(Square_test.area(), 81) | Test area() with height and witdth only | 625941be63b5f9789fde700f |
def harris_corner_detector(im): <NEW_LINE> <INDENT> Ix, Iy = der_im(im, D_X_CONV), der_im(im, D_Y_CONV) <NEW_LINE> IxIx, IyIy, IxIy = np.multiply(Ix, Ix), np.multiply(Iy, Iy), np.multiply(Ix, Iy) <NEW_LINE> blur_IxIx, blur_IyIy, blur_IxIy = blur_spatial(IxIx, KERNEL_SIZE), blur_spatial(IyIy, KERNEL_SIZE), blur_spatial(IxIy, KERNEL_SIZE) <NEW_LINE> M = defineM(blur_IxIx, blur_IyIy, blur_IxIy) <NEW_LINE> np.seterr(invalid='ignore') <NEW_LINE> R = np.linalg.det(M) - K * trace(M)**2 <NEW_LINE> lcl_max_R = non_maximum_suppression(R) <NEW_LINE> corners = np.transpose(np.where(lcl_max_R == CORNER_POINT)) <NEW_LINE> cornersT = np.empty(corners.shape) <NEW_LINE> cornersT[:,0], cornersT[:,1] = corners[:,1], corners[:,0] <NEW_LINE> return cornersT | Detects corners in im
:param im: grayscale image to find key points inside.
:return: An array with shape (N,2) of [x,y] key points locations in im. | 625941be287bf620b61d3990 |
def test_submit_trip(self): <NEW_LINE> <INDENT> self.trip.status = Trip.SUBMITTED <NEW_LINE> self.trip.save() <NEW_LINE> self.assertEqual(Trip.SUBMITTED, self.trip.status) <NEW_LINE> self.assertEqual(len(mail.outbox), 1) <NEW_LINE> self.assertTrue(self.trip.owner.first_name in mail.outbox[0].subject) <NEW_LINE> self.assertTrue('Submitted' in mail.outbox[0].subject) <NEW_LINE> self.assertTrue('Submitted' in mail.outbox[0].body) <NEW_LINE> self.assertTrue(self.trip.supervisor.email in mail.outbox[0].to) <NEW_LINE> self.assertTrue(self.trip.owner.email in mail.outbox[0].to) | Test that when a trip is submitted, the supervisor is informed | 625941befbf16365ca6f60e9 |
def setup_logging(self): <NEW_LINE> <INDENT> if len(logging.root.handlers) != 0: <NEW_LINE> <INDENT> logging.root.handlers = [] <NEW_LINE> <DEDENT> self.acquire_lock() <NEW_LINE> if self.config['general']['verbose']: <NEW_LINE> <INDENT> self.log_print_level = logging.DEBUG <NEW_LINE> <DEDENT> self.log_file = self.config['general']['log_file'] or self.log_file <NEW_LINE> self.log_file_format = ANSIStrippingFormatter(self.config['general']['log_file_fmt'], self.config['general']['datetime_fmt']) <NEW_LINE> self.log_format = self.config['general']['log_fmt'] <NEW_LINE> if self.config.general.color: <NEW_LINE> <INDENT> self.log_format = ANSIEmojiLoglevelFormatter(self.config.general.log_fmt, self.config.general.datetime_fmt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log_format = ANSIStrippingEmojiLoglevelFormatter(self.config.general.log_fmt, self.config.general.datetime_fmt) <NEW_LINE> <DEDENT> if self.log_file: <NEW_LINE> <INDENT> self.log_file_handler = logging.FileHandler(self.log_file, self.log_file_mode) <NEW_LINE> self.log_file_handler.setLevel(self.log_file_level) <NEW_LINE> self.log_file_handler.setFormatter(self.log_file_format) <NEW_LINE> logging.root.addHandler(self.log_file_handler) <NEW_LINE> <DEDENT> if self.log_print: <NEW_LINE> <INDENT> self.log_print_handler = logging.StreamHandler(self.log_print_to) <NEW_LINE> self.log_print_handler.setLevel(self.log_print_level) <NEW_LINE> self.log_print_handler.setFormatter(self.log_format) <NEW_LINE> logging.root.addHandler(self.log_print_handler) <NEW_LINE> <DEDENT> self.release_lock() | Called by __enter__() to setup the logging configuration.
| 625941be57b8e32f524833c4 |
def standard_scaler(X, mean=True, std=True, copy=True): <NEW_LINE> <INDENT> transformer = normalizer.StandardScaler(with_mean=mean, with_std=std, copy=copy).fit(X) <NEW_LINE> return transformer | Standardize features by removing the mean and scaling to unit variance.
:param X: numpy array. Input array
:param mean: boolean, True by default.
:param std: boolean, True by default. If True, scale the data to unit variance.
:param copy: boolean, optional, default True.
:return: Standard transformer | 625941bef548e778e58cd4a7 |
def get_random_id(message_id): <NEW_LINE> <INDENT> r = random.Random(message_id) <NEW_LINE> return r.getrandbits(31) * r.choice([-1, 1]) | Get random int32 number (signed) | 625941bed7e4931a7ee9de47 |
def download(self, bucket, object, filename=None): <NEW_LINE> <INDENT> service = self.get_conn() <NEW_LINE> downloaded_file_bytes = service .objects() .get_media(bucket=bucket, object=object) .execute() <NEW_LINE> if filename: <NEW_LINE> <INDENT> write_argument = 'wb' if isinstance(downloaded_file_bytes, bytes) else 'w' <NEW_LINE> with open(filename, write_argument) as file_fd: <NEW_LINE> <INDENT> file_fd.write(downloaded_file_bytes) <NEW_LINE> <DEDENT> <DEDENT> return downloaded_file_bytes | Get a file from Google Cloud Storage.
:param bucket: The bucket to fetch from.
:type bucket: string
:param object: The object to fetch.
:type object: string
:param filename: If set, a local file path where the file should be written to.
:type filename: string | 625941be5e10d32532c5ee52 |
def execute_rowcount(self, query, *parameters, **kwargs): <NEW_LINE> <INDENT> cursor = self._cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> self._execute(cursor, query, parameters, kwargs) <NEW_LINE> return cursor.rowcount <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> cursor.close() | Executes the given query, returning the rowcount from the query. | 625941be85dfad0860c3ad84 |
def _iter_desc(self): <NEW_LINE> <INDENT> return self._get_json_pile(self.fn[0], DescEntry) | Iterate over DescriptorRecord entries. | 625941bead47b63b2c509eab |
def test_make_regressor_1(): <NEW_LINE> <INDENT> condition = ([1, 20, 36.5], [2, 2, 2], [1, 1, 1]) <NEW_LINE> frametimes = np.linspace(0, 69, 70) <NEW_LINE> hrf_model = 'spm' <NEW_LINE> reg, reg_names = compute_regressor(condition, hrf_model, frametimes) <NEW_LINE> assert_almost_equal(reg.sum(), 6, 1) <NEW_LINE> assert reg_names[0] == 'cond' | test the generated regressor
| 625941be71ff763f4b5495b2 |
def FileNameFromPath(path): <NEW_LINE> <INDENT> return os.path.split(path)[1] | Returns the filename for a full path. | 625941bea4f1c619b28aff6a |
def addElementSilent(self,i): <NEW_LINE> <INDENT> self.elements.append(LoadedDataWidget( self.io_core.import_objects[i].data_handler, parent = self.data_list_loaded)) <NEW_LINE> self.elements[-1].vis_button.clicked.connect(self.openVisualWindow) <NEW_LINE> self.elements[-1].vis_button_2.clicked.connect(self.openVisualWindow4D) <NEW_LINE> self.setCurrentElement(i) | Add an element into the list which is loaded
from a custom widget. | 625941befff4ab517eb2f365 |
def main(): <NEW_LINE> <INDENT> root = tk.Tk(className = "~Quick Pick Number Generator~") <NEW_LINE> app = QuickPick(root) <NEW_LINE> root.mainloop() | Instantiate and pop up the window | 625941be3cc13d1c6d3c72a6 |
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): <NEW_LINE> <INDENT> cand_indexes = [] <NEW_LINE> for (i, token) in enumerate(tokens): <NEW_LINE> <INDENT> if token == "[CLS]" or token == "[SEP]": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (FLAGS.do_whole_word_mask and len(cand_indexes) >= 1 and token.startswith("##")): <NEW_LINE> <INDENT> cand_indexes[-1].append(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cand_indexes.append([i]) <NEW_LINE> <DEDENT> <DEDENT> rng.shuffle(cand_indexes) <NEW_LINE> output_tokens = list(tokens) <NEW_LINE> num_to_predict = min(max_predictions_per_seq, max(1, int(round(len(tokens) * masked_lm_prob)))) <NEW_LINE> masked_lms = [] <NEW_LINE> covered_indexes = set() <NEW_LINE> for index_set in cand_indexes: <NEW_LINE> <INDENT> if len(masked_lms) >= num_to_predict: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if len(masked_lms) + len(index_set) > num_to_predict: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> is_any_index_covered = False <NEW_LINE> for index in index_set: <NEW_LINE> <INDENT> if index in covered_indexes: <NEW_LINE> <INDENT> is_any_index_covered = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if is_any_index_covered: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for index in index_set: <NEW_LINE> <INDENT> covered_indexes.add(index) <NEW_LINE> masked_token = None <NEW_LINE> if rng.random() < 0.8: <NEW_LINE> <INDENT> masked_token = "[MASK]" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if rng.random() < 0.5: <NEW_LINE> <INDENT> masked_token = tokens[index] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> masked_token = vocab_words[rng.randint(0, len(vocab_words) - 1)] <NEW_LINE> <DEDENT> <DEDENT> output_tokens[index] = masked_token <NEW_LINE> masked_lms.append(MaskedLmInstance(index=index, label=tokens[index])) <NEW_LINE> <DEDENT> <DEDENT> assert len(masked_lms) <= num_to_predict <NEW_LINE> masked_lms = sorted(masked_lms, key=lambda x: x.index) <NEW_LINE> masked_lm_positions = [] <NEW_LINE> masked_lm_labels = [] <NEW_LINE> for p in masked_lms: <NEW_LINE> <INDENT> masked_lm_positions.append(p.index) <NEW_LINE> masked_lm_labels.append(p.label) <NEW_LINE> <DEDENT> return (output_tokens, masked_lm_positions, masked_lm_labels) | functions: 创建 mask LM 数据
args: tokens: 一句话中词,标点等组成的列表
return:
output_tokens:一个列表,其中有些词(字)被mask替换
masked_lm_positions: 列表,元素是output_tokens中被替换掉位置的索引(在当前句子中的索引)
masked_lm_labels: 列表,元素是output_tokens中被替换成mask地方的原来的词 | 625941be7cff6e4e811178b0 |
def theta_spot(forward, strike, maturity, vol, is_call=True, interest_rate=0.0): <NEW_LINE> <INDENT> zero = np.exp(-interest_rate * maturity) <NEW_LINE> stddev = vol * np.sqrt(maturity) <NEW_LINE> sign = np.where(is_call, 1, -1) <NEW_LINE> d1 = _d1(forward, strike, stddev) <NEW_LINE> d2 = d1 - stddev <NEW_LINE> price_ish = sign * (forward * norm.cdf(sign * d1) - strike * zero * norm.cdf(sign * d2)) <NEW_LINE> theta_fwd = theta_forward(forward, strike, maturity, vol, is_call) <NEW_LINE> return theta_fwd + interest_rate * price_ish | Spot Theta, the sensitivity of the present value to a change in time to maturity.
Unlike most of the methods in this module, this requires an interest rate,
as we are dealing with option price with respect to the Spot underlying
Parameters
----------
forward : numeric ndarray
Forward price or rate of the underlying asset
strike : numeric ndarray
Strike price of the option
maturity : numeric ndarray
Time to maturity of the option, expressed in years
vol : numeric ndarray
Lognormal (Black) volatility
is_call : bool, optional
True if option is a Call, False if a Put.
interest_rate : numeric ndarray, optional
Continuously compounded interest rate, i.e. Zero = Z(0,T) = exp(-rT) | 625941be435de62698dfdb77 |
def OnBuildTrackball( self, platform, center, event, width, height ): <NEW_LINE> <INDENT> from OpenGLContext.move import trackball <NEW_LINE> self.trackball = trackball.Trackball ( platform.position, platform.quaternion, center, event.getPickPoint()[0],event.getPickPoint()[1], width, height, ) | Build the trackball object
Customisation point for those wanting to use a different
trackball implementation. | 625941bee1aae11d1e749be0 |
def randprime(lower,upper): <NEW_LINE> <INDENT> alphas = [2,3,5,7,11,13,17,19] <NEW_LINE> while True: <NEW_LINE> <INDENT> n = randint(lower,upper) <NEW_LINE> if fermat_test(n,alphas): <NEW_LINE> <INDENT> return n | Returns a random prime in the interval [lower,upper]. | 625941be63b5f9789fde7010 |
def disable_key_rotation(key_id, region=None, key=None, keyid=None, profile=None): <NEW_LINE> <INDENT> conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) <NEW_LINE> r = {} <NEW_LINE> try: <NEW_LINE> <INDENT> key = conn.disable_key_rotation(key_id) <NEW_LINE> r["result"] = True <NEW_LINE> <DEDENT> except boto.exception.BotoServerError as e: <NEW_LINE> <INDENT> r["result"] = False <NEW_LINE> r["error"] = __utils__["boto.get_error"](e) <NEW_LINE> <DEDENT> return r | Disable key rotation for specified key.
CLI Example:
.. code-block:: bash
salt myminion boto_kms.disable_key_rotation 'alias/mykey' | 625941be23849d37ff7b2fbb |
def _update_and_launch_children(self, mapping): <NEW_LINE> <INDENT> ready = self._update_children(mapping) <NEW_LINE> for c in ready: <NEW_LINE> <INDENT> c.submit() <NEW_LINE> sleep(1) | Updates the children of the current job to populate the input params
Parameters
----------
mapping : dict of {int: int}
The mapping between output parameter and artifact | 625941be4f88993c3716bf96 |
def build_pipelines(self): <NEW_LINE> <INDENT> raise NotImplementedError | Pipelines and loss here. | 625941be66656f66f7cbc0d5 |
def read(self, pin): <NEW_LINE> <INDENT> port, pin = self.pin_to_port(pin) <NEW_LINE> self.i2c_write([0x12 + port]) <NEW_LINE> raw = self.i2c_read(1) <NEW_LINE> value = struct.unpack('>B', raw)[0] <NEW_LINE> return (value & (1 << pin)) > 0 | Read the pin state of an input pin.
Make sure you put the pin in input modus with the IODIR* register or direction_* attribute first.
:Example:
>>> expander = MCP23017I2C(gw)
>>> # Read the logic level on pin B3
>>> expander.read('B3')
False
>>> # Read the logic level on pin A1
>>> expander.read('A1')
True
:param pin: The label for the pin to read. (Ex. A0)
:return: Boolean representing the input level | 625941be07d97122c41787b1 |
def __get_fingers(self): <NEW_LINE> <INDENT> peer_list = [] <NEW_LINE> peer_list = list(set(((tuple(node.addr), node.id.decode()) for node in list(self.routing_table.values()) + self.awaiting_ids if node.addr))) <NEW_LINE> if self.next is not self: <NEW_LINE> <INDENT> peer_list.append((self.next.addr, self.next.id.decode())) <NEW_LINE> <DEDENT> if self.prev is not self: <NEW_LINE> <INDENT> peer_list.append((self.prev.addr, self.prev.id.decode())) <NEW_LINE> <DEDENT> return peer_list | Returns a finger table for your peer | 625941be8e7ae83300e4aef7 |
def plot_histogram(weights_list: list, image_name: str, include_zeros=True): <NEW_LINE> <INDENT> weights = [] <NEW_LINE> for w in weights_list: <NEW_LINE> <INDENT> weights.extend(list(w.ravel())) <NEW_LINE> <DEDENT> if not include_zeros: <NEW_LINE> <INDENT> weights = [w for w in weights if w != 0] <NEW_LINE> <DEDENT> fig = plt.figure(figsize=(10, 7)) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> ax.hist(weights, bins=100, facecolor='green', edgecolor='black', alpha=0.7, range=(-0.15, 0.15)) <NEW_LINE> ax.set_title('Weights distribution') <NEW_LINE> ax.set_xlabel('Weights values') <NEW_LINE> ax.set_ylabel('Number of weights') <NEW_LINE> fig.savefig(image_name + '.png') | A function to plot weights distribution | 625941beec188e330fd5a6cf |
def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> legal_actions = self.getLegalActions(state) <NEW_LINE> if not legal_actions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> best_actions = [] <NEW_LINE> best_value = self.computeValueFromQValues(state) <NEW_LINE> for action in legal_actions: <NEW_LINE> <INDENT> if self.getQValue(state, action) == best_value: <NEW_LINE> <INDENT> best_actions.append(action) <NEW_LINE> <DEDENT> <DEDENT> return random.choice(best_actions) | Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None. | 625941be24f1403a92600a94 |
def make_page(page, per_page=10): <NEW_LINE> <INDENT> posts = session.query(Post).order_by(Post.id.desc()) <NEW_LINE> pg = paginate(query=posts, page=page, page_size=per_page) <NEW_LINE> return pg | 分页的函数
:param page:
:param per_page:
:return: | 625941bef8510a7c17cf9626 |
def _set_node_writers_writer(self): <NEW_LINE> <INDENT> for key in self._nw: <NEW_LINE> <INDENT> self._nw[key].writer = self | To be called before writing since the file will change. | 625941be21bff66bcd684880 |
def ToString(self): <NEW_LINE> <INDENT> pass | ToString(self: DoseValue) -> str | 625941be566aa707497f4499 |
def fForInterp(self, a): <NEW_LINE> <INDENT> return a | Compton y projection kernel
| 625941be92d797404e3040b4 |
def get_device_owner(mac, serial): <NEW_LINE> <INDENT> device_id = b64encode('n200|null|{0}|{1}'.format(mac, serial)) <NEW_LINE> command_id = generate_command_id(serial) <NEW_LINE> parameters = { 'commandId': command_id, 'deviceId': device_id} <NEW_LINE> res = requests.get(GET_DEVICE_OWNER, params=parameters, headers=HEADERS, verify=False) <NEW_LINE> return res.json()["ownerId"] | Gets the internal/private/email id of the device owner | 625941be85dfad0860c3ad85 |
def stop(self, sig: int, frame: FrameType) -> None: <NEW_LINE> <INDENT> self.terminated = True | Captures SIGINT signal and and change terminition state | 625941be236d856c2ad44702 |
def _data(self, days): <NEW_LINE> <INDENT> def _key(d): <NEW_LINE> <INDENT> return time.strftime(str(d).split('T')[0]) <NEW_LINE> <DEDENT> base = RdiffTime().set_time(0, 0, 0) - datetime.timedelta(days=days) <NEW_LINE> data = { _key(base + datetime.timedelta(days=i)): [] for i in range(0, days + 1) } <NEW_LINE> success = { _key(base + datetime.timedelta(days=i)): 0 for i in range(0, days + 1) } <NEW_LINE> failure = success.copy() <NEW_LINE> for repo in self.app.currentuser.repo_objs: <NEW_LINE> <INDENT> if len(repo.session_statistics): <NEW_LINE> <INDENT> for stat in repo.session_statistics[base:]: <NEW_LINE> <INDENT> key = _key(stat.date) <NEW_LINE> success[key] += 1 <NEW_LINE> data[key].append(stat) <NEW_LINE> if stat.errors: <NEW_LINE> <INDENT> failure[key] += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return { 'backup_count': [ {'name': _('Successful Backup'), 'data': success}, {'name': _('Backup with errors'), 'data': failure} ], 'data': data, } | Return number of backups per days including failure. | 625941be96565a6dacc8f5f8 |
@blu.route('/') <NEW_LINE> def main(): <NEW_LINE> <INDENT> return render_template('index.html') | Initialise the connection to the db
Fetch all rows which are already stored and
display the list of all names on the main page | 625941bea17c0f6771cbdf7e |
def rm_rf(path): <NEW_LINE> <INDENT> return rmtree(path, ignore_errors=True) | Like `rm -rf` in unix | 625941be0383005118ecf50f |
def text_to_wordslist(text): <NEW_LINE> <INDENT> text_list = [] <NEW_LINE> for sentence in text: <NEW_LINE> <INDENT> words_list = sentence.split() <NEW_LINE> words_list = [clean_up(w) for w in words_list] <NEW_LINE> words_list = [w for w in words_list if w.strip()] <NEW_LINE> text_list.append(words_list) <NEW_LINE> <DEDENT> return text_list | (list of str) -> (list of list of str)
Do clean_up for the str in text, then remove all the commas,
then change the str into the list of single word
>>> text = ['James Fennimore Cooper
', 'Peter, Paul and Mary
']
>>> text_to_wordslist(text)
[['james', 'fennimore', 'cooper'], ['peter', 'paul', 'and', 'mary']]
>>> text = ['this is great
', 'This was awesome
', 'and, what about IS
']
>>> text_to_wordslist(text)
[['this', 'is', 'great'], ['this', 'was', 'awesome'], ['and', 'what', 'about', 'is']]
| 625941be9f2886367277a7bb |
def change_times_thread(prfs_d, fits_image): <NEW_LINE> <INDENT> data, header = fits.getdata('{}/{}'.format(prfs_d['fits_dir'], fits_image), header=True) <NEW_LINE> dither = fits_image[-6:-5] <NEW_LINE> print('dither {}'.format(dither)) <NEW_LINE> if dither == '1': <NEW_LINE> <INDENT> header['DATE-OBS'] = prfs_d['time_1'] <NEW_LINE> t = Time(prfs_d['time_1']) <NEW_LINE> t.format = 'mjd' <NEW_LINE> header['MJD-OBS'] = float(str(t)) <NEW_LINE> <DEDENT> elif dither == '2': <NEW_LINE> <INDENT> header['DATE-OBS'] = prfs_d['time_2'] <NEW_LINE> t = Time(prfs_d['time_2']) <NEW_LINE> t.format = 'mjd' <NEW_LINE> header['MJD-OBS'] = float(str(t)) <NEW_LINE> <DEDENT> elif dither == '3': <NEW_LINE> <INDENT> header['DATE-OBS'] = prfs_d['time_3'] <NEW_LINE> t = Time(prfs_d['time_3']) <NEW_LINE> t.format = 'mjd' <NEW_LINE> header['MJD-OBS'] = float(str(t)) <NEW_LINE> <DEDENT> elif dither == '4': <NEW_LINE> <INDENT> header['DATE-OBS'] = prfs_d['time_4'] <NEW_LINE> t = Time(prfs_d['time_4']) <NEW_LINE> t.format = 'mjd' <NEW_LINE> header['MJD-OBS'] = float(str(t)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> header['DATE-OBS'] = prfs_d['time_1'] <NEW_LINE> t = Time(prfs_d['time_1']) <NEW_LINE> t.format = 'mjd' <NEW_LINE> header['MJD-OBS'] = float(str(t)) <NEW_LINE> <DEDENT> print('opens {} date-obs {} mjd-obs {} d {}'.format(fits_image, header['DATE-OBS'], header['MJD-OBS'], dither)) <NEW_LINE> print('fits_image {}'.format(fits_image)) <NEW_LINE> fits.writeto('{}/{}_t.fits'.format(prfs_d['fits_dir'], fits_image[:-5]), data, header) <NEW_LINE> return True | @param prfs_d:
@param fits_image:
@return True: | 625941be8e05c05ec3eea29e |
def v(self, m, T): <NEW_LINE> <INDENT> return self.c * np.sqrt(1 - (1 / (T / (m * self.c**2) + 1 ) )**2 ) | Finding velocity from mass and energy of particle | 625941be97e22403b379cec4 |
def NumBinOp(operator, t0, t1, t2): <NEW_LINE> <INDENT> return [ "and", ["or", ["is-int", t1], ["is-real", t1]], ["or", ["is-int", t2], ["is-real", t2]], [ "ite", ["and", ["is-int", t1], ["is-int", t2]], ["=", t0, ["int", [operator, ["iv", t1], ["iv", t2]]]], [ "=", t0, [ "real", [ operator, ["ite", ["is-int", t1], ["to_real", ["iv", t1]], ["rv", t1]], ["ite", ["is-int", t2], ["to_real", ["iv", t2]], ["rv", t2]] ] ] ] ], ] | Return whether t0 == t1 <op> t2. | 625941be596a8972360899ef |
def update_imu(self, gyroscope, accelerometer): <NEW_LINE> <INDENT> q = self.quaternion <NEW_LINE> gyroscope = np.array(gyroscope, dtype=float).flatten() <NEW_LINE> accelerometer = np.array(accelerometer, dtype=float).flatten() <NEW_LINE> if norm(accelerometer) is 0: <NEW_LINE> <INDENT> warnings.warn("accelerometer is zero") <NEW_LINE> return <NEW_LINE> <DEDENT> accelerometer /= norm(accelerometer) <NEW_LINE> f = np.array([ 2 * (q[1] * q[3] - q[0] * q[2]) - accelerometer[0], 2 * (q[0] * q[1] + q[2] * q[3]) - accelerometer[1], 2 * (0.5 - q[1] ** 2 - q[2] ** 2) - accelerometer[2] ]) <NEW_LINE> j = np.array([ [-2 * q[2], 2 * q[3], -2 * q[0], 2 * q[1]], [2 * q[1], 2 * q[0], 2 * q[3], 2 * q[2]], [0, -4 * q[1], -4 * q[2], 0] ]) <NEW_LINE> step = j.T.dot(f) <NEW_LINE> step /= norm(step) <NEW_LINE> qdot = (q * Quaternion(0, gyroscope[0], gyroscope[1], gyroscope[2])) * 0.5 - self.beta * step.T <NEW_LINE> q += qdot * self.sample_period <NEW_LINE> self.quaternion = Quaternion(q / norm(q)) | Perform one update step with data from a IMU sensor array
:param gyroscope: A three-element array containing the gyroscope data in radians per second.
:param accelerometer: A three-element array containing the accelerometer data. | 625941bed8ef3951e3243469 |
def to_grayscale(img, output_channels=1): <NEW_LINE> <INDENT> if img.ndim == 2: <NEW_LINE> <INDENT> gray_img = img <NEW_LINE> <DEDENT> elif img.shape[2] == 3: <NEW_LINE> <INDENT> gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gray_img = np.mean(img, axis=2) <NEW_LINE> gray_img = gray_img.astype(img.dtype) <NEW_LINE> <DEDENT> if output_channels != 1: <NEW_LINE> <INDENT> gray_img = np.tile(gray_img, (output_channels, 1, 1)) <NEW_LINE> gray_img = np.transpose(gray_img, [1, 2, 0]) <NEW_LINE> <DEDENT> return gray_img | convert input ndarray image to gray sacle image.
Arguments:
img {ndarray} -- the input ndarray image
Keyword Arguments:
output_channels {int} -- output gray image channel (default: {1})
Returns:
ndarray -- gray scale ndarray image | 625941be7d43ff24873a2bca |
def get_hostname(): <NEW_LINE> <INDENT> return platform.node() | Get the hostname of the current host
Returns:
str: The hostname | 625941be9c8ee82313fbb6a0 |
def clear_value(value): <NEW_LINE> <INDENT> useful_char = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ","] <NEW_LINE> tmp = "" <NEW_LINE> for word in value: <NEW_LINE> <INDENT> if word in useful_char: <NEW_LINE> <INDENT> tmp += word <NEW_LINE> <DEDENT> <DEDENT> return tmp | Избавление от неугодных | 625941bed53ae8145f87a1a0 |
def wrapped_fn(self, executor): <NEW_LINE> <INDENT> if not isinstance(executor, context_base.Context): <NEW_LINE> <INDENT> context = execution_context.ExecutionContext(executor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context = executor <NEW_LINE> <DEDENT> with context_stack_impl.context_stack.install(context): <NEW_LINE> <INDENT> fn(self) | Install a particular execution context before running `fn`. | 625941bed6c5a10208143f74 |
@permission_required('trans.use_mt') <NEW_LINE> def translate(request, unit_id): <NEW_LINE> <INDENT> unit = get_object_or_404(Unit, pk=int(unit_id)) <NEW_LINE> unit.check_acl(request) <NEW_LINE> service_name = request.GET.get('service', 'INVALID') <NEW_LINE> if not service_name in MACHINE_TRANSLATION_SERVICES: <NEW_LINE> <INDENT> return HttpResponseBadRequest('Invalid service specified') <NEW_LINE> <DEDENT> translation_service = MACHINE_TRANSLATION_SERVICES[service_name] <NEW_LINE> response = { 'responseStatus': 500, 'service': translation_service.name, 'responseDetails': '', 'translations': [], } <NEW_LINE> try: <NEW_LINE> <INDENT> response['translations'] = translation_service.translate( unit.translation.language.code, unit.get_source_plurals()[0], unit, request.user ) <NEW_LINE> response['responseStatus'] = 200 <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> response['responseDetails'] = '%s: %s' % ( exc.__class__.__name__, str(exc) ) <NEW_LINE> <DEDENT> return HttpResponse( json.dumps(response), content_type='application/json' ) | AJAX handler for translating. | 625941be30bbd722463cbcef |
@task <NEW_LINE> def smoke_test(ctx): <NEW_LINE> <INDENT> print_test_header() <NEW_LINE> run("py.test --url={url} {app_root}/integration_tests/smoke".format( url=ctx.url, app_root=APP_ROOT)) | Run smoke test suite on actual living application | 625941be9b70327d1c4e0d00 |
def uni_total(string): <NEW_LINE> <INDENT> result = 0 <NEW_LINE> for i in string: <NEW_LINE> <INDENT> result += ord(i) <NEW_LINE> <DEDENT> return result | (str) -> int
You'll be given a string, and have to return the total of all the
unicode characters as an int.
Should be able to handle any characters sent at it.
>>> uni_total("aaa")
291 | 625941be4e696a04525c9378 |
def _retrieve_scan_results(results_url, scan_id, api_key=None): <NEW_LINE> <INDENT> headers = None <NEW_LINE> if api_key: <NEW_LINE> <INDENT> headers = {'apikey': api_key} <NEW_LINE> <DEDENT> scan_output = requests.get(results_url+scan_id, headers=headers) <NEW_LINE> return scan_output | Retrieves the results of a scan from Metadefender.
Parameters:
results_url - API URL for result retrieval
scan_id - scan ID returned my Metadefender on sample submission
Returns:
requests.Response object | 625941be851cf427c661a43e |
def add_interface(self, subnet=None, port=None): <NEW_LINE> <INDENT> if port: <NEW_LINE> <INDENT> self._http.put(self._url_resource_path, self._id, 'add_router_interface', data=dict(port_id=port.get_id())) <NEW_LINE> <DEDENT> elif subnet: <NEW_LINE> <INDENT> self._http.put(self._url_resource_path, self._id, 'add_router_interface', data=dict(subnet_id=subnet.get_id())) | Add an interface for router
Either subnet or port is required.
@keyword subnet: Subnet
@type subnet: yakumo.neutron.v2.subnet.Resource
@keyword port: Port
@type port: yakumo.neutron.v2.subnet.Resource
@rtype: None | 625941beeab8aa0e5d26da83 |
def multhop(ys: np.ndarray, αs: np.ndarray, chords: np.ndarray, dcls: np.ndarray, S:float, b:float, M:int=None, do_prep=True): <NEW_LINE> <INDENT> Λ = b**2 / S <NEW_LINE> if do_prep: <NEW_LINE> <INDENT> solverinput = _prepare_multhop(ys, αs, chords, dcls, S, b, M) <NEW_LINE> γs, α_is = _multhop_solve(*solverinput[1:], b) <NEW_LINE> ys, θs = solverinput[0:2] <NEW_LINE> chords = solverinput[3] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> M = len(ys) <NEW_LINE> θs = np.arccos(-2 * np.array(ys)/b) <NEW_LINE> γs, α_is = _multhop_solve(θs, αs, chords, dcls, b) <NEW_LINE> <DEDENT> c_ls = 2*b/(np.array(chords)) * np.array(γs) <NEW_LINE> C_L = π*Λ / (M+1) * np.sum(γs * np.sin(θs)) <NEW_LINE> C_Di = π*Λ/(M+1) * np.sum( γs * α_is * np.sin(θs)) <NEW_LINE> return MulthopResult(ys, c_ls, α_is, C_L, C_Di, γs) | Low level function for multhop quadrature calculation
The parameters except for S and b have to be numpy arrays of the
same length and determine the wing geometry as well calculation
grid points.
Parameters
----------
ys : np.ndarray
span positions at which lift is calculated
chords : np.ndarray
chord lengthes at span positions
αs: np.ndarray
array of angles of attack for chord positions
dcls : np.ndarray
lift coefficient slope regarding angle of attack
S : float
wing area
b : float
span width of wing
M: int
number of grid points
Returns
-------
tuple
multhop results - (c_ls, α_is, C_L, C_Di))
lift coefficients, induced angle of attack,
wing's lift coefficient, induced drag coefficient | 625941bef548e778e58cd4a8 |
def setUp(self): <NEW_LINE> <INDENT> self.ds1=Login_ds() <NEW_LINE> self.ds = home_page() <NEW_LINE> self.ds.openurl(url) | 初始化类,访问网站点击进入个人中心 | 625941be283ffb24f3c55830 |
def batch_flatten(self, input, batch_size): <NEW_LINE> <INDENT> tags = [] <NEW_LINE> out = [] <NEW_LINE> for n in range(batch_size): <NEW_LINE> <INDENT> tag = n * tf.ones((tf.shape(input)[1]), tf.int32) <NEW_LINE> tags.append(tag) <NEW_LINE> out.append(input[n]) <NEW_LINE> <DEDENT> tags = tf.concat(tags, 0) <NEW_LINE> out = tf.concat(out, 0) <NEW_LINE> return tags, out | Gives the tag that describes the batch index of a sample.
and a flatten tensor which is shaped to
(batch_size*rois, ?)
:param input: (batch_size, rois, ?)
:param batch_size: int
:return tags: (batch_size*rois)
:return out: (batch_size*rois, ?) | 625941bef9cc0f698b14052a |
def create_thread(self, *args): <NEW_LINE> <INDENT> if args is not None: <NEW_LINE> <INDENT> thread_name = args[0] <NEW_LINE> if len(list(args)) > 1: <NEW_LINE> <INDENT> thread_args = list(args[1:]) <NEW_LINE> <DEDENT> <DEDENT> if thread_name in ['manage_server', 'connect']: <NEW_LINE> <INDENT> self.new_thread = Thread( target=lambda: self.manage_thread(thread_args[0]), daemon=True) <NEW_LINE> self.new_thread.start() <NEW_LINE> <DEDENT> if thread_name == 'update_menu': <NEW_LINE> <INDENT> self.new_thread = Thread( target=lambda: self.update_menu(thread_args[0]), daemon=True) <NEW_LINE> self.new_thread.start() <NEW_LINE> <DEDENT> if thread_name == 'listen_server': <NEW_LINE> <INDENT> self.new_thread = Thread(target=self.listen_server, daemon=True) <NEW_LINE> self.new_thread.start() <NEW_LINE> <DEDENT> if thread_name == 'user_list': <NEW_LINE> <INDENT> self.new_thread = Thread(target=self.user_list_thread, daemon=True) <NEW_LINE> self.new_thread.start() | Creates a new Thread. | 625941bea79ad161976cc071 |
def __init__( self, hass: HomeAssistant, flow_dispatcher: FlowDispatcher, usb: list[dict[str, str]], ) -> None: <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.flow_dispatcher = flow_dispatcher <NEW_LINE> self.usb = usb <NEW_LINE> self.seen: set[tuple[str, ...]] = set() <NEW_LINE> self.observer_active = False <NEW_LINE> self._request_debouncer: Debouncer | None = None | Init USB Discovery. | 625941be5f7d997b871749c1 |
def make(**kwargs): <NEW_LINE> <INDENT> pass | combined register component, factories and adapters
:param kwargs:
:return: | 625941bee1aae11d1e749be1 |
def _file_name(self, dtype_out_time, extension='nc'): <NEW_LINE> <INDENT> if dtype_out_time is None: <NEW_LINE> <INDENT> dtype_out_time = '' <NEW_LINE> <DEDENT> out_lbl = utils.io.data_out_label(self.intvl_out, dtype_out_time, dtype_vert=self.dtype_out_vert) <NEW_LINE> in_lbl = utils.io.data_in_label(self.intvl_in, self.dtype_in_time, self.dtype_in_vert) <NEW_LINE> start_year = utils.times.infer_year(self.start_date) <NEW_LINE> end_year = utils.times.infer_year(self.end_date) <NEW_LINE> yr_lbl = utils.io.yr_label((start_year, end_year)) <NEW_LINE> return '.'.join( [self.name, out_lbl, in_lbl, self.model.name, self.run.name, yr_lbl, extension] ).replace('..', '.') | Create the name of the aospy file. | 625941be6aa9bd52df036ccf |
def is_url(url): <NEW_LINE> <INDENT> schemes = urllib.parse.uses_netloc[1:] <NEW_LINE> try: <NEW_LINE> <INDENT> return urllib.parse.urlparse(url).scheme in schemes <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False | Check if a string is a valid URL to a network location.
Parameters
----------
url : str
String containing a possible URL
Returns
-------
bool : bool
If `url` has a valid protocol return True otherwise False. | 625941be956e5f7376d70d9a |
def filter_by_regular(filename): <NEW_LINE> <INDENT> turnstile_data = pandas.read_csv(filename) <NEW_LINE> return turnstile_data[turnstile_data.DESCn == 'REGULAR'] | This function should read the csv file located at filename into a pandas dataframe,
and filter the dataframe to only rows where the 'DESCn' column has the value 'REGULAR'.
For example, if the pandas dataframe is as follows:
,C/A,UNIT,SCP,DATEn,TIMEn,DESCn,ENTRIESn,EXITSn
0,A002,R051,02-00-00,05-01-11,00:00:00,REGULAR,3144312,1088151
1,A002,R051,02-00-00,05-01-11,04:00:00,DOOR,3144335,1088159
2,A002,R051,02-00-00,05-01-11,08:00:00,REGULAR,3144353,1088177
3,A002,R051,02-00-00,05-01-11,12:00:00,DOOR,3144424,1088231
The dataframe will look like below after filtering to only rows where DESCn column
has the value 'REGULAR':
0,A002,R051,02-00-00,05-01-11,00:00:00,REGULAR,3144312,1088151
2,A002,R051,02-00-00,05-01-11,08:00:00,REGULAR,3144353,1088177 | 625941be4428ac0f6e5ba71d |
def cast(self, dtype): <NEW_LINE> <INDENT> if str(self.format).split('.')[-1] == "SCALAR": <NEW_LINE> <INDENT> if dtype in NTP.pTt.keys() and NTP.pTt[dtype] == str(self.tangoDType): <NEW_LINE> <INDENT> if isinstance(self.value, unicode): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.value == "" and ( dtype not in ['str', 'string', 'bytes']): <NEW_LINE> <INDENT> return NTP.convert[dtype](0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return NTP.convert[dtype](self.value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if dtype in NTP.pTt.keys() and NTP.pTt[dtype] == str(self.tangoDType) and (dtype not in ['str', 'string', 'bytes']): <NEW_LINE> <INDENT> if type(self.value).__name__ == 'ndarray' and self.value.dtype.name == dtype: <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return numpy.array(self.value, dtype=dtype) <NEW_LINE> <DEDENT> <DEDENT> elif dtype == "bool": <NEW_LINE> <INDENT> return numpy.array( NTP().createArray(self.value, NTP.convert[dtype]), dtype=dtype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return numpy.array(self.value, dtype=nptype(dtype)) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return numpy.array( NTP().createArray(self.value, NTP.convert[dtype]), dtype=nptype(dtype)) | casts the data into given type
:param dtype: given type of data
:type dtype: :obj:`str`
:returns: numpy array of defined type or list
for strings or value for SCALAR
:rtype: :class:`numpy.ndarray` | 625941bed268445f265b4d9a |
def IsSubclassOf(self, o): <NEW_LINE> <INDENT> return bool(_c.env_subclassP(self.__env, self.__defclass, o.__defclass)) | test whether this Class is a subclass of specified Class | 625941bea219f33f34628899 |
def cut_image(image): <NEW_LINE> <INDENT> width, height = image.size <NEW_LINE> item_width = int(width / 3) <NEW_LINE> box_list = [] <NEW_LINE> for i in range(0,3): <NEW_LINE> <INDENT> for j in range(0,3): <NEW_LINE> <INDENT> box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width) <NEW_LINE> box_list.append(box) <NEW_LINE> <DEDENT> <DEDENT> image_list = [image.crop(box) for box in box_list] <NEW_LINE> return image_list | 切割图片 | 625941bebe8e80087fb20b73 |
def testAdminPaginationResponse(self): <NEW_LINE> <INDENT> pass | Test AdminPaginationResponse | 625941beb545ff76a8913d42 |
def init_backround_markers(self): <NEW_LINE> <INDENT> self.markerDefine(Qsci.QsciScintilla.Background, 0) <NEW_LINE> self.setMarkerBackgroundColor(QColor("#40FF0000"), 0) | Define markers to make lines not properly formatted into a red-ish colour | 625941bea05bb46b383ec750 |
def GetRed(self): <NEW_LINE> <INDENT> return _itkSpatialObjectPointPython.itkSpatialObjectPoint2_GetRed(self) | GetRed(self) -> float | 625941be7d847024c06be1e5 |
def append_after(filename="", search_string="", new_string=""): <NEW_LINE> <INDENT> with open(filename, 'r+') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> if search_string in line: <NEW_LINE> <INDENT> print(line, end='') <NEW_LINE> print(new_string, end='') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(line, end='') | Search for text string in file
and append new text at end of
line | 625941bebf627c535bc130fb |
def __init__(self, organisation_id=None, user_id=None, validation_errors=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._organisation_id = None <NEW_LINE> self._user_id = None <NEW_LINE> self._validation_errors = None <NEW_LINE> self.discriminator = None <NEW_LINE> if organisation_id is not None: <NEW_LINE> <INDENT> self.organisation_id = organisation_id <NEW_LINE> <DEDENT> if user_id is not None: <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> <DEDENT> if validation_errors is not None: <NEW_LINE> <INDENT> self.validation_errors = validation_errors | UpdateProfileResponse - a model defined in OpenAPI | 625941be627d3e7fe0d68d7b |
def test_render_element_attr(): <NEW_LINE> <INDENT> e = Element("this is some text", id="TheList", style="line-height:200%") <NEW_LINE> file_contents = render_result(e).strip() <NEW_LINE> assert("this is some text") in file_contents <NEW_LINE> assert('id="TheList"') in file_contents <NEW_LINE> assert('style="line-height:200%"') in file_contents <NEW_LINE> assert file_contents.startswith("<html ") <NEW_LINE> assert file_contents.endswith("</html>") | Test whether the Element can take attributes. | 625941bea934411ee37515bf |
def recv_by_size(self): <NEW_LINE> <INDENT> str_size = "" <NEW_LINE> str_size += self.recv(HEADER_SIZE) <NEW_LINE> if str_size == "": <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> while len(str_size) < HEADER_SIZE: <NEW_LINE> <INDENT> str_size += self.recv(HEADER_SIZE - len(str_size)) <NEW_LINE> <DEDENT> size = int(str_size) <NEW_LINE> data = "" <NEW_LINE> while len(data) < size: <NEW_LINE> <INDENT> data += self.recv(size - len(data)) <NEW_LINE> <DEDENT> return data | Receives by size (with a pre-programmed header size).
The other side can use send_by_size to send the data. | 625941be21bff66bcd684881 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.