code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def upload(self, url, method="POST", file_path=None): """ :param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str """ if not os.path.exists(file_path): raise RuntimeError("") with open_file(file_path, 'rb') as file: size = os.path.getsize(file_path) label = "Uploading {filename} ({size:.2f}MB)".format( filename=os.path.basename(file_path), size=size / float(self.chunk_size) / self.chunk_size ) if method == "PUT": resp = put(url, data=file) elif method == "POST": resp = post(url, data=file) content_iter = resp.iter_content(chunk_size=self.chunk_size) with progressbar(content_iter, length=size / self.chunk_size, label=label) as bar: for _ in bar: pass
def function[upload, parameter[self, url, method, file_path]]: constant[ :param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str ] if <ast.UnaryOp object at 0x7da2044c23e0> begin[:] <ast.Raise object at 0x7da18f58c370> with call[name[open_file], parameter[name[file_path], constant[rb]]] begin[:] variable[size] assign[=] call[name[os].path.getsize, parameter[name[file_path]]] variable[label] assign[=] call[constant[Uploading {filename} ({size:.2f}MB)].format, parameter[]] if compare[name[method] equal[==] constant[PUT]] begin[:] variable[resp] assign[=] call[name[put], parameter[name[url]]] variable[content_iter] assign[=] call[name[resp].iter_content, parameter[]] with call[name[progressbar], parameter[name[content_iter]]] begin[:] for taget[name[_]] in starred[name[bar]] begin[:] pass
keyword[def] identifier[upload] ( identifier[self] , identifier[url] , identifier[method] = literal[string] , identifier[file_path] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[file_path] ): keyword[raise] identifier[RuntimeError] ( literal[string] ) keyword[with] identifier[open_file] ( identifier[file_path] , literal[string] ) keyword[as] identifier[file] : identifier[size] = identifier[os] . identifier[path] . identifier[getsize] ( identifier[file_path] ) identifier[label] = literal[string] . identifier[format] ( identifier[filename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[file_path] ), identifier[size] = identifier[size] / identifier[float] ( identifier[self] . identifier[chunk_size] )/ identifier[self] . identifier[chunk_size] ) keyword[if] identifier[method] == literal[string] : identifier[resp] = identifier[put] ( identifier[url] , identifier[data] = identifier[file] ) keyword[elif] identifier[method] == literal[string] : identifier[resp] = identifier[post] ( identifier[url] , identifier[data] = identifier[file] ) identifier[content_iter] = identifier[resp] . identifier[iter_content] ( identifier[chunk_size] = identifier[self] . identifier[chunk_size] ) keyword[with] identifier[progressbar] ( identifier[content_iter] , identifier[length] = identifier[size] / identifier[self] . identifier[chunk_size] , identifier[label] = identifier[label] ) keyword[as] identifier[bar] : keyword[for] identifier[_] keyword[in] identifier[bar] : keyword[pass]
def upload(self, url, method='POST', file_path=None): """ :param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str """ if not os.path.exists(file_path): raise RuntimeError('') # depends on [control=['if'], data=[]] with open_file(file_path, 'rb') as file: size = os.path.getsize(file_path) label = 'Uploading {filename} ({size:.2f}MB)'.format(filename=os.path.basename(file_path), size=size / float(self.chunk_size) / self.chunk_size) if method == 'PUT': resp = put(url, data=file) # depends on [control=['if'], data=[]] elif method == 'POST': resp = post(url, data=file) # depends on [control=['if'], data=[]] content_iter = resp.iter_content(chunk_size=self.chunk_size) with progressbar(content_iter, length=size / self.chunk_size, label=label) as bar: for _ in bar: pass # depends on [control=['for'], data=[]] # depends on [control=['with'], data=['bar']] # depends on [control=['with'], data=['file']]
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ course, __ = self.get_course_and_check_rights(courseid) msgs = [] if "replay" in web.input(): if not self.user_manager.has_admin_rights_on_course(course): raise web.notfound() input = self.get_input() tasks = course.get_tasks() data, __ = self.get_submissions(course, input) for submission in data: self.submission_manager.replay_job(tasks[submission["taskid"]], submission) msgs.append(_("{0} selected submissions were set for replay.").format(str(len(data)))) return self.page(course, msgs)
def function[POST_AUTH, parameter[self, courseid]]: constant[ POST request ] <ast.Tuple object at 0x7da18f58e950> assign[=] call[name[self].get_course_and_check_rights, parameter[name[courseid]]] variable[msgs] assign[=] list[[]] if compare[constant[replay] in call[name[web].input, parameter[]]] begin[:] if <ast.UnaryOp object at 0x7da18f58c2b0> begin[:] <ast.Raise object at 0x7da18f58e020> variable[input] assign[=] call[name[self].get_input, parameter[]] variable[tasks] assign[=] call[name[course].get_tasks, parameter[]] <ast.Tuple object at 0x7da18f58d810> assign[=] call[name[self].get_submissions, parameter[name[course], name[input]]] for taget[name[submission]] in starred[name[data]] begin[:] call[name[self].submission_manager.replay_job, parameter[call[name[tasks]][call[name[submission]][constant[taskid]]], name[submission]]] call[name[msgs].append, parameter[call[call[name[_], parameter[constant[{0} selected submissions were set for replay.]]].format, parameter[call[name[str], parameter[call[name[len], parameter[name[data]]]]]]]]] return[call[name[self].page, parameter[name[course], name[msgs]]]]
keyword[def] identifier[POST_AUTH] ( identifier[self] , identifier[courseid] ): literal[string] identifier[course] , identifier[__] = identifier[self] . identifier[get_course_and_check_rights] ( identifier[courseid] ) identifier[msgs] =[] keyword[if] literal[string] keyword[in] identifier[web] . identifier[input] (): keyword[if] keyword[not] identifier[self] . identifier[user_manager] . identifier[has_admin_rights_on_course] ( identifier[course] ): keyword[raise] identifier[web] . identifier[notfound] () identifier[input] = identifier[self] . identifier[get_input] () identifier[tasks] = identifier[course] . identifier[get_tasks] () identifier[data] , identifier[__] = identifier[self] . identifier[get_submissions] ( identifier[course] , identifier[input] ) keyword[for] identifier[submission] keyword[in] identifier[data] : identifier[self] . identifier[submission_manager] . identifier[replay_job] ( identifier[tasks] [ identifier[submission] [ literal[string] ]], identifier[submission] ) identifier[msgs] . identifier[append] ( identifier[_] ( literal[string] ). identifier[format] ( identifier[str] ( identifier[len] ( identifier[data] )))) keyword[return] identifier[self] . identifier[page] ( identifier[course] , identifier[msgs] )
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ ' POST request ' (course, __) = self.get_course_and_check_rights(courseid) msgs = [] if 'replay' in web.input(): if not self.user_manager.has_admin_rights_on_course(course): raise web.notfound() # depends on [control=['if'], data=[]] input = self.get_input() tasks = course.get_tasks() (data, __) = self.get_submissions(course, input) for submission in data: self.submission_manager.replay_job(tasks[submission['taskid']], submission) # depends on [control=['for'], data=['submission']] msgs.append(_('{0} selected submissions were set for replay.').format(str(len(data)))) # depends on [control=['if'], data=[]] return self.page(course, msgs)
def get_model(servoid): """ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202 """ data = [] data.append(0x09) data.append(servoid) data.append(EEP_READ_REQ) data.append(MODEL_NO1_EEP) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise HerkulexError("could not communicate with motors")
def function[get_model, parameter[servoid]]: constant[ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202 ] variable[data] assign[=] list[[]] call[name[data].append, parameter[constant[9]]] call[name[data].append, parameter[name[servoid]]] call[name[data].append, parameter[name[EEP_READ_REQ]]] call[name[data].append, parameter[name[MODEL_NO1_EEP]]] call[name[data].append, parameter[name[BYTE1]]] call[name[send_data], parameter[name[data]]] variable[rxdata] assign[=] list[[]] <ast.Try object at 0x7da1b25c3b80>
keyword[def] identifier[get_model] ( identifier[servoid] ): literal[string] identifier[data] =[] identifier[data] . identifier[append] ( literal[int] ) identifier[data] . identifier[append] ( identifier[servoid] ) identifier[data] . identifier[append] ( identifier[EEP_READ_REQ] ) identifier[data] . identifier[append] ( identifier[MODEL_NO1_EEP] ) identifier[data] . identifier[append] ( identifier[BYTE1] ) identifier[send_data] ( identifier[data] ) identifier[rxdata] =[] keyword[try] : identifier[rxdata] = identifier[SERPORT] . identifier[read] ( literal[int] ) keyword[return] identifier[ord] ( identifier[rxdata] [ literal[int] ])& literal[int] keyword[except] : keyword[raise] identifier[HerkulexError] ( literal[string] )
def get_model(servoid): """ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202 """ data = [] data.append(9) data.append(servoid) data.append(EEP_READ_REQ) data.append(MODEL_NO1_EEP) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9]) & 255 # depends on [control=['try'], data=[]] except: raise HerkulexError('could not communicate with motors') # depends on [control=['except'], data=[]]
def table_in(filehandle, pre_header_string): """ Generator that assumes a table starts the line after a given string """ in_histogram = False next_is_header = False headers = list() for line in stripped(filehandle): if not in_histogram and line.startswith(pre_header_string): in_histogram = True next_is_header = True elif in_histogram and next_is_header: next_is_header = False headers = line.split("\t") elif in_histogram: values = line.split("\t") if values != ['']: for couple in zip(headers, values): yield couple
def function[table_in, parameter[filehandle, pre_header_string]]: constant[ Generator that assumes a table starts the line after a given string ] variable[in_histogram] assign[=] constant[False] variable[next_is_header] assign[=] constant[False] variable[headers] assign[=] call[name[list], parameter[]] for taget[name[line]] in starred[call[name[stripped], parameter[name[filehandle]]]] begin[:] if <ast.BoolOp object at 0x7da18bcca7a0> begin[:] variable[in_histogram] assign[=] constant[True] variable[next_is_header] assign[=] constant[True]
keyword[def] identifier[table_in] ( identifier[filehandle] , identifier[pre_header_string] ): literal[string] identifier[in_histogram] = keyword[False] identifier[next_is_header] = keyword[False] identifier[headers] = identifier[list] () keyword[for] identifier[line] keyword[in] identifier[stripped] ( identifier[filehandle] ): keyword[if] keyword[not] identifier[in_histogram] keyword[and] identifier[line] . identifier[startswith] ( identifier[pre_header_string] ): identifier[in_histogram] = keyword[True] identifier[next_is_header] = keyword[True] keyword[elif] identifier[in_histogram] keyword[and] identifier[next_is_header] : identifier[next_is_header] = keyword[False] identifier[headers] = identifier[line] . identifier[split] ( literal[string] ) keyword[elif] identifier[in_histogram] : identifier[values] = identifier[line] . identifier[split] ( literal[string] ) keyword[if] identifier[values] !=[ literal[string] ]: keyword[for] identifier[couple] keyword[in] identifier[zip] ( identifier[headers] , identifier[values] ): keyword[yield] identifier[couple]
def table_in(filehandle, pre_header_string): """ Generator that assumes a table starts the line after a given string """ in_histogram = False next_is_header = False headers = list() for line in stripped(filehandle): if not in_histogram and line.startswith(pre_header_string): in_histogram = True next_is_header = True # depends on [control=['if'], data=[]] elif in_histogram and next_is_header: next_is_header = False headers = line.split('\t') # depends on [control=['if'], data=[]] elif in_histogram: values = line.split('\t') if values != ['']: for couple in zip(headers, values): yield couple # depends on [control=['for'], data=['couple']] # depends on [control=['if'], data=['values']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']]
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return "{} / {} ({}% completed) (~{} remaining)".format( current, total, int(current / total * 100), time_remaining)
def function[ratio_and_percentage_with_time_remaining, parameter[current, total, time_remaining]]: constant[Returns the progress ratio, percentage and time remaining.] return[call[constant[{} / {} ({}% completed) (~{} remaining)].format, parameter[name[current], name[total], call[name[int], parameter[binary_operation[binary_operation[name[current] / name[total]] * constant[100]]]], name[time_remaining]]]]
keyword[def] identifier[ratio_and_percentage_with_time_remaining] ( identifier[current] , identifier[total] , identifier[time_remaining] ): literal[string] keyword[return] literal[string] . identifier[format] ( identifier[current] , identifier[total] , identifier[int] ( identifier[current] / identifier[total] * literal[int] ), identifier[time_remaining] )
def ratio_and_percentage_with_time_remaining(current, total, time_remaining): """Returns the progress ratio, percentage and time remaining.""" return '{} / {} ({}% completed) (~{} remaining)'.format(current, total, int(current / total * 100), time_remaining)
def load(self, elem): """ Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict> """ self.testTag(elem, 'dict') out = {} for xitem in elem: key = xitem.get('key') try: value = XmlDataIO.fromXml(xitem[0]) except IndexError: value = None out[key] = value return out
def function[load, parameter[self, elem]]: constant[ Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict> ] call[name[self].testTag, parameter[name[elem], constant[dict]]] variable[out] assign[=] dictionary[[], []] for taget[name[xitem]] in starred[name[elem]] begin[:] variable[key] assign[=] call[name[xitem].get, parameter[constant[key]]] <ast.Try object at 0x7da1b2774610> call[name[out]][name[key]] assign[=] name[value] return[name[out]]
keyword[def] identifier[load] ( identifier[self] , identifier[elem] ): literal[string] identifier[self] . identifier[testTag] ( identifier[elem] , literal[string] ) identifier[out] ={} keyword[for] identifier[xitem] keyword[in] identifier[elem] : identifier[key] = identifier[xitem] . identifier[get] ( literal[string] ) keyword[try] : identifier[value] = identifier[XmlDataIO] . identifier[fromXml] ( identifier[xitem] [ literal[int] ]) keyword[except] identifier[IndexError] : identifier[value] = keyword[None] identifier[out] [ identifier[key] ]= identifier[value] keyword[return] identifier[out]
def load(self, elem): """ Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict> """ self.testTag(elem, 'dict') out = {} for xitem in elem: key = xitem.get('key') try: value = XmlDataIO.fromXml(xitem[0]) # depends on [control=['try'], data=[]] except IndexError: value = None # depends on [control=['except'], data=[]] out[key] = value # depends on [control=['for'], data=['xitem']] return out
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and not inserted: attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True node = getattr(node, attr) depth += 1 if inserted and depth == height: leaves.add(node) if len(leaves) == leaf_count: break return root
def function[tree, parameter[height, is_perfect]]: constant[Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 ] call[name[_validate_tree_height], parameter[name[height]]] variable[values] assign[=] call[name[_generate_random_node_values], parameter[name[height]]] if name[is_perfect] begin[:] return[call[name[build], parameter[name[values]]]] variable[leaf_count] assign[=] call[name[_generate_random_leaf_count], parameter[name[height]]] variable[root] assign[=] call[name[Node], parameter[call[name[values].pop, parameter[constant[0]]]]] variable[leaves] assign[=] call[name[set], parameter[]] for taget[name[value]] in starred[name[values]] begin[:] variable[node] assign[=] name[root] variable[depth] assign[=] constant[0] variable[inserted] assign[=] constant[False] while <ast.BoolOp object at 0x7da20c6c6140> begin[:] variable[attr] assign[=] call[name[random].choice, parameter[tuple[[<ast.Constant object at 0x7da20c6c7190>, <ast.Constant object at 0x7da20c6c5a20>]]]] if compare[call[name[getattr], parameter[name[node], name[attr]]] is constant[None]] begin[:] call[name[setattr], parameter[name[node], name[attr], call[name[Node], parameter[name[value]]]]] variable[inserted] assign[=] constant[True] variable[node] assign[=] call[name[getattr], parameter[name[node], name[attr]]] <ast.AugAssign object at 0x7da20c6c72e0> if <ast.BoolOp object at 0x7da20c6c7f70> begin[:] call[name[leaves].add, parameter[name[node]]] if compare[call[name[len], parameter[name[leaves]]] equal[==] name[leaf_count]] begin[:] break return[name[root]]
keyword[def] identifier[tree] ( identifier[height] = literal[int] , identifier[is_perfect] = keyword[False] ): literal[string] identifier[_validate_tree_height] ( identifier[height] ) identifier[values] = identifier[_generate_random_node_values] ( identifier[height] ) keyword[if] identifier[is_perfect] : keyword[return] identifier[build] ( identifier[values] ) identifier[leaf_count] = identifier[_generate_random_leaf_count] ( identifier[height] ) identifier[root] = identifier[Node] ( identifier[values] . identifier[pop] ( literal[int] )) identifier[leaves] = identifier[set] () keyword[for] identifier[value] keyword[in] identifier[values] : identifier[node] = identifier[root] identifier[depth] = literal[int] identifier[inserted] = keyword[False] keyword[while] identifier[depth] < identifier[height] keyword[and] keyword[not] identifier[inserted] : identifier[attr] = identifier[random] . identifier[choice] (( literal[string] , literal[string] )) keyword[if] identifier[getattr] ( identifier[node] , identifier[attr] ) keyword[is] keyword[None] : identifier[setattr] ( identifier[node] , identifier[attr] , identifier[Node] ( identifier[value] )) identifier[inserted] = keyword[True] identifier[node] = identifier[getattr] ( identifier[node] , identifier[attr] ) identifier[depth] += literal[int] keyword[if] identifier[inserted] keyword[and] identifier[depth] == identifier[height] : identifier[leaves] . identifier[add] ( identifier[node] ) keyword[if] identifier[len] ( identifier[leaves] )== identifier[leaf_count] : keyword[break] keyword[return] identifier[root]
def tree(height=3, is_perfect=False): """Generate a random binary tree and return its root node. :param height: Height of the tree (default: 3, range: 0 - 9 inclusive). :type height: int :param is_perfect: If set to True (default: False), a perfect binary tree with all levels filled is returned. If set to False, a perfect binary tree may still be generated by chance. :type is_perfect: bool :return: Root node of the binary tree. :rtype: binarytree.Node :raise binarytree.exceptions.TreeHeightError: If height is invalid. **Example**: .. doctest:: >>> from binarytree import tree >>> >>> root = tree() >>> >>> root.height 3 .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=5, is_perfect=True) >>> >>> root.height 5 >>> root.is_perfect True .. doctest:: >>> from binarytree import tree >>> >>> root = tree(height=20) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TreeHeightError: height must be an int between 0 - 9 """ _validate_tree_height(height) values = _generate_random_node_values(height) if is_perfect: return build(values) # depends on [control=['if'], data=[]] leaf_count = _generate_random_leaf_count(height) root = Node(values.pop(0)) leaves = set() for value in values: node = root depth = 0 inserted = False while depth < height and (not inserted): attr = random.choice(('left', 'right')) if getattr(node, attr) is None: setattr(node, attr, Node(value)) inserted = True # depends on [control=['if'], data=[]] node = getattr(node, attr) depth += 1 # depends on [control=['while'], data=[]] if inserted and depth == height: leaves.add(node) # depends on [control=['if'], data=[]] if len(leaves) == leaf_count: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['value']] return root
def discover_package_doc_dir(initial_dir): """Discover the ``doc/`` dir of a package given an initial directory. Parameters ---------- initial_dir : `str` The inititial directory to search from. In practice, this is often the directory that the user is running the package-docs CLI from. This directory needs to be somewhere inside the package's repository. Returns ------- root_dir : `str` The root documentation directory (``doc/``), containing ``conf.py``. Raises ------ FileNotFoundError Raised if a ``conf.py`` file is not found in the initial directory, or any parents, or in a ```doc/`` subdirectory. """ # Create an absolute Path to work with initial_dir = pathlib.Path(initial_dir).resolve() # Check if this is the doc/ dir already with a conf.py if _has_conf_py(initial_dir): return str(initial_dir) # Search for a doc/ directory in cwd (this covers the case of running # the CLI from the root of a repository). test_dir = initial_dir / 'doc' if test_dir.exists() and test_dir.is_dir(): if _has_conf_py(test_dir): return str(test_dir) # Search upwards until a conf.py is found try: return str(_search_parents(initial_dir)) except FileNotFoundError: raise
def function[discover_package_doc_dir, parameter[initial_dir]]: constant[Discover the ``doc/`` dir of a package given an initial directory. Parameters ---------- initial_dir : `str` The inititial directory to search from. In practice, this is often the directory that the user is running the package-docs CLI from. This directory needs to be somewhere inside the package's repository. Returns ------- root_dir : `str` The root documentation directory (``doc/``), containing ``conf.py``. Raises ------ FileNotFoundError Raised if a ``conf.py`` file is not found in the initial directory, or any parents, or in a ```doc/`` subdirectory. ] variable[initial_dir] assign[=] call[call[name[pathlib].Path, parameter[name[initial_dir]]].resolve, parameter[]] if call[name[_has_conf_py], parameter[name[initial_dir]]] begin[:] return[call[name[str], parameter[name[initial_dir]]]] variable[test_dir] assign[=] binary_operation[name[initial_dir] / constant[doc]] if <ast.BoolOp object at 0x7da1b23d6290> begin[:] if call[name[_has_conf_py], parameter[name[test_dir]]] begin[:] return[call[name[str], parameter[name[test_dir]]]] <ast.Try object at 0x7da1b23d49d0>
keyword[def] identifier[discover_package_doc_dir] ( identifier[initial_dir] ): literal[string] identifier[initial_dir] = identifier[pathlib] . identifier[Path] ( identifier[initial_dir] ). identifier[resolve] () keyword[if] identifier[_has_conf_py] ( identifier[initial_dir] ): keyword[return] identifier[str] ( identifier[initial_dir] ) identifier[test_dir] = identifier[initial_dir] / literal[string] keyword[if] identifier[test_dir] . identifier[exists] () keyword[and] identifier[test_dir] . identifier[is_dir] (): keyword[if] identifier[_has_conf_py] ( identifier[test_dir] ): keyword[return] identifier[str] ( identifier[test_dir] ) keyword[try] : keyword[return] identifier[str] ( identifier[_search_parents] ( identifier[initial_dir] )) keyword[except] identifier[FileNotFoundError] : keyword[raise]
def discover_package_doc_dir(initial_dir): """Discover the ``doc/`` dir of a package given an initial directory. Parameters ---------- initial_dir : `str` The inititial directory to search from. In practice, this is often the directory that the user is running the package-docs CLI from. This directory needs to be somewhere inside the package's repository. Returns ------- root_dir : `str` The root documentation directory (``doc/``), containing ``conf.py``. Raises ------ FileNotFoundError Raised if a ``conf.py`` file is not found in the initial directory, or any parents, or in a ```doc/`` subdirectory. """ # Create an absolute Path to work with initial_dir = pathlib.Path(initial_dir).resolve() # Check if this is the doc/ dir already with a conf.py if _has_conf_py(initial_dir): return str(initial_dir) # depends on [control=['if'], data=[]] # Search for a doc/ directory in cwd (this covers the case of running # the CLI from the root of a repository). test_dir = initial_dir / 'doc' if test_dir.exists() and test_dir.is_dir(): if _has_conf_py(test_dir): return str(test_dir) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # Search upwards until a conf.py is found try: return str(_search_parents(initial_dir)) # depends on [control=['try'], data=[]] except FileNotFoundError: raise # depends on [control=['except'], data=[]]
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = time.ctime(modified) modified = datetime.strptime(modified, '%a %b %d %H:%M:%S %Y') return datetime.now() - modified <= CACHE_EXPIRATION_INTERVAL
def function[_is_valid_cache, parameter[]]: constant[ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` ] if <ast.UnaryOp object at 0x7da18f00e6b0> begin[:] return[constant[False]] variable[modified] assign[=] call[name[os].path.getmtime, parameter[call[name[get_cache_location], parameter[]]]] variable[modified] assign[=] call[name[time].ctime, parameter[name[modified]]] variable[modified] assign[=] call[name[datetime].strptime, parameter[name[modified], constant[%a %b %d %H:%M:%S %Y]]] return[compare[binary_operation[call[name[datetime].now, parameter[]] - name[modified]] less_or_equal[<=] name[CACHE_EXPIRATION_INTERVAL]]]
keyword[def] identifier[_is_valid_cache] (): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[get_cache_location] ()): keyword[return] keyword[False] identifier[modified] = identifier[os] . identifier[path] . identifier[getmtime] ( identifier[get_cache_location] ()) identifier[modified] = identifier[time] . identifier[ctime] ( identifier[modified] ) identifier[modified] = identifier[datetime] . identifier[strptime] ( identifier[modified] , literal[string] ) keyword[return] identifier[datetime] . identifier[now] ()- identifier[modified] <= identifier[CACHE_EXPIRATION_INTERVAL]
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False # depends on [control=['if'], data=[]] modified = os.path.getmtime(get_cache_location()) modified = time.ctime(modified) modified = datetime.strptime(modified, '%a %b %d %H:%M:%S %Y') return datetime.now() - modified <= CACHE_EXPIRATION_INTERVAL
def confirm_email(self, username, confirmation_key): """ Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmation key is invalid. :param confirmation_key: String containing the secret SHA1 that is used for verification. :return: The verified :class:`User` or ``False`` if not successful. """ if SHA1_RE.search(confirmation_key): try: user = self.select_related().get(username=username, email_confirmation_key=confirmation_key, email_unconfirmed__isnull=False) except self.model.DoesNotExist: return False else: user.email = user.email_unconfirmed user.email_unconfirmed, user.email_confirmation_key = '','' user.save(using=self._db) # Send the confirmation_complete signal accounts_signals.confirmation_complete.send(sender=None, user=user) return user return False
def function[confirm_email, parameter[self, username, confirmation_key]]: constant[ Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmation key is invalid. :param confirmation_key: String containing the secret SHA1 that is used for verification. :return: The verified :class:`User` or ``False`` if not successful. ] if call[name[SHA1_RE].search, parameter[name[confirmation_key]]] begin[:] <ast.Try object at 0x7da20e954400> return[constant[False]]
keyword[def] identifier[confirm_email] ( identifier[self] , identifier[username] , identifier[confirmation_key] ): literal[string] keyword[if] identifier[SHA1_RE] . identifier[search] ( identifier[confirmation_key] ): keyword[try] : identifier[user] = identifier[self] . identifier[select_related] (). identifier[get] ( identifier[username] = identifier[username] , identifier[email_confirmation_key] = identifier[confirmation_key] , identifier[email_unconfirmed__isnull] = keyword[False] ) keyword[except] identifier[self] . identifier[model] . identifier[DoesNotExist] : keyword[return] keyword[False] keyword[else] : identifier[user] . identifier[email] = identifier[user] . identifier[email_unconfirmed] identifier[user] . identifier[email_unconfirmed] , identifier[user] . identifier[email_confirmation_key] = literal[string] , literal[string] identifier[user] . identifier[save] ( identifier[using] = identifier[self] . identifier[_db] ) identifier[accounts_signals] . identifier[confirmation_complete] . identifier[send] ( identifier[sender] = keyword[None] , identifier[user] = identifier[user] ) keyword[return] identifier[user] keyword[return] keyword[False]
def confirm_email(self, username, confirmation_key): """ Confirm an email address by checking a ``confirmation_key``. A valid ``confirmation_key`` will set the newly wanted email address as the current email address. Returns the user after success or ``False`` when the confirmation key is invalid. :param confirmation_key: String containing the secret SHA1 that is used for verification. :return: The verified :class:`User` or ``False`` if not successful. """ if SHA1_RE.search(confirmation_key): try: user = self.select_related().get(username=username, email_confirmation_key=confirmation_key, email_unconfirmed__isnull=False) # depends on [control=['try'], data=[]] except self.model.DoesNotExist: return False # depends on [control=['except'], data=[]] else: user.email = user.email_unconfirmed (user.email_unconfirmed, user.email_confirmation_key) = ('', '') user.save(using=self._db) # Send the confirmation_complete signal accounts_signals.confirmation_complete.send(sender=None, user=user) return user # depends on [control=['if'], data=[]] return False
def rangefinder_send(self, distance, voltage, force_mavlink1=False): ''' Rangefinder reporting distance : distance in meters (float) voltage : raw voltage if available, zero otherwise (float) ''' return self.send(self.rangefinder_encode(distance, voltage), force_mavlink1=force_mavlink1)
def function[rangefinder_send, parameter[self, distance, voltage, force_mavlink1]]: constant[ Rangefinder reporting distance : distance in meters (float) voltage : raw voltage if available, zero otherwise (float) ] return[call[name[self].send, parameter[call[name[self].rangefinder_encode, parameter[name[distance], name[voltage]]]]]]
keyword[def] identifier[rangefinder_send] ( identifier[self] , identifier[distance] , identifier[voltage] , identifier[force_mavlink1] = keyword[False] ): literal[string] keyword[return] identifier[self] . identifier[send] ( identifier[self] . identifier[rangefinder_encode] ( identifier[distance] , identifier[voltage] ), identifier[force_mavlink1] = identifier[force_mavlink1] )
def rangefinder_send(self, distance, voltage, force_mavlink1=False): """ Rangefinder reporting distance : distance in meters (float) voltage : raw voltage if available, zero otherwise (float) """ return self.send(self.rangefinder_encode(distance, voltage), force_mavlink1=force_mavlink1)
def get_calendar_event(self, calendar_event): """ Return single Calendar Event by id :calls: `GET /api/v1/calendar_events/:id \ <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_ :param calendar_event: The object or ID of the calendar event. :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ from canvasapi.calendar_event import CalendarEvent calendar_event_id = obj_or_id(calendar_event, "calendar_event", (CalendarEvent,)) response = self.__requester.request( 'GET', 'calendar_events/{}'.format(calendar_event_id) ) return CalendarEvent(self.__requester, response.json())
def function[get_calendar_event, parameter[self, calendar_event]]: constant[ Return single Calendar Event by id :calls: `GET /api/v1/calendar_events/:id <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_ :param calendar_event: The object or ID of the calendar event. :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int :rtype: :class:`canvasapi.calendar_event.CalendarEvent` ] from relative_module[canvasapi.calendar_event] import module[CalendarEvent] variable[calendar_event_id] assign[=] call[name[obj_or_id], parameter[name[calendar_event], constant[calendar_event], tuple[[<ast.Name object at 0x7da1b1e44970>]]]] variable[response] assign[=] call[name[self].__requester.request, parameter[constant[GET], call[constant[calendar_events/{}].format, parameter[name[calendar_event_id]]]]] return[call[name[CalendarEvent], parameter[name[self].__requester, call[name[response].json, parameter[]]]]]
keyword[def] identifier[get_calendar_event] ( identifier[self] , identifier[calendar_event] ): literal[string] keyword[from] identifier[canvasapi] . identifier[calendar_event] keyword[import] identifier[CalendarEvent] identifier[calendar_event_id] = identifier[obj_or_id] ( identifier[calendar_event] , literal[string] ,( identifier[CalendarEvent] ,)) identifier[response] = identifier[self] . identifier[__requester] . identifier[request] ( literal[string] , literal[string] . identifier[format] ( identifier[calendar_event_id] ) ) keyword[return] identifier[CalendarEvent] ( identifier[self] . identifier[__requester] , identifier[response] . identifier[json] ())
def get_calendar_event(self, calendar_event): """ Return single Calendar Event by id :calls: `GET /api/v1/calendar_events/:id <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.show>`_ :param calendar_event: The object or ID of the calendar event. :type calendar_event: :class:`canvasapi.calendar_event.CalendarEvent` or int :rtype: :class:`canvasapi.calendar_event.CalendarEvent` """ from canvasapi.calendar_event import CalendarEvent calendar_event_id = obj_or_id(calendar_event, 'calendar_event', (CalendarEvent,)) response = self.__requester.request('GET', 'calendar_events/{}'.format(calendar_event_id)) return CalendarEvent(self.__requester, response.json())
def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
def function[_is_installation_local, parameter[name]]: constant[Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. ] variable[loc] assign[=] call[name[os].path.normcase, parameter[call[name[pkg_resources].working_set.by_key][name[name]].location]] variable[pre] assign[=] call[name[os].path.normcase, parameter[name[sys].prefix]] return[compare[call[name[os].path.commonprefix, parameter[list[[<ast.Name object at 0x7da1b1ea24d0>, <ast.Name object at 0x7da1b1ea3190>]]]] equal[==] name[pre]]]
keyword[def] identifier[_is_installation_local] ( identifier[name] ): literal[string] identifier[loc] = identifier[os] . identifier[path] . identifier[normcase] ( identifier[pkg_resources] . identifier[working_set] . identifier[by_key] [ identifier[name] ]. identifier[location] ) identifier[pre] = identifier[os] . identifier[path] . identifier[normcase] ( identifier[sys] . identifier[prefix] ) keyword[return] identifier[os] . identifier[path] . identifier[commonprefix] ([ identifier[loc] , identifier[pre] ])== identifier[pre]
def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
def ensure_data(): ''' Ensure that the Garuda directory and files ''' if not os.path.exists(GARUDA_DIR): os.makedirs(GARUDA_DIR) Path(f'{GARUDA_DIR}/__init__.py').touch()
def function[ensure_data, parameter[]]: constant[ Ensure that the Garuda directory and files ] if <ast.UnaryOp object at 0x7da1b1a1ccd0> begin[:] call[name[os].makedirs, parameter[name[GARUDA_DIR]]] call[call[name[Path], parameter[<ast.JoinedStr object at 0x7da1b1a1f940>]].touch, parameter[]]
keyword[def] identifier[ensure_data] (): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[GARUDA_DIR] ): identifier[os] . identifier[makedirs] ( identifier[GARUDA_DIR] ) identifier[Path] ( literal[string] ). identifier[touch] ()
def ensure_data(): """ Ensure that the Garuda directory and files """ if not os.path.exists(GARUDA_DIR): os.makedirs(GARUDA_DIR) # depends on [control=['if'], data=[]] Path(f'{GARUDA_DIR}/__init__.py').touch()
def rm_job(user, cmd, minute=None, hour=None, daymonth=None, month=None, dayweek=None, identifier=None): ''' Remove a cron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' cron.rm_job root /usr/local/weekly salt '*' cron.rm_job root /usr/bin/foo dayweek=1 ''' lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break if _cron_matched(lst['crons'][ind], cmd, identifier=identifier): if not any([x is not None for x in (minute, hour, daymonth, month, dayweek)]): # No date/time params were specified rm_ = ind else: if _date_time_match(lst['crons'][ind], minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek): rm_ = ind if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret
def function[rm_job, parameter[user, cmd, minute, hour, daymonth, month, dayweek, identifier]]: constant[ Remove a cron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' cron.rm_job root /usr/local/weekly salt '*' cron.rm_job root /usr/bin/foo dayweek=1 ] variable[lst] assign[=] call[name[list_tab], parameter[name[user]]] variable[ret] assign[=] constant[absent] variable[rm_] assign[=] constant[None] for taget[name[ind]] in starred[call[name[range], parameter[call[name[len], parameter[call[name[lst]][constant[crons]]]]]]] begin[:] if compare[name[rm_] is_not constant[None]] begin[:] break if call[name[_cron_matched], parameter[call[call[name[lst]][constant[crons]]][name[ind]], name[cmd]]] begin[:] if <ast.UnaryOp object at 0x7da18dc05e40> begin[:] variable[rm_] assign[=] name[ind] if compare[name[rm_] is_not constant[None]] begin[:] call[call[name[lst]][constant[crons]].pop, parameter[name[rm_]]] variable[ret] assign[=] constant[removed] variable[comdat] assign[=] call[name[_write_cron_lines], parameter[name[user], call[name[_render_tab], parameter[name[lst]]]]] if call[name[comdat]][constant[retcode]] begin[:] return[call[name[comdat]][constant[stderr]]] return[name[ret]]
keyword[def] identifier[rm_job] ( identifier[user] , identifier[cmd] , identifier[minute] = keyword[None] , identifier[hour] = keyword[None] , identifier[daymonth] = keyword[None] , identifier[month] = keyword[None] , identifier[dayweek] = keyword[None] , identifier[identifier] = keyword[None] ): literal[string] identifier[lst] = identifier[list_tab] ( identifier[user] ) identifier[ret] = literal[string] identifier[rm_] = keyword[None] keyword[for] identifier[ind] keyword[in] identifier[range] ( identifier[len] ( identifier[lst] [ literal[string] ])): keyword[if] identifier[rm_] keyword[is] keyword[not] keyword[None] : keyword[break] keyword[if] identifier[_cron_matched] ( identifier[lst] [ literal[string] ][ identifier[ind] ], identifier[cmd] , identifier[identifier] = identifier[identifier] ): keyword[if] keyword[not] identifier[any] ([ identifier[x] keyword[is] keyword[not] keyword[None] keyword[for] identifier[x] keyword[in] ( identifier[minute] , identifier[hour] , identifier[daymonth] , identifier[month] , identifier[dayweek] )]): identifier[rm_] = identifier[ind] keyword[else] : keyword[if] identifier[_date_time_match] ( identifier[lst] [ literal[string] ][ identifier[ind] ], identifier[minute] = identifier[minute] , identifier[hour] = identifier[hour] , identifier[daymonth] = identifier[daymonth] , identifier[month] = identifier[month] , identifier[dayweek] = identifier[dayweek] ): identifier[rm_] = identifier[ind] keyword[if] identifier[rm_] keyword[is] keyword[not] keyword[None] : identifier[lst] [ literal[string] ]. identifier[pop] ( identifier[rm_] ) identifier[ret] = literal[string] identifier[comdat] = identifier[_write_cron_lines] ( identifier[user] , identifier[_render_tab] ( identifier[lst] )) keyword[if] identifier[comdat] [ literal[string] ]: keyword[return] identifier[comdat] [ literal[string] ] keyword[return] identifier[ret]
def rm_job(user, cmd, minute=None, hour=None, daymonth=None, month=None, dayweek=None, identifier=None): """ Remove a cron job for a specified user. If any of the day/time params are specified, the job will only be removed if the specified params match. CLI Example: .. code-block:: bash salt '*' cron.rm_job root /usr/local/weekly salt '*' cron.rm_job root /usr/bin/foo dayweek=1 """ lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['crons'])): if rm_ is not None: break # depends on [control=['if'], data=[]] if _cron_matched(lst['crons'][ind], cmd, identifier=identifier): if not any([x is not None for x in (minute, hour, daymonth, month, dayweek)]): # No date/time params were specified rm_ = ind # depends on [control=['if'], data=[]] elif _date_time_match(lst['crons'][ind], minute=minute, hour=hour, daymonth=daymonth, month=month, dayweek=dayweek): rm_ = ind # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ind']] if rm_ is not None: lst['crons'].pop(rm_) ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['rm_']] return ret
def render_meta(meta, fn="meta.pandas.html", title="Project Metadata - MSMBuilder", pandas_kwargs=None): """Render a metadata dataframe as an html webpage for inspection. Parameters ---------- meta : pd.Dataframe The DataFrame of metadata fn : str Output filename (should end in html) title : str Page title pandas_kwargs : dict Arguments to be passed to pandas """ if pandas_kwargs is None: pandas_kwargs = {} kwargs_with_defaults = { 'classes': ('table', 'table-condensed', 'table-hover'), } kwargs_with_defaults.update(**pandas_kwargs) env = Environment(loader=PackageLoader('msmbuilder', 'io_templates')) templ = env.get_template("twitter-bootstrap.html") rendered = templ.render( title=title, content=meta.to_html(**kwargs_with_defaults) ) # Ugh, pandas hardcodes border="1" rendered = re.sub(r' border="1"', '', rendered) backup(fn) with open(fn, 'w') as f: f.write(rendered)
def function[render_meta, parameter[meta, fn, title, pandas_kwargs]]: constant[Render a metadata dataframe as an html webpage for inspection. Parameters ---------- meta : pd.Dataframe The DataFrame of metadata fn : str Output filename (should end in html) title : str Page title pandas_kwargs : dict Arguments to be passed to pandas ] if compare[name[pandas_kwargs] is constant[None]] begin[:] variable[pandas_kwargs] assign[=] dictionary[[], []] variable[kwargs_with_defaults] assign[=] dictionary[[<ast.Constant object at 0x7da1b0669c60>], [<ast.Tuple object at 0x7da1b0669bd0>]] call[name[kwargs_with_defaults].update, parameter[]] variable[env] assign[=] call[name[Environment], parameter[]] variable[templ] assign[=] call[name[env].get_template, parameter[constant[twitter-bootstrap.html]]] variable[rendered] assign[=] call[name[templ].render, parameter[]] variable[rendered] assign[=] call[name[re].sub, parameter[constant[ border="1"], constant[], name[rendered]]] call[name[backup], parameter[name[fn]]] with call[name[open], parameter[name[fn], constant[w]]] begin[:] call[name[f].write, parameter[name[rendered]]]
keyword[def] identifier[render_meta] ( identifier[meta] , identifier[fn] = literal[string] , identifier[title] = literal[string] , identifier[pandas_kwargs] = keyword[None] ): literal[string] keyword[if] identifier[pandas_kwargs] keyword[is] keyword[None] : identifier[pandas_kwargs] ={} identifier[kwargs_with_defaults] ={ literal[string] :( literal[string] , literal[string] , literal[string] ), } identifier[kwargs_with_defaults] . identifier[update] (** identifier[pandas_kwargs] ) identifier[env] = identifier[Environment] ( identifier[loader] = identifier[PackageLoader] ( literal[string] , literal[string] )) identifier[templ] = identifier[env] . identifier[get_template] ( literal[string] ) identifier[rendered] = identifier[templ] . identifier[render] ( identifier[title] = identifier[title] , identifier[content] = identifier[meta] . identifier[to_html] (** identifier[kwargs_with_defaults] ) ) identifier[rendered] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[rendered] ) identifier[backup] ( identifier[fn] ) keyword[with] identifier[open] ( identifier[fn] , literal[string] ) keyword[as] identifier[f] : identifier[f] . identifier[write] ( identifier[rendered] )
def render_meta(meta, fn='meta.pandas.html', title='Project Metadata - MSMBuilder', pandas_kwargs=None): """Render a metadata dataframe as an html webpage for inspection. Parameters ---------- meta : pd.Dataframe The DataFrame of metadata fn : str Output filename (should end in html) title : str Page title pandas_kwargs : dict Arguments to be passed to pandas """ if pandas_kwargs is None: pandas_kwargs = {} # depends on [control=['if'], data=['pandas_kwargs']] kwargs_with_defaults = {'classes': ('table', 'table-condensed', 'table-hover')} kwargs_with_defaults.update(**pandas_kwargs) env = Environment(loader=PackageLoader('msmbuilder', 'io_templates')) templ = env.get_template('twitter-bootstrap.html') rendered = templ.render(title=title, content=meta.to_html(**kwargs_with_defaults)) # Ugh, pandas hardcodes border="1" rendered = re.sub(' border="1"', '', rendered) backup(fn) with open(fn, 'w') as f: f.write(rendered) # depends on [control=['with'], data=['f']]
def pie(self, key="wall_time", minfract=0.05, ax=None, **kwargs): """ Plot pie chart for this timer. Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure """ ax, fig, plt = get_ax_fig_plt(ax=ax) # Set aspect ratio to be equal so that pie is drawn as a circle. ax.axis("equal") # Don't show section whose value is less that minfract labels, vals = self.names_and_values(key, minfract=minfract) ax.pie(vals, explode=None, labels=labels, autopct='%1.1f%%', shadow=True) return fig
def function[pie, parameter[self, key, minfract, ax]]: constant[ Plot pie chart for this timer. Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure ] <ast.Tuple object at 0x7da20c6c4d30> assign[=] call[name[get_ax_fig_plt], parameter[]] call[name[ax].axis, parameter[constant[equal]]] <ast.Tuple object at 0x7da204567f70> assign[=] call[name[self].names_and_values, parameter[name[key]]] call[name[ax].pie, parameter[name[vals]]] return[name[fig]]
keyword[def] identifier[pie] ( identifier[self] , identifier[key] = literal[string] , identifier[minfract] = literal[int] , identifier[ax] = keyword[None] ,** identifier[kwargs] ): literal[string] identifier[ax] , identifier[fig] , identifier[plt] = identifier[get_ax_fig_plt] ( identifier[ax] = identifier[ax] ) identifier[ax] . identifier[axis] ( literal[string] ) identifier[labels] , identifier[vals] = identifier[self] . identifier[names_and_values] ( identifier[key] , identifier[minfract] = identifier[minfract] ) identifier[ax] . identifier[pie] ( identifier[vals] , identifier[explode] = keyword[None] , identifier[labels] = identifier[labels] , identifier[autopct] = literal[string] , identifier[shadow] = keyword[True] ) keyword[return] identifier[fig]
def pie(self, key='wall_time', minfract=0.05, ax=None, **kwargs): """ Plot pie chart for this timer. Args: key: Keyword used to extract data from the timer. minfract: Don't show sections whose relative weight is less that minfract. ax: matplotlib :class:`Axes` or None if a new figure should be created. Returns: `matplotlib` figure """ (ax, fig, plt) = get_ax_fig_plt(ax=ax) # Set aspect ratio to be equal so that pie is drawn as a circle. ax.axis('equal') # Don't show section whose value is less that minfract (labels, vals) = self.names_and_values(key, minfract=minfract) ax.pie(vals, explode=None, labels=labels, autopct='%1.1f%%', shadow=True) return fig
def get_proxy(self, input): """Gets a proxy. :param input: a proxy condition :type input: ``osid.proxy.ProxyCondition`` :return: a proxy :rtype: ``osid.proxy.Proxy`` :raise: ``NullArgument`` -- ``input`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``PermissionDenied`` -- authorization failure :raise: ``Unsupported`` -- ``input`` is not of this service *compliance: mandatory -- This method is must be implemented.* """ from ..authentication_process.objects import Authentication agent_id = input.user.username host = settings.HOST url_path = ('/handcar/services/authentication/agentkeys/' + agent_id + '?proxyname=' + settings.APP_KEYS[host.lower()]) authentication = Authentication(agent_id, self._get_request(url_path)) return rules.Proxy(authentication=authentication)
def function[get_proxy, parameter[self, input]]: constant[Gets a proxy. :param input: a proxy condition :type input: ``osid.proxy.ProxyCondition`` :return: a proxy :rtype: ``osid.proxy.Proxy`` :raise: ``NullArgument`` -- ``input`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``PermissionDenied`` -- authorization failure :raise: ``Unsupported`` -- ``input`` is not of this service *compliance: mandatory -- This method is must be implemented.* ] from relative_module[authentication_process.objects] import module[Authentication] variable[agent_id] assign[=] name[input].user.username variable[host] assign[=] name[settings].HOST variable[url_path] assign[=] binary_operation[binary_operation[binary_operation[constant[/handcar/services/authentication/agentkeys/] + name[agent_id]] + constant[?proxyname=]] + call[name[settings].APP_KEYS][call[name[host].lower, parameter[]]]] variable[authentication] assign[=] call[name[Authentication], parameter[name[agent_id], call[name[self]._get_request, parameter[name[url_path]]]]] return[call[name[rules].Proxy, parameter[]]]
keyword[def] identifier[get_proxy] ( identifier[self] , identifier[input] ): literal[string] keyword[from] .. identifier[authentication_process] . identifier[objects] keyword[import] identifier[Authentication] identifier[agent_id] = identifier[input] . identifier[user] . identifier[username] identifier[host] = identifier[settings] . identifier[HOST] identifier[url_path] =( literal[string] + identifier[agent_id] + literal[string] + identifier[settings] . identifier[APP_KEYS] [ identifier[host] . identifier[lower] ()]) identifier[authentication] = identifier[Authentication] ( identifier[agent_id] , identifier[self] . identifier[_get_request] ( identifier[url_path] )) keyword[return] identifier[rules] . identifier[Proxy] ( identifier[authentication] = identifier[authentication] )
def get_proxy(self, input): """Gets a proxy. :param input: a proxy condition :type input: ``osid.proxy.ProxyCondition`` :return: a proxy :rtype: ``osid.proxy.Proxy`` :raise: ``NullArgument`` -- ``input`` is ``null`` :raise: ``OperationFailed`` -- unable to complete request :raise: ``PermissionDenied`` -- authorization failure :raise: ``Unsupported`` -- ``input`` is not of this service *compliance: mandatory -- This method is must be implemented.* """ from ..authentication_process.objects import Authentication agent_id = input.user.username host = settings.HOST url_path = '/handcar/services/authentication/agentkeys/' + agent_id + '?proxyname=' + settings.APP_KEYS[host.lower()] authentication = Authentication(agent_id, self._get_request(url_path)) return rules.Proxy(authentication=authentication)
def modhex_decode(data): """ Convert a modhex bytestring to ordinary hex. """ try: maketrans = string.maketrans except AttributeError: # Python 3 maketrans = bytes.maketrans t_map = maketrans(b"cbdefghijklnrtuv", b"0123456789abcdef") return data.translate(t_map)
def function[modhex_decode, parameter[data]]: constant[ Convert a modhex bytestring to ordinary hex. ] <ast.Try object at 0x7da1b0865180> variable[t_map] assign[=] call[name[maketrans], parameter[constant[b'cbdefghijklnrtuv'], constant[b'0123456789abcdef']]] return[call[name[data].translate, parameter[name[t_map]]]]
keyword[def] identifier[modhex_decode] ( identifier[data] ): literal[string] keyword[try] : identifier[maketrans] = identifier[string] . identifier[maketrans] keyword[except] identifier[AttributeError] : identifier[maketrans] = identifier[bytes] . identifier[maketrans] identifier[t_map] = identifier[maketrans] ( literal[string] , literal[string] ) keyword[return] identifier[data] . identifier[translate] ( identifier[t_map] )
def modhex_decode(data): """ Convert a modhex bytestring to ordinary hex. """ try: maketrans = string.maketrans # depends on [control=['try'], data=[]] except AttributeError: # Python 3 maketrans = bytes.maketrans # depends on [control=['except'], data=[]] t_map = maketrans(b'cbdefghijklnrtuv', b'0123456789abcdef') return data.translate(t_map)
def _gpio_callback(self, gpio): """ Gets triggered whenever the the gpio state changes :param gpio: Number of gpio that changed :type gpio: int :rtype: None """ self.debug(u"Triggered #{}".format(gpio)) try: index = self.gpios.index(gpio) except ValueError: self.error(u"{} not present in GPIO list".format(gpio)) return with self._people_lock: person = self.people[index] read_val = GPIO.input(gpio) if read_val == person.sitting: # Nothing changed? time.sleep(self.gpio_bouncetime_sleep) # Really sure? read_val = GPIO.input(gpio) if person.sitting != read_val: person.sitting = read_val self.debug(u"Person is now {}sitting".format( "" if person.sitting else "not ") ) try: self.changer.on_person_update(self.people) except: self.exception( u"Failed to update people (Person: {})".format(person) ) else: self.warning(u"Nothing changed on {}".format(gpio))
def function[_gpio_callback, parameter[self, gpio]]: constant[ Gets triggered whenever the the gpio state changes :param gpio: Number of gpio that changed :type gpio: int :rtype: None ] call[name[self].debug, parameter[call[constant[Triggered #{}].format, parameter[name[gpio]]]]] <ast.Try object at 0x7da18f00c8b0> with name[self]._people_lock begin[:] variable[person] assign[=] call[name[self].people][name[index]] variable[read_val] assign[=] call[name[GPIO].input, parameter[name[gpio]]] if compare[name[read_val] equal[==] name[person].sitting] begin[:] call[name[time].sleep, parameter[name[self].gpio_bouncetime_sleep]] variable[read_val] assign[=] call[name[GPIO].input, parameter[name[gpio]]] if compare[name[person].sitting not_equal[!=] name[read_val]] begin[:] name[person].sitting assign[=] name[read_val] call[name[self].debug, parameter[call[constant[Person is now {}sitting].format, parameter[<ast.IfExp object at 0x7da18f00eaa0>]]]] <ast.Try object at 0x7da18f00f340>
keyword[def] identifier[_gpio_callback] ( identifier[self] , identifier[gpio] ): literal[string] identifier[self] . identifier[debug] ( literal[string] . identifier[format] ( identifier[gpio] )) keyword[try] : identifier[index] = identifier[self] . identifier[gpios] . identifier[index] ( identifier[gpio] ) keyword[except] identifier[ValueError] : identifier[self] . identifier[error] ( literal[string] . identifier[format] ( identifier[gpio] )) keyword[return] keyword[with] identifier[self] . identifier[_people_lock] : identifier[person] = identifier[self] . identifier[people] [ identifier[index] ] identifier[read_val] = identifier[GPIO] . identifier[input] ( identifier[gpio] ) keyword[if] identifier[read_val] == identifier[person] . identifier[sitting] : identifier[time] . identifier[sleep] ( identifier[self] . identifier[gpio_bouncetime_sleep] ) identifier[read_val] = identifier[GPIO] . identifier[input] ( identifier[gpio] ) keyword[if] identifier[person] . identifier[sitting] != identifier[read_val] : identifier[person] . identifier[sitting] = identifier[read_val] identifier[self] . identifier[debug] ( literal[string] . identifier[format] ( literal[string] keyword[if] identifier[person] . identifier[sitting] keyword[else] literal[string] ) ) keyword[try] : identifier[self] . identifier[changer] . identifier[on_person_update] ( identifier[self] . identifier[people] ) keyword[except] : identifier[self] . identifier[exception] ( literal[string] . identifier[format] ( identifier[person] ) ) keyword[else] : identifier[self] . identifier[warning] ( literal[string] . identifier[format] ( identifier[gpio] ))
def _gpio_callback(self, gpio): """ Gets triggered whenever the the gpio state changes :param gpio: Number of gpio that changed :type gpio: int :rtype: None """ self.debug(u'Triggered #{}'.format(gpio)) try: index = self.gpios.index(gpio) # depends on [control=['try'], data=[]] except ValueError: self.error(u'{} not present in GPIO list'.format(gpio)) return # depends on [control=['except'], data=[]] with self._people_lock: person = self.people[index] read_val = GPIO.input(gpio) if read_val == person.sitting: # Nothing changed? time.sleep(self.gpio_bouncetime_sleep) # Really sure? read_val = GPIO.input(gpio) # depends on [control=['if'], data=['read_val']] if person.sitting != read_val: person.sitting = read_val self.debug(u'Person is now {}sitting'.format('' if person.sitting else 'not ')) try: self.changer.on_person_update(self.people) # depends on [control=['try'], data=[]] except: self.exception(u'Failed to update people (Person: {})'.format(person)) # depends on [control=['except'], data=[]] # depends on [control=['if'], data=['read_val']] else: self.warning(u'Nothing changed on {}'.format(gpio)) # depends on [control=['with'], data=[]]
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout): """Hook to dispatch a single job""" raise NotImplementedError("SysInterface.dispatch_job_hook")
def function[dispatch_job_hook, parameter[self, link, key, job_config, logfile, stream]]: constant[Hook to dispatch a single job] <ast.Raise object at 0x7da18eb57a60>
keyword[def] identifier[dispatch_job_hook] ( identifier[self] , identifier[link] , identifier[key] , identifier[job_config] , identifier[logfile] , identifier[stream] = identifier[sys] . identifier[stdout] ): literal[string] keyword[raise] identifier[NotImplementedError] ( literal[string] )
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout): """Hook to dispatch a single job""" raise NotImplementedError('SysInterface.dispatch_job_hook')
def _set_categories(self): """ Inplace conversion from categories. """ for column, _ in self._categories.items(): if column in self.columns: self[column] = self[column].astype('category')
def function[_set_categories, parameter[self]]: constant[ Inplace conversion from categories. ] for taget[tuple[[<ast.Name object at 0x7da18c4cff40>, <ast.Name object at 0x7da18c4cc5b0>]]] in starred[call[name[self]._categories.items, parameter[]]] begin[:] if compare[name[column] in name[self].columns] begin[:] call[name[self]][name[column]] assign[=] call[call[name[self]][name[column]].astype, parameter[constant[category]]]
keyword[def] identifier[_set_categories] ( identifier[self] ): literal[string] keyword[for] identifier[column] , identifier[_] keyword[in] identifier[self] . identifier[_categories] . identifier[items] (): keyword[if] identifier[column] keyword[in] identifier[self] . identifier[columns] : identifier[self] [ identifier[column] ]= identifier[self] [ identifier[column] ]. identifier[astype] ( literal[string] )
def _set_categories(self): """ Inplace conversion from categories. """ for (column, _) in self._categories.items(): if column in self.columns: self[column] = self[column].astype('category') # depends on [control=['if'], data=['column']] # depends on [control=['for'], data=[]]
def _find_current_fn_call(co, lasti): """Find current function call in the byte code.""" qj._DEBUG_QJ and qj.LOG_FN('co = {}'.format(co)) if sys.version_info[0] < 3: stack = _build_instruction_stack(co, lasti) else: stack = _build_instruction_stack3(co, lasti) source_lines, source_offset = inspect.getsourcelines(co) source_lines = [l.strip() for l in source_lines] # Apply stack effects backwards until we arrive at the stack entries for a complete function call fn_stack = _collect_pops(stack[:-1], stack[-1].stack_depth, [], 0) if not fn_stack and stack[-1].stack_depth == 0: # The function call took 0 arguments, so return early with a special string. return '<empty log>' qj._DEBUG_QJ and qj.LOG_FN('collected fn_stack:\n%s\n\n' % '\n'.join(str(se) for se in fn_stack)) # Prepare to annotate the stack with extra symbols, and filter out MAKE_FUNCTION and MAKE_CLOSURE calls, which are no longer needed. annotate_stack = [se for se in fn_stack if not se.opname.startswith('MAKE_')] annotate_stack.reverse() _annotate_fn_args(annotate_stack, stack[-1].opname, stack[-1].oparg, -1, False) qj._DEBUG_QJ and qj.LOG_FN('annotated fn_stack:\n%s\n\n' % '\n'.join(str(se) for se in fn_stack)) # Find the range of lines to search over. min_l = stack[-1].curr_l max_l = stack[0].curr_l for se in fn_stack: min_l = min(min_l, se.curr_l) max_l = max(max_l, se.curr_l) qj._DEBUG_QJ and qj.LOG_FN('source lines range: %d -> %d (indices: %d, %d)' % (min_l, max_l, min_l - source_offset, max_l - source_offset + 1)) source_chunk = ' '.join( [l for l in source_lines[min_l - source_offset:max_l - source_offset + 1] if l and not l.startswith('#')]) qj._DEBUG_QJ and qj.LOG_FN('source_chunk: %r' % source_chunk) # Build up all of the tokens for the function call. tokens = [] for se in fn_stack: opname = se.opname for oparg_repr in se.oparg_repr[::-1]: # Clean up the tokens if not oparg_repr: continue oparg_repr = re.escape(oparg_repr.replace('\n', '\\n')) tokens.append(oparg_repr) tokens.reverse() qj._DEBUG_QJ and qj.LOG_FN('extracted tokens: {}'.format(tokens)) if qj._DEBUG_QJ: assert tokens # Add tokens for the function call we're extracting. tokens = ['\\('] + tokens + ['\\)'] reg = '\b*?.*?\b*?'.join(tokens) qj._DEBUG_QJ and qj.LOG_FN(reg) # Search for the function call using the full set of tokens. # Expand the search with source lines after the current set if we don't find a match. shortest_match = None match_attempts = 0 max_match_attempts = 10 while not shortest_match and match_attempts < max_match_attempts: (shortest_match, _, _) = ( _find_earliest_shortest_match(source_chunk, reg, 0, len(source_chunk), num_attempts=10)) if not shortest_match: match_attempts += 1 min_l -= 1 prev_line = '' while not prev_line and min_l - source_offset >= 0 and min_l - source_offset < len(source_lines): prev_line = source_lines[min_l - source_offset] if prev_line.startswith('#'): prev_line = '' if not prev_line: min_l -= 1 prev_line += ' ' if prev_line else '' source_chunk = prev_line + source_chunk max_l += 1 next_line = '' while not next_line and max_l - source_offset >= 0 and max_l - source_offset < len(source_lines): next_line = source_lines[max_l - source_offset] if next_line.startswith('#'): next_line = '' if not next_line: max_l += 1 next_line = (' ' if next_line else '') + next_line source_chunk += next_line # Return the string for the function call if qj._DEBUG_QJ: assert shortest_match if shortest_match is not None: match = shortest_match.group(0) if qj._DEBUG_QJ: assert match.startswith('(') and match.endswith(')') # Do some parentheses cleanup. if match.startswith('('): match = match[1:] lparens = match.count('(') rparens = match.count(')') if lparens > rparens: match += ')' * (lparens - rparens) elif lparens < rparens: rparens_to_remove = rparens - lparens while len(match) and match[-1] == ')' and rparens_to_remove > 0: match = match[:-1] rparens_to_remove -= 1 match = match.strip() return match else: return ''
def function[_find_current_fn_call, parameter[co, lasti]]: constant[Find current function call in the byte code.] <ast.BoolOp object at 0x7da1b20d4130> if compare[call[name[sys].version_info][constant[0]] less[<] constant[3]] begin[:] variable[stack] assign[=] call[name[_build_instruction_stack], parameter[name[co], name[lasti]]] <ast.Tuple object at 0x7da1b20d5750> assign[=] call[name[inspect].getsourcelines, parameter[name[co]]] variable[source_lines] assign[=] <ast.ListComp object at 0x7da1b20d56f0> variable[fn_stack] assign[=] call[name[_collect_pops], parameter[call[name[stack]][<ast.Slice object at 0x7da1b20d5f90>], call[name[stack]][<ast.UnaryOp object at 0x7da1b20d4ca0>].stack_depth, list[[]], constant[0]]] if <ast.BoolOp object at 0x7da1b1f20970> begin[:] return[constant[<empty log>]] <ast.BoolOp object at 0x7da1b1f21420> variable[annotate_stack] assign[=] <ast.ListComp object at 0x7da1b1f204f0> call[name[annotate_stack].reverse, parameter[]] call[name[_annotate_fn_args], parameter[name[annotate_stack], call[name[stack]][<ast.UnaryOp object at 0x7da1b1f20f40>].opname, call[name[stack]][<ast.UnaryOp object at 0x7da1b1f21450>].oparg, <ast.UnaryOp object at 0x7da1b1f20ee0>, constant[False]]] <ast.BoolOp object at 0x7da1b1f20e50> variable[min_l] assign[=] call[name[stack]][<ast.UnaryOp object at 0x7da1b1f21600>].curr_l variable[max_l] assign[=] call[name[stack]][constant[0]].curr_l for taget[name[se]] in starred[name[fn_stack]] begin[:] variable[min_l] assign[=] call[name[min], parameter[name[min_l], name[se].curr_l]] variable[max_l] assign[=] call[name[max], parameter[name[max_l], name[se].curr_l]] <ast.BoolOp object at 0x7da1b2369d50> variable[source_chunk] assign[=] call[constant[ ].join, parameter[<ast.ListComp object at 0x7da1b236bee0>]] <ast.BoolOp object at 0x7da1b236b610> variable[tokens] assign[=] list[[]] for taget[name[se]] in starred[name[fn_stack]] begin[:] variable[opname] assign[=] name[se].opname for taget[name[oparg_repr]] in starred[call[name[se].oparg_repr][<ast.Slice object at 0x7da18fe92830>]] begin[:] if <ast.UnaryOp object at 0x7da18fe912a0> begin[:] continue variable[oparg_repr] assign[=] call[name[re].escape, parameter[call[name[oparg_repr].replace, parameter[constant[ ], constant[\n]]]]] call[name[tokens].append, parameter[name[oparg_repr]]] call[name[tokens].reverse, parameter[]] <ast.BoolOp object at 0x7da18fe93b50> if name[qj]._DEBUG_QJ begin[:] assert[name[tokens]] variable[tokens] assign[=] binary_operation[binary_operation[list[[<ast.Constant object at 0x7da1b209e020>]] + name[tokens]] + list[[<ast.Constant object at 0x7da1b209e5f0>]]] variable[reg] assign[=] call[constant[*?.*?*?].join, parameter[name[tokens]]] <ast.BoolOp object at 0x7da1b209e800> variable[shortest_match] assign[=] constant[None] variable[match_attempts] assign[=] constant[0] variable[max_match_attempts] assign[=] constant[10] while <ast.BoolOp object at 0x7da1b209e980> begin[:] <ast.Tuple object at 0x7da1b209da50> assign[=] call[name[_find_earliest_shortest_match], parameter[name[source_chunk], name[reg], constant[0], call[name[len], parameter[name[source_chunk]]]]] if <ast.UnaryOp object at 0x7da1b209d600> begin[:] <ast.AugAssign object at 0x7da1b209de10> <ast.AugAssign object at 0x7da1b209ce80> variable[prev_line] assign[=] constant[] while <ast.BoolOp object at 0x7da1b209e260> begin[:] variable[prev_line] assign[=] call[name[source_lines]][binary_operation[name[min_l] - name[source_offset]]] if call[name[prev_line].startswith, parameter[constant[#]]] begin[:] variable[prev_line] assign[=] constant[] if <ast.UnaryOp object at 0x7da1b209c3d0> begin[:] <ast.AugAssign object at 0x7da1b209c280> <ast.AugAssign object at 0x7da1b209e380> variable[source_chunk] assign[=] binary_operation[name[prev_line] + name[source_chunk]] <ast.AugAssign object at 0x7da1b209e410> variable[next_line] assign[=] constant[] while <ast.BoolOp object at 0x7da1b209e320> begin[:] variable[next_line] assign[=] call[name[source_lines]][binary_operation[name[max_l] - name[source_offset]]] if call[name[next_line].startswith, parameter[constant[#]]] begin[:] variable[next_line] assign[=] constant[] if <ast.UnaryOp object at 0x7da1b209c040> begin[:] <ast.AugAssign object at 0x7da1b209d1b0> variable[next_line] assign[=] binary_operation[<ast.IfExp object at 0x7da1b209ceb0> + name[next_line]] <ast.AugAssign object at 0x7da1b209d720> if name[qj]._DEBUG_QJ begin[:] assert[name[shortest_match]] if compare[name[shortest_match] is_not constant[None]] begin[:] variable[match] assign[=] call[name[shortest_match].group, parameter[constant[0]]] if name[qj]._DEBUG_QJ begin[:] assert[<ast.BoolOp object at 0x7da1b209c8b0>] if call[name[match].startswith, parameter[constant[(]]] begin[:] variable[match] assign[=] call[name[match]][<ast.Slice object at 0x7da1b1f7d6f0>] variable[lparens] assign[=] call[name[match].count, parameter[constant[(]]] variable[rparens] assign[=] call[name[match].count, parameter[constant[)]]] if compare[name[lparens] greater[>] name[rparens]] begin[:] <ast.AugAssign object at 0x7da1b1f7d180> variable[match] assign[=] call[name[match].strip, parameter[]] return[name[match]]
keyword[def] identifier[_find_current_fn_call] ( identifier[co] , identifier[lasti] ): literal[string] identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] . identifier[format] ( identifier[co] )) keyword[if] identifier[sys] . identifier[version_info] [ literal[int] ]< literal[int] : identifier[stack] = identifier[_build_instruction_stack] ( identifier[co] , identifier[lasti] ) keyword[else] : identifier[stack] = identifier[_build_instruction_stack3] ( identifier[co] , identifier[lasti] ) identifier[source_lines] , identifier[source_offset] = identifier[inspect] . identifier[getsourcelines] ( identifier[co] ) identifier[source_lines] =[ identifier[l] . identifier[strip] () keyword[for] identifier[l] keyword[in] identifier[source_lines] ] identifier[fn_stack] = identifier[_collect_pops] ( identifier[stack] [:- literal[int] ], identifier[stack] [- literal[int] ]. identifier[stack_depth] ,[], literal[int] ) keyword[if] keyword[not] identifier[fn_stack] keyword[and] identifier[stack] [- literal[int] ]. identifier[stack_depth] == literal[int] : keyword[return] literal[string] identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] % literal[string] . identifier[join] ( identifier[str] ( identifier[se] ) keyword[for] identifier[se] keyword[in] identifier[fn_stack] )) identifier[annotate_stack] =[ identifier[se] keyword[for] identifier[se] keyword[in] identifier[fn_stack] keyword[if] keyword[not] identifier[se] . identifier[opname] . identifier[startswith] ( literal[string] )] identifier[annotate_stack] . identifier[reverse] () identifier[_annotate_fn_args] ( identifier[annotate_stack] , identifier[stack] [- literal[int] ]. identifier[opname] , identifier[stack] [- literal[int] ]. identifier[oparg] ,- literal[int] , keyword[False] ) identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] % literal[string] . identifier[join] ( identifier[str] ( identifier[se] ) keyword[for] identifier[se] keyword[in] identifier[fn_stack] )) identifier[min_l] = identifier[stack] [- literal[int] ]. identifier[curr_l] identifier[max_l] = identifier[stack] [ literal[int] ]. identifier[curr_l] keyword[for] identifier[se] keyword[in] identifier[fn_stack] : identifier[min_l] = identifier[min] ( identifier[min_l] , identifier[se] . identifier[curr_l] ) identifier[max_l] = identifier[max] ( identifier[max_l] , identifier[se] . identifier[curr_l] ) identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] %( identifier[min_l] , identifier[max_l] , identifier[min_l] - identifier[source_offset] , identifier[max_l] - identifier[source_offset] + literal[int] )) identifier[source_chunk] = literal[string] . identifier[join] ( [ identifier[l] keyword[for] identifier[l] keyword[in] identifier[source_lines] [ identifier[min_l] - identifier[source_offset] : identifier[max_l] - identifier[source_offset] + literal[int] ] keyword[if] identifier[l] keyword[and] keyword[not] identifier[l] . identifier[startswith] ( literal[string] )]) identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] % identifier[source_chunk] ) identifier[tokens] =[] keyword[for] identifier[se] keyword[in] identifier[fn_stack] : identifier[opname] = identifier[se] . identifier[opname] keyword[for] identifier[oparg_repr] keyword[in] identifier[se] . identifier[oparg_repr] [::- literal[int] ]: keyword[if] keyword[not] identifier[oparg_repr] : keyword[continue] identifier[oparg_repr] = identifier[re] . identifier[escape] ( identifier[oparg_repr] . identifier[replace] ( literal[string] , literal[string] )) identifier[tokens] . identifier[append] ( identifier[oparg_repr] ) identifier[tokens] . identifier[reverse] () identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( literal[string] . identifier[format] ( identifier[tokens] )) keyword[if] identifier[qj] . identifier[_DEBUG_QJ] : keyword[assert] identifier[tokens] identifier[tokens] =[ literal[string] ]+ identifier[tokens] +[ literal[string] ] identifier[reg] = literal[string] . identifier[join] ( identifier[tokens] ) identifier[qj] . identifier[_DEBUG_QJ] keyword[and] identifier[qj] . identifier[LOG_FN] ( identifier[reg] ) identifier[shortest_match] = keyword[None] identifier[match_attempts] = literal[int] identifier[max_match_attempts] = literal[int] keyword[while] keyword[not] identifier[shortest_match] keyword[and] identifier[match_attempts] < identifier[max_match_attempts] : ( identifier[shortest_match] , identifier[_] , identifier[_] )=( identifier[_find_earliest_shortest_match] ( identifier[source_chunk] , identifier[reg] , literal[int] , identifier[len] ( identifier[source_chunk] ), identifier[num_attempts] = literal[int] )) keyword[if] keyword[not] identifier[shortest_match] : identifier[match_attempts] += literal[int] identifier[min_l] -= literal[int] identifier[prev_line] = literal[string] keyword[while] keyword[not] identifier[prev_line] keyword[and] identifier[min_l] - identifier[source_offset] >= literal[int] keyword[and] identifier[min_l] - identifier[source_offset] < identifier[len] ( identifier[source_lines] ): identifier[prev_line] = identifier[source_lines] [ identifier[min_l] - identifier[source_offset] ] keyword[if] identifier[prev_line] . identifier[startswith] ( literal[string] ): identifier[prev_line] = literal[string] keyword[if] keyword[not] identifier[prev_line] : identifier[min_l] -= literal[int] identifier[prev_line] += literal[string] keyword[if] identifier[prev_line] keyword[else] literal[string] identifier[source_chunk] = identifier[prev_line] + identifier[source_chunk] identifier[max_l] += literal[int] identifier[next_line] = literal[string] keyword[while] keyword[not] identifier[next_line] keyword[and] identifier[max_l] - identifier[source_offset] >= literal[int] keyword[and] identifier[max_l] - identifier[source_offset] < identifier[len] ( identifier[source_lines] ): identifier[next_line] = identifier[source_lines] [ identifier[max_l] - identifier[source_offset] ] keyword[if] identifier[next_line] . identifier[startswith] ( literal[string] ): identifier[next_line] = literal[string] keyword[if] keyword[not] identifier[next_line] : identifier[max_l] += literal[int] identifier[next_line] =( literal[string] keyword[if] identifier[next_line] keyword[else] literal[string] )+ identifier[next_line] identifier[source_chunk] += identifier[next_line] keyword[if] identifier[qj] . identifier[_DEBUG_QJ] : keyword[assert] identifier[shortest_match] keyword[if] identifier[shortest_match] keyword[is] keyword[not] keyword[None] : identifier[match] = identifier[shortest_match] . identifier[group] ( literal[int] ) keyword[if] identifier[qj] . identifier[_DEBUG_QJ] : keyword[assert] identifier[match] . identifier[startswith] ( literal[string] ) keyword[and] identifier[match] . identifier[endswith] ( literal[string] ) keyword[if] identifier[match] . identifier[startswith] ( literal[string] ): identifier[match] = identifier[match] [ literal[int] :] identifier[lparens] = identifier[match] . identifier[count] ( literal[string] ) identifier[rparens] = identifier[match] . identifier[count] ( literal[string] ) keyword[if] identifier[lparens] > identifier[rparens] : identifier[match] += literal[string] *( identifier[lparens] - identifier[rparens] ) keyword[elif] identifier[lparens] < identifier[rparens] : identifier[rparens_to_remove] = identifier[rparens] - identifier[lparens] keyword[while] identifier[len] ( identifier[match] ) keyword[and] identifier[match] [- literal[int] ]== literal[string] keyword[and] identifier[rparens_to_remove] > literal[int] : identifier[match] = identifier[match] [:- literal[int] ] identifier[rparens_to_remove] -= literal[int] identifier[match] = identifier[match] . identifier[strip] () keyword[return] identifier[match] keyword[else] : keyword[return] literal[string]
def _find_current_fn_call(co, lasti): """Find current function call in the byte code.""" qj._DEBUG_QJ and qj.LOG_FN('co = {}'.format(co)) if sys.version_info[0] < 3: stack = _build_instruction_stack(co, lasti) # depends on [control=['if'], data=[]] else: stack = _build_instruction_stack3(co, lasti) (source_lines, source_offset) = inspect.getsourcelines(co) source_lines = [l.strip() for l in source_lines] # Apply stack effects backwards until we arrive at the stack entries for a complete function call fn_stack = _collect_pops(stack[:-1], stack[-1].stack_depth, [], 0) if not fn_stack and stack[-1].stack_depth == 0: # The function call took 0 arguments, so return early with a special string. return '<empty log>' # depends on [control=['if'], data=[]] qj._DEBUG_QJ and qj.LOG_FN('collected fn_stack:\n%s\n\n' % '\n'.join((str(se) for se in fn_stack))) # Prepare to annotate the stack with extra symbols, and filter out MAKE_FUNCTION and MAKE_CLOSURE calls, which are no longer needed. annotate_stack = [se for se in fn_stack if not se.opname.startswith('MAKE_')] annotate_stack.reverse() _annotate_fn_args(annotate_stack, stack[-1].opname, stack[-1].oparg, -1, False) qj._DEBUG_QJ and qj.LOG_FN('annotated fn_stack:\n%s\n\n' % '\n'.join((str(se) for se in fn_stack))) # Find the range of lines to search over. min_l = stack[-1].curr_l max_l = stack[0].curr_l for se in fn_stack: min_l = min(min_l, se.curr_l) max_l = max(max_l, se.curr_l) # depends on [control=['for'], data=['se']] qj._DEBUG_QJ and qj.LOG_FN('source lines range: %d -> %d (indices: %d, %d)' % (min_l, max_l, min_l - source_offset, max_l - source_offset + 1)) source_chunk = ' '.join([l for l in source_lines[min_l - source_offset:max_l - source_offset + 1] if l and (not l.startswith('#'))]) qj._DEBUG_QJ and qj.LOG_FN('source_chunk: %r' % source_chunk) # Build up all of the tokens for the function call. tokens = [] for se in fn_stack: opname = se.opname for oparg_repr in se.oparg_repr[::-1]: # Clean up the tokens if not oparg_repr: continue # depends on [control=['if'], data=[]] oparg_repr = re.escape(oparg_repr.replace('\n', '\\n')) tokens.append(oparg_repr) # depends on [control=['for'], data=['oparg_repr']] # depends on [control=['for'], data=['se']] tokens.reverse() qj._DEBUG_QJ and qj.LOG_FN('extracted tokens: {}'.format(tokens)) if qj._DEBUG_QJ: assert tokens # depends on [control=['if'], data=[]] # Add tokens for the function call we're extracting. tokens = ['\\('] + tokens + ['\\)'] reg = '\x08*?.*?\x08*?'.join(tokens) qj._DEBUG_QJ and qj.LOG_FN(reg) # Search for the function call using the full set of tokens. # Expand the search with source lines after the current set if we don't find a match. shortest_match = None match_attempts = 0 max_match_attempts = 10 while not shortest_match and match_attempts < max_match_attempts: (shortest_match, _, _) = _find_earliest_shortest_match(source_chunk, reg, 0, len(source_chunk), num_attempts=10) if not shortest_match: match_attempts += 1 min_l -= 1 prev_line = '' while not prev_line and min_l - source_offset >= 0 and (min_l - source_offset < len(source_lines)): prev_line = source_lines[min_l - source_offset] if prev_line.startswith('#'): prev_line = '' # depends on [control=['if'], data=[]] if not prev_line: min_l -= 1 # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] prev_line += ' ' if prev_line else '' source_chunk = prev_line + source_chunk max_l += 1 next_line = '' while not next_line and max_l - source_offset >= 0 and (max_l - source_offset < len(source_lines)): next_line = source_lines[max_l - source_offset] if next_line.startswith('#'): next_line = '' # depends on [control=['if'], data=[]] if not next_line: max_l += 1 # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] next_line = (' ' if next_line else '') + next_line source_chunk += next_line # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] # Return the string for the function call if qj._DEBUG_QJ: assert shortest_match # depends on [control=['if'], data=[]] if shortest_match is not None: match = shortest_match.group(0) if qj._DEBUG_QJ: assert match.startswith('(') and match.endswith(')') # depends on [control=['if'], data=[]] # Do some parentheses cleanup. if match.startswith('('): match = match[1:] # depends on [control=['if'], data=[]] lparens = match.count('(') rparens = match.count(')') if lparens > rparens: match += ')' * (lparens - rparens) # depends on [control=['if'], data=['lparens', 'rparens']] elif lparens < rparens: rparens_to_remove = rparens - lparens while len(match) and match[-1] == ')' and (rparens_to_remove > 0): match = match[:-1] rparens_to_remove -= 1 # depends on [control=['while'], data=[]] # depends on [control=['if'], data=['lparens', 'rparens']] match = match.strip() return match # depends on [control=['if'], data=['shortest_match']] else: return ''
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_dim = end_dim return marginals
def function[_split_covariance_into_marginals, parameter[covariance, block_sizes]]: constant[Split a covariance matrix into block-diagonal marginals of given sizes.] variable[start_dim] assign[=] constant[0] variable[marginals] assign[=] list[[]] for taget[name[size]] in starred[name[block_sizes]] begin[:] variable[end_dim] assign[=] binary_operation[name[start_dim] + name[size]] call[name[marginals].append, parameter[call[name[covariance]][tuple[[<ast.Constant object at 0x7da1b03e3be0>, <ast.Slice object at 0x7da1b03e3bb0>, <ast.Slice object at 0x7da1b03e3a30>]]]]] variable[start_dim] assign[=] name[end_dim] return[name[marginals]]
keyword[def] identifier[_split_covariance_into_marginals] ( identifier[covariance] , identifier[block_sizes] ): literal[string] identifier[start_dim] = literal[int] identifier[marginals] =[] keyword[for] identifier[size] keyword[in] identifier[block_sizes] : identifier[end_dim] = identifier[start_dim] + identifier[size] identifier[marginals] . identifier[append] ( identifier[covariance] [..., identifier[start_dim] : identifier[end_dim] , identifier[start_dim] : identifier[end_dim] ]) identifier[start_dim] = identifier[end_dim] keyword[return] identifier[marginals]
def _split_covariance_into_marginals(covariance, block_sizes): """Split a covariance matrix into block-diagonal marginals of given sizes.""" start_dim = 0 marginals = [] for size in block_sizes: end_dim = start_dim + size marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim]) start_dim = end_dim # depends on [control=['for'], data=['size']] return marginals
def all_states(self) -> Tuple[State, ...]: """ Return all the possible states of this influence graph. """ return tuple(self._transform_list_of_states_to_state(states) for states in self._cartesian_product_of_every_states_of_each_genes())
def function[all_states, parameter[self]]: constant[ Return all the possible states of this influence graph. ] return[call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da204622e60>]]]
keyword[def] identifier[all_states] ( identifier[self] )-> identifier[Tuple] [ identifier[State] ,...]: literal[string] keyword[return] identifier[tuple] ( identifier[self] . identifier[_transform_list_of_states_to_state] ( identifier[states] ) keyword[for] identifier[states] keyword[in] identifier[self] . identifier[_cartesian_product_of_every_states_of_each_genes] ())
def all_states(self) -> Tuple[State, ...]: """ Return all the possible states of this influence graph. """ return tuple((self._transform_list_of_states_to_state(states) for states in self._cartesian_product_of_every_states_of_each_genes()))
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_filename(template_filename) yield files.template(state, host, template_filename, temp_file, **data) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) else: yield temp_file
def function[script_template, parameter[state, host, template_filename, chdir]]: constant[ Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ] variable[temp_file] assign[=] call[name[state].get_temp_filename, parameter[name[template_filename]]] <ast.Yield object at 0x7da18dc07940> <ast.Yield object at 0x7da18dc04dc0> if name[chdir] begin[:] <ast.Yield object at 0x7da18dc04670>
keyword[def] identifier[script_template] ( identifier[state] , identifier[host] , identifier[template_filename] , identifier[chdir] = keyword[None] ,** identifier[data] ): literal[string] identifier[temp_file] = identifier[state] . identifier[get_temp_filename] ( identifier[template_filename] ) keyword[yield] identifier[files] . identifier[template] ( identifier[state] , identifier[host] , identifier[template_filename] , identifier[temp_file] ,** identifier[data] ) keyword[yield] identifier[chmod] ( identifier[temp_file] , literal[string] ) keyword[if] identifier[chdir] : keyword[yield] literal[string] . identifier[format] ( identifier[chdir] , identifier[temp_file] ) keyword[else] : keyword[yield] identifier[temp_file]
def script_template(state, host, template_filename, chdir=None, **data): """ Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script """ temp_file = state.get_temp_filename(template_filename) yield files.template(state, host, template_filename, temp_file, **data) yield chmod(temp_file, '+x') if chdir: yield 'cd {0} && {1}'.format(chdir, temp_file) # depends on [control=['if'], data=[]] else: yield temp_file
def search(cls, five9, filters): """Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. """ return cls._name_search(five9.configuration.getDispositions, filters)
def function[search, parameter[cls, five9, filters]]: constant[Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. ] return[call[name[cls]._name_search, parameter[name[five9].configuration.getDispositions, name[filters]]]]
keyword[def] identifier[search] ( identifier[cls] , identifier[five9] , identifier[filters] ): literal[string] keyword[return] identifier[cls] . identifier[_name_search] ( identifier[five9] . identifier[configuration] . identifier[getDispositions] , identifier[filters] )
def search(cls, five9, filters): """Search for a record on the remote and return the results. Args: five9 (five9.Five9): The authenticated Five9 remote. filters (dict): A dictionary of search parameters, keyed by the name of the field to search. This should conform to the schema defined in :func:`five9.Five9.create_criteria`. Returns: list[BaseModel]: A list of records representing the result. """ return cls._name_search(five9.configuration.getDispositions, filters)
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([ item[0] for item in sorted( dict_obj.items(), key=lambda item: item[1], reverse=True )[:n] ])
def function[get_keys_of_max_n, parameter[dict_obj, n]]: constant[Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] ] return[call[name[sorted], parameter[<ast.ListComp object at 0x7da18ede43a0>]]]
keyword[def] identifier[get_keys_of_max_n] ( identifier[dict_obj] , identifier[n] ): literal[string] keyword[return] identifier[sorted] ([ identifier[item] [ literal[int] ] keyword[for] identifier[item] keyword[in] identifier[sorted] ( identifier[dict_obj] . identifier[items] (), identifier[key] = keyword[lambda] identifier[item] : identifier[item] [ literal[int] ], identifier[reverse] = keyword[True] )[: identifier[n] ] ])
def get_keys_of_max_n(dict_obj, n): """Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c'] """ return sorted([item[0] for item in sorted(dict_obj.items(), key=lambda item: item[1], reverse=True)[:n]])
def write_bits(self, bits): """Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream. """ for bit in bits: self._bits.append(bit) while len(self._bits) >= 8: byte_bits = [self._bits.popleft() for x in six.moves.range(8)] byte = bits_to_bytes(byte_bits) self._stream.write(byte)
def function[write_bits, parameter[self, bits]]: constant[Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream. ] for taget[name[bit]] in starred[name[bits]] begin[:] call[name[self]._bits.append, parameter[name[bit]]] while compare[call[name[len], parameter[name[self]._bits]] greater_or_equal[>=] constant[8]] begin[:] variable[byte_bits] assign[=] <ast.ListComp object at 0x7da204623a00> variable[byte] assign[=] call[name[bits_to_bytes], parameter[name[byte_bits]]] call[name[self]._stream.write, parameter[name[byte]]]
keyword[def] identifier[write_bits] ( identifier[self] , identifier[bits] ): literal[string] keyword[for] identifier[bit] keyword[in] identifier[bits] : identifier[self] . identifier[_bits] . identifier[append] ( identifier[bit] ) keyword[while] identifier[len] ( identifier[self] . identifier[_bits] )>= literal[int] : identifier[byte_bits] =[ identifier[self] . identifier[_bits] . identifier[popleft] () keyword[for] identifier[x] keyword[in] identifier[six] . identifier[moves] . identifier[range] ( literal[int] )] identifier[byte] = identifier[bits_to_bytes] ( identifier[byte_bits] ) identifier[self] . identifier[_stream] . identifier[write] ( identifier[byte] )
def write_bits(self, bits): """Write the bits to the stream. Add the bits to the existing unflushed bits and write complete bytes to the stream. """ for bit in bits: self._bits.append(bit) # depends on [control=['for'], data=['bit']] while len(self._bits) >= 8: byte_bits = [self._bits.popleft() for x in six.moves.range(8)] byte = bits_to_bytes(byte_bits) self._stream.write(byte) # depends on [control=['while'], data=[]]
def compareChunks(handles, chunk_size=CHUNK_SIZE): """Group a list of file handles based on equality of the next chunk of data read from them. :param handles: A list of open handles for file-like objects with otentially-identical contents. :param chunk_size: The amount of data to read from each handle every time this function is called. :returns: Two lists of lists: * Lists to be fed back into this function individually * Finished groups of duplicate paths. (including unique files as single-file lists) :rtype: ``(list, list)`` .. attention:: File handles will be closed when no longer needed .. todo:: Discard chunk contents immediately once they're no longer needed """ chunks = [(path, fh, fh.read(chunk_size)) for path, fh, _ in handles] more, done = [], [] # While there are combinations not yet tried... while chunks: # Compare the first chunk to all successive chunks matches, non_matches = [chunks[0]], [] for chunk in chunks[1:]: if matches[0][2] == chunk[2]: matches.append(chunk) else: non_matches.append(chunk) # Check for EOF or obviously unique files if len(matches) == 1 or matches[0][2] == "": for x in matches: x[1].close() done.append([x[0] for x in matches]) else: more.append(matches) chunks = non_matches return more, done
def function[compareChunks, parameter[handles, chunk_size]]: constant[Group a list of file handles based on equality of the next chunk of data read from them. :param handles: A list of open handles for file-like objects with otentially-identical contents. :param chunk_size: The amount of data to read from each handle every time this function is called. :returns: Two lists of lists: * Lists to be fed back into this function individually * Finished groups of duplicate paths. (including unique files as single-file lists) :rtype: ``(list, list)`` .. attention:: File handles will be closed when no longer needed .. todo:: Discard chunk contents immediately once they're no longer needed ] variable[chunks] assign[=] <ast.ListComp object at 0x7da1b2344d00> <ast.Tuple object at 0x7da1b2347f70> assign[=] tuple[[<ast.List object at 0x7da1b2346920>, <ast.List object at 0x7da1b2345600>]] while name[chunks] begin[:] <ast.Tuple object at 0x7da1b23456c0> assign[=] tuple[[<ast.List object at 0x7da1b2347190>, <ast.List object at 0x7da1b23455a0>]] for taget[name[chunk]] in starred[call[name[chunks]][<ast.Slice object at 0x7da1b2344430>]] begin[:] if compare[call[call[name[matches]][constant[0]]][constant[2]] equal[==] call[name[chunk]][constant[2]]] begin[:] call[name[matches].append, parameter[name[chunk]]] if <ast.BoolOp object at 0x7da1b2347250> begin[:] for taget[name[x]] in starred[name[matches]] begin[:] call[call[name[x]][constant[1]].close, parameter[]] call[name[done].append, parameter[<ast.ListComp object at 0x7da1b2347100>]] variable[chunks] assign[=] name[non_matches] return[tuple[[<ast.Name object at 0x7da1b2344370>, <ast.Name object at 0x7da1b2345ab0>]]]
keyword[def] identifier[compareChunks] ( identifier[handles] , identifier[chunk_size] = identifier[CHUNK_SIZE] ): literal[string] identifier[chunks] =[( identifier[path] , identifier[fh] , identifier[fh] . identifier[read] ( identifier[chunk_size] )) keyword[for] identifier[path] , identifier[fh] , identifier[_] keyword[in] identifier[handles] ] identifier[more] , identifier[done] =[],[] keyword[while] identifier[chunks] : identifier[matches] , identifier[non_matches] =[ identifier[chunks] [ literal[int] ]],[] keyword[for] identifier[chunk] keyword[in] identifier[chunks] [ literal[int] :]: keyword[if] identifier[matches] [ literal[int] ][ literal[int] ]== identifier[chunk] [ literal[int] ]: identifier[matches] . identifier[append] ( identifier[chunk] ) keyword[else] : identifier[non_matches] . identifier[append] ( identifier[chunk] ) keyword[if] identifier[len] ( identifier[matches] )== literal[int] keyword[or] identifier[matches] [ literal[int] ][ literal[int] ]== literal[string] : keyword[for] identifier[x] keyword[in] identifier[matches] : identifier[x] [ literal[int] ]. identifier[close] () identifier[done] . identifier[append] ([ identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[matches] ]) keyword[else] : identifier[more] . identifier[append] ( identifier[matches] ) identifier[chunks] = identifier[non_matches] keyword[return] identifier[more] , identifier[done]
def compareChunks(handles, chunk_size=CHUNK_SIZE): """Group a list of file handles based on equality of the next chunk of data read from them. :param handles: A list of open handles for file-like objects with otentially-identical contents. :param chunk_size: The amount of data to read from each handle every time this function is called. :returns: Two lists of lists: * Lists to be fed back into this function individually * Finished groups of duplicate paths. (including unique files as single-file lists) :rtype: ``(list, list)`` .. attention:: File handles will be closed when no longer needed .. todo:: Discard chunk contents immediately once they're no longer needed """ chunks = [(path, fh, fh.read(chunk_size)) for (path, fh, _) in handles] (more, done) = ([], []) # While there are combinations not yet tried... while chunks: # Compare the first chunk to all successive chunks (matches, non_matches) = ([chunks[0]], []) for chunk in chunks[1:]: if matches[0][2] == chunk[2]: matches.append(chunk) # depends on [control=['if'], data=[]] else: non_matches.append(chunk) # depends on [control=['for'], data=['chunk']] # Check for EOF or obviously unique files if len(matches) == 1 or matches[0][2] == '': for x in matches: x[1].close() # depends on [control=['for'], data=['x']] done.append([x[0] for x in matches]) # depends on [control=['if'], data=[]] else: more.append(matches) chunks = non_matches # depends on [control=['while'], data=[]] return (more, done)
def auth_in_stage2(self,stanza): """Handle the second stage (<iq type='set'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if "plain" not in self.auth_methods and "digest" not in self.auth_methods: iq=stanza.make_error_response("not-allowed") self.send(iq) return username=stanza.xpath_eval("a:query/a:username",{"a":"jabber:iq:auth"}) if username: username=from_utf8(username[0].getContent()) resource=stanza.xpath_eval("a:query/a:resource",{"a":"jabber:iq:auth"}) if resource: resource=from_utf8(resource[0].getContent()) if not username or not resource: self.__logger.debug("No username or resource found in auth request") iq=stanza.make_error_response("bad-request") self.send(iq) return if stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}): if "plain" not in self.auth_methods: iq=stanza.make_error_response("not-allowed") self.send(iq) return else: return self._plain_auth_in_stage2(username,resource,stanza) if stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}): if "plain" not in self.auth_methods: iq=stanza.make_error_response("not-allowed") self.send(iq) return else: return self._digest_auth_in_stage2(username,resource,stanza) finally: self.lock.release()
def function[auth_in_stage2, parameter[self, stanza]]: constant[Handle the second stage (<iq type='set'/>) of legacy ("plain" or "digest") authentication. [server only]] call[name[self].lock.acquire, parameter[]] <ast.Try object at 0x7da1b00e6e90>
keyword[def] identifier[auth_in_stage2] ( identifier[self] , identifier[stanza] ): literal[string] identifier[self] . identifier[lock] . identifier[acquire] () keyword[try] : keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[auth_methods] keyword[and] literal[string] keyword[not] keyword[in] identifier[self] . identifier[auth_methods] : identifier[iq] = identifier[stanza] . identifier[make_error_response] ( literal[string] ) identifier[self] . identifier[send] ( identifier[iq] ) keyword[return] identifier[username] = identifier[stanza] . identifier[xpath_eval] ( literal[string] ,{ literal[string] : literal[string] }) keyword[if] identifier[username] : identifier[username] = identifier[from_utf8] ( identifier[username] [ literal[int] ]. identifier[getContent] ()) identifier[resource] = identifier[stanza] . identifier[xpath_eval] ( literal[string] ,{ literal[string] : literal[string] }) keyword[if] identifier[resource] : identifier[resource] = identifier[from_utf8] ( identifier[resource] [ literal[int] ]. identifier[getContent] ()) keyword[if] keyword[not] identifier[username] keyword[or] keyword[not] identifier[resource] : identifier[self] . identifier[__logger] . identifier[debug] ( literal[string] ) identifier[iq] = identifier[stanza] . identifier[make_error_response] ( literal[string] ) identifier[self] . identifier[send] ( identifier[iq] ) keyword[return] keyword[if] identifier[stanza] . identifier[xpath_eval] ( literal[string] ,{ literal[string] : literal[string] }): keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[auth_methods] : identifier[iq] = identifier[stanza] . identifier[make_error_response] ( literal[string] ) identifier[self] . identifier[send] ( identifier[iq] ) keyword[return] keyword[else] : keyword[return] identifier[self] . identifier[_plain_auth_in_stage2] ( identifier[username] , identifier[resource] , identifier[stanza] ) keyword[if] identifier[stanza] . identifier[xpath_eval] ( literal[string] ,{ literal[string] : literal[string] }): keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[auth_methods] : identifier[iq] = identifier[stanza] . identifier[make_error_response] ( literal[string] ) identifier[self] . identifier[send] ( identifier[iq] ) keyword[return] keyword[else] : keyword[return] identifier[self] . identifier[_digest_auth_in_stage2] ( identifier[username] , identifier[resource] , identifier[stanza] ) keyword[finally] : identifier[self] . identifier[lock] . identifier[release] ()
def auth_in_stage2(self, stanza): """Handle the second stage (<iq type='set'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if 'plain' not in self.auth_methods and 'digest' not in self.auth_methods: iq = stanza.make_error_response('not-allowed') self.send(iq) return # depends on [control=['if'], data=[]] username = stanza.xpath_eval('a:query/a:username', {'a': 'jabber:iq:auth'}) if username: username = from_utf8(username[0].getContent()) # depends on [control=['if'], data=[]] resource = stanza.xpath_eval('a:query/a:resource', {'a': 'jabber:iq:auth'}) if resource: resource = from_utf8(resource[0].getContent()) # depends on [control=['if'], data=[]] if not username or not resource: self.__logger.debug('No username or resource found in auth request') iq = stanza.make_error_response('bad-request') self.send(iq) return # depends on [control=['if'], data=[]] if stanza.xpath_eval('a:query/a:password', {'a': 'jabber:iq:auth'}): if 'plain' not in self.auth_methods: iq = stanza.make_error_response('not-allowed') self.send(iq) return # depends on [control=['if'], data=[]] else: return self._plain_auth_in_stage2(username, resource, stanza) # depends on [control=['if'], data=[]] if stanza.xpath_eval('a:query/a:digest', {'a': 'jabber:iq:auth'}): if 'plain' not in self.auth_methods: iq = stanza.make_error_response('not-allowed') self.send(iq) return # depends on [control=['if'], data=[]] else: return self._digest_auth_in_stage2(username, resource, stanza) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] finally: self.lock.release()
def add_hosted_zone_id_for_alias_target_if_missing(self, rs): """Add proper hosted zone id to record set alias target if missing.""" alias_target = getattr(rs, "AliasTarget", None) if alias_target: hosted_zone_id = getattr(alias_target, "HostedZoneId", None) if not hosted_zone_id: dns_name = alias_target.DNSName if dns_name.endswith(CF_DOMAIN): alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID elif dns_name.endswith(ELB_DOMAIN): region = dns_name.split('.')[-5] alias_target.HostedZoneId = ELB_ZONE_IDS[region] elif dns_name in S3_WEBSITE_ZONE_IDS: alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name] else: alias_target.HostedZoneId = self.hosted_zone_id return rs
def function[add_hosted_zone_id_for_alias_target_if_missing, parameter[self, rs]]: constant[Add proper hosted zone id to record set alias target if missing.] variable[alias_target] assign[=] call[name[getattr], parameter[name[rs], constant[AliasTarget], constant[None]]] if name[alias_target] begin[:] variable[hosted_zone_id] assign[=] call[name[getattr], parameter[name[alias_target], constant[HostedZoneId], constant[None]]] if <ast.UnaryOp object at 0x7da1b069fa90> begin[:] variable[dns_name] assign[=] name[alias_target].DNSName if call[name[dns_name].endswith, parameter[name[CF_DOMAIN]]] begin[:] name[alias_target].HostedZoneId assign[=] name[CLOUDFRONT_ZONE_ID] return[name[rs]]
keyword[def] identifier[add_hosted_zone_id_for_alias_target_if_missing] ( identifier[self] , identifier[rs] ): literal[string] identifier[alias_target] = identifier[getattr] ( identifier[rs] , literal[string] , keyword[None] ) keyword[if] identifier[alias_target] : identifier[hosted_zone_id] = identifier[getattr] ( identifier[alias_target] , literal[string] , keyword[None] ) keyword[if] keyword[not] identifier[hosted_zone_id] : identifier[dns_name] = identifier[alias_target] . identifier[DNSName] keyword[if] identifier[dns_name] . identifier[endswith] ( identifier[CF_DOMAIN] ): identifier[alias_target] . identifier[HostedZoneId] = identifier[CLOUDFRONT_ZONE_ID] keyword[elif] identifier[dns_name] . identifier[endswith] ( identifier[ELB_DOMAIN] ): identifier[region] = identifier[dns_name] . identifier[split] ( literal[string] )[- literal[int] ] identifier[alias_target] . identifier[HostedZoneId] = identifier[ELB_ZONE_IDS] [ identifier[region] ] keyword[elif] identifier[dns_name] keyword[in] identifier[S3_WEBSITE_ZONE_IDS] : identifier[alias_target] . identifier[HostedZoneId] = identifier[S3_WEBSITE_ZONE_IDS] [ identifier[dns_name] ] keyword[else] : identifier[alias_target] . identifier[HostedZoneId] = identifier[self] . identifier[hosted_zone_id] keyword[return] identifier[rs]
def add_hosted_zone_id_for_alias_target_if_missing(self, rs): """Add proper hosted zone id to record set alias target if missing.""" alias_target = getattr(rs, 'AliasTarget', None) if alias_target: hosted_zone_id = getattr(alias_target, 'HostedZoneId', None) if not hosted_zone_id: dns_name = alias_target.DNSName if dns_name.endswith(CF_DOMAIN): alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID # depends on [control=['if'], data=[]] elif dns_name.endswith(ELB_DOMAIN): region = dns_name.split('.')[-5] alias_target.HostedZoneId = ELB_ZONE_IDS[region] # depends on [control=['if'], data=[]] elif dns_name in S3_WEBSITE_ZONE_IDS: alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name] # depends on [control=['if'], data=['dns_name', 'S3_WEBSITE_ZONE_IDS']] else: alias_target.HostedZoneId = self.hosted_zone_id # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return rs
def start(state_registration_number, state_abbreviation): """ This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins) """ state_abbreviation = state_abbreviation.upper() states_validations = { 'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")", 'AL': "al.start(" + "\"" + state_registration_number + "\"" + ")", 'AM': "am.start(" + "\"" + state_registration_number + "\"" + ")", 'AP': "ap.start(" + "\"" + state_registration_number + "\"" + ")", 'BA': "ba.start(" + "\"" + state_registration_number + "\"" + ")", 'CE': "ce.start(" + "\"" + state_registration_number + "\"" + ")", 'DF': "df.start(" + "\"" + state_registration_number + "\"" + ")", 'ES': "es.start(" + "\"" + state_registration_number + "\"" + ")", 'GO': "go.start(" + "\"" + state_registration_number + "\"" + ")", 'MA': "ma.start(" + "\"" + state_registration_number + "\"" + ")", 'MG': "mg.start(" + "\"" + state_registration_number + "\"" + ")", 'MS': "ms.start(" + "\"" + state_registration_number + "\"" + ")", 'MT': "mt.start(" + "\"" + state_registration_number + "\"" + ")", 'PA': "pa.start(" + "\"" + state_registration_number + "\"" + ")", 'PB': "pb.start(" + "\"" + state_registration_number + "\"" + ")", 'PE': "pe.start(" + "\"" + state_registration_number + "\"" + ")", 'PI': "pi.start(" + "\"" + state_registration_number + "\"" + ")", 'PR': "pr.start(" + "\"" + state_registration_number + "\"" + ")", 'RJ': "rj.start(" + "\"" + state_registration_number + "\"" + ")", 'RN': "rn.start(" + "\"" + state_registration_number + "\"" + ")", 'RO': "ro.start(" + "\"" + state_registration_number + "\"" + ")", 'RR': "rr.start(" + "\"" + state_registration_number + "\"" + ")", 'RS': "rs.start(" + "\"" + state_registration_number + "\"" + ")", 'SC': "sc.start(" + "\"" + state_registration_number + "\"" + ")", 'SE': "se.start(" + "\"" + state_registration_number + "\"" + ")", 'SP': "sp.start(" + "\"" + state_registration_number + "\"" + ")", 'TO': "to.start(" + "\"" + state_registration_number + "\"" + ")" } exec('validity = ' + states_validations[state_abbreviation]) return validity
def function[start, parameter[state_registration_number, state_abbreviation]]: constant[ This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins) ] variable[state_abbreviation] assign[=] call[name[state_abbreviation].upper, parameter[]] variable[states_validations] assign[=] dictionary[[<ast.Constant object at 0x7da1b1993b50>, <ast.Constant object at 0x7da1b1993b20>, <ast.Constant object at 0x7da1b1993af0>, <ast.Constant object at 0x7da1b1993ac0>, <ast.Constant object at 0x7da1b1993a90>, <ast.Constant object at 0x7da1b1993a60>, <ast.Constant object at 0x7da1b1993a30>, <ast.Constant object at 0x7da1b1993a00>, <ast.Constant object at 0x7da1b19939d0>, <ast.Constant object at 0x7da1b19939a0>, <ast.Constant object at 0x7da1b1993970>, <ast.Constant object at 0x7da1b1993940>, <ast.Constant object at 0x7da1b1993910>, <ast.Constant object at 0x7da1b19938e0>, <ast.Constant object at 0x7da1b19938b0>, <ast.Constant object at 0x7da1b1993880>, <ast.Constant object at 0x7da1b1993850>, <ast.Constant object at 0x7da1b1993820>, <ast.Constant object at 0x7da1b19937f0>, <ast.Constant object at 0x7da1b19937c0>, <ast.Constant object at 0x7da1b1993790>, <ast.Constant object at 0x7da1b1993760>, <ast.Constant object at 0x7da1b1993730>, <ast.Constant object at 0x7da1b1993700>, <ast.Constant object at 0x7da1b19936d0>, <ast.Constant object at 0x7da1b19936a0>, <ast.Constant object at 0x7da1b1993670>], [<ast.BinOp object at 0x7da1b1993640>, <ast.BinOp object at 0x7da1b1993490>, <ast.BinOp object at 0x7da1b19932e0>, <ast.BinOp object at 0x7da1b1993130>, <ast.BinOp object at 0x7da1b1992f80>, <ast.BinOp object at 0x7da1b1992dd0>, <ast.BinOp object at 0x7da1b1992c20>, <ast.BinOp object at 0x7da1b1992a70>, <ast.BinOp object at 0x7da1b19928c0>, <ast.BinOp object at 0x7da1b1992710>, <ast.BinOp object at 0x7da1b1992560>, <ast.BinOp object at 0x7da1b19923b0>, <ast.BinOp object at 0x7da1b1992200>, <ast.BinOp object at 0x7da1b1992050>, <ast.BinOp object at 0x7da1b1991ea0>, <ast.BinOp object at 0x7da1b1991cf0>, <ast.BinOp object at 0x7da1b1991b40>, <ast.BinOp object at 0x7da1b1991990>, <ast.BinOp object at 0x7da1b1990520>, <ast.BinOp object at 0x7da1b1990370>, <ast.BinOp object at 0x7da1b19901c0>, <ast.BinOp object at 0x7da1b19905b0>, <ast.BinOp object at 0x7da1b1990760>, <ast.BinOp object at 0x7da1b1990910>, <ast.BinOp object at 0x7da1b19914e0>, <ast.BinOp object at 0x7da1b1991690>, <ast.BinOp object at 0x7da1b1991720>]] call[name[exec], parameter[binary_operation[constant[validity = ] + call[name[states_validations]][name[state_abbreviation]]]]] return[name[validity]]
keyword[def] identifier[start] ( identifier[state_registration_number] , identifier[state_abbreviation] ): literal[string] identifier[state_abbreviation] = identifier[state_abbreviation] . identifier[upper] () identifier[states_validations] ={ literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] , literal[string] : literal[string] + literal[string] + identifier[state_registration_number] + literal[string] + literal[string] } identifier[exec] ( literal[string] + identifier[states_validations] [ identifier[state_abbreviation] ]) keyword[return] identifier[validity]
def start(state_registration_number, state_abbreviation): """ This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (Bahia) CE (Ceará) DF (Distrito Federal) ES (Espírito Santo') GO (Goias) MA (Maranhão) MG (Minas Gerais) MS (Mato Grosso do Sul) MT (Mato Grosso) PA (Pará) PB (Paraíba) PE (Pernambuco) PI (Piauí) PR (Paraná) RJ (Rio de Janeiro) RN (Rio Grande do Norte) RO (Rondônia) RR (Roraima) RS (Rio Grande do Sul) SC (Santa Catarina) SE (Sergipe) SP (São Paulo) TO (Tocantins) """ state_abbreviation = state_abbreviation.upper() states_validations = {'AC': 'ac.start(' + '"' + state_registration_number + '"' + ')', 'AL': 'al.start(' + '"' + state_registration_number + '"' + ')', 'AM': 'am.start(' + '"' + state_registration_number + '"' + ')', 'AP': 'ap.start(' + '"' + state_registration_number + '"' + ')', 'BA': 'ba.start(' + '"' + state_registration_number + '"' + ')', 'CE': 'ce.start(' + '"' + state_registration_number + '"' + ')', 'DF': 'df.start(' + '"' + state_registration_number + '"' + ')', 'ES': 'es.start(' + '"' + state_registration_number + '"' + ')', 'GO': 'go.start(' + '"' + state_registration_number + '"' + ')', 'MA': 'ma.start(' + '"' + state_registration_number + '"' + ')', 'MG': 'mg.start(' + '"' + state_registration_number + '"' + ')', 'MS': 'ms.start(' + '"' + state_registration_number + '"' + ')', 'MT': 'mt.start(' + '"' + state_registration_number + '"' + ')', 'PA': 'pa.start(' + '"' + state_registration_number + '"' + ')', 'PB': 'pb.start(' + '"' + state_registration_number + '"' + ')', 'PE': 'pe.start(' + '"' + state_registration_number + '"' + ')', 'PI': 'pi.start(' + '"' + state_registration_number + '"' + ')', 'PR': 'pr.start(' + '"' + state_registration_number + '"' + ')', 'RJ': 'rj.start(' + '"' + state_registration_number + '"' + ')', 'RN': 'rn.start(' + '"' + state_registration_number + '"' + ')', 'RO': 'ro.start(' + '"' + state_registration_number + '"' + ')', 'RR': 'rr.start(' + '"' + state_registration_number + '"' + ')', 'RS': 'rs.start(' + '"' + state_registration_number + '"' + ')', 'SC': 'sc.start(' + '"' + state_registration_number + '"' + ')', 'SE': 'se.start(' + '"' + state_registration_number + '"' + ')', 'SP': 'sp.start(' + '"' + state_registration_number + '"' + ')', 'TO': 'to.start(' + '"' + state_registration_number + '"' + ')'} exec('validity = ' + states_validations[state_abbreviation]) return validity
def format_vars(args): """Format the given vars in the form: 'flag=value'""" variables = [] for key, value in args.items(): if value: variables += ['{0}={1}'.format(key, value)] return variables
def function[format_vars, parameter[args]]: constant[Format the given vars in the form: 'flag=value'] variable[variables] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b1db7700>, <ast.Name object at 0x7da1b1db7730>]]] in starred[call[name[args].items, parameter[]]] begin[:] if name[value] begin[:] <ast.AugAssign object at 0x7da2041d82e0> return[name[variables]]
keyword[def] identifier[format_vars] ( identifier[args] ): literal[string] identifier[variables] =[] keyword[for] identifier[key] , identifier[value] keyword[in] identifier[args] . identifier[items] (): keyword[if] identifier[value] : identifier[variables] +=[ literal[string] . identifier[format] ( identifier[key] , identifier[value] )] keyword[return] identifier[variables]
def format_vars(args): """Format the given vars in the form: 'flag=value'""" variables = [] for (key, value) in args.items(): if value: variables += ['{0}={1}'.format(key, value)] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] return variables
def parse_timestamp(ts): """Takes ISO 8601 format(string) and converts into a utc datetime(naive)""" return ( datetime.datetime.strptime(ts[:-7], "%Y-%m-%dT%H:%M:%S") + datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:])) * int(ts[-6:-5] + "1") )
def function[parse_timestamp, parameter[ts]]: constant[Takes ISO 8601 format(string) and converts into a utc datetime(naive)] return[binary_operation[call[name[datetime].datetime.strptime, parameter[call[name[ts]][<ast.Slice object at 0x7da20cabc880>], constant[%Y-%m-%dT%H:%M:%S]]] + binary_operation[call[name[datetime].timedelta, parameter[]] * call[name[int], parameter[binary_operation[call[name[ts]][<ast.Slice object at 0x7da212db5030>] + constant[1]]]]]]]
keyword[def] identifier[parse_timestamp] ( identifier[ts] ): literal[string] keyword[return] ( identifier[datetime] . identifier[datetime] . identifier[strptime] ( identifier[ts] [:- literal[int] ], literal[string] )+ identifier[datetime] . identifier[timedelta] ( identifier[hours] = identifier[int] ( identifier[ts] [- literal[int] :- literal[int] ]), identifier[minutes] = identifier[int] ( identifier[ts] [- literal[int] :]))* identifier[int] ( identifier[ts] [- literal[int] :- literal[int] ]+ literal[string] ) )
def parse_timestamp(ts): """Takes ISO 8601 format(string) and converts into a utc datetime(naive)""" return datetime.datetime.strptime(ts[:-7], '%Y-%m-%dT%H:%M:%S') + datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:])) * int(ts[-6:-5] + '1')
def function( receiver ): """Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound """ if hasattr(receiver, '__call__'): # Reassign receiver to the actual method that will be called. if hasattr( receiver.__call__, im_func) or hasattr( receiver.__call__, im_code): receiver = receiver.__call__ if hasattr( receiver, im_func ): # an instance-method... return receiver, getattr(getattr(receiver, im_func), func_code), 1 elif not hasattr( receiver, func_code): raise ValueError('unknown reciever type %s %s'%(receiver, type(receiver))) return receiver, getattr(receiver,func_code), 0
def function[function, parameter[receiver]]: constant[Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound ] if call[name[hasattr], parameter[name[receiver], constant[__call__]]] begin[:] if <ast.BoolOp object at 0x7da20e955450> begin[:] variable[receiver] assign[=] name[receiver].__call__ if call[name[hasattr], parameter[name[receiver], name[im_func]]] begin[:] return[tuple[[<ast.Name object at 0x7da20e955ed0>, <ast.Call object at 0x7da20e9573a0>, <ast.Constant object at 0x7da20e9542e0>]]] return[tuple[[<ast.Name object at 0x7da20e9565f0>, <ast.Call object at 0x7da20e955c90>, <ast.Constant object at 0x7da20e957f40>]]]
keyword[def] identifier[function] ( identifier[receiver] ): literal[string] keyword[if] identifier[hasattr] ( identifier[receiver] , literal[string] ): keyword[if] identifier[hasattr] ( identifier[receiver] . identifier[__call__] , identifier[im_func] ) keyword[or] identifier[hasattr] ( identifier[receiver] . identifier[__call__] , identifier[im_code] ): identifier[receiver] = identifier[receiver] . identifier[__call__] keyword[if] identifier[hasattr] ( identifier[receiver] , identifier[im_func] ): keyword[return] identifier[receiver] , identifier[getattr] ( identifier[getattr] ( identifier[receiver] , identifier[im_func] ), identifier[func_code] ), literal[int] keyword[elif] keyword[not] identifier[hasattr] ( identifier[receiver] , identifier[func_code] ): keyword[raise] identifier[ValueError] ( literal[string] %( identifier[receiver] , identifier[type] ( identifier[receiver] ))) keyword[return] identifier[receiver] , identifier[getattr] ( identifier[receiver] , identifier[func_code] ), literal[int]
def function(receiver): """Get function-like callable object for given receiver returns (function_or_method, codeObject, fromMethod) If fromMethod is true, then the callable already has its first argument bound """ if hasattr(receiver, '__call__'): # Reassign receiver to the actual method that will be called. if hasattr(receiver.__call__, im_func) or hasattr(receiver.__call__, im_code): receiver = receiver.__call__ # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if hasattr(receiver, im_func): # an instance-method... return (receiver, getattr(getattr(receiver, im_func), func_code), 1) # depends on [control=['if'], data=[]] elif not hasattr(receiver, func_code): raise ValueError('unknown reciever type %s %s' % (receiver, type(receiver))) # depends on [control=['if'], data=[]] return (receiver, getattr(receiver, func_code), 0)
def get_chat_id(self, username): """Lookup chat_id of username if chat_id is unknown via API call.""" if username is not None: chats = requests.get(self.base_url + "/getUpdates").json() user = username.split("@")[-1] for chat in chats["result"]: if chat["message"]["from"]["username"] == user: return chat["message"]["from"]["id"]
def function[get_chat_id, parameter[self, username]]: constant[Lookup chat_id of username if chat_id is unknown via API call.] if compare[name[username] is_not constant[None]] begin[:] variable[chats] assign[=] call[call[name[requests].get, parameter[binary_operation[name[self].base_url + constant[/getUpdates]]]].json, parameter[]] variable[user] assign[=] call[call[name[username].split, parameter[constant[@]]]][<ast.UnaryOp object at 0x7da20e955060>] for taget[name[chat]] in starred[call[name[chats]][constant[result]]] begin[:] if compare[call[call[call[name[chat]][constant[message]]][constant[from]]][constant[username]] equal[==] name[user]] begin[:] return[call[call[call[name[chat]][constant[message]]][constant[from]]][constant[id]]]
keyword[def] identifier[get_chat_id] ( identifier[self] , identifier[username] ): literal[string] keyword[if] identifier[username] keyword[is] keyword[not] keyword[None] : identifier[chats] = identifier[requests] . identifier[get] ( identifier[self] . identifier[base_url] + literal[string] ). identifier[json] () identifier[user] = identifier[username] . identifier[split] ( literal[string] )[- literal[int] ] keyword[for] identifier[chat] keyword[in] identifier[chats] [ literal[string] ]: keyword[if] identifier[chat] [ literal[string] ][ literal[string] ][ literal[string] ]== identifier[user] : keyword[return] identifier[chat] [ literal[string] ][ literal[string] ][ literal[string] ]
def get_chat_id(self, username): """Lookup chat_id of username if chat_id is unknown via API call.""" if username is not None: chats = requests.get(self.base_url + '/getUpdates').json() user = username.split('@')[-1] for chat in chats['result']: if chat['message']['from']['username'] == user: return chat['message']['from']['id'] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['chat']] # depends on [control=['if'], data=['username']]
def check_version(): """ Tells you if you have an old version of intern. """ import requests r = requests.get('https://pypi.python.org/pypi/intern/json').json() r = r['info']['version'] if r != __version__: print("You are using version {}. A newer version of intern is available: {} ".format(__version__, r) + "\n\n'pip install -U intern' to update.") return r
def function[check_version, parameter[]]: constant[ Tells you if you have an old version of intern. ] import module[requests] variable[r] assign[=] call[call[name[requests].get, parameter[constant[https://pypi.python.org/pypi/intern/json]]].json, parameter[]] variable[r] assign[=] call[call[name[r]][constant[info]]][constant[version]] if compare[name[r] not_equal[!=] name[__version__]] begin[:] call[name[print], parameter[binary_operation[call[constant[You are using version {}. A newer version of intern is available: {} ].format, parameter[name[__version__], name[r]]] + constant[ 'pip install -U intern' to update.]]]] return[name[r]]
keyword[def] identifier[check_version] (): literal[string] keyword[import] identifier[requests] identifier[r] = identifier[requests] . identifier[get] ( literal[string] ). identifier[json] () identifier[r] = identifier[r] [ literal[string] ][ literal[string] ] keyword[if] identifier[r] != identifier[__version__] : identifier[print] ( literal[string] . identifier[format] ( identifier[__version__] , identifier[r] )+ literal[string] ) keyword[return] identifier[r]
def check_version(): """ Tells you if you have an old version of intern. """ import requests r = requests.get('https://pypi.python.org/pypi/intern/json').json() r = r['info']['version'] if r != __version__: print('You are using version {}. A newer version of intern is available: {} '.format(__version__, r) + "\n\n'pip install -U intern' to update.") # depends on [control=['if'], data=['r', '__version__']] return r
def ping(self, timeout=12): """ Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active """ self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id), auth=SkypeConnection.Auth.RegToken, json={"timeout": timeout})
def function[ping, parameter[self, timeout]]: constant[ Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active ] call[name[self].conn, parameter[constant[POST], call[constant[{0}/users/ME/endpoints/{1}/active].format, parameter[name[self].conn.msgsHost, name[self].id]]]]
keyword[def] identifier[ping] ( identifier[self] , identifier[timeout] = literal[int] ): literal[string] identifier[self] . identifier[conn] ( literal[string] , literal[string] . identifier[format] ( identifier[self] . identifier[conn] . identifier[msgsHost] , identifier[self] . identifier[id] ), identifier[auth] = identifier[SkypeConnection] . identifier[Auth] . identifier[RegToken] , identifier[json] ={ literal[string] : identifier[timeout] })
def ping(self, timeout=12): """ Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active """ self.conn('POST', '{0}/users/ME/endpoints/{1}/active'.format(self.conn.msgsHost, self.id), auth=SkypeConnection.Auth.RegToken, json={'timeout': timeout})
def iter_cast(inputs, dst_type, return_type=None): """Cast elements of an iterable object into some type. Args: inputs (Iterable): The input object. dst_type (type): Destination type. return_type (type, optional): If specified, the output object will be converted to this type, otherwise an iterator. Returns: iterator or specified type: The converted object. """ if not isinstance(inputs, collections_abc.Iterable): raise TypeError('inputs must be an iterable object') if not isinstance(dst_type, type): raise TypeError('"dst_type" must be a valid type') out_iterable = six.moves.map(dst_type, inputs) if return_type is None: return out_iterable else: return return_type(out_iterable)
def function[iter_cast, parameter[inputs, dst_type, return_type]]: constant[Cast elements of an iterable object into some type. Args: inputs (Iterable): The input object. dst_type (type): Destination type. return_type (type, optional): If specified, the output object will be converted to this type, otherwise an iterator. Returns: iterator or specified type: The converted object. ] if <ast.UnaryOp object at 0x7da18f811ba0> begin[:] <ast.Raise object at 0x7da18f812cb0> if <ast.UnaryOp object at 0x7da18f8112d0> begin[:] <ast.Raise object at 0x7da18f812e60> variable[out_iterable] assign[=] call[name[six].moves.map, parameter[name[dst_type], name[inputs]]] if compare[name[return_type] is constant[None]] begin[:] return[name[out_iterable]]
keyword[def] identifier[iter_cast] ( identifier[inputs] , identifier[dst_type] , identifier[return_type] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[inputs] , identifier[collections_abc] . identifier[Iterable] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[dst_type] , identifier[type] ): keyword[raise] identifier[TypeError] ( literal[string] ) identifier[out_iterable] = identifier[six] . identifier[moves] . identifier[map] ( identifier[dst_type] , identifier[inputs] ) keyword[if] identifier[return_type] keyword[is] keyword[None] : keyword[return] identifier[out_iterable] keyword[else] : keyword[return] identifier[return_type] ( identifier[out_iterable] )
def iter_cast(inputs, dst_type, return_type=None): """Cast elements of an iterable object into some type. Args: inputs (Iterable): The input object. dst_type (type): Destination type. return_type (type, optional): If specified, the output object will be converted to this type, otherwise an iterator. Returns: iterator or specified type: The converted object. """ if not isinstance(inputs, collections_abc.Iterable): raise TypeError('inputs must be an iterable object') # depends on [control=['if'], data=[]] if not isinstance(dst_type, type): raise TypeError('"dst_type" must be a valid type') # depends on [control=['if'], data=[]] out_iterable = six.moves.map(dst_type, inputs) if return_type is None: return out_iterable # depends on [control=['if'], data=[]] else: return return_type(out_iterable)
def get_es_label(obj, def_obj): """ Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values """ label_flds = LABEL_FIELDS if def_obj.es_defs.get('kds_esLabel'): label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS try: for label in label_flds: if def_obj.cls_defs.get(label): obj['label'] = def_obj.cls_defs[label][0] break if not obj.get('label'): obj['label'] = def_obj.__class__.__name__.split("_")[-1] except AttributeError: # an attribute error is caused when the class is only # an instance of the BaseRdfClass. We will search the rdf_type # property and construct a label from rdf_type value if def_obj.get('rdf_type'): obj['label'] = def_obj['rdf_type'][-1].value[-1] else: obj['label'] = "no_label" return obj
def function[get_es_label, parameter[obj, def_obj]]: constant[ Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values ] variable[label_flds] assign[=] name[LABEL_FIELDS] if call[name[def_obj].es_defs.get, parameter[constant[kds_esLabel]]] begin[:] variable[label_flds] assign[=] binary_operation[call[name[def_obj].es_defs][constant[kds_esLabel]] + name[LABEL_FIELDS]] <ast.Try object at 0x7da18f7202b0> return[name[obj]]
keyword[def] identifier[get_es_label] ( identifier[obj] , identifier[def_obj] ): literal[string] identifier[label_flds] = identifier[LABEL_FIELDS] keyword[if] identifier[def_obj] . identifier[es_defs] . identifier[get] ( literal[string] ): identifier[label_flds] = identifier[def_obj] . identifier[es_defs] [ literal[string] ]+ identifier[LABEL_FIELDS] keyword[try] : keyword[for] identifier[label] keyword[in] identifier[label_flds] : keyword[if] identifier[def_obj] . identifier[cls_defs] . identifier[get] ( identifier[label] ): identifier[obj] [ literal[string] ]= identifier[def_obj] . identifier[cls_defs] [ identifier[label] ][ literal[int] ] keyword[break] keyword[if] keyword[not] identifier[obj] . identifier[get] ( literal[string] ): identifier[obj] [ literal[string] ]= identifier[def_obj] . identifier[__class__] . identifier[__name__] . identifier[split] ( literal[string] )[- literal[int] ] keyword[except] identifier[AttributeError] : keyword[if] identifier[def_obj] . identifier[get] ( literal[string] ): identifier[obj] [ literal[string] ]= identifier[def_obj] [ literal[string] ][- literal[int] ]. identifier[value] [- literal[int] ] keyword[else] : identifier[obj] [ literal[string] ]= literal[string] keyword[return] identifier[obj]
def get_es_label(obj, def_obj): """ Returns object with label for an object that goes into the elacticsearch 'label' field args: obj: data object to update def_obj: the class instance that has defintion values """ label_flds = LABEL_FIELDS if def_obj.es_defs.get('kds_esLabel'): label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS # depends on [control=['if'], data=[]] try: for label in label_flds: if def_obj.cls_defs.get(label): obj['label'] = def_obj.cls_defs[label][0] break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['label']] if not obj.get('label'): obj['label'] = def_obj.__class__.__name__.split('_')[-1] # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except AttributeError: # an attribute error is caused when the class is only # an instance of the BaseRdfClass. We will search the rdf_type # property and construct a label from rdf_type value if def_obj.get('rdf_type'): obj['label'] = def_obj['rdf_type'][-1].value[-1] # depends on [control=['if'], data=[]] else: obj['label'] = 'no_label' # depends on [control=['except'], data=[]] return obj
def count(cls, name): """Return the count of ``name``""" counter = cls.collection.find_one({'name': name}) or {} return counter.get('seq', 0)
def function[count, parameter[cls, name]]: constant[Return the count of ``name``] variable[counter] assign[=] <ast.BoolOp object at 0x7da204621870> return[call[name[counter].get, parameter[constant[seq], constant[0]]]]
keyword[def] identifier[count] ( identifier[cls] , identifier[name] ): literal[string] identifier[counter] = identifier[cls] . identifier[collection] . identifier[find_one] ({ literal[string] : identifier[name] }) keyword[or] {} keyword[return] identifier[counter] . identifier[get] ( literal[string] , literal[int] )
def count(cls, name): """Return the count of ``name``""" counter = cls.collection.find_one({'name': name}) or {} return counter.get('seq', 0)
def leaveEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(False)
def function[leaveEvent, parameter[self, event]]: constant[ Toggles the display for the tracker item. ] variable[item] assign[=] call[name[self].trackerItem, parameter[]] if name[item] begin[:] call[name[item].setVisible, parameter[constant[False]]]
keyword[def] identifier[leaveEvent] ( identifier[self] , identifier[event] ): literal[string] identifier[item] = identifier[self] . identifier[trackerItem] () keyword[if] ( identifier[item] ): identifier[item] . identifier[setVisible] ( keyword[False] )
def leaveEvent(self, event): """ Toggles the display for the tracker item. """ item = self.trackerItem() if item: item.setVisible(False) # depends on [control=['if'], data=[]]
def prepare(self, start=-1): """Setup the parser for parsing. Takes the starting symbol as an argument. """ if start == -1: start = self.grammar.start self.root = None current_node = Node(start, None, [], 0, 0) self.stack = [] self.stack.append((self.grammar.dfas[start - 256], 0, current_node))
def function[prepare, parameter[self, start]]: constant[Setup the parser for parsing. Takes the starting symbol as an argument. ] if compare[name[start] equal[==] <ast.UnaryOp object at 0x7da20e961b40>] begin[:] variable[start] assign[=] name[self].grammar.start name[self].root assign[=] constant[None] variable[current_node] assign[=] call[name[Node], parameter[name[start], constant[None], list[[]], constant[0], constant[0]]] name[self].stack assign[=] list[[]] call[name[self].stack.append, parameter[tuple[[<ast.Subscript object at 0x7da20e9625c0>, <ast.Constant object at 0x7da20e9603a0>, <ast.Name object at 0x7da20e962890>]]]]
keyword[def] identifier[prepare] ( identifier[self] , identifier[start] =- literal[int] ): literal[string] keyword[if] identifier[start] ==- literal[int] : identifier[start] = identifier[self] . identifier[grammar] . identifier[start] identifier[self] . identifier[root] = keyword[None] identifier[current_node] = identifier[Node] ( identifier[start] , keyword[None] ,[], literal[int] , literal[int] ) identifier[self] . identifier[stack] =[] identifier[self] . identifier[stack] . identifier[append] (( identifier[self] . identifier[grammar] . identifier[dfas] [ identifier[start] - literal[int] ], literal[int] , identifier[current_node] ))
def prepare(self, start=-1): """Setup the parser for parsing. Takes the starting symbol as an argument. """ if start == -1: start = self.grammar.start # depends on [control=['if'], data=['start']] self.root = None current_node = Node(start, None, [], 0, 0) self.stack = [] self.stack.append((self.grammar.dfas[start - 256], 0, current_node))
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed to be an unknown token. This script produces two artifacts: A new vocabulary file with the <S> and </S> tokens inserted and a glove formatted embedding file containing word : vector pairs, one per line, with all values separated by a space. """ # Load the vocabulary words and convert to char ids with open(vocab_path, 'r') as vocab_file: tokens = vocab_file.read().strip().split('\n') # Insert the sentence boundary tokens which elmo uses at positions 1 and 2. if tokens[0] != DEFAULT_OOV_TOKEN and not use_custom_oov_token: raise ConfigurationError("ELMo embeddings require the use of a OOV token.") tokens = [tokens[0]] + ["<S>", "</S>"] + tokens[1:] indexer = ELMoTokenCharactersIndexer() indices = indexer.tokens_to_indices([Token(token) for token in tokens], Vocabulary(), "indices")["indices"] sentences = [] for k in range((len(indices) // 50) + 1): sentences.append(indexer.pad_token_sequence(indices[(k * 50):((k + 1) * 50)], desired_num_tokens=50, padding_lengths={})) last_batch_remainder = 50 - (len(indices) % 50) if device != -1: elmo_token_embedder = _ElmoCharacterEncoder(elmo_config_path, elmo_weights_path).cuda(device) else: elmo_token_embedder = _ElmoCharacterEncoder(elmo_config_path, elmo_weights_path) all_embeddings = [] for i in range((len(sentences) // batch_size) + 1): array = numpy.array(sentences[i * batch_size: (i + 1) * batch_size]) if device != -1: batch = torch.from_numpy(array).cuda(device) else: batch = torch.from_numpy(array) token_embedding = elmo_token_embedder(batch)['token_embedding'].data # Reshape back to a list of words of shape (batch_size * 50, encoding_dim) # We also need to remove the <S>, </S> tokens appended by the encoder. per_word_embeddings = token_embedding[:, 1:-1, :].contiguous().view(-1, token_embedding.size(-1)) all_embeddings.append(per_word_embeddings) # Remove the embeddings associated with padding in the last batch. all_embeddings[-1] = all_embeddings[-1][:-last_batch_remainder, :] embedding_weight = torch.cat(all_embeddings, 0).cpu().numpy() # Write out the embedding in a glove format. os.makedirs(output_dir, exist_ok=True) with gzip.open(os.path.join(output_dir, "elmo_embeddings.txt.gz"), 'wb') as embeddings_file: for i, word in enumerate(tokens): string_array = " ".join([str(x) for x in list(embedding_weight[i, :])]) embeddings_file.write(f"{word} {string_array}\n".encode('utf-8')) # Write out the new vocab with the <S> and </S> tokens. _, vocab_file_name = os.path.split(vocab_path) with open(os.path.join(output_dir, vocab_file_name), "w") as new_vocab_file: for word in tokens: new_vocab_file.write(f"{word}\n")
def function[main, parameter[vocab_path, elmo_config_path, elmo_weights_path, output_dir, batch_size, device, use_custom_oov_token]]: constant[ Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed to be an unknown token. This script produces two artifacts: A new vocabulary file with the <S> and </S> tokens inserted and a glove formatted embedding file containing word : vector pairs, one per line, with all values separated by a space. ] with call[name[open], parameter[name[vocab_path], constant[r]]] begin[:] variable[tokens] assign[=] call[call[call[name[vocab_file].read, parameter[]].strip, parameter[]].split, parameter[constant[ ]]] if <ast.BoolOp object at 0x7da20c794b50> begin[:] <ast.Raise object at 0x7da20c796230> variable[tokens] assign[=] binary_operation[binary_operation[list[[<ast.Subscript object at 0x7da20c795690>]] + list[[<ast.Constant object at 0x7da20c794f10>, <ast.Constant object at 0x7da20c7946a0>]]] + call[name[tokens]][<ast.Slice object at 0x7da20c794460>]] variable[indexer] assign[=] call[name[ELMoTokenCharactersIndexer], parameter[]] variable[indices] assign[=] call[call[name[indexer].tokens_to_indices, parameter[<ast.ListComp object at 0x7da20c796a40>, call[name[Vocabulary], parameter[]], constant[indices]]]][constant[indices]] variable[sentences] assign[=] list[[]] for taget[name[k]] in starred[call[name[range], parameter[binary_operation[binary_operation[call[name[len], parameter[name[indices]]] <ast.FloorDiv object at 0x7da2590d6bc0> constant[50]] + constant[1]]]]] begin[:] call[name[sentences].append, parameter[call[name[indexer].pad_token_sequence, parameter[call[name[indices]][<ast.Slice object at 0x7da20c794f70>]]]]] variable[last_batch_remainder] assign[=] binary_operation[constant[50] - binary_operation[call[name[len], parameter[name[indices]]] <ast.Mod object at 0x7da2590d6920> constant[50]]] if compare[name[device] not_equal[!=] <ast.UnaryOp object at 0x7da20c7969e0>] begin[:] variable[elmo_token_embedder] assign[=] call[call[name[_ElmoCharacterEncoder], parameter[name[elmo_config_path], name[elmo_weights_path]]].cuda, parameter[name[device]]] variable[all_embeddings] assign[=] list[[]] for taget[name[i]] in starred[call[name[range], parameter[binary_operation[binary_operation[call[name[len], parameter[name[sentences]]] <ast.FloorDiv object at 0x7da2590d6bc0> name[batch_size]] + constant[1]]]]] begin[:] variable[array] assign[=] call[name[numpy].array, parameter[call[name[sentences]][<ast.Slice object at 0x7da20e955090>]]] if compare[name[device] not_equal[!=] <ast.UnaryOp object at 0x7da20e9579a0>] begin[:] variable[batch] assign[=] call[call[name[torch].from_numpy, parameter[name[array]]].cuda, parameter[name[device]]] variable[token_embedding] assign[=] call[call[name[elmo_token_embedder], parameter[name[batch]]]][constant[token_embedding]].data variable[per_word_embeddings] assign[=] call[call[call[name[token_embedding]][tuple[[<ast.Slice object at 0x7da20e9548e0>, <ast.Slice object at 0x7da20e9540d0>, <ast.Slice object at 0x7da20e954820>]]].contiguous, parameter[]].view, parameter[<ast.UnaryOp object at 0x7da20e957ee0>, call[name[token_embedding].size, parameter[<ast.UnaryOp object at 0x7da20e9549d0>]]]] call[name[all_embeddings].append, parameter[name[per_word_embeddings]]] call[name[all_embeddings]][<ast.UnaryOp object at 0x7da20e956470>] assign[=] call[call[name[all_embeddings]][<ast.UnaryOp object at 0x7da20e9544f0>]][tuple[[<ast.Slice object at 0x7da20e9557b0>, <ast.Slice object at 0x7da20e956260>]]] variable[embedding_weight] assign[=] call[call[call[name[torch].cat, parameter[name[all_embeddings], constant[0]]].cpu, parameter[]].numpy, parameter[]] call[name[os].makedirs, parameter[name[output_dir]]] with call[name[gzip].open, parameter[call[name[os].path.join, parameter[name[output_dir], constant[elmo_embeddings.txt.gz]]], constant[wb]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da20c76dae0>, <ast.Name object at 0x7da20c76ddb0>]]] in starred[call[name[enumerate], parameter[name[tokens]]]] begin[:] variable[string_array] assign[=] call[constant[ ].join, parameter[<ast.ListComp object at 0x7da20c76d1e0>]] call[name[embeddings_file].write, parameter[call[<ast.JoinedStr object at 0x7da20c76d9f0>.encode, parameter[constant[utf-8]]]]] <ast.Tuple object at 0x7da20c76c400> assign[=] call[name[os].path.split, parameter[name[vocab_path]]] with call[name[open], parameter[call[name[os].path.join, parameter[name[output_dir], name[vocab_file_name]]], constant[w]]] begin[:] for taget[name[word]] in starred[name[tokens]] begin[:] call[name[new_vocab_file].write, parameter[<ast.JoinedStr object at 0x7da2054a6650>]]
keyword[def] identifier[main] ( identifier[vocab_path] : identifier[str] , identifier[elmo_config_path] : identifier[str] , identifier[elmo_weights_path] : identifier[str] , identifier[output_dir] : identifier[str] , identifier[batch_size] : identifier[int] , identifier[device] : identifier[int] , identifier[use_custom_oov_token] : identifier[bool] = keyword[False] ): literal[string] keyword[with] identifier[open] ( identifier[vocab_path] , literal[string] ) keyword[as] identifier[vocab_file] : identifier[tokens] = identifier[vocab_file] . identifier[read] (). identifier[strip] (). identifier[split] ( literal[string] ) keyword[if] identifier[tokens] [ literal[int] ]!= identifier[DEFAULT_OOV_TOKEN] keyword[and] keyword[not] identifier[use_custom_oov_token] : keyword[raise] identifier[ConfigurationError] ( literal[string] ) identifier[tokens] =[ identifier[tokens] [ literal[int] ]]+[ literal[string] , literal[string] ]+ identifier[tokens] [ literal[int] :] identifier[indexer] = identifier[ELMoTokenCharactersIndexer] () identifier[indices] = identifier[indexer] . identifier[tokens_to_indices] ([ identifier[Token] ( identifier[token] ) keyword[for] identifier[token] keyword[in] identifier[tokens] ], identifier[Vocabulary] (), literal[string] )[ literal[string] ] identifier[sentences] =[] keyword[for] identifier[k] keyword[in] identifier[range] (( identifier[len] ( identifier[indices] )// literal[int] )+ literal[int] ): identifier[sentences] . identifier[append] ( identifier[indexer] . identifier[pad_token_sequence] ( identifier[indices] [( identifier[k] * literal[int] ):(( identifier[k] + literal[int] )* literal[int] )], identifier[desired_num_tokens] = literal[int] , identifier[padding_lengths] ={})) identifier[last_batch_remainder] = literal[int] -( identifier[len] ( identifier[indices] )% literal[int] ) keyword[if] identifier[device] !=- literal[int] : identifier[elmo_token_embedder] = identifier[_ElmoCharacterEncoder] ( identifier[elmo_config_path] , identifier[elmo_weights_path] ). identifier[cuda] ( identifier[device] ) keyword[else] : identifier[elmo_token_embedder] = identifier[_ElmoCharacterEncoder] ( identifier[elmo_config_path] , identifier[elmo_weights_path] ) identifier[all_embeddings] =[] keyword[for] identifier[i] keyword[in] identifier[range] (( identifier[len] ( identifier[sentences] )// identifier[batch_size] )+ literal[int] ): identifier[array] = identifier[numpy] . identifier[array] ( identifier[sentences] [ identifier[i] * identifier[batch_size] :( identifier[i] + literal[int] )* identifier[batch_size] ]) keyword[if] identifier[device] !=- literal[int] : identifier[batch] = identifier[torch] . identifier[from_numpy] ( identifier[array] ). identifier[cuda] ( identifier[device] ) keyword[else] : identifier[batch] = identifier[torch] . identifier[from_numpy] ( identifier[array] ) identifier[token_embedding] = identifier[elmo_token_embedder] ( identifier[batch] )[ literal[string] ]. identifier[data] identifier[per_word_embeddings] = identifier[token_embedding] [:, literal[int] :- literal[int] ,:]. identifier[contiguous] (). identifier[view] (- literal[int] , identifier[token_embedding] . identifier[size] (- literal[int] )) identifier[all_embeddings] . identifier[append] ( identifier[per_word_embeddings] ) identifier[all_embeddings] [- literal[int] ]= identifier[all_embeddings] [- literal[int] ][:- identifier[last_batch_remainder] ,:] identifier[embedding_weight] = identifier[torch] . identifier[cat] ( identifier[all_embeddings] , literal[int] ). identifier[cpu] (). identifier[numpy] () identifier[os] . identifier[makedirs] ( identifier[output_dir] , identifier[exist_ok] = keyword[True] ) keyword[with] identifier[gzip] . identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[output_dir] , literal[string] ), literal[string] ) keyword[as] identifier[embeddings_file] : keyword[for] identifier[i] , identifier[word] keyword[in] identifier[enumerate] ( identifier[tokens] ): identifier[string_array] = literal[string] . identifier[join] ([ identifier[str] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[list] ( identifier[embedding_weight] [ identifier[i] ,:])]) identifier[embeddings_file] . identifier[write] ( literal[string] . identifier[encode] ( literal[string] )) identifier[_] , identifier[vocab_file_name] = identifier[os] . identifier[path] . identifier[split] ( identifier[vocab_path] ) keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[output_dir] , identifier[vocab_file_name] ), literal[string] ) keyword[as] identifier[new_vocab_file] : keyword[for] identifier[word] keyword[in] identifier[tokens] : identifier[new_vocab_file] . identifier[write] ( literal[string] )
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool=False): """ Creates ELMo word representations from a vocabulary file. These word representations are _independent_ - they are the result of running the CNN and Highway layers of the ELMo model, but not the Bidirectional LSTM. ELMo requires 2 additional tokens: <S> and </S>. The first token in this file is assumed to be an unknown token. This script produces two artifacts: A new vocabulary file with the <S> and </S> tokens inserted and a glove formatted embedding file containing word : vector pairs, one per line, with all values separated by a space. """ # Load the vocabulary words and convert to char ids with open(vocab_path, 'r') as vocab_file: tokens = vocab_file.read().strip().split('\n') # depends on [control=['with'], data=['vocab_file']] # Insert the sentence boundary tokens which elmo uses at positions 1 and 2. if tokens[0] != DEFAULT_OOV_TOKEN and (not use_custom_oov_token): raise ConfigurationError('ELMo embeddings require the use of a OOV token.') # depends on [control=['if'], data=[]] tokens = [tokens[0]] + ['<S>', '</S>'] + tokens[1:] indexer = ELMoTokenCharactersIndexer() indices = indexer.tokens_to_indices([Token(token) for token in tokens], Vocabulary(), 'indices')['indices'] sentences = [] for k in range(len(indices) // 50 + 1): sentences.append(indexer.pad_token_sequence(indices[k * 50:(k + 1) * 50], desired_num_tokens=50, padding_lengths={})) # depends on [control=['for'], data=['k']] last_batch_remainder = 50 - len(indices) % 50 if device != -1: elmo_token_embedder = _ElmoCharacterEncoder(elmo_config_path, elmo_weights_path).cuda(device) # depends on [control=['if'], data=['device']] else: elmo_token_embedder = _ElmoCharacterEncoder(elmo_config_path, elmo_weights_path) all_embeddings = [] for i in range(len(sentences) // batch_size + 1): array = numpy.array(sentences[i * batch_size:(i + 1) * batch_size]) if device != -1: batch = torch.from_numpy(array).cuda(device) # depends on [control=['if'], data=['device']] else: batch = torch.from_numpy(array) token_embedding = elmo_token_embedder(batch)['token_embedding'].data # Reshape back to a list of words of shape (batch_size * 50, encoding_dim) # We also need to remove the <S>, </S> tokens appended by the encoder. per_word_embeddings = token_embedding[:, 1:-1, :].contiguous().view(-1, token_embedding.size(-1)) all_embeddings.append(per_word_embeddings) # depends on [control=['for'], data=['i']] # Remove the embeddings associated with padding in the last batch. all_embeddings[-1] = all_embeddings[-1][:-last_batch_remainder, :] embedding_weight = torch.cat(all_embeddings, 0).cpu().numpy() # Write out the embedding in a glove format. os.makedirs(output_dir, exist_ok=True) with gzip.open(os.path.join(output_dir, 'elmo_embeddings.txt.gz'), 'wb') as embeddings_file: for (i, word) in enumerate(tokens): string_array = ' '.join([str(x) for x in list(embedding_weight[i, :])]) embeddings_file.write(f'{word} {string_array}\n'.encode('utf-8')) # depends on [control=['for'], data=[]] # depends on [control=['with'], data=['embeddings_file']] # Write out the new vocab with the <S> and </S> tokens. (_, vocab_file_name) = os.path.split(vocab_path) with open(os.path.join(output_dir, vocab_file_name), 'w') as new_vocab_file: for word in tokens: new_vocab_file.write(f'{word}\n') # depends on [control=['for'], data=['word']] # depends on [control=['with'], data=['new_vocab_file']]
def make_param(self, name, raw_uri, disk_size): """Return a MountParam given a GCS bucket, disk image or local path.""" if raw_uri.startswith('https://www.googleapis.com/compute'): # Full Image URI should look something like: # https://www.googleapis.com/compute/v1/projects/<project>/global/images/ # But don't validate further, should the form of a valid image URI # change (v1->v2, for example) docker_path = self._parse_image_uri(raw_uri) return job_model.PersistentDiskMountParam( name, raw_uri, docker_path, disk_size, disk_type=None) elif raw_uri.startswith('file://'): local_path, docker_path = self._parse_local_mount_uri(raw_uri) return job_model.LocalMountParam(name, raw_uri, docker_path, local_path) elif raw_uri.startswith('gs://'): docker_path = self._parse_gcs_uri(raw_uri) return job_model.GCSMountParam(name, raw_uri, docker_path) else: raise ValueError( 'Mount parameter {} must begin with valid prefix.'.format(raw_uri))
def function[make_param, parameter[self, name, raw_uri, disk_size]]: constant[Return a MountParam given a GCS bucket, disk image or local path.] if call[name[raw_uri].startswith, parameter[constant[https://www.googleapis.com/compute]]] begin[:] variable[docker_path] assign[=] call[name[self]._parse_image_uri, parameter[name[raw_uri]]] return[call[name[job_model].PersistentDiskMountParam, parameter[name[name], name[raw_uri], name[docker_path], name[disk_size]]]]
keyword[def] identifier[make_param] ( identifier[self] , identifier[name] , identifier[raw_uri] , identifier[disk_size] ): literal[string] keyword[if] identifier[raw_uri] . identifier[startswith] ( literal[string] ): identifier[docker_path] = identifier[self] . identifier[_parse_image_uri] ( identifier[raw_uri] ) keyword[return] identifier[job_model] . identifier[PersistentDiskMountParam] ( identifier[name] , identifier[raw_uri] , identifier[docker_path] , identifier[disk_size] , identifier[disk_type] = keyword[None] ) keyword[elif] identifier[raw_uri] . identifier[startswith] ( literal[string] ): identifier[local_path] , identifier[docker_path] = identifier[self] . identifier[_parse_local_mount_uri] ( identifier[raw_uri] ) keyword[return] identifier[job_model] . identifier[LocalMountParam] ( identifier[name] , identifier[raw_uri] , identifier[docker_path] , identifier[local_path] ) keyword[elif] identifier[raw_uri] . identifier[startswith] ( literal[string] ): identifier[docker_path] = identifier[self] . identifier[_parse_gcs_uri] ( identifier[raw_uri] ) keyword[return] identifier[job_model] . identifier[GCSMountParam] ( identifier[name] , identifier[raw_uri] , identifier[docker_path] ) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[raw_uri] ))
def make_param(self, name, raw_uri, disk_size): """Return a MountParam given a GCS bucket, disk image or local path.""" if raw_uri.startswith('https://www.googleapis.com/compute'): # Full Image URI should look something like: # https://www.googleapis.com/compute/v1/projects/<project>/global/images/ # But don't validate further, should the form of a valid image URI # change (v1->v2, for example) docker_path = self._parse_image_uri(raw_uri) return job_model.PersistentDiskMountParam(name, raw_uri, docker_path, disk_size, disk_type=None) # depends on [control=['if'], data=[]] elif raw_uri.startswith('file://'): (local_path, docker_path) = self._parse_local_mount_uri(raw_uri) return job_model.LocalMountParam(name, raw_uri, docker_path, local_path) # depends on [control=['if'], data=[]] elif raw_uri.startswith('gs://'): docker_path = self._parse_gcs_uri(raw_uri) return job_model.GCSMountParam(name, raw_uri, docker_path) # depends on [control=['if'], data=[]] else: raise ValueError('Mount parameter {} must begin with valid prefix.'.format(raw_uri))
def output_waiting(self): """Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCOUTQ, buf, True) except OSError as e: raise SerialError(e.errno, "Querying output waiting: " + e.strerror) return buf[0]
def function[output_waiting, parameter[self]]: constant[Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs. ] variable[buf] assign[=] call[name[array].array, parameter[constant[I], list[[<ast.Constant object at 0x7da18f720550>]]]] <ast.Try object at 0x7da18f721720> return[call[name[buf]][constant[0]]]
keyword[def] identifier[output_waiting] ( identifier[self] ): literal[string] identifier[buf] = identifier[array] . identifier[array] ( literal[string] ,[ literal[int] ]) keyword[try] : identifier[fcntl] . identifier[ioctl] ( identifier[self] . identifier[_fd] , identifier[termios] . identifier[TIOCOUTQ] , identifier[buf] , keyword[True] ) keyword[except] identifier[OSError] keyword[as] identifier[e] : keyword[raise] identifier[SerialError] ( identifier[e] . identifier[errno] , literal[string] + identifier[e] . identifier[strerror] ) keyword[return] identifier[buf] [ literal[int] ]
def output_waiting(self): """Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCOUTQ, buf, True) # depends on [control=['try'], data=[]] except OSError as e: raise SerialError(e.errno, 'Querying output waiting: ' + e.strerror) # depends on [control=['except'], data=['e']] return buf[0]
def total_size(o, handlers={}, verbose=False, count=False): """Returns the approximate memory footprint an object and all of its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers to iterate over their contents: handlers = {SomeContainerClass: iter, OtherContainerClass: OtherContainerClass.get_elements} Source: http://code.activestate.com/recipes/577504/ (r3) """ # How to make different types of objects iterable dict_handler = lambda d: chain.from_iterable(d.items()) all_handlers = {tuple: iter, list: iter, deque: iter, dict: dict_handler, set: iter, frozenset: iter} all_handlers.update(handlers) # user handlers take precedence seen = set() # track which object id's have already been seen default_size = getsizeof(0) # estimate sizeof object without __sizeof__ def sizeof(o): "Calculate size of `o` and all its children" if id(o) in seen: # do not double count the same object return 0 seen.add(id(o)) if count: s = 1 else: s = getsizeof(o, default_size) # If `o` is iterable, add size of its members for typ, handler in all_handlers.items(): if isinstance(o, typ): s += sum(map(sizeof, handler(o))) break return s return sizeof(o)
def function[total_size, parameter[o, handlers, verbose, count]]: constant[Returns the approximate memory footprint an object and all of its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers to iterate over their contents: handlers = {SomeContainerClass: iter, OtherContainerClass: OtherContainerClass.get_elements} Source: http://code.activestate.com/recipes/577504/ (r3) ] variable[dict_handler] assign[=] <ast.Lambda object at 0x7da212db5060> variable[all_handlers] assign[=] dictionary[[<ast.Name object at 0x7da20c9918a0>, <ast.Name object at 0x7da20c9910f0>, <ast.Name object at 0x7da20c991c90>, <ast.Name object at 0x7da20c9908b0>, <ast.Name object at 0x7da20c992aa0>, <ast.Name object at 0x7da20c992a40>], [<ast.Name object at 0x7da20c993a00>, <ast.Name object at 0x7da20c992530>, <ast.Name object at 0x7da20c992e90>, <ast.Name object at 0x7da20c9919f0>, <ast.Name object at 0x7da20c991630>, <ast.Name object at 0x7da20c993f70>]] call[name[all_handlers].update, parameter[name[handlers]]] variable[seen] assign[=] call[name[set], parameter[]] variable[default_size] assign[=] call[name[getsizeof], parameter[constant[0]]] def function[sizeof, parameter[o]]: constant[Calculate size of `o` and all its children] if compare[call[name[id], parameter[name[o]]] in name[seen]] begin[:] return[constant[0]] call[name[seen].add, parameter[call[name[id], parameter[name[o]]]]] if name[count] begin[:] variable[s] assign[=] constant[1] for taget[tuple[[<ast.Name object at 0x7da1b0381a20>, <ast.Name object at 0x7da1b0381600>]]] in starred[call[name[all_handlers].items, parameter[]]] begin[:] if call[name[isinstance], parameter[name[o], name[typ]]] begin[:] <ast.AugAssign object at 0x7da1b0380580> break return[name[s]] return[call[name[sizeof], parameter[name[o]]]]
keyword[def] identifier[total_size] ( identifier[o] , identifier[handlers] ={}, identifier[verbose] = keyword[False] , identifier[count] = keyword[False] ): literal[string] identifier[dict_handler] = keyword[lambda] identifier[d] : identifier[chain] . identifier[from_iterable] ( identifier[d] . identifier[items] ()) identifier[all_handlers] ={ identifier[tuple] : identifier[iter] , identifier[list] : identifier[iter] , identifier[deque] : identifier[iter] , identifier[dict] : identifier[dict_handler] , identifier[set] : identifier[iter] , identifier[frozenset] : identifier[iter] } identifier[all_handlers] . identifier[update] ( identifier[handlers] ) identifier[seen] = identifier[set] () identifier[default_size] = identifier[getsizeof] ( literal[int] ) keyword[def] identifier[sizeof] ( identifier[o] ): literal[string] keyword[if] identifier[id] ( identifier[o] ) keyword[in] identifier[seen] : keyword[return] literal[int] identifier[seen] . identifier[add] ( identifier[id] ( identifier[o] )) keyword[if] identifier[count] : identifier[s] = literal[int] keyword[else] : identifier[s] = identifier[getsizeof] ( identifier[o] , identifier[default_size] ) keyword[for] identifier[typ] , identifier[handler] keyword[in] identifier[all_handlers] . identifier[items] (): keyword[if] identifier[isinstance] ( identifier[o] , identifier[typ] ): identifier[s] += identifier[sum] ( identifier[map] ( identifier[sizeof] , identifier[handler] ( identifier[o] ))) keyword[break] keyword[return] identifier[s] keyword[return] identifier[sizeof] ( identifier[o] )
def total_size(o, handlers={}, verbose=False, count=False): """Returns the approximate memory footprint an object and all of its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers to iterate over their contents: handlers = {SomeContainerClass: iter, OtherContainerClass: OtherContainerClass.get_elements} Source: http://code.activestate.com/recipes/577504/ (r3) """ # How to make different types of objects iterable dict_handler = lambda d: chain.from_iterable(d.items()) all_handlers = {tuple: iter, list: iter, deque: iter, dict: dict_handler, set: iter, frozenset: iter} all_handlers.update(handlers) # user handlers take precedence seen = set() # track which object id's have already been seen default_size = getsizeof(0) # estimate sizeof object without __sizeof__ def sizeof(o): """Calculate size of `o` and all its children""" if id(o) in seen: # do not double count the same object return 0 # depends on [control=['if'], data=[]] seen.add(id(o)) if count: s = 1 # depends on [control=['if'], data=[]] else: s = getsizeof(o, default_size) # If `o` is iterable, add size of its members for (typ, handler) in all_handlers.items(): if isinstance(o, typ): s += sum(map(sizeof, handler(o))) break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] return s return sizeof(o)
def promote_type(orig_type, new_type): """Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one""" if not new_type: return orig_type if not orig_type: return new_type try: orig_type = orig_type.__name__ except AttributeError: pass try: new_type = new_type.__name__ except AttributeError: pass type_precidence = ['unknown', 'int', 'float', 'date', 'time', 'datetime', 'str', 'bytes', 'unicode'] # TODO This will fail for dates and times. if type_precidence.index(new_type) > type_precidence.index(orig_type): return new_type else: return orig_type
def function[promote_type, parameter[orig_type, new_type]]: constant[Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one] if <ast.UnaryOp object at 0x7da20e955870> begin[:] return[name[orig_type]] if <ast.UnaryOp object at 0x7da20e957a60> begin[:] return[name[new_type]] <ast.Try object at 0x7da20e955750> <ast.Try object at 0x7da20e957910> variable[type_precidence] assign[=] list[[<ast.Constant object at 0x7da20e956e60>, <ast.Constant object at 0x7da20e957fd0>, <ast.Constant object at 0x7da20e956140>, <ast.Constant object at 0x7da20e955360>, <ast.Constant object at 0x7da20e956290>, <ast.Constant object at 0x7da20e957dc0>, <ast.Constant object at 0x7da20e9544f0>, <ast.Constant object at 0x7da20e9558d0>, <ast.Constant object at 0x7da20e9547c0>]] if compare[call[name[type_precidence].index, parameter[name[new_type]]] greater[>] call[name[type_precidence].index, parameter[name[orig_type]]]] begin[:] return[name[new_type]]
keyword[def] identifier[promote_type] ( identifier[orig_type] , identifier[new_type] ): literal[string] keyword[if] keyword[not] identifier[new_type] : keyword[return] identifier[orig_type] keyword[if] keyword[not] identifier[orig_type] : keyword[return] identifier[new_type] keyword[try] : identifier[orig_type] = identifier[orig_type] . identifier[__name__] keyword[except] identifier[AttributeError] : keyword[pass] keyword[try] : identifier[new_type] = identifier[new_type] . identifier[__name__] keyword[except] identifier[AttributeError] : keyword[pass] identifier[type_precidence] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ] keyword[if] identifier[type_precidence] . identifier[index] ( identifier[new_type] )> identifier[type_precidence] . identifier[index] ( identifier[orig_type] ): keyword[return] identifier[new_type] keyword[else] : keyword[return] identifier[orig_type]
def promote_type(orig_type, new_type): """Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one""" if not new_type: return orig_type # depends on [control=['if'], data=[]] if not orig_type: return new_type # depends on [control=['if'], data=[]] try: orig_type = orig_type.__name__ # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] try: new_type = new_type.__name__ # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] type_precidence = ['unknown', 'int', 'float', 'date', 'time', 'datetime', 'str', 'bytes', 'unicode'] # TODO This will fail for dates and times. if type_precidence.index(new_type) > type_precidence.index(orig_type): return new_type # depends on [control=['if'], data=[]] else: return orig_type
def get_fragility_model(node, fname): """ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, ff_id -> fragility function list """ with context(fname, node): fid = node['id'] asset_category = node['assetCategory'] loss_type = node['lossCategory'] description = ~node.description limit_states = ~node.limitStates ffs = node[2:] fmodel = scientific.FragilityModel( fid, asset_category, loss_type, description, limit_states) for ff in ffs: array, attrs = ffconvert(fname, limit_states, ff) attrs['id'] = ff['id'] ffl = scientific.FragilityFunctionList(array, **attrs) fmodel[ff.imls['imt'], ff['id']] = ffl return fmodel
def function[get_fragility_model, parameter[node, fname]]: constant[ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, ff_id -> fragility function list ] with call[name[context], parameter[name[fname], name[node]]] begin[:] variable[fid] assign[=] call[name[node]][constant[id]] variable[asset_category] assign[=] call[name[node]][constant[assetCategory]] variable[loss_type] assign[=] call[name[node]][constant[lossCategory]] variable[description] assign[=] <ast.UnaryOp object at 0x7da18dc07610> variable[limit_states] assign[=] <ast.UnaryOp object at 0x7da18dc04d00> variable[ffs] assign[=] call[name[node]][<ast.Slice object at 0x7da18dc06890>] variable[fmodel] assign[=] call[name[scientific].FragilityModel, parameter[name[fid], name[asset_category], name[loss_type], name[description], name[limit_states]]] for taget[name[ff]] in starred[name[ffs]] begin[:] <ast.Tuple object at 0x7da18dc06230> assign[=] call[name[ffconvert], parameter[name[fname], name[limit_states], name[ff]]] call[name[attrs]][constant[id]] assign[=] call[name[ff]][constant[id]] variable[ffl] assign[=] call[name[scientific].FragilityFunctionList, parameter[name[array]]] call[name[fmodel]][tuple[[<ast.Subscript object at 0x7da18dc04ca0>, <ast.Subscript object at 0x7da18dc06800>]]] assign[=] name[ffl] return[name[fmodel]]
keyword[def] identifier[get_fragility_model] ( identifier[node] , identifier[fname] ): literal[string] keyword[with] identifier[context] ( identifier[fname] , identifier[node] ): identifier[fid] = identifier[node] [ literal[string] ] identifier[asset_category] = identifier[node] [ literal[string] ] identifier[loss_type] = identifier[node] [ literal[string] ] identifier[description] =~ identifier[node] . identifier[description] identifier[limit_states] =~ identifier[node] . identifier[limitStates] identifier[ffs] = identifier[node] [ literal[int] :] identifier[fmodel] = identifier[scientific] . identifier[FragilityModel] ( identifier[fid] , identifier[asset_category] , identifier[loss_type] , identifier[description] , identifier[limit_states] ) keyword[for] identifier[ff] keyword[in] identifier[ffs] : identifier[array] , identifier[attrs] = identifier[ffconvert] ( identifier[fname] , identifier[limit_states] , identifier[ff] ) identifier[attrs] [ literal[string] ]= identifier[ff] [ literal[string] ] identifier[ffl] = identifier[scientific] . identifier[FragilityFunctionList] ( identifier[array] ,** identifier[attrs] ) identifier[fmodel] [ identifier[ff] . identifier[imls] [ literal[string] ], identifier[ff] [ literal[string] ]]= identifier[ffl] keyword[return] identifier[fmodel]
def get_fragility_model(node, fname): """ :param node: a vulnerabilityModel node :param fname: path to the vulnerability file :returns: a dictionary imt, ff_id -> fragility function list """ with context(fname, node): fid = node['id'] asset_category = node['assetCategory'] loss_type = node['lossCategory'] description = ~node.description limit_states = ~node.limitStates ffs = node[2:] # depends on [control=['with'], data=[]] fmodel = scientific.FragilityModel(fid, asset_category, loss_type, description, limit_states) for ff in ffs: (array, attrs) = ffconvert(fname, limit_states, ff) attrs['id'] = ff['id'] ffl = scientific.FragilityFunctionList(array, **attrs) fmodel[ff.imls['imt'], ff['id']] = ffl # depends on [control=['for'], data=['ff']] return fmodel
def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name """Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] """ global _KEY # pylint: disable=global-statement assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.bracket_id, self.i) params = json2paramater(searchspace_json, random_state) params[_KEY] = r hyperparameter_configs[params_id] = params self._record_hyper_configs(hyperparameter_configs) return [[key, value] for key, value in hyperparameter_configs.items()]
def function[get_hyperparameter_configurations, parameter[self, num, r, searchspace_json, random_state]]: constant[Randomly generate num hyperparameter configurations from search space Parameters ---------- num: int the number of hyperparameter configurations Returns ------- list a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...] ] <ast.Global object at 0x7da1b2040d60> assert[compare[name[self].i equal[==] constant[0]]] variable[hyperparameter_configs] assign[=] call[name[dict], parameter[]] for taget[name[_]] in starred[call[name[range], parameter[name[num]]]] begin[:] variable[params_id] assign[=] call[name[create_bracket_parameter_id], parameter[name[self].bracket_id, name[self].i]] variable[params] assign[=] call[name[json2paramater], parameter[name[searchspace_json], name[random_state]]] call[name[params]][name[_KEY]] assign[=] name[r] call[name[hyperparameter_configs]][name[params_id]] assign[=] name[params] call[name[self]._record_hyper_configs, parameter[name[hyperparameter_configs]]] return[<ast.ListComp object at 0x7da1b2043df0>]
keyword[def] identifier[get_hyperparameter_configurations] ( identifier[self] , identifier[num] , identifier[r] , identifier[searchspace_json] , identifier[random_state] ): literal[string] keyword[global] identifier[_KEY] keyword[assert] identifier[self] . identifier[i] == literal[int] identifier[hyperparameter_configs] = identifier[dict] () keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[num] ): identifier[params_id] = identifier[create_bracket_parameter_id] ( identifier[self] . identifier[bracket_id] , identifier[self] . identifier[i] ) identifier[params] = identifier[json2paramater] ( identifier[searchspace_json] , identifier[random_state] ) identifier[params] [ identifier[_KEY] ]= identifier[r] identifier[hyperparameter_configs] [ identifier[params_id] ]= identifier[params] identifier[self] . identifier[_record_hyper_configs] ( identifier[hyperparameter_configs] ) keyword[return] [[ identifier[key] , identifier[value] ] keyword[for] identifier[key] , identifier[value] keyword[in] identifier[hyperparameter_configs] . identifier[items] ()]
def get_hyperparameter_configurations(self, num, r, searchspace_json, random_state): # pylint: disable=invalid-name 'Randomly generate num hyperparameter configurations from search space\n\n Parameters\n ----------\n num: int\n the number of hyperparameter configurations\n \n Returns\n -------\n list\n a list of hyperparameter configurations. Format: [[key1, value1], [key2, value2], ...]\n ' global _KEY # pylint: disable=global-statement assert self.i == 0 hyperparameter_configs = dict() for _ in range(num): params_id = create_bracket_parameter_id(self.bracket_id, self.i) params = json2paramater(searchspace_json, random_state) params[_KEY] = r hyperparameter_configs[params_id] = params # depends on [control=['for'], data=[]] self._record_hyper_configs(hyperparameter_configs) return [[key, value] for (key, value) in hyperparameter_configs.items()]
def _lookup_host_mappings(query_type, session=None, **bfilter): """Look up 'query_type' Nexus mappings matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param bfilter: filter for mappings query :returns: mappings if query gave a result, else raise NexusHostMappingNotFound. """ if session is None: session = bc.get_reader_session() query_method = getattr(session.query( nexus_models_v2.NexusHostMapping).filter_by(**bfilter), query_type) try: mappings = query_method() if mappings: return mappings except sa_exc.NoResultFound: pass raise c_exc.NexusHostMappingNotFound(**bfilter)
def function[_lookup_host_mappings, parameter[query_type, session]]: constant[Look up 'query_type' Nexus mappings matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param bfilter: filter for mappings query :returns: mappings if query gave a result, else raise NexusHostMappingNotFound. ] if compare[name[session] is constant[None]] begin[:] variable[session] assign[=] call[name[bc].get_reader_session, parameter[]] variable[query_method] assign[=] call[name[getattr], parameter[call[call[name[session].query, parameter[name[nexus_models_v2].NexusHostMapping]].filter_by, parameter[]], name[query_type]]] <ast.Try object at 0x7da18bc704f0> <ast.Raise object at 0x7da1b1befc10>
keyword[def] identifier[_lookup_host_mappings] ( identifier[query_type] , identifier[session] = keyword[None] ,** identifier[bfilter] ): literal[string] keyword[if] identifier[session] keyword[is] keyword[None] : identifier[session] = identifier[bc] . identifier[get_reader_session] () identifier[query_method] = identifier[getattr] ( identifier[session] . identifier[query] ( identifier[nexus_models_v2] . identifier[NexusHostMapping] ). identifier[filter_by] (** identifier[bfilter] ), identifier[query_type] ) keyword[try] : identifier[mappings] = identifier[query_method] () keyword[if] identifier[mappings] : keyword[return] identifier[mappings] keyword[except] identifier[sa_exc] . identifier[NoResultFound] : keyword[pass] keyword[raise] identifier[c_exc] . identifier[NexusHostMappingNotFound] (** identifier[bfilter] )
def _lookup_host_mappings(query_type, session=None, **bfilter): """Look up 'query_type' Nexus mappings matching the filter. :param query_type: 'all', 'one' or 'first' :param session: db session :param bfilter: filter for mappings query :returns: mappings if query gave a result, else raise NexusHostMappingNotFound. """ if session is None: session = bc.get_reader_session() # depends on [control=['if'], data=['session']] query_method = getattr(session.query(nexus_models_v2.NexusHostMapping).filter_by(**bfilter), query_type) try: mappings = query_method() if mappings: return mappings # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except sa_exc.NoResultFound: pass # depends on [control=['except'], data=[]] raise c_exc.NexusHostMappingNotFound(**bfilter)
def add(self, term, name, overwrite=False): """ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : zipline.pipeline.Term A Filter, Factor, or Classifier to add to the pipeline. name : str Name of the column to add. overwrite : bool Whether to overwrite the existing entry if we already have a column named `name`. """ self.validate_column(name, term) columns = self.columns if name in columns: if overwrite: self.remove(name) else: raise KeyError("Column '{}' already exists.".format(name)) if not isinstance(term, ComputableTerm): raise TypeError( "{term} is not a valid pipeline column. Did you mean to " "append '.latest'?".format(term=term) ) self._columns[name] = term
def function[add, parameter[self, term, name, overwrite]]: constant[ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : zipline.pipeline.Term A Filter, Factor, or Classifier to add to the pipeline. name : str Name of the column to add. overwrite : bool Whether to overwrite the existing entry if we already have a column named `name`. ] call[name[self].validate_column, parameter[name[name], name[term]]] variable[columns] assign[=] name[self].columns if compare[name[name] in name[columns]] begin[:] if name[overwrite] begin[:] call[name[self].remove, parameter[name[name]]] if <ast.UnaryOp object at 0x7da1b2042e60> begin[:] <ast.Raise object at 0x7da1b2043190> call[name[self]._columns][name[name]] assign[=] name[term]
keyword[def] identifier[add] ( identifier[self] , identifier[term] , identifier[name] , identifier[overwrite] = keyword[False] ): literal[string] identifier[self] . identifier[validate_column] ( identifier[name] , identifier[term] ) identifier[columns] = identifier[self] . identifier[columns] keyword[if] identifier[name] keyword[in] identifier[columns] : keyword[if] identifier[overwrite] : identifier[self] . identifier[remove] ( identifier[name] ) keyword[else] : keyword[raise] identifier[KeyError] ( literal[string] . identifier[format] ( identifier[name] )) keyword[if] keyword[not] identifier[isinstance] ( identifier[term] , identifier[ComputableTerm] ): keyword[raise] identifier[TypeError] ( literal[string] literal[string] . identifier[format] ( identifier[term] = identifier[term] ) ) identifier[self] . identifier[_columns] [ identifier[name] ]= identifier[term]
def add(self, term, name, overwrite=False): """ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : zipline.pipeline.Term A Filter, Factor, or Classifier to add to the pipeline. name : str Name of the column to add. overwrite : bool Whether to overwrite the existing entry if we already have a column named `name`. """ self.validate_column(name, term) columns = self.columns if name in columns: if overwrite: self.remove(name) # depends on [control=['if'], data=[]] else: raise KeyError("Column '{}' already exists.".format(name)) # depends on [control=['if'], data=['name']] if not isinstance(term, ComputableTerm): raise TypeError("{term} is not a valid pipeline column. Did you mean to append '.latest'?".format(term=term)) # depends on [control=['if'], data=[]] self._columns[name] = term
def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) # transform these into values permitted_operators_list = set( [self.savedsearch.operators.get(op) for op in permitted_operators] ) return permitted_operators_list
def function[show_condition_operators, parameter[self, condition]]: constant[ Show available operators for a given saved search condition ] variable[permitted_operators] assign[=] call[name[self].savedsearch.conditions_operators.get, parameter[name[condition]]] variable[permitted_operators_list] assign[=] call[name[set], parameter[<ast.ListComp object at 0x7da1b021c280>]] return[name[permitted_operators_list]]
keyword[def] identifier[show_condition_operators] ( identifier[self] , identifier[condition] ): literal[string] identifier[permitted_operators] = identifier[self] . identifier[savedsearch] . identifier[conditions_operators] . identifier[get] ( identifier[condition] ) identifier[permitted_operators_list] = identifier[set] ( [ identifier[self] . identifier[savedsearch] . identifier[operators] . identifier[get] ( identifier[op] ) keyword[for] identifier[op] keyword[in] identifier[permitted_operators] ] ) keyword[return] identifier[permitted_operators_list]
def show_condition_operators(self, condition): """ Show available operators for a given saved search condition """ # dict keys of allowed operators for the current condition permitted_operators = self.savedsearch.conditions_operators.get(condition) # transform these into values permitted_operators_list = set([self.savedsearch.operators.get(op) for op in permitted_operators]) return permitted_operators_list
def truncation_selection(random, population, args): """Selects the best individuals from the population. This function performs truncation selection, which means that only the best individuals from the current population are selected. This is a completely deterministic selection mechanism. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default len(population)) """ num_selected = args.setdefault('num_selected', len(population)) population.sort(reverse=True) return population[:num_selected]
def function[truncation_selection, parameter[random, population, args]]: constant[Selects the best individuals from the population. This function performs truncation selection, which means that only the best individuals from the current population are selected. This is a completely deterministic selection mechanism. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default len(population)) ] variable[num_selected] assign[=] call[name[args].setdefault, parameter[constant[num_selected], call[name[len], parameter[name[population]]]]] call[name[population].sort, parameter[]] return[call[name[population]][<ast.Slice object at 0x7da1b13e2dd0>]]
keyword[def] identifier[truncation_selection] ( identifier[random] , identifier[population] , identifier[args] ): literal[string] identifier[num_selected] = identifier[args] . identifier[setdefault] ( literal[string] , identifier[len] ( identifier[population] )) identifier[population] . identifier[sort] ( identifier[reverse] = keyword[True] ) keyword[return] identifier[population] [: identifier[num_selected] ]
def truncation_selection(random, population, args): """Selects the best individuals from the population. This function performs truncation selection, which means that only the best individuals from the current population are selected. This is a completely deterministic selection mechanism. .. Arguments: random -- the random number generator object population -- the population of individuals args -- a dictionary of keyword arguments Optional keyword arguments in args: - *num_selected* -- the number of individuals to be selected (default len(population)) """ num_selected = args.setdefault('num_selected', len(population)) population.sort(reverse=True) return population[:num_selected]
def tool(self): """The tool that was in use during this event. If the caller keeps a reference to a tool, the tool object will compare equal to the previously obtained tool object. Note: Physical tool tracking requires hardware support. If unavailable, libinput creates one tool per type per tablet. See `Tracking unique tools`_ for more details. Returns: ~libinput.define.TabletTool: The new tool triggering this event. """ htablettool = self._libinput.libinput_event_tablet_tool_get_tool( self._handle) return TabletTool(htablettool, self._libinput)
def function[tool, parameter[self]]: constant[The tool that was in use during this event. If the caller keeps a reference to a tool, the tool object will compare equal to the previously obtained tool object. Note: Physical tool tracking requires hardware support. If unavailable, libinput creates one tool per type per tablet. See `Tracking unique tools`_ for more details. Returns: ~libinput.define.TabletTool: The new tool triggering this event. ] variable[htablettool] assign[=] call[name[self]._libinput.libinput_event_tablet_tool_get_tool, parameter[name[self]._handle]] return[call[name[TabletTool], parameter[name[htablettool], name[self]._libinput]]]
keyword[def] identifier[tool] ( identifier[self] ): literal[string] identifier[htablettool] = identifier[self] . identifier[_libinput] . identifier[libinput_event_tablet_tool_get_tool] ( identifier[self] . identifier[_handle] ) keyword[return] identifier[TabletTool] ( identifier[htablettool] , identifier[self] . identifier[_libinput] )
def tool(self): """The tool that was in use during this event. If the caller keeps a reference to a tool, the tool object will compare equal to the previously obtained tool object. Note: Physical tool tracking requires hardware support. If unavailable, libinput creates one tool per type per tablet. See `Tracking unique tools`_ for more details. Returns: ~libinput.define.TabletTool: The new tool triggering this event. """ htablettool = self._libinput.libinput_event_tablet_tool_get_tool(self._handle) return TabletTool(htablettool, self._libinput)
def rename_local_untracked(self): """ Rename local untracked files that would require pulls """ # Find what files have been added! new_upstream_files = self.find_upstream_changed('A') for f in new_upstream_files: if os.path.exists(f): # If there's a file extension, put the timestamp before that ts = datetime.datetime.now().strftime('__%Y%m%d%H%M%S') path_head, path_tail = os.path.split(f) path_tail = ts.join(os.path.splitext(path_tail)) new_file_name = os.path.join(path_head, path_tail) os.rename(f, new_file_name) yield 'Renamed {} to {} to avoid conflict with upstream'.format(f, new_file_name)
def function[rename_local_untracked, parameter[self]]: constant[ Rename local untracked files that would require pulls ] variable[new_upstream_files] assign[=] call[name[self].find_upstream_changed, parameter[constant[A]]] for taget[name[f]] in starred[name[new_upstream_files]] begin[:] if call[name[os].path.exists, parameter[name[f]]] begin[:] variable[ts] assign[=] call[call[name[datetime].datetime.now, parameter[]].strftime, parameter[constant[__%Y%m%d%H%M%S]]] <ast.Tuple object at 0x7da1b1288310> assign[=] call[name[os].path.split, parameter[name[f]]] variable[path_tail] assign[=] call[name[ts].join, parameter[call[name[os].path.splitext, parameter[name[path_tail]]]]] variable[new_file_name] assign[=] call[name[os].path.join, parameter[name[path_head], name[path_tail]]] call[name[os].rename, parameter[name[f], name[new_file_name]]] <ast.Yield object at 0x7da1b1151b40>
keyword[def] identifier[rename_local_untracked] ( identifier[self] ): literal[string] identifier[new_upstream_files] = identifier[self] . identifier[find_upstream_changed] ( literal[string] ) keyword[for] identifier[f] keyword[in] identifier[new_upstream_files] : keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[f] ): identifier[ts] = identifier[datetime] . identifier[datetime] . identifier[now] (). identifier[strftime] ( literal[string] ) identifier[path_head] , identifier[path_tail] = identifier[os] . identifier[path] . identifier[split] ( identifier[f] ) identifier[path_tail] = identifier[ts] . identifier[join] ( identifier[os] . identifier[path] . identifier[splitext] ( identifier[path_tail] )) identifier[new_file_name] = identifier[os] . identifier[path] . identifier[join] ( identifier[path_head] , identifier[path_tail] ) identifier[os] . identifier[rename] ( identifier[f] , identifier[new_file_name] ) keyword[yield] literal[string] . identifier[format] ( identifier[f] , identifier[new_file_name] )
def rename_local_untracked(self): """ Rename local untracked files that would require pulls """ # Find what files have been added! new_upstream_files = self.find_upstream_changed('A') for f in new_upstream_files: if os.path.exists(f): # If there's a file extension, put the timestamp before that ts = datetime.datetime.now().strftime('__%Y%m%d%H%M%S') (path_head, path_tail) = os.path.split(f) path_tail = ts.join(os.path.splitext(path_tail)) new_file_name = os.path.join(path_head, path_tail) os.rename(f, new_file_name) yield 'Renamed {} to {} to avoid conflict with upstream'.format(f, new_file_name) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']]
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show() """ if title == "": title = " " if xlabel == "": xlabel = " " if ylabel == "": ylabel = " " if title is None: title = "" # C++ otherwise gets "None" as std::string if xlabel is None: xlabel = "" if ylabel is None: ylabel = "" return Plot(self.__proxy__.plot(title, xlabel, ylabel))
def function[plot, parameter[self, title, xlabel, ylabel]]: constant[ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show() ] if compare[name[title] equal[==] constant[]] begin[:] variable[title] assign[=] constant[ ] if compare[name[xlabel] equal[==] constant[]] begin[:] variable[xlabel] assign[=] constant[ ] if compare[name[ylabel] equal[==] constant[]] begin[:] variable[ylabel] assign[=] constant[ ] if compare[name[title] is constant[None]] begin[:] variable[title] assign[=] constant[] if compare[name[xlabel] is constant[None]] begin[:] variable[xlabel] assign[=] constant[] if compare[name[ylabel] is constant[None]] begin[:] variable[ylabel] assign[=] constant[] return[call[name[Plot], parameter[call[name[self].__proxy__.plot, parameter[name[title], name[xlabel], name[ylabel]]]]]]
keyword[def] identifier[plot] ( identifier[self] , identifier[title] = identifier[LABEL_DEFAULT] , identifier[xlabel] = identifier[LABEL_DEFAULT] , identifier[ylabel] = identifier[LABEL_DEFAULT] ): literal[string] keyword[if] identifier[title] == literal[string] : identifier[title] = literal[string] keyword[if] identifier[xlabel] == literal[string] : identifier[xlabel] = literal[string] keyword[if] identifier[ylabel] == literal[string] : identifier[ylabel] = literal[string] keyword[if] identifier[title] keyword[is] keyword[None] : identifier[title] = literal[string] keyword[if] identifier[xlabel] keyword[is] keyword[None] : identifier[xlabel] = literal[string] keyword[if] identifier[ylabel] keyword[is] keyword[None] : identifier[ylabel] = literal[string] keyword[return] identifier[Plot] ( identifier[self] . identifier[__proxy__] . identifier[plot] ( identifier[title] , identifier[xlabel] , identifier[ylabel] ))
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). Parameters ---------- title : str The plot title to show for the resulting visualization. If the title is None, the title will be omitted. xlabel : str The X axis label to show for the resulting visualization. If the xlabel is None, the X axis label will be omitted. ylabel : str The Y axis label to show for the resulting visualization. If the ylabel is None, the Y axis label will be omitted. Returns ------- out : Plot A :class: Plot object that is the visualization of the SArray. Examples -------- Suppose 'sa' is an SArray, we can create a plot of it using: >>> plt = sa.plot() To override the default plot title and axis labels: >>> plt = sa.plot(title="My Plot Title", xlabel="My X Axis", ylabel="My Y Axis") We can then visualize the plot using: >>> plt.show() """ if title == '': title = ' ' # depends on [control=['if'], data=['title']] if xlabel == '': xlabel = ' ' # depends on [control=['if'], data=['xlabel']] if ylabel == '': ylabel = ' ' # depends on [control=['if'], data=['ylabel']] if title is None: title = '' # C++ otherwise gets "None" as std::string # depends on [control=['if'], data=['title']] if xlabel is None: xlabel = '' # depends on [control=['if'], data=['xlabel']] if ylabel is None: ylabel = '' # depends on [control=['if'], data=['ylabel']] return Plot(self.__proxy__.plot(title, xlabel, ylabel))
def random_numbers(n): """ Generate a random string from 0-9 :param n: length of the string :return: the random string """ return ''.join(random.SystemRandom().choice(string.digits) for _ in range(n))
def function[random_numbers, parameter[n]]: constant[ Generate a random string from 0-9 :param n: length of the string :return: the random string ] return[call[constant[].join, parameter[<ast.GeneratorExp object at 0x7da1b00b7be0>]]]
keyword[def] identifier[random_numbers] ( identifier[n] ): literal[string] keyword[return] literal[string] . identifier[join] ( identifier[random] . identifier[SystemRandom] (). identifier[choice] ( identifier[string] . identifier[digits] ) keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[n] ))
def random_numbers(n): """ Generate a random string from 0-9 :param n: length of the string :return: the random string """ return ''.join((random.SystemRandom().choice(string.digits) for _ in range(n)))
def _read_extensions(self, context): """Return list of extensions as str to be passed on to the Jinja2 env. If context does not contain the relevant info, return an empty list instead. """ try: extensions = context['cookiecutter']['_extensions'] except KeyError: return [] else: return [str(ext) for ext in extensions]
def function[_read_extensions, parameter[self, context]]: constant[Return list of extensions as str to be passed on to the Jinja2 env. If context does not contain the relevant info, return an empty list instead. ] <ast.Try object at 0x7da1b1f47310>
keyword[def] identifier[_read_extensions] ( identifier[self] , identifier[context] ): literal[string] keyword[try] : identifier[extensions] = identifier[context] [ literal[string] ][ literal[string] ] keyword[except] identifier[KeyError] : keyword[return] [] keyword[else] : keyword[return] [ identifier[str] ( identifier[ext] ) keyword[for] identifier[ext] keyword[in] identifier[extensions] ]
def _read_extensions(self, context): """Return list of extensions as str to be passed on to the Jinja2 env. If context does not contain the relevant info, return an empty list instead. """ try: extensions = context['cookiecutter']['_extensions'] # depends on [control=['try'], data=[]] except KeyError: return [] # depends on [control=['except'], data=[]] else: return [str(ext) for ext in extensions]
def cwd(self, new_path): '''Sets the cwd during reads and writes''' old_cwd = self._cwd self._cwd = new_path return old_cwd
def function[cwd, parameter[self, new_path]]: constant[Sets the cwd during reads and writes] variable[old_cwd] assign[=] name[self]._cwd name[self]._cwd assign[=] name[new_path] return[name[old_cwd]]
keyword[def] identifier[cwd] ( identifier[self] , identifier[new_path] ): literal[string] identifier[old_cwd] = identifier[self] . identifier[_cwd] identifier[self] . identifier[_cwd] = identifier[new_path] keyword[return] identifier[old_cwd]
def cwd(self, new_path): """Sets the cwd during reads and writes""" old_cwd = self._cwd self._cwd = new_path return old_cwd
def snappy_encode(payload, xerial_compatible=False, xerial_blocksize=32 * 1024): """ Compress the given data with the Snappy algorithm. :param bytes payload: Data to compress. :param bool xerial_compatible: If set then the stream is broken into length-prefixed blocks in a fashion compatible with the xerial snappy library. The format winds up being:: +-------------+------------+--------------+------------+--------------+ | Header | Block1_len | Block1 data | BlockN len | BlockN data | |-------------+------------+--------------+------------+--------------| | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | +-------------+------------+--------------+------------+--------------+ :param int xerial_blocksize: Number of bytes per chunk to independently Snappy encode. 32k is the default in the xerial library. :returns: Compressed bytes. :rtype: :class:`bytes` """ if not has_snappy(): # FIXME This should be static, not checked every call. raise NotImplementedError("Snappy codec is not available") if xerial_compatible: def _chunker(): for i in range(0, len(payload), xerial_blocksize): yield payload[i:i+xerial_blocksize] out = BytesIO() out.write(_XERIAL_HEADER) for chunk in _chunker(): block = snappy.compress(chunk) out.write(struct.pack('!i', len(block))) out.write(block) out.seek(0) return out.read() else: return snappy.compress(payload)
def function[snappy_encode, parameter[payload, xerial_compatible, xerial_blocksize]]: constant[ Compress the given data with the Snappy algorithm. :param bytes payload: Data to compress. :param bool xerial_compatible: If set then the stream is broken into length-prefixed blocks in a fashion compatible with the xerial snappy library. The format winds up being:: +-------------+------------+--------------+------------+--------------+ | Header | Block1_len | Block1 data | BlockN len | BlockN data | |-------------+------------+--------------+------------+--------------| | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | +-------------+------------+--------------+------------+--------------+ :param int xerial_blocksize: Number of bytes per chunk to independently Snappy encode. 32k is the default in the xerial library. :returns: Compressed bytes. :rtype: :class:`bytes` ] if <ast.UnaryOp object at 0x7da1b0414880> begin[:] <ast.Raise object at 0x7da1b04153f0> if name[xerial_compatible] begin[:] def function[_chunker, parameter[]]: for taget[name[i]] in starred[call[name[range], parameter[constant[0], call[name[len], parameter[name[payload]]], name[xerial_blocksize]]]] begin[:] <ast.Yield object at 0x7da1b0415c30> variable[out] assign[=] call[name[BytesIO], parameter[]] call[name[out].write, parameter[name[_XERIAL_HEADER]]] for taget[name[chunk]] in starred[call[name[_chunker], parameter[]]] begin[:] variable[block] assign[=] call[name[snappy].compress, parameter[name[chunk]]] call[name[out].write, parameter[call[name[struct].pack, parameter[constant[!i], call[name[len], parameter[name[block]]]]]]] call[name[out].write, parameter[name[block]]] call[name[out].seek, parameter[constant[0]]] return[call[name[out].read, parameter[]]]
keyword[def] identifier[snappy_encode] ( identifier[payload] , identifier[xerial_compatible] = keyword[False] , identifier[xerial_blocksize] = literal[int] * literal[int] ): literal[string] keyword[if] keyword[not] identifier[has_snappy] (): keyword[raise] identifier[NotImplementedError] ( literal[string] ) keyword[if] identifier[xerial_compatible] : keyword[def] identifier[_chunker] (): keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[payload] ), identifier[xerial_blocksize] ): keyword[yield] identifier[payload] [ identifier[i] : identifier[i] + identifier[xerial_blocksize] ] identifier[out] = identifier[BytesIO] () identifier[out] . identifier[write] ( identifier[_XERIAL_HEADER] ) keyword[for] identifier[chunk] keyword[in] identifier[_chunker] (): identifier[block] = identifier[snappy] . identifier[compress] ( identifier[chunk] ) identifier[out] . identifier[write] ( identifier[struct] . identifier[pack] ( literal[string] , identifier[len] ( identifier[block] ))) identifier[out] . identifier[write] ( identifier[block] ) identifier[out] . identifier[seek] ( literal[int] ) keyword[return] identifier[out] . identifier[read] () keyword[else] : keyword[return] identifier[snappy] . identifier[compress] ( identifier[payload] )
def snappy_encode(payload, xerial_compatible=False, xerial_blocksize=32 * 1024): """ Compress the given data with the Snappy algorithm. :param bytes payload: Data to compress. :param bool xerial_compatible: If set then the stream is broken into length-prefixed blocks in a fashion compatible with the xerial snappy library. The format winds up being:: +-------------+------------+--------------+------------+--------------+ | Header | Block1_len | Block1 data | BlockN len | BlockN data | |-------------+------------+--------------+------------+--------------| | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | +-------------+------------+--------------+------------+--------------+ :param int xerial_blocksize: Number of bytes per chunk to independently Snappy encode. 32k is the default in the xerial library. :returns: Compressed bytes. :rtype: :class:`bytes` """ if not has_snappy(): # FIXME This should be static, not checked every call. raise NotImplementedError('Snappy codec is not available') # depends on [control=['if'], data=[]] if xerial_compatible: def _chunker(): for i in range(0, len(payload), xerial_blocksize): yield payload[i:i + xerial_blocksize] # depends on [control=['for'], data=['i']] out = BytesIO() out.write(_XERIAL_HEADER) for chunk in _chunker(): block = snappy.compress(chunk) out.write(struct.pack('!i', len(block))) out.write(block) # depends on [control=['for'], data=['chunk']] out.seek(0) return out.read() # depends on [control=['if'], data=[]] else: return snappy.compress(payload)
def read_record_public(self, orcid_id, request_type, token, put_code=None, accept_type='application/orcid+json'): """Get the public info about the researcher. Parameters ---------- :param orcid_id: string Id of the queried author. :param request_type: string For example: 'record'. See https://members.orcid.org/api/tutorial/read-orcid-records for possible values. :param token: string Token received from OAuth 2 3-legged authorization. :param put_code: string | list of strings The id of the queried work. In case of 'works' request_type might be a list of strings :param accept_type: expected MIME type of received data Returns ------- :returns: dict | lxml.etree._Element Record(s) in JSON-compatible dictionary representation or in XML E-tree, depending on accept_type specified. """ return self._get_info(orcid_id, self._get_public_info, request_type, token, put_code, accept_type)
def function[read_record_public, parameter[self, orcid_id, request_type, token, put_code, accept_type]]: constant[Get the public info about the researcher. Parameters ---------- :param orcid_id: string Id of the queried author. :param request_type: string For example: 'record'. See https://members.orcid.org/api/tutorial/read-orcid-records for possible values. :param token: string Token received from OAuth 2 3-legged authorization. :param put_code: string | list of strings The id of the queried work. In case of 'works' request_type might be a list of strings :param accept_type: expected MIME type of received data Returns ------- :returns: dict | lxml.etree._Element Record(s) in JSON-compatible dictionary representation or in XML E-tree, depending on accept_type specified. ] return[call[name[self]._get_info, parameter[name[orcid_id], name[self]._get_public_info, name[request_type], name[token], name[put_code], name[accept_type]]]]
keyword[def] identifier[read_record_public] ( identifier[self] , identifier[orcid_id] , identifier[request_type] , identifier[token] , identifier[put_code] = keyword[None] , identifier[accept_type] = literal[string] ): literal[string] keyword[return] identifier[self] . identifier[_get_info] ( identifier[orcid_id] , identifier[self] . identifier[_get_public_info] , identifier[request_type] , identifier[token] , identifier[put_code] , identifier[accept_type] )
def read_record_public(self, orcid_id, request_type, token, put_code=None, accept_type='application/orcid+json'): """Get the public info about the researcher. Parameters ---------- :param orcid_id: string Id of the queried author. :param request_type: string For example: 'record'. See https://members.orcid.org/api/tutorial/read-orcid-records for possible values. :param token: string Token received from OAuth 2 3-legged authorization. :param put_code: string | list of strings The id of the queried work. In case of 'works' request_type might be a list of strings :param accept_type: expected MIME type of received data Returns ------- :returns: dict | lxml.etree._Element Record(s) in JSON-compatible dictionary representation or in XML E-tree, depending on accept_type specified. """ return self._get_info(orcid_id, self._get_public_info, request_type, token, put_code, accept_type)
def image_linear_solve(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=False): """ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalization of the brightness profiles) :param kwargs_lens: list of keyword arguments corresponding to the superposition of different lens profiles :param kwargs_source: list of keyword arguments corresponding to the superposition of different source light profiles :param kwargs_lens_light: list of keyword arguments corresponding to different lens light surface brightness profiles :param kwargs_else: keyword arguments corresponding to "other" parameters, such as external shear and point source image positions :param inv_bool: if True, invert the full linear solver Matrix Ax = y for the purpose of the covariance matrix. :return: 1d array of surface brightness pixels of the optimal solution of the linear parameters to match the data """ wls_list, error_map_list, cov_param_list, param_list = [], [], [], [] for i in range(self._num_bands): wls_model, error_map, cov_param, param = self._imageModel_list[i].image_linear_solve(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=inv_bool) wls_list.append(wls_model) error_map_list.append(error_map) cov_param_list.append(cov_param) param_list.append(param) return wls_list, error_map_list, cov_param_list, param_list
def function[image_linear_solve, parameter[self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool]]: constant[ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalization of the brightness profiles) :param kwargs_lens: list of keyword arguments corresponding to the superposition of different lens profiles :param kwargs_source: list of keyword arguments corresponding to the superposition of different source light profiles :param kwargs_lens_light: list of keyword arguments corresponding to different lens light surface brightness profiles :param kwargs_else: keyword arguments corresponding to "other" parameters, such as external shear and point source image positions :param inv_bool: if True, invert the full linear solver Matrix Ax = y for the purpose of the covariance matrix. :return: 1d array of surface brightness pixels of the optimal solution of the linear parameters to match the data ] <ast.Tuple object at 0x7da18bccad10> assign[=] tuple[[<ast.List object at 0x7da18bcca0e0>, <ast.List object at 0x7da18bcc85b0>, <ast.List object at 0x7da18bccbd00>, <ast.List object at 0x7da18bccab30>]] for taget[name[i]] in starred[call[name[range], parameter[name[self]._num_bands]]] begin[:] <ast.Tuple object at 0x7da18bcc90f0> assign[=] call[call[name[self]._imageModel_list][name[i]].image_linear_solve, parameter[name[kwargs_lens], name[kwargs_source], name[kwargs_lens_light], name[kwargs_else]]] call[name[wls_list].append, parameter[name[wls_model]]] call[name[error_map_list].append, parameter[name[error_map]]] call[name[cov_param_list].append, parameter[name[cov_param]]] call[name[param_list].append, parameter[name[param]]] return[tuple[[<ast.Name object at 0x7da18bccb790>, <ast.Name object at 0x7da18bcc8cd0>, <ast.Name object at 0x7da18bcc8bb0>, <ast.Name object at 0x7da18bcc9210>]]]
keyword[def] identifier[image_linear_solve] ( identifier[self] , identifier[kwargs_lens] , identifier[kwargs_source] , identifier[kwargs_lens_light] , identifier[kwargs_else] , identifier[inv_bool] = keyword[False] ): literal[string] identifier[wls_list] , identifier[error_map_list] , identifier[cov_param_list] , identifier[param_list] =[],[],[],[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[_num_bands] ): identifier[wls_model] , identifier[error_map] , identifier[cov_param] , identifier[param] = identifier[self] . identifier[_imageModel_list] [ identifier[i] ]. identifier[image_linear_solve] ( identifier[kwargs_lens] , identifier[kwargs_source] , identifier[kwargs_lens_light] , identifier[kwargs_else] , identifier[inv_bool] = identifier[inv_bool] ) identifier[wls_list] . identifier[append] ( identifier[wls_model] ) identifier[error_map_list] . identifier[append] ( identifier[error_map] ) identifier[cov_param_list] . identifier[append] ( identifier[cov_param] ) identifier[param_list] . identifier[append] ( identifier[param] ) keyword[return] identifier[wls_list] , identifier[error_map_list] , identifier[cov_param_list] , identifier[param_list]
def image_linear_solve(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=False): """ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalization of the brightness profiles) :param kwargs_lens: list of keyword arguments corresponding to the superposition of different lens profiles :param kwargs_source: list of keyword arguments corresponding to the superposition of different source light profiles :param kwargs_lens_light: list of keyword arguments corresponding to different lens light surface brightness profiles :param kwargs_else: keyword arguments corresponding to "other" parameters, such as external shear and point source image positions :param inv_bool: if True, invert the full linear solver Matrix Ax = y for the purpose of the covariance matrix. :return: 1d array of surface brightness pixels of the optimal solution of the linear parameters to match the data """ (wls_list, error_map_list, cov_param_list, param_list) = ([], [], [], []) for i in range(self._num_bands): (wls_model, error_map, cov_param, param) = self._imageModel_list[i].image_linear_solve(kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=inv_bool) wls_list.append(wls_model) error_map_list.append(error_map) cov_param_list.append(cov_param) param_list.append(param) # depends on [control=['for'], data=['i']] return (wls_list, error_map_list, cov_param_list, param_list)
def __load_section(self, section_key): """ Reads the set of article links for a section if they are not cached. """ if self._sections[section_key] is not None: return articles = [] for page in count(1): if page > 50: raise Exception('Last page detection is probably broken') url = '{domain}{section}&iMenuID=1&iSubMenuID={page}'.format( domain = DOMAIN, section = SECTIONS[section_key], page = page ) body = self._session.get(url).content # This is a very hacky way of detecting the last page # that will probably break again in the future if "알수 없는 주소" in body: # "Unknown Address" break # Parse out all the article links root = html.fromstring(body) title_lines = root.find_class('ListNewsLineTitle') for title_line in title_lines: title_link = title_line.find('a') # The links do a JS open in a new window, so we need to parse # it out using this ugly, brittle junk href = title_link.get('href') match = re.match("javascript:article_open\('(.+)'\)", href) if not match: raise Exception("The site's link format has changed and is not compatible") path = match.group(1).decode('string_escape') articles.append(Article( self._session, title_link.text_content().strip(), DOMAIN + '/en/' + path )) self._sections[section_key] = articles
def function[__load_section, parameter[self, section_key]]: constant[ Reads the set of article links for a section if they are not cached. ] if compare[call[name[self]._sections][name[section_key]] is_not constant[None]] begin[:] return[None] variable[articles] assign[=] list[[]] for taget[name[page]] in starred[call[name[count], parameter[constant[1]]]] begin[:] if compare[name[page] greater[>] constant[50]] begin[:] <ast.Raise object at 0x7da1b1304730> variable[url] assign[=] call[constant[{domain}{section}&iMenuID=1&iSubMenuID={page}].format, parameter[]] variable[body] assign[=] call[name[self]._session.get, parameter[name[url]]].content if compare[constant[알수 없는 주소] in name[body]] begin[:] break variable[root] assign[=] call[name[html].fromstring, parameter[name[body]]] variable[title_lines] assign[=] call[name[root].find_class, parameter[constant[ListNewsLineTitle]]] for taget[name[title_line]] in starred[name[title_lines]] begin[:] variable[title_link] assign[=] call[name[title_line].find, parameter[constant[a]]] variable[href] assign[=] call[name[title_link].get, parameter[constant[href]]] variable[match] assign[=] call[name[re].match, parameter[constant[javascript:article_open\('(.+)'\)], name[href]]] if <ast.UnaryOp object at 0x7da1b13ba4a0> begin[:] <ast.Raise object at 0x7da1b13ba440> variable[path] assign[=] call[call[name[match].group, parameter[constant[1]]].decode, parameter[constant[string_escape]]] call[name[articles].append, parameter[call[name[Article], parameter[name[self]._session, call[call[name[title_link].text_content, parameter[]].strip, parameter[]], binary_operation[binary_operation[name[DOMAIN] + constant[/en/]] + name[path]]]]]] call[name[self]._sections][name[section_key]] assign[=] name[articles]
keyword[def] identifier[__load_section] ( identifier[self] , identifier[section_key] ): literal[string] keyword[if] identifier[self] . identifier[_sections] [ identifier[section_key] ] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[articles] =[] keyword[for] identifier[page] keyword[in] identifier[count] ( literal[int] ): keyword[if] identifier[page] > literal[int] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[url] = literal[string] . identifier[format] ( identifier[domain] = identifier[DOMAIN] , identifier[section] = identifier[SECTIONS] [ identifier[section_key] ], identifier[page] = identifier[page] ) identifier[body] = identifier[self] . identifier[_session] . identifier[get] ( identifier[url] ). identifier[content] keyword[if] literal[string] keyword[in] identifier[body] : keyword[break] identifier[root] = identifier[html] . identifier[fromstring] ( identifier[body] ) identifier[title_lines] = identifier[root] . identifier[find_class] ( literal[string] ) keyword[for] identifier[title_line] keyword[in] identifier[title_lines] : identifier[title_link] = identifier[title_line] . identifier[find] ( literal[string] ) identifier[href] = identifier[title_link] . identifier[get] ( literal[string] ) identifier[match] = identifier[re] . identifier[match] ( literal[string] , identifier[href] ) keyword[if] keyword[not] identifier[match] : keyword[raise] identifier[Exception] ( literal[string] ) identifier[path] = identifier[match] . identifier[group] ( literal[int] ). identifier[decode] ( literal[string] ) identifier[articles] . identifier[append] ( identifier[Article] ( identifier[self] . identifier[_session] , identifier[title_link] . identifier[text_content] (). identifier[strip] (), identifier[DOMAIN] + literal[string] + identifier[path] )) identifier[self] . identifier[_sections] [ identifier[section_key] ]= identifier[articles]
def __load_section(self, section_key): """ Reads the set of article links for a section if they are not cached. """ if self._sections[section_key] is not None: return # depends on [control=['if'], data=[]] articles = [] for page in count(1): if page > 50: raise Exception('Last page detection is probably broken') # depends on [control=['if'], data=[]] url = '{domain}{section}&iMenuID=1&iSubMenuID={page}'.format(domain=DOMAIN, section=SECTIONS[section_key], page=page) body = self._session.get(url).content # This is a very hacky way of detecting the last page # that will probably break again in the future if '알수 없는 주소' in body: # "Unknown Address" break # depends on [control=['if'], data=[]] # Parse out all the article links root = html.fromstring(body) title_lines = root.find_class('ListNewsLineTitle') for title_line in title_lines: title_link = title_line.find('a') # The links do a JS open in a new window, so we need to parse # it out using this ugly, brittle junk href = title_link.get('href') match = re.match("javascript:article_open\\('(.+)'\\)", href) if not match: raise Exception("The site's link format has changed and is not compatible") # depends on [control=['if'], data=[]] path = match.group(1).decode('string_escape') articles.append(Article(self._session, title_link.text_content().strip(), DOMAIN + '/en/' + path)) # depends on [control=['for'], data=['title_line']] # depends on [control=['for'], data=['page']] self._sections[section_key] = articles
def config(list): # pylint:disable=redefined-builtin """Set and get the global configurations.""" if list: _config = GlobalConfigManager.get_config_or_default() Printer.print_header('Current config:') dict_tabulate(_config.to_dict())
def function[config, parameter[list]]: constant[Set and get the global configurations.] if name[list] begin[:] variable[_config] assign[=] call[name[GlobalConfigManager].get_config_or_default, parameter[]] call[name[Printer].print_header, parameter[constant[Current config:]]] call[name[dict_tabulate], parameter[call[name[_config].to_dict, parameter[]]]]
keyword[def] identifier[config] ( identifier[list] ): literal[string] keyword[if] identifier[list] : identifier[_config] = identifier[GlobalConfigManager] . identifier[get_config_or_default] () identifier[Printer] . identifier[print_header] ( literal[string] ) identifier[dict_tabulate] ( identifier[_config] . identifier[to_dict] ())
def config(list): # pylint:disable=redefined-builtin 'Set and get the global configurations.' if list: _config = GlobalConfigManager.get_config_or_default() Printer.print_header('Current config:') dict_tabulate(_config.to_dict()) # depends on [control=['if'], data=[]]
def add(self, cell, overwrite_duplicate=False): """ Add one or more cells to the library. Parameters ---------- cell : ``Cell`` of list of ``Cell`` Cells to be included in the library. overwrite_duplicate : bool If True an existing cell with the same name in the library will be overwritten. Returns ------- out : ``GdsLibrary`` This object. """ if isinstance(cell, Cell): if (not overwrite_duplicate and cell.name in self.cell_dict and self.cell_dict[cell.name] is not cell): raise ValueError("[GDSPY] cell named {0} already present in " "library.".format(cell.name)) self.cell_dict[cell.name] = cell else: for c in cell: if (not overwrite_duplicate and c.name in self.cell_dict and self.cell_dict[c.name] is not c): raise ValueError("[GDSPY] cell named {0} already present " "in library.".format(c.name)) self.cell_dict[c.name] = c return self
def function[add, parameter[self, cell, overwrite_duplicate]]: constant[ Add one or more cells to the library. Parameters ---------- cell : ``Cell`` of list of ``Cell`` Cells to be included in the library. overwrite_duplicate : bool If True an existing cell with the same name in the library will be overwritten. Returns ------- out : ``GdsLibrary`` This object. ] if call[name[isinstance], parameter[name[cell], name[Cell]]] begin[:] if <ast.BoolOp object at 0x7da1b065e920> begin[:] <ast.Raise object at 0x7da18f723670> call[name[self].cell_dict][name[cell].name] assign[=] name[cell] return[name[self]]
keyword[def] identifier[add] ( identifier[self] , identifier[cell] , identifier[overwrite_duplicate] = keyword[False] ): literal[string] keyword[if] identifier[isinstance] ( identifier[cell] , identifier[Cell] ): keyword[if] ( keyword[not] identifier[overwrite_duplicate] keyword[and] identifier[cell] . identifier[name] keyword[in] identifier[self] . identifier[cell_dict] keyword[and] identifier[self] . identifier[cell_dict] [ identifier[cell] . identifier[name] ] keyword[is] keyword[not] identifier[cell] ): keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[cell] . identifier[name] )) identifier[self] . identifier[cell_dict] [ identifier[cell] . identifier[name] ]= identifier[cell] keyword[else] : keyword[for] identifier[c] keyword[in] identifier[cell] : keyword[if] ( keyword[not] identifier[overwrite_duplicate] keyword[and] identifier[c] . identifier[name] keyword[in] identifier[self] . identifier[cell_dict] keyword[and] identifier[self] . identifier[cell_dict] [ identifier[c] . identifier[name] ] keyword[is] keyword[not] identifier[c] ): keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[c] . identifier[name] )) identifier[self] . identifier[cell_dict] [ identifier[c] . identifier[name] ]= identifier[c] keyword[return] identifier[self]
def add(self, cell, overwrite_duplicate=False): """ Add one or more cells to the library. Parameters ---------- cell : ``Cell`` of list of ``Cell`` Cells to be included in the library. overwrite_duplicate : bool If True an existing cell with the same name in the library will be overwritten. Returns ------- out : ``GdsLibrary`` This object. """ if isinstance(cell, Cell): if not overwrite_duplicate and cell.name in self.cell_dict and (self.cell_dict[cell.name] is not cell): raise ValueError('[GDSPY] cell named {0} already present in library.'.format(cell.name)) # depends on [control=['if'], data=[]] self.cell_dict[cell.name] = cell # depends on [control=['if'], data=[]] else: for c in cell: if not overwrite_duplicate and c.name in self.cell_dict and (self.cell_dict[c.name] is not c): raise ValueError('[GDSPY] cell named {0} already present in library.'.format(c.name)) # depends on [control=['if'], data=[]] self.cell_dict[c.name] = c # depends on [control=['for'], data=['c']] return self
async def delete(self, turn_context: TurnContext) -> None: """ Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None """ if turn_context == None: raise TypeError('BotState.delete(): turn_context cannot be None.') turn_context.turn_state.pop(self._context_service_key) storage_key = self.get_storage_key(turn_context) await self._storage.delete({ storage_key })
<ast.AsyncFunctionDef object at 0x7da18f09c7c0>
keyword[async] keyword[def] identifier[delete] ( identifier[self] , identifier[turn_context] : identifier[TurnContext] )-> keyword[None] : literal[string] keyword[if] identifier[turn_context] == keyword[None] : keyword[raise] identifier[TypeError] ( literal[string] ) identifier[turn_context] . identifier[turn_state] . identifier[pop] ( identifier[self] . identifier[_context_service_key] ) identifier[storage_key] = identifier[self] . identifier[get_storage_key] ( identifier[turn_context] ) keyword[await] identifier[self] . identifier[_storage] . identifier[delete] ({ identifier[storage_key] })
async def delete(self, turn_context: TurnContext) -> None: """ Delete any state currently stored in this state scope. :param turn_context: The context object for this turn. :return: None """ if turn_context == None: raise TypeError('BotState.delete(): turn_context cannot be None.') # depends on [control=['if'], data=[]] turn_context.turn_state.pop(self._context_service_key) storage_key = self.get_storage_key(turn_context) await self._storage.delete({storage_key})
def uninstall(self): """ Uninstalls the bundle """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework.uninstall_bundle(self)
def function[uninstall, parameter[self]]: constant[ Uninstalls the bundle ] with name[self]._lock begin[:] if compare[name[self]._state equal[==] name[Bundle].ACTIVE] begin[:] call[name[self].stop, parameter[]] name[self]._state assign[=] name[Bundle].UNINSTALLED call[name[self].__framework.uninstall_bundle, parameter[name[self]]]
keyword[def] identifier[uninstall] ( identifier[self] ): literal[string] keyword[with] identifier[self] . identifier[_lock] : keyword[if] identifier[self] . identifier[_state] == identifier[Bundle] . identifier[ACTIVE] : identifier[self] . identifier[stop] () identifier[self] . identifier[_state] = identifier[Bundle] . identifier[UNINSTALLED] identifier[self] . identifier[__framework] . identifier[uninstall_bundle] ( identifier[self] )
def uninstall(self): """ Uninstalls the bundle """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() # depends on [control=['if'], data=[]] # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework.uninstall_bundle(self) # depends on [control=['with'], data=[]]
def auto_subscribe(self, app_manager): """Called to subscribe the handlers on init.""" for handler in app_manager.handler_classes: app_manager.subscribe(handler.channel(), self)
def function[auto_subscribe, parameter[self, app_manager]]: constant[Called to subscribe the handlers on init.] for taget[name[handler]] in starred[name[app_manager].handler_classes] begin[:] call[name[app_manager].subscribe, parameter[call[name[handler].channel, parameter[]], name[self]]]
keyword[def] identifier[auto_subscribe] ( identifier[self] , identifier[app_manager] ): literal[string] keyword[for] identifier[handler] keyword[in] identifier[app_manager] . identifier[handler_classes] : identifier[app_manager] . identifier[subscribe] ( identifier[handler] . identifier[channel] (), identifier[self] )
def auto_subscribe(self, app_manager): """Called to subscribe the handlers on init.""" for handler in app_manager.handler_classes: app_manager.subscribe(handler.channel(), self) # depends on [control=['for'], data=['handler']]
def authorization_url(self, **kwargs): """Generates an authorization URL. This is the first step in the OAuth 2.0 Authorization Flow. The user's browser should be redirected to the returned URL. This method calls :meth:`requests_oauthlib.OAuth2Session.authorization_url` and specifies the client configuration's authorization URI (usually Google's authorization server) and specifies that "offline" access is desired. This is required in order to obtain a refresh token. Args: kwargs: Additional arguments passed through to :meth:`requests_oauthlib.OAuth2Session.authorization_url` Returns: Tuple[str, str]: The generated authorization URL and state. The user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different :class:`Flow` instance to obtain the token, you will need to specify the ``state`` when constructing the :class:`Flow`. """ kwargs.setdefault('access_type', 'offline') url, state = self.oauth2session.authorization_url( self.client_config['auth_uri'], **kwargs) return url, state
def function[authorization_url, parameter[self]]: constant[Generates an authorization URL. This is the first step in the OAuth 2.0 Authorization Flow. The user's browser should be redirected to the returned URL. This method calls :meth:`requests_oauthlib.OAuth2Session.authorization_url` and specifies the client configuration's authorization URI (usually Google's authorization server) and specifies that "offline" access is desired. This is required in order to obtain a refresh token. Args: kwargs: Additional arguments passed through to :meth:`requests_oauthlib.OAuth2Session.authorization_url` Returns: Tuple[str, str]: The generated authorization URL and state. The user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different :class:`Flow` instance to obtain the token, you will need to specify the ``state`` when constructing the :class:`Flow`. ] call[name[kwargs].setdefault, parameter[constant[access_type], constant[offline]]] <ast.Tuple object at 0x7da1b16b20e0> assign[=] call[name[self].oauth2session.authorization_url, parameter[call[name[self].client_config][constant[auth_uri]]]] return[tuple[[<ast.Name object at 0x7da1b16b1ab0>, <ast.Name object at 0x7da1b16b1fc0>]]]
keyword[def] identifier[authorization_url] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[kwargs] . identifier[setdefault] ( literal[string] , literal[string] ) identifier[url] , identifier[state] = identifier[self] . identifier[oauth2session] . identifier[authorization_url] ( identifier[self] . identifier[client_config] [ literal[string] ],** identifier[kwargs] ) keyword[return] identifier[url] , identifier[state]
def authorization_url(self, **kwargs): """Generates an authorization URL. This is the first step in the OAuth 2.0 Authorization Flow. The user's browser should be redirected to the returned URL. This method calls :meth:`requests_oauthlib.OAuth2Session.authorization_url` and specifies the client configuration's authorization URI (usually Google's authorization server) and specifies that "offline" access is desired. This is required in order to obtain a refresh token. Args: kwargs: Additional arguments passed through to :meth:`requests_oauthlib.OAuth2Session.authorization_url` Returns: Tuple[str, str]: The generated authorization URL and state. The user must visit the URL to complete the flow. The state is used when completing the flow to verify that the request originated from your application. If your application is using a different :class:`Flow` instance to obtain the token, you will need to specify the ``state`` when constructing the :class:`Flow`. """ kwargs.setdefault('access_type', 'offline') (url, state) = self.oauth2session.authorization_url(self.client_config['auth_uri'], **kwargs) return (url, state)
def _x_format(self): """Return the value formatter for this graph""" def timedelta_to_str(x): td = timedelta(seconds=x) return self.x_value_formatter(td) return timedelta_to_str
def function[_x_format, parameter[self]]: constant[Return the value formatter for this graph] def function[timedelta_to_str, parameter[x]]: variable[td] assign[=] call[name[timedelta], parameter[]] return[call[name[self].x_value_formatter, parameter[name[td]]]] return[name[timedelta_to_str]]
keyword[def] identifier[_x_format] ( identifier[self] ): literal[string] keyword[def] identifier[timedelta_to_str] ( identifier[x] ): identifier[td] = identifier[timedelta] ( identifier[seconds] = identifier[x] ) keyword[return] identifier[self] . identifier[x_value_formatter] ( identifier[td] ) keyword[return] identifier[timedelta_to_str]
def _x_format(self): """Return the value formatter for this graph""" def timedelta_to_str(x): td = timedelta(seconds=x) return self.x_value_formatter(td) return timedelta_to_str
def raw(url): """Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly version as it is the one they usually see. If this function recognizes one of those cases, it converts the user-friendly URL into the raw - otherwise it returns the original URL. The function works by default for two git providers: github and gitlab. You can use others by passing in your own url_rewriters list. There is also a special case for Github gists. """ try: # If it's a user-friendly gist URL, get the real data by parsing # the file. parts = url.split('/') if parts[2] == 'gist.github.com' and '.' not in parts[:-1]: soup = BeautifulSoup(requests.get(url).text, 'html.parser') raw_links = [i for i in soup.find_all('a') if i.text == 'Raw'] return ('https://gist.githubusercontent.com' + raw_links[0].attrs['href']) except Exception as e: print('Failed open and parse', url, e) pass # https: / /github.com/user/ project/ blob/ master/tox.ini try: protocol, empty, provider, user, project, _, *rest = url.split('/') except: return url rewriter = URL_REWRITERS.get(provider) if protocol and (not empty) and user and project and rest and rewriter: parts = [protocol, empty, rewriter['provider'], user, project] return '/'.join(parts + rewriter['path'] + rest) return url
def function[raw, parameter[url]]: constant[Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly version as it is the one they usually see. If this function recognizes one of those cases, it converts the user-friendly URL into the raw - otherwise it returns the original URL. The function works by default for two git providers: github and gitlab. You can use others by passing in your own url_rewriters list. There is also a special case for Github gists. ] <ast.Try object at 0x7da1b237be50> <ast.Try object at 0x7da1b2461720> variable[rewriter] assign[=] call[name[URL_REWRITERS].get, parameter[name[provider]]] if <ast.BoolOp object at 0x7da1b2462500> begin[:] variable[parts] assign[=] list[[<ast.Name object at 0x7da1b2460580>, <ast.Name object at 0x7da1b2460e80>, <ast.Subscript object at 0x7da1b24613c0>, <ast.Name object at 0x7da1b2460ca0>, <ast.Name object at 0x7da1b2462620>]] return[call[constant[/].join, parameter[binary_operation[binary_operation[name[parts] + call[name[rewriter]][constant[path]]] + name[rest]]]]] return[name[url]]
keyword[def] identifier[raw] ( identifier[url] ): literal[string] keyword[try] : identifier[parts] = identifier[url] . identifier[split] ( literal[string] ) keyword[if] identifier[parts] [ literal[int] ]== literal[string] keyword[and] literal[string] keyword[not] keyword[in] identifier[parts] [:- literal[int] ]: identifier[soup] = identifier[BeautifulSoup] ( identifier[requests] . identifier[get] ( identifier[url] ). identifier[text] , literal[string] ) identifier[raw_links] =[ identifier[i] keyword[for] identifier[i] keyword[in] identifier[soup] . identifier[find_all] ( literal[string] ) keyword[if] identifier[i] . identifier[text] == literal[string] ] keyword[return] ( literal[string] + identifier[raw_links] [ literal[int] ]. identifier[attrs] [ literal[string] ]) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[print] ( literal[string] , identifier[url] , identifier[e] ) keyword[pass] keyword[try] : identifier[protocol] , identifier[empty] , identifier[provider] , identifier[user] , identifier[project] , identifier[_] ,* identifier[rest] = identifier[url] . identifier[split] ( literal[string] ) keyword[except] : keyword[return] identifier[url] identifier[rewriter] = identifier[URL_REWRITERS] . identifier[get] ( identifier[provider] ) keyword[if] identifier[protocol] keyword[and] ( keyword[not] identifier[empty] ) keyword[and] identifier[user] keyword[and] identifier[project] keyword[and] identifier[rest] keyword[and] identifier[rewriter] : identifier[parts] =[ identifier[protocol] , identifier[empty] , identifier[rewriter] [ literal[string] ], identifier[user] , identifier[project] ] keyword[return] literal[string] . identifier[join] ( identifier[parts] + identifier[rewriter] [ literal[string] ]+ identifier[rest] ) keyword[return] identifier[url]
def raw(url): """Return a raw version of the URL if there is one. Otherwise returns the original URL. Many repos have "raw" and "user-friendly" versions of each URL. Usually when you want to download something programmatically, you want the raw version, but users will enter the user-friendly version as it is the one they usually see. If this function recognizes one of those cases, it converts the user-friendly URL into the raw - otherwise it returns the original URL. The function works by default for two git providers: github and gitlab. You can use others by passing in your own url_rewriters list. There is also a special case for Github gists. """ try: # If it's a user-friendly gist URL, get the real data by parsing # the file. parts = url.split('/') if parts[2] == 'gist.github.com' and '.' not in parts[:-1]: soup = BeautifulSoup(requests.get(url).text, 'html.parser') raw_links = [i for i in soup.find_all('a') if i.text == 'Raw'] return 'https://gist.githubusercontent.com' + raw_links[0].attrs['href'] # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except Exception as e: print('Failed open and parse', url, e) pass # depends on [control=['except'], data=['e']] # https: / /github.com/user/ project/ blob/ master/tox.ini try: (protocol, empty, provider, user, project, _, *rest) = url.split('/') # depends on [control=['try'], data=[]] except: return url # depends on [control=['except'], data=[]] rewriter = URL_REWRITERS.get(provider) if protocol and (not empty) and user and project and rest and rewriter: parts = [protocol, empty, rewriter['provider'], user, project] return '/'.join(parts + rewriter['path'] + rest) # depends on [control=['if'], data=[]] return url
def set_attributes(path, archive=None, hidden=None, normal=None, notIndexed=None, readonly=None, system=None, temporary=None): ''' Set file attributes for a file. Note that the normal attribute means that all others are false. So setting it will clear all others. Args: path (str): The path to the file or directory archive (bool): Sets the archive attribute. Default is None hidden (bool): Sets the hidden attribute. Default is None normal (bool): Resets the file attributes. Cannot be used in conjunction with any other attribute. Default is None notIndexed (bool): Sets the indexed attribute. Default is None readonly (bool): Sets the readonly attribute. Default is None system (bool): Sets the system attribute. Default is None temporary (bool): Sets the temporary attribute. Default is None Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' file.set_attributes c:\\temp\\a.txt normal=True salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True ''' if not os.path.exists(path): raise CommandExecutionError('Path not found: {0}'.format(path)) if normal: if archive or hidden or notIndexed or readonly or system or temporary: raise CommandExecutionError( 'Normal attribute may not be used with any other attributes') ret = win32file.SetFileAttributes(path, 128) return True if ret is None else False # Get current attributes intAttributes = win32file.GetFileAttributes(path) # individually set or clear bits for appropriate attributes if archive is not None: if archive: intAttributes |= 0x20 else: intAttributes &= 0xFFDF if hidden is not None: if hidden: intAttributes |= 0x2 else: intAttributes &= 0xFFFD if notIndexed is not None: if notIndexed: intAttributes |= 0x2000 else: intAttributes &= 0xDFFF if readonly is not None: if readonly: intAttributes |= 0x1 else: intAttributes &= 0xFFFE if system is not None: if system: intAttributes |= 0x4 else: intAttributes &= 0xFFFB if temporary is not None: if temporary: intAttributes |= 0x100 else: intAttributes &= 0xFEFF ret = win32file.SetFileAttributes(path, intAttributes) return True if ret is None else False
def function[set_attributes, parameter[path, archive, hidden, normal, notIndexed, readonly, system, temporary]]: constant[ Set file attributes for a file. Note that the normal attribute means that all others are false. So setting it will clear all others. Args: path (str): The path to the file or directory archive (bool): Sets the archive attribute. Default is None hidden (bool): Sets the hidden attribute. Default is None normal (bool): Resets the file attributes. Cannot be used in conjunction with any other attribute. Default is None notIndexed (bool): Sets the indexed attribute. Default is None readonly (bool): Sets the readonly attribute. Default is None system (bool): Sets the system attribute. Default is None temporary (bool): Sets the temporary attribute. Default is None Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' file.set_attributes c:\temp\a.txt normal=True salt '*' file.set_attributes c:\temp\a.txt readonly=True hidden=True ] if <ast.UnaryOp object at 0x7da1b2197fd0> begin[:] <ast.Raise object at 0x7da1b2195d20> if name[normal] begin[:] if <ast.BoolOp object at 0x7da1b2194340> begin[:] <ast.Raise object at 0x7da1b2197400> variable[ret] assign[=] call[name[win32file].SetFileAttributes, parameter[name[path], constant[128]]] return[<ast.IfExp object at 0x7da1b2195cf0>] variable[intAttributes] assign[=] call[name[win32file].GetFileAttributes, parameter[name[path]]] if compare[name[archive] is_not constant[None]] begin[:] if name[archive] begin[:] <ast.AugAssign object at 0x7da1b2194b50> if compare[name[hidden] is_not constant[None]] begin[:] if name[hidden] begin[:] <ast.AugAssign object at 0x7da1b2196c50> if compare[name[notIndexed] is_not constant[None]] begin[:] if name[notIndexed] begin[:] <ast.AugAssign object at 0x7da1b2195390> if compare[name[readonly] is_not constant[None]] begin[:] if name[readonly] begin[:] <ast.AugAssign object at 0x7da1b21954b0> if compare[name[system] is_not constant[None]] begin[:] if name[system] begin[:] <ast.AugAssign object at 0x7da1b2197af0> if compare[name[temporary] is_not constant[None]] begin[:] if name[temporary] begin[:] <ast.AugAssign object at 0x7da1b2197f70> variable[ret] assign[=] call[name[win32file].SetFileAttributes, parameter[name[path], name[intAttributes]]] return[<ast.IfExp object at 0x7da1b2194ee0>]
keyword[def] identifier[set_attributes] ( identifier[path] , identifier[archive] = keyword[None] , identifier[hidden] = keyword[None] , identifier[normal] = keyword[None] , identifier[notIndexed] = keyword[None] , identifier[readonly] = keyword[None] , identifier[system] = keyword[None] , identifier[temporary] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ): keyword[raise] identifier[CommandExecutionError] ( literal[string] . identifier[format] ( identifier[path] )) keyword[if] identifier[normal] : keyword[if] identifier[archive] keyword[or] identifier[hidden] keyword[or] identifier[notIndexed] keyword[or] identifier[readonly] keyword[or] identifier[system] keyword[or] identifier[temporary] : keyword[raise] identifier[CommandExecutionError] ( literal[string] ) identifier[ret] = identifier[win32file] . identifier[SetFileAttributes] ( identifier[path] , literal[int] ) keyword[return] keyword[True] keyword[if] identifier[ret] keyword[is] keyword[None] keyword[else] keyword[False] identifier[intAttributes] = identifier[win32file] . identifier[GetFileAttributes] ( identifier[path] ) keyword[if] identifier[archive] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[archive] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] keyword[if] identifier[hidden] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[hidden] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] keyword[if] identifier[notIndexed] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[notIndexed] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] keyword[if] identifier[readonly] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[readonly] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] keyword[if] identifier[system] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[system] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] keyword[if] identifier[temporary] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[temporary] : identifier[intAttributes] |= literal[int] keyword[else] : identifier[intAttributes] &= literal[int] identifier[ret] = identifier[win32file] . identifier[SetFileAttributes] ( identifier[path] , identifier[intAttributes] ) keyword[return] keyword[True] keyword[if] identifier[ret] keyword[is] keyword[None] keyword[else] keyword[False]
def set_attributes(path, archive=None, hidden=None, normal=None, notIndexed=None, readonly=None, system=None, temporary=None): """ Set file attributes for a file. Note that the normal attribute means that all others are false. So setting it will clear all others. Args: path (str): The path to the file or directory archive (bool): Sets the archive attribute. Default is None hidden (bool): Sets the hidden attribute. Default is None normal (bool): Resets the file attributes. Cannot be used in conjunction with any other attribute. Default is None notIndexed (bool): Sets the indexed attribute. Default is None readonly (bool): Sets the readonly attribute. Default is None system (bool): Sets the system attribute. Default is None temporary (bool): Sets the temporary attribute. Default is None Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' file.set_attributes c:\\temp\\a.txt normal=True salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True """ if not os.path.exists(path): raise CommandExecutionError('Path not found: {0}'.format(path)) # depends on [control=['if'], data=[]] if normal: if archive or hidden or notIndexed or readonly or system or temporary: raise CommandExecutionError('Normal attribute may not be used with any other attributes') # depends on [control=['if'], data=[]] ret = win32file.SetFileAttributes(path, 128) return True if ret is None else False # depends on [control=['if'], data=[]] # Get current attributes intAttributes = win32file.GetFileAttributes(path) # individually set or clear bits for appropriate attributes if archive is not None: if archive: intAttributes |= 32 # depends on [control=['if'], data=[]] else: intAttributes &= 65503 # depends on [control=['if'], data=['archive']] if hidden is not None: if hidden: intAttributes |= 2 # depends on [control=['if'], data=[]] else: intAttributes &= 65533 # depends on [control=['if'], data=['hidden']] if notIndexed is not None: if notIndexed: intAttributes |= 8192 # depends on [control=['if'], data=[]] else: intAttributes &= 57343 # depends on [control=['if'], data=['notIndexed']] if readonly is not None: if readonly: intAttributes |= 1 # depends on [control=['if'], data=[]] else: intAttributes &= 65534 # depends on [control=['if'], data=['readonly']] if system is not None: if system: intAttributes |= 4 # depends on [control=['if'], data=[]] else: intAttributes &= 65531 # depends on [control=['if'], data=['system']] if temporary is not None: if temporary: intAttributes |= 256 # depends on [control=['if'], data=[]] else: intAttributes &= 65279 # depends on [control=['if'], data=['temporary']] ret = win32file.SetFileAttributes(path, intAttributes) return True if ret is None else False
def install_dependencies(self, requirement): """ Install missing dependencies for the given requirement. :param requirement: A :class:`.Requirement` object. :returns: :data:`True` when missing system packages were installed, :data:`False` otherwise. :raises: :exc:`.DependencyInstallationRefused` when automatic installation is disabled or refused by the operator. :raises: :exc:`.DependencyInstallationFailed` when the installation of missing system packages fails. If `pip-accel` fails to build a binary distribution, it will call this method as a last chance to install missing dependencies. If this function does not raise an exception, `pip-accel` will retry the build once. """ install_timer = Timer() missing_dependencies = self.find_missing_dependencies(requirement) if missing_dependencies: # Compose the command line for the install command. install_command = shlex.split(self.install_command) + missing_dependencies # Prepend `sudo' to the command line? if not WINDOWS and not is_root(): # FIXME Ideally this should properly detect the presence of `sudo'. # Or maybe this should just be embedded in the *.ini files? install_command.insert(0, 'sudo') # Always suggest the installation command to the operator. logger.info("You seem to be missing %s: %s", pluralize(len(missing_dependencies), "dependency", "dependencies"), concatenate(missing_dependencies)) logger.info("You can install %s with this command: %s", "it" if len(missing_dependencies) == 1 else "them", " ".join(install_command)) if self.config.auto_install is False: # Refuse automatic installation and don't prompt the operator when the configuration says no. self.installation_refused(requirement, missing_dependencies, "automatic installation is disabled") # Get the operator's permission to install the missing package(s). if self.config.auto_install: logger.info("Got permission to install %s (via auto_install option).", pluralize(len(missing_dependencies), "dependency", "dependencies")) elif self.confirm_installation(requirement, missing_dependencies, install_command): logger.info("Got permission to install %s (via interactive prompt).", pluralize(len(missing_dependencies), "dependency", "dependencies")) else: logger.error("Refused installation of missing %s!", "dependency" if len(missing_dependencies) == 1 else "dependencies") self.installation_refused(requirement, missing_dependencies, "manual installation was refused") if subprocess.call(install_command) == 0: logger.info("Successfully installed %s in %s.", pluralize(len(missing_dependencies), "dependency", "dependencies"), install_timer) return True else: logger.error("Failed to install %s.", pluralize(len(missing_dependencies), "dependency", "dependencies")) msg = "Failed to install %s required by Python package %s! (%s)" raise DependencyInstallationFailed(msg % (pluralize(len(missing_dependencies), "system package", "system packages"), requirement.name, concatenate(missing_dependencies))) return False
def function[install_dependencies, parameter[self, requirement]]: constant[ Install missing dependencies for the given requirement. :param requirement: A :class:`.Requirement` object. :returns: :data:`True` when missing system packages were installed, :data:`False` otherwise. :raises: :exc:`.DependencyInstallationRefused` when automatic installation is disabled or refused by the operator. :raises: :exc:`.DependencyInstallationFailed` when the installation of missing system packages fails. If `pip-accel` fails to build a binary distribution, it will call this method as a last chance to install missing dependencies. If this function does not raise an exception, `pip-accel` will retry the build once. ] variable[install_timer] assign[=] call[name[Timer], parameter[]] variable[missing_dependencies] assign[=] call[name[self].find_missing_dependencies, parameter[name[requirement]]] if name[missing_dependencies] begin[:] variable[install_command] assign[=] binary_operation[call[name[shlex].split, parameter[name[self].install_command]] + name[missing_dependencies]] if <ast.BoolOp object at 0x7da1b05bd630> begin[:] call[name[install_command].insert, parameter[constant[0], constant[sudo]]] call[name[logger].info, parameter[constant[You seem to be missing %s: %s], call[name[pluralize], parameter[call[name[len], parameter[name[missing_dependencies]]], constant[dependency], constant[dependencies]]], call[name[concatenate], parameter[name[missing_dependencies]]]]] call[name[logger].info, parameter[constant[You can install %s with this command: %s], <ast.IfExp object at 0x7da1b05be830>, call[constant[ ].join, parameter[name[install_command]]]]] if compare[name[self].config.auto_install is constant[False]] begin[:] call[name[self].installation_refused, parameter[name[requirement], name[missing_dependencies], constant[automatic installation is disabled]]] if name[self].config.auto_install begin[:] call[name[logger].info, parameter[constant[Got permission to install %s (via auto_install option).], call[name[pluralize], parameter[call[name[len], parameter[name[missing_dependencies]]], constant[dependency], constant[dependencies]]]]] if compare[call[name[subprocess].call, parameter[name[install_command]]] equal[==] constant[0]] begin[:] call[name[logger].info, parameter[constant[Successfully installed %s in %s.], call[name[pluralize], parameter[call[name[len], parameter[name[missing_dependencies]]], constant[dependency], constant[dependencies]]], name[install_timer]]] return[constant[True]] return[constant[False]]
keyword[def] identifier[install_dependencies] ( identifier[self] , identifier[requirement] ): literal[string] identifier[install_timer] = identifier[Timer] () identifier[missing_dependencies] = identifier[self] . identifier[find_missing_dependencies] ( identifier[requirement] ) keyword[if] identifier[missing_dependencies] : identifier[install_command] = identifier[shlex] . identifier[split] ( identifier[self] . identifier[install_command] )+ identifier[missing_dependencies] keyword[if] keyword[not] identifier[WINDOWS] keyword[and] keyword[not] identifier[is_root] (): identifier[install_command] . identifier[insert] ( literal[int] , literal[string] ) identifier[logger] . identifier[info] ( literal[string] , identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] ), identifier[concatenate] ( identifier[missing_dependencies] )) identifier[logger] . identifier[info] ( literal[string] , literal[string] keyword[if] identifier[len] ( identifier[missing_dependencies] )== literal[int] keyword[else] literal[string] , literal[string] . identifier[join] ( identifier[install_command] )) keyword[if] identifier[self] . identifier[config] . identifier[auto_install] keyword[is] keyword[False] : identifier[self] . identifier[installation_refused] ( identifier[requirement] , identifier[missing_dependencies] , literal[string] ) keyword[if] identifier[self] . identifier[config] . identifier[auto_install] : identifier[logger] . identifier[info] ( literal[string] , identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] )) keyword[elif] identifier[self] . identifier[confirm_installation] ( identifier[requirement] , identifier[missing_dependencies] , identifier[install_command] ): identifier[logger] . identifier[info] ( literal[string] , identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] )) keyword[else] : identifier[logger] . identifier[error] ( literal[string] , literal[string] keyword[if] identifier[len] ( identifier[missing_dependencies] )== literal[int] keyword[else] literal[string] ) identifier[self] . identifier[installation_refused] ( identifier[requirement] , identifier[missing_dependencies] , literal[string] ) keyword[if] identifier[subprocess] . identifier[call] ( identifier[install_command] )== literal[int] : identifier[logger] . identifier[info] ( literal[string] , identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] ), identifier[install_timer] ) keyword[return] keyword[True] keyword[else] : identifier[logger] . identifier[error] ( literal[string] , identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] )) identifier[msg] = literal[string] keyword[raise] identifier[DependencyInstallationFailed] ( identifier[msg] %( identifier[pluralize] ( identifier[len] ( identifier[missing_dependencies] ), literal[string] , literal[string] ), identifier[requirement] . identifier[name] , identifier[concatenate] ( identifier[missing_dependencies] ))) keyword[return] keyword[False]
def install_dependencies(self, requirement): """ Install missing dependencies for the given requirement. :param requirement: A :class:`.Requirement` object. :returns: :data:`True` when missing system packages were installed, :data:`False` otherwise. :raises: :exc:`.DependencyInstallationRefused` when automatic installation is disabled or refused by the operator. :raises: :exc:`.DependencyInstallationFailed` when the installation of missing system packages fails. If `pip-accel` fails to build a binary distribution, it will call this method as a last chance to install missing dependencies. If this function does not raise an exception, `pip-accel` will retry the build once. """ install_timer = Timer() missing_dependencies = self.find_missing_dependencies(requirement) if missing_dependencies: # Compose the command line for the install command. install_command = shlex.split(self.install_command) + missing_dependencies # Prepend `sudo' to the command line? if not WINDOWS and (not is_root()): # FIXME Ideally this should properly detect the presence of `sudo'. # Or maybe this should just be embedded in the *.ini files? install_command.insert(0, 'sudo') # depends on [control=['if'], data=[]] # Always suggest the installation command to the operator. logger.info('You seem to be missing %s: %s', pluralize(len(missing_dependencies), 'dependency', 'dependencies'), concatenate(missing_dependencies)) logger.info('You can install %s with this command: %s', 'it' if len(missing_dependencies) == 1 else 'them', ' '.join(install_command)) if self.config.auto_install is False: # Refuse automatic installation and don't prompt the operator when the configuration says no. self.installation_refused(requirement, missing_dependencies, 'automatic installation is disabled') # depends on [control=['if'], data=[]] # Get the operator's permission to install the missing package(s). if self.config.auto_install: logger.info('Got permission to install %s (via auto_install option).', pluralize(len(missing_dependencies), 'dependency', 'dependencies')) # depends on [control=['if'], data=[]] elif self.confirm_installation(requirement, missing_dependencies, install_command): logger.info('Got permission to install %s (via interactive prompt).', pluralize(len(missing_dependencies), 'dependency', 'dependencies')) # depends on [control=['if'], data=[]] else: logger.error('Refused installation of missing %s!', 'dependency' if len(missing_dependencies) == 1 else 'dependencies') self.installation_refused(requirement, missing_dependencies, 'manual installation was refused') if subprocess.call(install_command) == 0: logger.info('Successfully installed %s in %s.', pluralize(len(missing_dependencies), 'dependency', 'dependencies'), install_timer) return True # depends on [control=['if'], data=[]] else: logger.error('Failed to install %s.', pluralize(len(missing_dependencies), 'dependency', 'dependencies')) msg = 'Failed to install %s required by Python package %s! (%s)' raise DependencyInstallationFailed(msg % (pluralize(len(missing_dependencies), 'system package', 'system packages'), requirement.name, concatenate(missing_dependencies))) # depends on [control=['if'], data=[]] return False
def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous operator. """ try: prev_op, prev_op_binding = self.nested_ops[-2] except IndexError: prev_op, prev_op_binding = None, 0 try: curr_op, curr_op_binding = self.nested_ops[-1] except IndexError: curr_op, curr_op_binding = None, 0 # special case if prev_op is ast.Pow and isinstance(curr_op, (ast.Invert, ast.USub)): return 1 # print(prev_op, prev_op_binding, curr_op, curr_op_binding) return curr_op_binding - prev_op_binding
def function[diff_binding, parameter[self]]: constant[Return the difference betweens the binding levels of the current and the previous operator. ] <ast.Try object at 0x7da1b2873bb0> <ast.Try object at 0x7da1b2873400> if <ast.BoolOp object at 0x7da1b28bd870> begin[:] return[constant[1]] return[binary_operation[name[curr_op_binding] - name[prev_op_binding]]]
keyword[def] identifier[diff_binding] ( identifier[self] )-> identifier[int] : literal[string] keyword[try] : identifier[prev_op] , identifier[prev_op_binding] = identifier[self] . identifier[nested_ops] [- literal[int] ] keyword[except] identifier[IndexError] : identifier[prev_op] , identifier[prev_op_binding] = keyword[None] , literal[int] keyword[try] : identifier[curr_op] , identifier[curr_op_binding] = identifier[self] . identifier[nested_ops] [- literal[int] ] keyword[except] identifier[IndexError] : identifier[curr_op] , identifier[curr_op_binding] = keyword[None] , literal[int] keyword[if] identifier[prev_op] keyword[is] identifier[ast] . identifier[Pow] keyword[and] identifier[isinstance] ( identifier[curr_op] ,( identifier[ast] . identifier[Invert] , identifier[ast] . identifier[USub] )): keyword[return] literal[int] keyword[return] identifier[curr_op_binding] - identifier[prev_op_binding]
def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous operator. """ try: (prev_op, prev_op_binding) = self.nested_ops[-2] # depends on [control=['try'], data=[]] except IndexError: (prev_op, prev_op_binding) = (None, 0) # depends on [control=['except'], data=[]] try: (curr_op, curr_op_binding) = self.nested_ops[-1] # depends on [control=['try'], data=[]] except IndexError: (curr_op, curr_op_binding) = (None, 0) # depends on [control=['except'], data=[]] # special case if prev_op is ast.Pow and isinstance(curr_op, (ast.Invert, ast.USub)): return 1 # depends on [control=['if'], data=[]] # print(prev_op, prev_op_binding, curr_op, curr_op_binding) return curr_op_binding - prev_op_binding
def get_cluster( self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_cluster" not in self._inner_api_calls: self._inner_api_calls[ "get_cluster" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_cluster, default_retry=self._method_configs["GetCluster"].retry, default_timeout=self._method_configs["GetCluster"].timeout, client_info=self._client_info, ) request = clusters_pb2.GetClusterRequest( project_id=project_id, region=region, cluster_name=cluster_name ) return self._inner_api_calls["get_cluster"]( request, retry=retry, timeout=timeout, metadata=metadata )
def function[get_cluster, parameter[self, project_id, region, cluster_name, retry, timeout, metadata]]: constant[ Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. ] if compare[constant[get_cluster] <ast.NotIn object at 0x7da2590d7190> name[self]._inner_api_calls] begin[:] call[name[self]._inner_api_calls][constant[get_cluster]] assign[=] call[name[google].api_core.gapic_v1.method.wrap_method, parameter[name[self].transport.get_cluster]] variable[request] assign[=] call[name[clusters_pb2].GetClusterRequest, parameter[]] return[call[call[name[self]._inner_api_calls][constant[get_cluster]], parameter[name[request]]]]
keyword[def] identifier[get_cluster] ( identifier[self] , identifier[project_id] , identifier[region] , identifier[cluster_name] , identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] , identifier[timeout] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] , identifier[metadata] = keyword[None] , ): literal[string] keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[_inner_api_calls] : identifier[self] . identifier[_inner_api_calls] [ literal[string] ]= identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[wrap_method] ( identifier[self] . identifier[transport] . identifier[get_cluster] , identifier[default_retry] = identifier[self] . identifier[_method_configs] [ literal[string] ]. identifier[retry] , identifier[default_timeout] = identifier[self] . identifier[_method_configs] [ literal[string] ]. identifier[timeout] , identifier[client_info] = identifier[self] . identifier[_client_info] , ) identifier[request] = identifier[clusters_pb2] . identifier[GetClusterRequest] ( identifier[project_id] = identifier[project_id] , identifier[region] = identifier[region] , identifier[cluster_name] = identifier[cluster_name] ) keyword[return] identifier[self] . identifier[_inner_api_calls] [ literal[string] ]( identifier[request] , identifier[retry] = identifier[retry] , identifier[timeout] = identifier[timeout] , identifier[metadata] = identifier[metadata] )
def get_cluster(self, project_id, region, cluster_name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): """ Gets the resource representation for a cluster in a project. Example: >>> from google.cloud import dataproc_v1beta2 >>> >>> client = dataproc_v1beta2.ClusterControllerClient() >>> >>> # TODO: Initialize `project_id`: >>> project_id = '' >>> >>> # TODO: Initialize `region`: >>> region = '' >>> >>> # TODO: Initialize `cluster_name`: >>> cluster_name = '' >>> >>> response = client.get_cluster(project_id, region, cluster_name) Args: project_id (str): Required. The ID of the Google Cloud Platform project that the cluster belongs to. region (str): Required. The Cloud Dataproc region in which to handle the request. cluster_name (str): Required. The cluster name. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.dataproc_v1beta2.types.Cluster` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if 'get_cluster' not in self._inner_api_calls: self._inner_api_calls['get_cluster'] = google.api_core.gapic_v1.method.wrap_method(self.transport.get_cluster, default_retry=self._method_configs['GetCluster'].retry, default_timeout=self._method_configs['GetCluster'].timeout, client_info=self._client_info) # depends on [control=['if'], data=[]] request = clusters_pb2.GetClusterRequest(project_id=project_id, region=region, cluster_name=cluster_name) return self._inner_api_calls['get_cluster'](request, retry=retry, timeout=timeout, metadata=metadata)
def get_data_checksum(proc_input, proc_slug, proc_version): """Compute checksum of processor inputs, name and version.""" checksum = hashlib.sha256() checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8')) checksum.update(proc_slug.encode('utf-8')) checksum.update(str(proc_version).encode('utf-8')) return checksum.hexdigest()
def function[get_data_checksum, parameter[proc_input, proc_slug, proc_version]]: constant[Compute checksum of processor inputs, name and version.] variable[checksum] assign[=] call[name[hashlib].sha256, parameter[]] call[name[checksum].update, parameter[call[call[name[json].dumps, parameter[name[proc_input]]].encode, parameter[constant[utf-8]]]]] call[name[checksum].update, parameter[call[name[proc_slug].encode, parameter[constant[utf-8]]]]] call[name[checksum].update, parameter[call[call[name[str], parameter[name[proc_version]]].encode, parameter[constant[utf-8]]]]] return[call[name[checksum].hexdigest, parameter[]]]
keyword[def] identifier[get_data_checksum] ( identifier[proc_input] , identifier[proc_slug] , identifier[proc_version] ): literal[string] identifier[checksum] = identifier[hashlib] . identifier[sha256] () identifier[checksum] . identifier[update] ( identifier[json] . identifier[dumps] ( identifier[proc_input] , identifier[sort_keys] = keyword[True] ). identifier[encode] ( literal[string] )) identifier[checksum] . identifier[update] ( identifier[proc_slug] . identifier[encode] ( literal[string] )) identifier[checksum] . identifier[update] ( identifier[str] ( identifier[proc_version] ). identifier[encode] ( literal[string] )) keyword[return] identifier[checksum] . identifier[hexdigest] ()
def get_data_checksum(proc_input, proc_slug, proc_version): """Compute checksum of processor inputs, name and version.""" checksum = hashlib.sha256() checksum.update(json.dumps(proc_input, sort_keys=True).encode('utf-8')) checksum.update(proc_slug.encode('utf-8')) checksum.update(str(proc_version).encode('utf-8')) return checksum.hexdigest()
def check_file(filepath): ''' - Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific. ''' check_path(filepath) if not os.path.exists(filepath): print("WARNING: File does not exist. Creating it: %s" % filepath) open(filepath, 'a').close() try: print("Setting access rights for %s for www-data user" % (filepath)) uid = pwd.getpwnam("www-data").pw_uid gid = grp.getgrnam("www-data").gr_gid os.chown(filepath, uid, gid) os.chmod(filepath, 0o660) # rw-rw--- except Exception: print("WARNING: Could not adjust file system permissions for %s. Make sure your web server can write into it." % filepath)
def function[check_file, parameter[filepath]]: constant[ - Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific. ] call[name[check_path], parameter[name[filepath]]] if <ast.UnaryOp object at 0x7da2044c05b0> begin[:] call[name[print], parameter[binary_operation[constant[WARNING: File does not exist. Creating it: %s] <ast.Mod object at 0x7da2590d6920> name[filepath]]]] call[call[name[open], parameter[name[filepath], constant[a]]].close, parameter[]] <ast.Try object at 0x7da2044c08e0>
keyword[def] identifier[check_file] ( identifier[filepath] ): literal[string] identifier[check_path] ( identifier[filepath] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[filepath] ): identifier[print] ( literal[string] % identifier[filepath] ) identifier[open] ( identifier[filepath] , literal[string] ). identifier[close] () keyword[try] : identifier[print] ( literal[string] %( identifier[filepath] )) identifier[uid] = identifier[pwd] . identifier[getpwnam] ( literal[string] ). identifier[pw_uid] identifier[gid] = identifier[grp] . identifier[getgrnam] ( literal[string] ). identifier[gr_gid] identifier[os] . identifier[chown] ( identifier[filepath] , identifier[uid] , identifier[gid] ) identifier[os] . identifier[chmod] ( identifier[filepath] , literal[int] ) keyword[except] identifier[Exception] : identifier[print] ( literal[string] % identifier[filepath] )
def check_file(filepath): """ - Checks if the parent directories for this path exist. - Checks that the file exists. - Donates the file to the web server user. TODO: This is Debian / Ubuntu specific. """ check_path(filepath) if not os.path.exists(filepath): print('WARNING: File does not exist. Creating it: %s' % filepath) open(filepath, 'a').close() # depends on [control=['if'], data=[]] try: print('Setting access rights for %s for www-data user' % filepath) uid = pwd.getpwnam('www-data').pw_uid gid = grp.getgrnam('www-data').gr_gid os.chown(filepath, uid, gid) os.chmod(filepath, 432) # rw-rw--- # depends on [control=['try'], data=[]] except Exception: print('WARNING: Could not adjust file system permissions for %s. Make sure your web server can write into it.' % filepath) # depends on [control=['except'], data=[]]
def get_jira(profile=None, url="http://localhost:2990", username="admin", password="admin", appid=None, autofix=False, verify=True): """Return a JIRA object by loading the connection details from the `config.ini` file. :param profile: The name of the section from config.ini file that stores server config url/username/password :param url: URL of the Jira server :param username: username to use for authentication :param password: password to use for authentication :param verify: boolean indicating whether SSL certificates should be verified :return: JIRA -- an instance to a JIRA object. :raises: EnvironmentError Usage: >>> from jira.config import get_jira >>> >>> jira = get_jira(profile='jira') Also create a `config.ini` like this and put it in current directory, user home directory or PYTHONPATH. .. code-block:: none [jira] url=https://jira.atlassian.com # only the `url` is mandatory user=... pass=... appid=... verify=... """ def findfile(path): """Find the file named path in the sys.path. Returns the full path name if found, None if not found """ paths = ['.', os.path.expanduser('~')] paths.extend(sys.path) for dirname in paths: possible = os.path.abspath(os.path.join(dirname, path)) if os.path.isfile(possible): return possible return None config = configparser.ConfigParser(defaults={'user': None, 'pass': None, 'appid': appid, 'autofix': autofix, 'verify': 'yes' if verify else 'no'}, allow_no_value=True) config_file = findfile('config.ini') if config_file: logging.debug("Found %s config file" % config_file) if not profile: if config_file: config.read(config_file) try: profile = config.get('general', 'default-jira-profile') except configparser.NoOptionError: pass if profile: if config_file: config.read(config_file) url = config.get(profile, 'url') username = config.get(profile, 'user') password = config.get(profile, 'pass') appid = config.get(profile, 'appid') autofix = config.get(profile, 'autofix') verify = config.getboolean(profile, 'verify') else: raise EnvironmentError( "%s was not able to locate the config.ini file in current directory, user home directory or PYTHONPATH." % __name__) options = JIRA.DEFAULT_OPTIONS options['server'] = url options['autofix'] = autofix options['appid'] = appid options['verify'] = verify return JIRA(options=options, basic_auth=(username, password))
def function[get_jira, parameter[profile, url, username, password, appid, autofix, verify]]: constant[Return a JIRA object by loading the connection details from the `config.ini` file. :param profile: The name of the section from config.ini file that stores server config url/username/password :param url: URL of the Jira server :param username: username to use for authentication :param password: password to use for authentication :param verify: boolean indicating whether SSL certificates should be verified :return: JIRA -- an instance to a JIRA object. :raises: EnvironmentError Usage: >>> from jira.config import get_jira >>> >>> jira = get_jira(profile='jira') Also create a `config.ini` like this and put it in current directory, user home directory or PYTHONPATH. .. code-block:: none [jira] url=https://jira.atlassian.com # only the `url` is mandatory user=... pass=... appid=... verify=... ] def function[findfile, parameter[path]]: constant[Find the file named path in the sys.path. Returns the full path name if found, None if not found ] variable[paths] assign[=] list[[<ast.Constant object at 0x7da18dc9b670>, <ast.Call object at 0x7da18dc9b550>]] call[name[paths].extend, parameter[name[sys].path]] for taget[name[dirname]] in starred[name[paths]] begin[:] variable[possible] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.join, parameter[name[dirname], name[path]]]]] if call[name[os].path.isfile, parameter[name[possible]]] begin[:] return[name[possible]] return[constant[None]] variable[config] assign[=] call[name[configparser].ConfigParser, parameter[]] variable[config_file] assign[=] call[name[findfile], parameter[constant[config.ini]]] if name[config_file] begin[:] call[name[logging].debug, parameter[binary_operation[constant[Found %s config file] <ast.Mod object at 0x7da2590d6920> name[config_file]]]] if <ast.UnaryOp object at 0x7da18dc9bdc0> begin[:] if name[config_file] begin[:] call[name[config].read, parameter[name[config_file]]] <ast.Try object at 0x7da18dc9bbe0> if name[profile] begin[:] if name[config_file] begin[:] call[name[config].read, parameter[name[config_file]]] variable[url] assign[=] call[name[config].get, parameter[name[profile], constant[url]]] variable[username] assign[=] call[name[config].get, parameter[name[profile], constant[user]]] variable[password] assign[=] call[name[config].get, parameter[name[profile], constant[pass]]] variable[appid] assign[=] call[name[config].get, parameter[name[profile], constant[appid]]] variable[autofix] assign[=] call[name[config].get, parameter[name[profile], constant[autofix]]] variable[verify] assign[=] call[name[config].getboolean, parameter[name[profile], constant[verify]]] variable[options] assign[=] name[JIRA].DEFAULT_OPTIONS call[name[options]][constant[server]] assign[=] name[url] call[name[options]][constant[autofix]] assign[=] name[autofix] call[name[options]][constant[appid]] assign[=] name[appid] call[name[options]][constant[verify]] assign[=] name[verify] return[call[name[JIRA], parameter[]]]
keyword[def] identifier[get_jira] ( identifier[profile] = keyword[None] , identifier[url] = literal[string] , identifier[username] = literal[string] , identifier[password] = literal[string] , identifier[appid] = keyword[None] , identifier[autofix] = keyword[False] , identifier[verify] = keyword[True] ): literal[string] keyword[def] identifier[findfile] ( identifier[path] ): literal[string] identifier[paths] =[ literal[string] , identifier[os] . identifier[path] . identifier[expanduser] ( literal[string] )] identifier[paths] . identifier[extend] ( identifier[sys] . identifier[path] ) keyword[for] identifier[dirname] keyword[in] identifier[paths] : identifier[possible] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[dirname] , identifier[path] )) keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[possible] ): keyword[return] identifier[possible] keyword[return] keyword[None] identifier[config] = identifier[configparser] . identifier[ConfigParser] ( identifier[defaults] ={ literal[string] : keyword[None] , literal[string] : keyword[None] , literal[string] : identifier[appid] , literal[string] : identifier[autofix] , literal[string] : literal[string] keyword[if] identifier[verify] keyword[else] literal[string] }, identifier[allow_no_value] = keyword[True] ) identifier[config_file] = identifier[findfile] ( literal[string] ) keyword[if] identifier[config_file] : identifier[logging] . identifier[debug] ( literal[string] % identifier[config_file] ) keyword[if] keyword[not] identifier[profile] : keyword[if] identifier[config_file] : identifier[config] . identifier[read] ( identifier[config_file] ) keyword[try] : identifier[profile] = identifier[config] . identifier[get] ( literal[string] , literal[string] ) keyword[except] identifier[configparser] . identifier[NoOptionError] : keyword[pass] keyword[if] identifier[profile] : keyword[if] identifier[config_file] : identifier[config] . identifier[read] ( identifier[config_file] ) identifier[url] = identifier[config] . identifier[get] ( identifier[profile] , literal[string] ) identifier[username] = identifier[config] . identifier[get] ( identifier[profile] , literal[string] ) identifier[password] = identifier[config] . identifier[get] ( identifier[profile] , literal[string] ) identifier[appid] = identifier[config] . identifier[get] ( identifier[profile] , literal[string] ) identifier[autofix] = identifier[config] . identifier[get] ( identifier[profile] , literal[string] ) identifier[verify] = identifier[config] . identifier[getboolean] ( identifier[profile] , literal[string] ) keyword[else] : keyword[raise] identifier[EnvironmentError] ( literal[string] % identifier[__name__] ) identifier[options] = identifier[JIRA] . identifier[DEFAULT_OPTIONS] identifier[options] [ literal[string] ]= identifier[url] identifier[options] [ literal[string] ]= identifier[autofix] identifier[options] [ literal[string] ]= identifier[appid] identifier[options] [ literal[string] ]= identifier[verify] keyword[return] identifier[JIRA] ( identifier[options] = identifier[options] , identifier[basic_auth] =( identifier[username] , identifier[password] ))
def get_jira(profile=None, url='http://localhost:2990', username='admin', password='admin', appid=None, autofix=False, verify=True): """Return a JIRA object by loading the connection details from the `config.ini` file. :param profile: The name of the section from config.ini file that stores server config url/username/password :param url: URL of the Jira server :param username: username to use for authentication :param password: password to use for authentication :param verify: boolean indicating whether SSL certificates should be verified :return: JIRA -- an instance to a JIRA object. :raises: EnvironmentError Usage: >>> from jira.config import get_jira >>> >>> jira = get_jira(profile='jira') Also create a `config.ini` like this and put it in current directory, user home directory or PYTHONPATH. .. code-block:: none [jira] url=https://jira.atlassian.com # only the `url` is mandatory user=... pass=... appid=... verify=... """ def findfile(path): """Find the file named path in the sys.path. Returns the full path name if found, None if not found """ paths = ['.', os.path.expanduser('~')] paths.extend(sys.path) for dirname in paths: possible = os.path.abspath(os.path.join(dirname, path)) if os.path.isfile(possible): return possible # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['dirname']] return None config = configparser.ConfigParser(defaults={'user': None, 'pass': None, 'appid': appid, 'autofix': autofix, 'verify': 'yes' if verify else 'no'}, allow_no_value=True) config_file = findfile('config.ini') if config_file: logging.debug('Found %s config file' % config_file) # depends on [control=['if'], data=[]] if not profile: if config_file: config.read(config_file) try: profile = config.get('general', 'default-jira-profile') # depends on [control=['try'], data=[]] except configparser.NoOptionError: pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if profile: if config_file: config.read(config_file) url = config.get(profile, 'url') username = config.get(profile, 'user') password = config.get(profile, 'pass') appid = config.get(profile, 'appid') autofix = config.get(profile, 'autofix') verify = config.getboolean(profile, 'verify') # depends on [control=['if'], data=[]] else: raise EnvironmentError('%s was not able to locate the config.ini file in current directory, user home directory or PYTHONPATH.' % __name__) # depends on [control=['if'], data=[]] options = JIRA.DEFAULT_OPTIONS options['server'] = url options['autofix'] = autofix options['appid'] = appid options['verify'] = verify return JIRA(options=options, basic_auth=(username, password))
def train(self): """ This method generates the classifier. This method assumes that the training data has been loaded """ if not self.training_data: self.import_training_data() training_feature_set = [(self.extract_features(line), label) for (line, label) in self.training_data] self.classifier = nltk.NaiveBayesClassifier.train(training_feature_set)
def function[train, parameter[self]]: constant[ This method generates the classifier. This method assumes that the training data has been loaded ] if <ast.UnaryOp object at 0x7da1b2369900> begin[:] call[name[self].import_training_data, parameter[]] variable[training_feature_set] assign[=] <ast.ListComp object at 0x7da1b236bca0> name[self].classifier assign[=] call[name[nltk].NaiveBayesClassifier.train, parameter[name[training_feature_set]]]
keyword[def] identifier[train] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[training_data] : identifier[self] . identifier[import_training_data] () identifier[training_feature_set] =[( identifier[self] . identifier[extract_features] ( identifier[line] ), identifier[label] ) keyword[for] ( identifier[line] , identifier[label] ) keyword[in] identifier[self] . identifier[training_data] ] identifier[self] . identifier[classifier] = identifier[nltk] . identifier[NaiveBayesClassifier] . identifier[train] ( identifier[training_feature_set] )
def train(self): """ This method generates the classifier. This method assumes that the training data has been loaded """ if not self.training_data: self.import_training_data() # depends on [control=['if'], data=[]] training_feature_set = [(self.extract_features(line), label) for (line, label) in self.training_data] self.classifier = nltk.NaiveBayesClassifier.train(training_feature_set)
def apply_to_transcript_if_exists(effect, fn, default): """ Apply function to transcript associated with effect, if it exists, otherwise return default. """ return apply_to_field_if_exists( effect=effect, field_name="transcript", fn=fn, default=default)
def function[apply_to_transcript_if_exists, parameter[effect, fn, default]]: constant[ Apply function to transcript associated with effect, if it exists, otherwise return default. ] return[call[name[apply_to_field_if_exists], parameter[]]]
keyword[def] identifier[apply_to_transcript_if_exists] ( identifier[effect] , identifier[fn] , identifier[default] ): literal[string] keyword[return] identifier[apply_to_field_if_exists] ( identifier[effect] = identifier[effect] , identifier[field_name] = literal[string] , identifier[fn] = identifier[fn] , identifier[default] = identifier[default] )
def apply_to_transcript_if_exists(effect, fn, default): """ Apply function to transcript associated with effect, if it exists, otherwise return default. """ return apply_to_field_if_exists(effect=effect, field_name='transcript', fn=fn, default=default)
def get_as_integer_with_default(self, key, default_value): """ Converts map element into an integer or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. """ value = self.get(key) return IntegerConverter.to_integer_with_default(value, default_value)
def function[get_as_integer_with_default, parameter[self, key, default_value]]: constant[ Converts map element into an integer or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. ] variable[value] assign[=] call[name[self].get, parameter[name[key]]] return[call[name[IntegerConverter].to_integer_with_default, parameter[name[value], name[default_value]]]]
keyword[def] identifier[get_as_integer_with_default] ( identifier[self] , identifier[key] , identifier[default_value] ): literal[string] identifier[value] = identifier[self] . identifier[get] ( identifier[key] ) keyword[return] identifier[IntegerConverter] . identifier[to_integer_with_default] ( identifier[value] , identifier[default_value] )
def get_as_integer_with_default(self, key, default_value): """ Converts map element into an integer or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. """ value = self.get(key) return IntegerConverter.to_integer_with_default(value, default_value)
def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return alt = page.data.get('label') or page.data.get('title') img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % (alt, alt) img += "align=\"right\" width=\"240\">" return img
def function[_html_image, parameter[page]]: constant[ returns HTML img tag ] variable[source] assign[=] call[name[_image], parameter[name[page]]] if <ast.UnaryOp object at 0x7da1b1252c50> begin[:] return[None] variable[alt] assign[=] <ast.BoolOp object at 0x7da1b12505e0> variable[img] assign[=] binary_operation[constant[<img src="%s"] <ast.Mod object at 0x7da2590d6920> name[source]] <ast.AugAssign object at 0x7da1b1251510> <ast.AugAssign object at 0x7da1b1253f40> return[name[img]]
keyword[def] identifier[_html_image] ( identifier[page] ): literal[string] identifier[source] = identifier[_image] ( identifier[page] ) keyword[if] keyword[not] identifier[source] : keyword[return] identifier[alt] = identifier[page] . identifier[data] . identifier[get] ( literal[string] ) keyword[or] identifier[page] . identifier[data] . identifier[get] ( literal[string] ) identifier[img] = literal[string] % identifier[source] identifier[img] += literal[string] %( identifier[alt] , identifier[alt] ) identifier[img] += literal[string] keyword[return] identifier[img]
def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return # depends on [control=['if'], data=[]] alt = page.data.get('label') or page.data.get('title') img = '<img src="%s"' % source img += ' alt="%s" title="%s" ' % (alt, alt) img += 'align="right" width="240">' return img
def _orientation(self, edge, point): """ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. """ v1 = self.pts[point] - self.pts[edge[0]] v2 = self.pts[edge[1]] - self.pts[edge[0]] c = np.cross(v1, v2) # positive if v1 is CW from v2 return 1 if c > 0 else (-1 if c < 0 else 0)
def function[_orientation, parameter[self, edge, point]]: constant[ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. ] variable[v1] assign[=] binary_operation[call[name[self].pts][name[point]] - call[name[self].pts][call[name[edge]][constant[0]]]] variable[v2] assign[=] binary_operation[call[name[self].pts][call[name[edge]][constant[1]]] - call[name[self].pts][call[name[edge]][constant[0]]]] variable[c] assign[=] call[name[np].cross, parameter[name[v1], name[v2]]] return[<ast.IfExp object at 0x7da1b0ea08b0>]
keyword[def] identifier[_orientation] ( identifier[self] , identifier[edge] , identifier[point] ): literal[string] identifier[v1] = identifier[self] . identifier[pts] [ identifier[point] ]- identifier[self] . identifier[pts] [ identifier[edge] [ literal[int] ]] identifier[v2] = identifier[self] . identifier[pts] [ identifier[edge] [ literal[int] ]]- identifier[self] . identifier[pts] [ identifier[edge] [ literal[int] ]] identifier[c] = identifier[np] . identifier[cross] ( identifier[v1] , identifier[v2] ) keyword[return] literal[int] keyword[if] identifier[c] > literal[int] keyword[else] (- literal[int] keyword[if] identifier[c] < literal[int] keyword[else] literal[int] )
def _orientation(self, edge, point): """ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. """ v1 = self.pts[point] - self.pts[edge[0]] v2 = self.pts[edge[1]] - self.pts[edge[0]] c = np.cross(v1, v2) # positive if v1 is CW from v2 return 1 if c > 0 else -1 if c < 0 else 0
def set_by_Id(self, Id, is_added): """Update selected_ids with given Id""" row = self.collection.index_from_id(Id) if row is None: return self._set_id(Id, is_added, self.index(row, 0))
def function[set_by_Id, parameter[self, Id, is_added]]: constant[Update selected_ids with given Id] variable[row] assign[=] call[name[self].collection.index_from_id, parameter[name[Id]]] if compare[name[row] is constant[None]] begin[:] return[None] call[name[self]._set_id, parameter[name[Id], name[is_added], call[name[self].index, parameter[name[row], constant[0]]]]]
keyword[def] identifier[set_by_Id] ( identifier[self] , identifier[Id] , identifier[is_added] ): literal[string] identifier[row] = identifier[self] . identifier[collection] . identifier[index_from_id] ( identifier[Id] ) keyword[if] identifier[row] keyword[is] keyword[None] : keyword[return] identifier[self] . identifier[_set_id] ( identifier[Id] , identifier[is_added] , identifier[self] . identifier[index] ( identifier[row] , literal[int] ))
def set_by_Id(self, Id, is_added): """Update selected_ids with given Id""" row = self.collection.index_from_id(Id) if row is None: return # depends on [control=['if'], data=[]] self._set_id(Id, is_added, self.index(row, 0))
def _info(self, source, key, filetype, ignore): """ Generates the union of the source.specs and the metadata dictionary loaded by the filetype object. """ specs, mdata = [], {} mdata_clashes = set() for spec in source.specs: if key not in spec: raise Exception("Key %r not available in 'source'." % key) mdata = dict((k,v) for (k,v) in filetype.metadata(spec[key]).items() if k not in ignore) mdata_spec = {} mdata_spec.update(spec) mdata_spec.update(mdata) specs.append(mdata_spec) mdata_clashes = mdata_clashes | (set(spec.keys()) & set(mdata.keys())) # Metadata clashes can be avoided by using the ignore list. if mdata_clashes: self.warning("Loaded metadata keys overriding source keys.") return specs
def function[_info, parameter[self, source, key, filetype, ignore]]: constant[ Generates the union of the source.specs and the metadata dictionary loaded by the filetype object. ] <ast.Tuple object at 0x7da1afe79d50> assign[=] tuple[[<ast.List object at 0x7da1afe7bf10>, <ast.Dict object at 0x7da1afe793c0>]] variable[mdata_clashes] assign[=] call[name[set], parameter[]] for taget[name[spec]] in starred[name[source].specs] begin[:] if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[spec]] begin[:] <ast.Raise object at 0x7da1afe7a5c0> variable[mdata] assign[=] call[name[dict], parameter[<ast.GeneratorExp object at 0x7da1afe78280>]] variable[mdata_spec] assign[=] dictionary[[], []] call[name[mdata_spec].update, parameter[name[spec]]] call[name[mdata_spec].update, parameter[name[mdata]]] call[name[specs].append, parameter[name[mdata_spec]]] variable[mdata_clashes] assign[=] binary_operation[name[mdata_clashes] <ast.BitOr object at 0x7da2590d6aa0> binary_operation[call[name[set], parameter[call[name[spec].keys, parameter[]]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[set], parameter[call[name[mdata].keys, parameter[]]]]]] if name[mdata_clashes] begin[:] call[name[self].warning, parameter[constant[Loaded metadata keys overriding source keys.]]] return[name[specs]]
keyword[def] identifier[_info] ( identifier[self] , identifier[source] , identifier[key] , identifier[filetype] , identifier[ignore] ): literal[string] identifier[specs] , identifier[mdata] =[],{} identifier[mdata_clashes] = identifier[set] () keyword[for] identifier[spec] keyword[in] identifier[source] . identifier[specs] : keyword[if] identifier[key] keyword[not] keyword[in] identifier[spec] : keyword[raise] identifier[Exception] ( literal[string] % identifier[key] ) identifier[mdata] = identifier[dict] (( identifier[k] , identifier[v] ) keyword[for] ( identifier[k] , identifier[v] ) keyword[in] identifier[filetype] . identifier[metadata] ( identifier[spec] [ identifier[key] ]). identifier[items] () keyword[if] identifier[k] keyword[not] keyword[in] identifier[ignore] ) identifier[mdata_spec] ={} identifier[mdata_spec] . identifier[update] ( identifier[spec] ) identifier[mdata_spec] . identifier[update] ( identifier[mdata] ) identifier[specs] . identifier[append] ( identifier[mdata_spec] ) identifier[mdata_clashes] = identifier[mdata_clashes] |( identifier[set] ( identifier[spec] . identifier[keys] ())& identifier[set] ( identifier[mdata] . identifier[keys] ())) keyword[if] identifier[mdata_clashes] : identifier[self] . identifier[warning] ( literal[string] ) keyword[return] identifier[specs]
def _info(self, source, key, filetype, ignore): """ Generates the union of the source.specs and the metadata dictionary loaded by the filetype object. """ (specs, mdata) = ([], {}) mdata_clashes = set() for spec in source.specs: if key not in spec: raise Exception("Key %r not available in 'source'." % key) # depends on [control=['if'], data=['key']] mdata = dict(((k, v) for (k, v) in filetype.metadata(spec[key]).items() if k not in ignore)) mdata_spec = {} mdata_spec.update(spec) mdata_spec.update(mdata) specs.append(mdata_spec) mdata_clashes = mdata_clashes | set(spec.keys()) & set(mdata.keys()) # depends on [control=['for'], data=['spec']] # Metadata clashes can be avoided by using the ignore list. if mdata_clashes: self.warning('Loaded metadata keys overriding source keys.') # depends on [control=['if'], data=[]] return specs
def _poor_convergence(z, r, f, bn, mvec): """ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. """ check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j) diffs = [] ftests = [] for check_point in check_points: rtest = r * check_point ztest = z + rtest ftest = f(ztest) # Evaluate powerseries: comp = np.sum(bn * np.power(check_point, mvec)) ftests.append(ftest) diffs.append(comp - ftest) max_abs_error = np.max(np.abs(diffs)) max_f_value = np.max(np.abs(ftests)) return max_abs_error > 1e-3 * max_f_value
def function[_poor_convergence, parameter[z, r, f, bn, mvec]]: constant[ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. ] variable[check_points] assign[=] tuple[[<ast.BinOp object at 0x7da1b07f64a0>, <ast.BinOp object at 0x7da1b07f72b0>, <ast.BinOp object at 0x7da1b07f4a90>]] variable[diffs] assign[=] list[[]] variable[ftests] assign[=] list[[]] for taget[name[check_point]] in starred[name[check_points]] begin[:] variable[rtest] assign[=] binary_operation[name[r] * name[check_point]] variable[ztest] assign[=] binary_operation[name[z] + name[rtest]] variable[ftest] assign[=] call[name[f], parameter[name[ztest]]] variable[comp] assign[=] call[name[np].sum, parameter[binary_operation[name[bn] * call[name[np].power, parameter[name[check_point], name[mvec]]]]]] call[name[ftests].append, parameter[name[ftest]]] call[name[diffs].append, parameter[binary_operation[name[comp] - name[ftest]]]] variable[max_abs_error] assign[=] call[name[np].max, parameter[call[name[np].abs, parameter[name[diffs]]]]] variable[max_f_value] assign[=] call[name[np].max, parameter[call[name[np].abs, parameter[name[ftests]]]]] return[compare[name[max_abs_error] greater[>] binary_operation[constant[0.001] * name[max_f_value]]]]
keyword[def] identifier[_poor_convergence] ( identifier[z] , identifier[r] , identifier[f] , identifier[bn] , identifier[mvec] ): literal[string] identifier[check_points] =(- literal[int] + literal[int] , literal[int] + literal[int] , literal[int] - literal[int] ) identifier[diffs] =[] identifier[ftests] =[] keyword[for] identifier[check_point] keyword[in] identifier[check_points] : identifier[rtest] = identifier[r] * identifier[check_point] identifier[ztest] = identifier[z] + identifier[rtest] identifier[ftest] = identifier[f] ( identifier[ztest] ) identifier[comp] = identifier[np] . identifier[sum] ( identifier[bn] * identifier[np] . identifier[power] ( identifier[check_point] , identifier[mvec] )) identifier[ftests] . identifier[append] ( identifier[ftest] ) identifier[diffs] . identifier[append] ( identifier[comp] - identifier[ftest] ) identifier[max_abs_error] = identifier[np] . identifier[max] ( identifier[np] . identifier[abs] ( identifier[diffs] )) identifier[max_f_value] = identifier[np] . identifier[max] ( identifier[np] . identifier[abs] ( identifier[ftests] )) keyword[return] identifier[max_abs_error] > literal[int] * identifier[max_f_value]
def _poor_convergence(z, r, f, bn, mvec): """ Test for poor convergence based on three function evaluations. This test evaluates the function at the three points and returns false if the relative error is greater than 1e-3. """ check_points = (-0.4 + 0.3j, 0.7 + 0.2j, 0.02 - 0.06j) diffs = [] ftests = [] for check_point in check_points: rtest = r * check_point ztest = z + rtest ftest = f(ztest) # Evaluate powerseries: comp = np.sum(bn * np.power(check_point, mvec)) ftests.append(ftest) diffs.append(comp - ftest) # depends on [control=['for'], data=['check_point']] max_abs_error = np.max(np.abs(diffs)) max_f_value = np.max(np.abs(ftests)) return max_abs_error > 0.001 * max_f_value
def plugins(): """Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes """ return ( ClassFactoring, ConstantLogic, ExceptStatements, FutureCompatibility, ImportOrder, Indentation, MissingContextManager, NewStyleClasses, Newlines, PrintStatements, TrailingWhitespace, PEP8VariableNames, PyflakesChecker, PyCodeStyleChecker, )
def function[plugins, parameter[]]: constant[Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes ] return[tuple[[<ast.Name object at 0x7da1b22492a0>, <ast.Name object at 0x7da1b22482e0>, <ast.Name object at 0x7da1b2249480>, <ast.Name object at 0x7da1b2248e50>, <ast.Name object at 0x7da1b22490c0>, <ast.Name object at 0x7da1b224a170>, <ast.Name object at 0x7da1b224b250>, <ast.Name object at 0x7da1b2249f90>, <ast.Name object at 0x7da1b2249db0>, <ast.Name object at 0x7da1b2248a60>, <ast.Name object at 0x7da1b2249ff0>, <ast.Name object at 0x7da1b224b970>, <ast.Name object at 0x7da1b2249ea0>, <ast.Name object at 0x7da1b224a770>]]]
keyword[def] identifier[plugins] (): literal[string] keyword[return] ( identifier[ClassFactoring] , identifier[ConstantLogic] , identifier[ExceptStatements] , identifier[FutureCompatibility] , identifier[ImportOrder] , identifier[Indentation] , identifier[MissingContextManager] , identifier[NewStyleClasses] , identifier[Newlines] , identifier[PrintStatements] , identifier[TrailingWhitespace] , identifier[PEP8VariableNames] , identifier[PyflakesChecker] , identifier[PyCodeStyleChecker] , )
def plugins(): """Returns a tuple of the plugin classes registered with the python style checker. :rtype: tuple of :class:`pants.contrib.python.checks.checker.common.CheckstylePlugin` subtypes """ return (ClassFactoring, ConstantLogic, ExceptStatements, FutureCompatibility, ImportOrder, Indentation, MissingContextManager, NewStyleClasses, Newlines, PrintStatements, TrailingWhitespace, PEP8VariableNames, PyflakesChecker, PyCodeStyleChecker)
def generic_function(target, prop, func, **kwargs): r""" Runs an arbitrary function on the given data This allows users to place a customized calculation into the automatated model regeneration pipeline. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop : string The dictionary key containing the array to be operated on func : Numpy function A handle to the function to apply kwargs : keyward arguments All arguments required by the specific Numpy function Examples -------- The following example shows how to use a Numpy function, but any function can be used, as long as it returns an array object: >>> import openpnm as op >>> import numpy as np >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> geo = op.geometry.GenericGeometry(network=pn, pores=pn.Ps, throats=pn.Ts) >>> geo['pore.rand'] = np.random.rand(geo.Np) >>> geo.add_model(propname='pore.cos', ... model=op.models.misc.generic_function, ... func=np.cos, ... prop='pore.rand') """ values = target[prop] result = func(values, **kwargs) if not isinstance(result, np.ndarray): logger.warning('Given function must return a Numpy array') return result
def function[generic_function, parameter[target, prop, func]]: constant[ Runs an arbitrary function on the given data This allows users to place a customized calculation into the automatated model regeneration pipeline. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop : string The dictionary key containing the array to be operated on func : Numpy function A handle to the function to apply kwargs : keyward arguments All arguments required by the specific Numpy function Examples -------- The following example shows how to use a Numpy function, but any function can be used, as long as it returns an array object: >>> import openpnm as op >>> import numpy as np >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> geo = op.geometry.GenericGeometry(network=pn, pores=pn.Ps, throats=pn.Ts) >>> geo['pore.rand'] = np.random.rand(geo.Np) >>> geo.add_model(propname='pore.cos', ... model=op.models.misc.generic_function, ... func=np.cos, ... prop='pore.rand') ] variable[values] assign[=] call[name[target]][name[prop]] variable[result] assign[=] call[name[func], parameter[name[values]]] if <ast.UnaryOp object at 0x7da18f58fa00> begin[:] call[name[logger].warning, parameter[constant[Given function must return a Numpy array]]] return[name[result]]
keyword[def] identifier[generic_function] ( identifier[target] , identifier[prop] , identifier[func] ,** identifier[kwargs] ): literal[string] identifier[values] = identifier[target] [ identifier[prop] ] identifier[result] = identifier[func] ( identifier[values] ,** identifier[kwargs] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[result] , identifier[np] . identifier[ndarray] ): identifier[logger] . identifier[warning] ( literal[string] ) keyword[return] identifier[result]
def generic_function(target, prop, func, **kwargs): """ Runs an arbitrary function on the given data This allows users to place a customized calculation into the automatated model regeneration pipeline. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. prop : string The dictionary key containing the array to be operated on func : Numpy function A handle to the function to apply kwargs : keyward arguments All arguments required by the specific Numpy function Examples -------- The following example shows how to use a Numpy function, but any function can be used, as long as it returns an array object: >>> import openpnm as op >>> import numpy as np >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> geo = op.geometry.GenericGeometry(network=pn, pores=pn.Ps, throats=pn.Ts) >>> geo['pore.rand'] = np.random.rand(geo.Np) >>> geo.add_model(propname='pore.cos', ... model=op.models.misc.generic_function, ... func=np.cos, ... prop='pore.rand') """ values = target[prop] result = func(values, **kwargs) if not isinstance(result, np.ndarray): logger.warning('Given function must return a Numpy array') # depends on [control=['if'], data=[]] return result
def field_values(self): """ Access the field_values :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList """ if self._field_values is None: self._field_values = FieldValueList( self._version, assistant_sid=self._solution['assistant_sid'], field_type_sid=self._solution['sid'], ) return self._field_values
def function[field_values, parameter[self]]: constant[ Access the field_values :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList ] if compare[name[self]._field_values is constant[None]] begin[:] name[self]._field_values assign[=] call[name[FieldValueList], parameter[name[self]._version]] return[name[self]._field_values]
keyword[def] identifier[field_values] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_field_values] keyword[is] keyword[None] : identifier[self] . identifier[_field_values] = identifier[FieldValueList] ( identifier[self] . identifier[_version] , identifier[assistant_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[field_type_sid] = identifier[self] . identifier[_solution] [ literal[string] ], ) keyword[return] identifier[self] . identifier[_field_values]
def field_values(self): """ Access the field_values :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList """ if self._field_values is None: self._field_values = FieldValueList(self._version, assistant_sid=self._solution['assistant_sid'], field_type_sid=self._solution['sid']) # depends on [control=['if'], data=[]] return self._field_values
def pprint(self): """Return tag key=value pairs in a human-readable format.""" items = sorted(self.items()) return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items)
def function[pprint, parameter[self]]: constant[Return tag key=value pairs in a human-readable format.] variable[items] assign[=] call[name[sorted], parameter[call[name[self].items, parameter[]]]] return[call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da1b1e941f0>]]]
keyword[def] identifier[pprint] ( identifier[self] ): literal[string] identifier[items] = identifier[sorted] ( identifier[self] . identifier[items] ()) keyword[return] literal[string] . identifier[join] ( literal[string] %( identifier[k] , identifier[v] . identifier[pprint] ()) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[items] )
def pprint(self): """Return tag key=value pairs in a human-readable format.""" items = sorted(self.items()) return u'\n'.join((u'%s=%s' % (k, v.pprint()) for (k, v) in items))
def mail_setup(path): """ Set the variables to be able to send emails. :param path: path to the config file """ global dest_mails global smtp_server global smtp_port global src_server config = configparser.RawConfigParser() config.readfp(path) dest_mails = config.get('mail', 'dest_mail').split(',') smtp_server = config.get('mail', 'smtp_server') smtp_port = config.get('mail', 'smtp_port') src_server = config.get('mail', 'src_server')
def function[mail_setup, parameter[path]]: constant[ Set the variables to be able to send emails. :param path: path to the config file ] <ast.Global object at 0x7da1b16013c0> <ast.Global object at 0x7da1b1601510> <ast.Global object at 0x7da1b16015a0> <ast.Global object at 0x7da1b16030d0> variable[config] assign[=] call[name[configparser].RawConfigParser, parameter[]] call[name[config].readfp, parameter[name[path]]] variable[dest_mails] assign[=] call[call[name[config].get, parameter[constant[mail], constant[dest_mail]]].split, parameter[constant[,]]] variable[smtp_server] assign[=] call[name[config].get, parameter[constant[mail], constant[smtp_server]]] variable[smtp_port] assign[=] call[name[config].get, parameter[constant[mail], constant[smtp_port]]] variable[src_server] assign[=] call[name[config].get, parameter[constant[mail], constant[src_server]]]
keyword[def] identifier[mail_setup] ( identifier[path] ): literal[string] keyword[global] identifier[dest_mails] keyword[global] identifier[smtp_server] keyword[global] identifier[smtp_port] keyword[global] identifier[src_server] identifier[config] = identifier[configparser] . identifier[RawConfigParser] () identifier[config] . identifier[readfp] ( identifier[path] ) identifier[dest_mails] = identifier[config] . identifier[get] ( literal[string] , literal[string] ). identifier[split] ( literal[string] ) identifier[smtp_server] = identifier[config] . identifier[get] ( literal[string] , literal[string] ) identifier[smtp_port] = identifier[config] . identifier[get] ( literal[string] , literal[string] ) identifier[src_server] = identifier[config] . identifier[get] ( literal[string] , literal[string] )
def mail_setup(path): """ Set the variables to be able to send emails. :param path: path to the config file """ global dest_mails global smtp_server global smtp_port global src_server config = configparser.RawConfigParser() config.readfp(path) dest_mails = config.get('mail', 'dest_mail').split(',') smtp_server = config.get('mail', 'smtp_server') smtp_port = config.get('mail', 'smtp_port') src_server = config.get('mail', 'src_server')
def log_shapes(logger): """ Decorator to log the shapes of input and output dataframes It considers all the dataframes passed either as arguments or keyword arguments as inputs and all the dataframes returned as outputs. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): input_shapes = _get_dfs_shapes(*args, **kwargs) result = func(*args, **kwargs) output_shapes = _get_dfs_shapes(result) _log_shapes(logger, func.__name__, input_shapes, output_shapes) return result return wrapper return decorator
def function[log_shapes, parameter[logger]]: constant[ Decorator to log the shapes of input and output dataframes It considers all the dataframes passed either as arguments or keyword arguments as inputs and all the dataframes returned as outputs. ] def function[decorator, parameter[func]]: def function[wrapper, parameter[]]: variable[input_shapes] assign[=] call[name[_get_dfs_shapes], parameter[<ast.Starred object at 0x7da1b032f190>]] variable[result] assign[=] call[name[func], parameter[<ast.Starred object at 0x7da1b032cf40>]] variable[output_shapes] assign[=] call[name[_get_dfs_shapes], parameter[name[result]]] call[name[_log_shapes], parameter[name[logger], name[func].__name__, name[input_shapes], name[output_shapes]]] return[name[result]] return[name[wrapper]] return[name[decorator]]
keyword[def] identifier[log_shapes] ( identifier[logger] ): literal[string] keyword[def] identifier[decorator] ( identifier[func] ): @ identifier[wraps] ( identifier[func] ) keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ): identifier[input_shapes] = identifier[_get_dfs_shapes] (* identifier[args] ,** identifier[kwargs] ) identifier[result] = identifier[func] (* identifier[args] ,** identifier[kwargs] ) identifier[output_shapes] = identifier[_get_dfs_shapes] ( identifier[result] ) identifier[_log_shapes] ( identifier[logger] , identifier[func] . identifier[__name__] , identifier[input_shapes] , identifier[output_shapes] ) keyword[return] identifier[result] keyword[return] identifier[wrapper] keyword[return] identifier[decorator]
def log_shapes(logger): """ Decorator to log the shapes of input and output dataframes It considers all the dataframes passed either as arguments or keyword arguments as inputs and all the dataframes returned as outputs. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): input_shapes = _get_dfs_shapes(*args, **kwargs) result = func(*args, **kwargs) output_shapes = _get_dfs_shapes(result) _log_shapes(logger, func.__name__, input_shapes, output_shapes) return result return wrapper return decorator
def compute_rotsym(self, threshold=1e-3*angstrom): """Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself. """ # Generate a graph with a more permissive threshold for bond lengths: # (is convenient in case of transition state geometries) graph = MolecularGraph.from_geometry(self, scaling=1.5) try: return compute_rotsym(self, graph, threshold) except ValueError: raise ValueError("The rotational symmetry number can only be computed when the graph is fully connected.")
def function[compute_rotsym, parameter[self, threshold]]: constant[Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself. ] variable[graph] assign[=] call[name[MolecularGraph].from_geometry, parameter[name[self]]] <ast.Try object at 0x7da20c6abd00>
keyword[def] identifier[compute_rotsym] ( identifier[self] , identifier[threshold] = literal[int] * identifier[angstrom] ): literal[string] identifier[graph] = identifier[MolecularGraph] . identifier[from_geometry] ( identifier[self] , identifier[scaling] = literal[int] ) keyword[try] : keyword[return] identifier[compute_rotsym] ( identifier[self] , identifier[graph] , identifier[threshold] ) keyword[except] identifier[ValueError] : keyword[raise] identifier[ValueError] ( literal[string] )
def compute_rotsym(self, threshold=0.001 * angstrom): """Compute the rotational symmetry number. Optional argument: | ``threshold`` -- only when a rotation results in an rmsd below the given threshold, the rotation is considered to transform the molecule onto itself. """ # Generate a graph with a more permissive threshold for bond lengths: # (is convenient in case of transition state geometries) graph = MolecularGraph.from_geometry(self, scaling=1.5) try: return compute_rotsym(self, graph, threshold) # depends on [control=['try'], data=[]] except ValueError: raise ValueError('The rotational symmetry number can only be computed when the graph is fully connected.') # depends on [control=['except'], data=[]]
def _get_snapshots_recursively(snapshots, snapshot_location): """ Recursively traverses child snapshots and returns dictinary of snapshots :param snapshots: list of snapshots to examine :param snapshot_location: current path of snapshots :return: dictinary of snapshot path and snapshot instances :rtype: dict(str,vim.vm.Snapshot) """ snapshot_paths = collections.OrderedDict() if not snapshots: return snapshot_paths for snapshot in snapshots: if snapshot_location: current_snapshot_path = SnapshotRetriever.combine(snapshot_location, snapshot.name) else: current_snapshot_path = snapshot.name snapshot_paths[current_snapshot_path] = snapshot.snapshot child_snapshots = SnapshotRetriever._get_snapshots_recursively(snapshot.childSnapshotList, current_snapshot_path) snapshot_paths.update(child_snapshots) return snapshot_paths
def function[_get_snapshots_recursively, parameter[snapshots, snapshot_location]]: constant[ Recursively traverses child snapshots and returns dictinary of snapshots :param snapshots: list of snapshots to examine :param snapshot_location: current path of snapshots :return: dictinary of snapshot path and snapshot instances :rtype: dict(str,vim.vm.Snapshot) ] variable[snapshot_paths] assign[=] call[name[collections].OrderedDict, parameter[]] if <ast.UnaryOp object at 0x7da18dc9bb50> begin[:] return[name[snapshot_paths]] for taget[name[snapshot]] in starred[name[snapshots]] begin[:] if name[snapshot_location] begin[:] variable[current_snapshot_path] assign[=] call[name[SnapshotRetriever].combine, parameter[name[snapshot_location], name[snapshot].name]] call[name[snapshot_paths]][name[current_snapshot_path]] assign[=] name[snapshot].snapshot variable[child_snapshots] assign[=] call[name[SnapshotRetriever]._get_snapshots_recursively, parameter[name[snapshot].childSnapshotList, name[current_snapshot_path]]] call[name[snapshot_paths].update, parameter[name[child_snapshots]]] return[name[snapshot_paths]]
keyword[def] identifier[_get_snapshots_recursively] ( identifier[snapshots] , identifier[snapshot_location] ): literal[string] identifier[snapshot_paths] = identifier[collections] . identifier[OrderedDict] () keyword[if] keyword[not] identifier[snapshots] : keyword[return] identifier[snapshot_paths] keyword[for] identifier[snapshot] keyword[in] identifier[snapshots] : keyword[if] identifier[snapshot_location] : identifier[current_snapshot_path] = identifier[SnapshotRetriever] . identifier[combine] ( identifier[snapshot_location] , identifier[snapshot] . identifier[name] ) keyword[else] : identifier[current_snapshot_path] = identifier[snapshot] . identifier[name] identifier[snapshot_paths] [ identifier[current_snapshot_path] ]= identifier[snapshot] . identifier[snapshot] identifier[child_snapshots] = identifier[SnapshotRetriever] . identifier[_get_snapshots_recursively] ( identifier[snapshot] . identifier[childSnapshotList] , identifier[current_snapshot_path] ) identifier[snapshot_paths] . identifier[update] ( identifier[child_snapshots] ) keyword[return] identifier[snapshot_paths]
def _get_snapshots_recursively(snapshots, snapshot_location): """ Recursively traverses child snapshots and returns dictinary of snapshots :param snapshots: list of snapshots to examine :param snapshot_location: current path of snapshots :return: dictinary of snapshot path and snapshot instances :rtype: dict(str,vim.vm.Snapshot) """ snapshot_paths = collections.OrderedDict() if not snapshots: return snapshot_paths # depends on [control=['if'], data=[]] for snapshot in snapshots: if snapshot_location: current_snapshot_path = SnapshotRetriever.combine(snapshot_location, snapshot.name) # depends on [control=['if'], data=[]] else: current_snapshot_path = snapshot.name snapshot_paths[current_snapshot_path] = snapshot.snapshot child_snapshots = SnapshotRetriever._get_snapshots_recursively(snapshot.childSnapshotList, current_snapshot_path) snapshot_paths.update(child_snapshots) # depends on [control=['for'], data=['snapshot']] return snapshot_paths
def to_dict(self): '''Save this component group to a dictionary.''' d = {'groupId': self.group_id} members = [] for m in self.members: members.append(m.to_dict()) if members: d['members'] = members return d
def function[to_dict, parameter[self]]: constant[Save this component group to a dictionary.] variable[d] assign[=] dictionary[[<ast.Constant object at 0x7da1b0abbd90>], [<ast.Attribute object at 0x7da1b0ab9ea0>]] variable[members] assign[=] list[[]] for taget[name[m]] in starred[name[self].members] begin[:] call[name[members].append, parameter[call[name[m].to_dict, parameter[]]]] if name[members] begin[:] call[name[d]][constant[members]] assign[=] name[members] return[name[d]]
keyword[def] identifier[to_dict] ( identifier[self] ): literal[string] identifier[d] ={ literal[string] : identifier[self] . identifier[group_id] } identifier[members] =[] keyword[for] identifier[m] keyword[in] identifier[self] . identifier[members] : identifier[members] . identifier[append] ( identifier[m] . identifier[to_dict] ()) keyword[if] identifier[members] : identifier[d] [ literal[string] ]= identifier[members] keyword[return] identifier[d]
def to_dict(self): """Save this component group to a dictionary.""" d = {'groupId': self.group_id} members = [] for m in self.members: members.append(m.to_dict()) # depends on [control=['for'], data=['m']] if members: d['members'] = members # depends on [control=['if'], data=[]] return d
def forbild(space, resolution=False, ear=True, value_type='density', scale='auto'): """Standard FORBILD phantom in 2 dimensions. The FORBILD phantom is intended for testing CT algorithms and is intended to be similar to a human head. The phantom is defined using the following materials: ========================= ===== ================ Material Index Density (g/cm^3) ========================= ===== ================ Air 0 0.0000 Cerebrospinal fluid (CSF) 1 1.0450 Small less dense sphere 2 1.0475 Brain 3 1.0500 Small more dense sphere 4 1.0525 Blood 5 1.0550 Eyes 6 1.0600 Bone 7 1.8000 ========================= ===== ================ Parameters ---------- space : `DiscreteLp` The space in which the phantom should be corrected. Needs to be two- dimensional. resolution : bool, optional If ``True``, insert a small resolution test pattern to the left. ear : bool, optional If ``True``, insert an ear-like structure to the right. value_type : {'density', 'materials'}, optional The format the phantom should be given in. 'density' returns floats in the range [0, 1.8] (g/cm^3) 'materials' returns indices in the range [0, 7]. scale : {'auto', 'cm', 'meters', 'mm'}, optional Controls how ``space`` should be rescaled to fit the definition of the forbild phantom, which is defined on the square [-12.8, 12.8] x [-12.8, 12.8] cm. * ``'auto'`` means that space is rescaled to fit exactly. The space is also centered at [0, 0]. * ``'cm'`` means the dimensions of the space should be used as-is. * ``'m'`` means all dimensions of the space are multiplied by 100. * ``'mm'`` means all dimensions of the space are divided by 10. Returns ------- forbild : ``space``-element FORBILD phantom discretized by ``space``. See Also -------- shepp_logan : A simpler phantom for similar purposes, also working in 3d. References ---------- .. _FORBILD phantom: www.imp.uni-erlangen.de/phantoms/head/head.html .. _algorithm: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3426508/ """ def transposeravel(arr): """Implement MATLAB's ``transpose(arr(:))``.""" return arr.T.ravel() if not isinstance(space, DiscreteLp): raise TypeError('`space` must be a `DiscreteLp`') if space.ndim != 2: raise TypeError('`space` must be two-dimensional') scale, scale_in = str(scale).lower(), scale value_type, value_type_in = str(value_type).lower(), value_type # Create analytic description of phantom phantomE, phantomC = _analytical_forbild_phantom(resolution, ear) # Rescale points to the default grid. # The forbild phantom is defined on [-12.8, 12.8] x [-12.8, 12.8] xcoord, ycoord = space.points().T if scale == 'auto': xcoord = ((xcoord - space.min_pt[0]) / (space.max_pt[0] - space.min_pt[0])) xcoord = 25.8 * xcoord - 12.8 ycoord = ((ycoord - space.min_pt[1]) / (space.max_pt[1] - space.min_pt[1])) ycoord = 25.8 * ycoord - 12.8 elif scale == 'cm': pass # dimensions already correct. elif scale == 'm': xcoord *= 100.0 ycoord *= 100.0 elif scale == 'mm': xcoord /= 10.0 ycoord /= 10.0 else: raise ValueError('unknown `scale` {}'.format(scale_in)) # Compute the phantom values in each voxel image = np.zeros(space.size) nclipinfo = 0 for k in range(phantomE.shape[0]): # Handle elliptic bounds Vx0 = np.array([transposeravel(xcoord) - phantomE[k, 0], transposeravel(ycoord) - phantomE[k, 1]]) D = np.array([[1 / phantomE[k, 2], 0], [0, 1 / phantomE[k, 3]]]) phi = np.deg2rad(phantomE[k, 4]) Q = np.array([[np.cos(phi), np.sin(phi)], [-np.sin(phi), np.cos(phi)]]) f = phantomE[k, 5] nclip = int(phantomE[k, 6]) equation1 = np.sum(D.dot(Q).dot(Vx0) ** 2, axis=0) i = (equation1 <= 1.0) # Handle clipping surfaces for _ in range(nclip): # note: nclib can be 0 d = phantomC[0, nclipinfo] psi = np.deg2rad(phantomC[1, nclipinfo]) equation2 = np.array([np.cos(psi), np.sin(psi)]).dot(Vx0) i &= (equation2 < d) nclipinfo += 1 image[i] += f if value_type == 'materials': materials = np.zeros(space.size, dtype=space.dtype) # csf materials[(image > 1.043) & (image <= 1.047)] = 1 # less_dense_sphere materials[(image > 1.047) & (image <= 1.048)] = 2 # brain materials[(image > 1.048) & (image <= 1.052)] = 3 # denser_sphere materials[(image > 1.052) & (image <= 1.053)] = 4 # blood materials[(image > 1.053) & (image <= 1.058)] = 5 # eye materials[(image > 1.058) & (image <= 1.062)] = 6 # Bone materials[image > 1.75] = 7 return space.element(materials.reshape(space.shape)) elif value_type == 'density': return space.element(image.reshape(space.shape)) else: raise ValueError('unknown `value_type` {}'.format(value_type_in))
def function[forbild, parameter[space, resolution, ear, value_type, scale]]: constant[Standard FORBILD phantom in 2 dimensions. The FORBILD phantom is intended for testing CT algorithms and is intended to be similar to a human head. The phantom is defined using the following materials: ========================= ===== ================ Material Index Density (g/cm^3) ========================= ===== ================ Air 0 0.0000 Cerebrospinal fluid (CSF) 1 1.0450 Small less dense sphere 2 1.0475 Brain 3 1.0500 Small more dense sphere 4 1.0525 Blood 5 1.0550 Eyes 6 1.0600 Bone 7 1.8000 ========================= ===== ================ Parameters ---------- space : `DiscreteLp` The space in which the phantom should be corrected. Needs to be two- dimensional. resolution : bool, optional If ``True``, insert a small resolution test pattern to the left. ear : bool, optional If ``True``, insert an ear-like structure to the right. value_type : {'density', 'materials'}, optional The format the phantom should be given in. 'density' returns floats in the range [0, 1.8] (g/cm^3) 'materials' returns indices in the range [0, 7]. scale : {'auto', 'cm', 'meters', 'mm'}, optional Controls how ``space`` should be rescaled to fit the definition of the forbild phantom, which is defined on the square [-12.8, 12.8] x [-12.8, 12.8] cm. * ``'auto'`` means that space is rescaled to fit exactly. The space is also centered at [0, 0]. * ``'cm'`` means the dimensions of the space should be used as-is. * ``'m'`` means all dimensions of the space are multiplied by 100. * ``'mm'`` means all dimensions of the space are divided by 10. Returns ------- forbild : ``space``-element FORBILD phantom discretized by ``space``. See Also -------- shepp_logan : A simpler phantom for similar purposes, also working in 3d. References ---------- .. _FORBILD phantom: www.imp.uni-erlangen.de/phantoms/head/head.html .. _algorithm: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3426508/ ] def function[transposeravel, parameter[arr]]: constant[Implement MATLAB's ``transpose(arr(:))``.] return[call[name[arr].T.ravel, parameter[]]] if <ast.UnaryOp object at 0x7da1b1ea2770> begin[:] <ast.Raise object at 0x7da1b1ea2c20> if compare[name[space].ndim not_equal[!=] constant[2]] begin[:] <ast.Raise object at 0x7da1b1ea3b50> <ast.Tuple object at 0x7da1b1ea2590> assign[=] tuple[[<ast.Call object at 0x7da1b1ea3ee0>, <ast.Name object at 0x7da1b1ea0df0>]] <ast.Tuple object at 0x7da1b1ea2e30> assign[=] tuple[[<ast.Call object at 0x7da1b1ea1990>, <ast.Name object at 0x7da1b1ea2ad0>]] <ast.Tuple object at 0x7da1b1ea21d0> assign[=] call[name[_analytical_forbild_phantom], parameter[name[resolution], name[ear]]] <ast.Tuple object at 0x7da1b1ea1ba0> assign[=] call[name[space].points, parameter[]].T if compare[name[scale] equal[==] constant[auto]] begin[:] variable[xcoord] assign[=] binary_operation[binary_operation[name[xcoord] - call[name[space].min_pt][constant[0]]] / binary_operation[call[name[space].max_pt][constant[0]] - call[name[space].min_pt][constant[0]]]] variable[xcoord] assign[=] binary_operation[binary_operation[constant[25.8] * name[xcoord]] - constant[12.8]] variable[ycoord] assign[=] binary_operation[binary_operation[name[ycoord] - call[name[space].min_pt][constant[1]]] / binary_operation[call[name[space].max_pt][constant[1]] - call[name[space].min_pt][constant[1]]]] variable[ycoord] assign[=] binary_operation[binary_operation[constant[25.8] * name[ycoord]] - constant[12.8]] variable[image] assign[=] call[name[np].zeros, parameter[name[space].size]] variable[nclipinfo] assign[=] constant[0] for taget[name[k]] in starred[call[name[range], parameter[call[name[phantomE].shape][constant[0]]]]] begin[:] variable[Vx0] assign[=] call[name[np].array, parameter[list[[<ast.BinOp object at 0x7da1b20b77c0>, <ast.BinOp object at 0x7da1b20b6c20>]]]] variable[D] assign[=] call[name[np].array, parameter[list[[<ast.List object at 0x7da1b20b7340>, <ast.List object at 0x7da1b20b78b0>]]]] variable[phi] assign[=] call[name[np].deg2rad, parameter[call[name[phantomE]][tuple[[<ast.Name object at 0x7da1b20b51e0>, <ast.Constant object at 0x7da1b20b5cc0>]]]]] variable[Q] assign[=] call[name[np].array, parameter[list[[<ast.List object at 0x7da1b20b6ad0>, <ast.List object at 0x7da1b20b7a90>]]]] variable[f] assign[=] call[name[phantomE]][tuple[[<ast.Name object at 0x7da1b1e44b80>, <ast.Constant object at 0x7da1b1e45a80>]]] variable[nclip] assign[=] call[name[int], parameter[call[name[phantomE]][tuple[[<ast.Name object at 0x7da1b1e44880>, <ast.Constant object at 0x7da1b1e45630>]]]]] variable[equation1] assign[=] call[name[np].sum, parameter[binary_operation[call[call[name[D].dot, parameter[name[Q]]].dot, parameter[name[Vx0]]] ** constant[2]]]] variable[i] assign[=] compare[name[equation1] less_or_equal[<=] constant[1.0]] for taget[name[_]] in starred[call[name[range], parameter[name[nclip]]]] begin[:] variable[d] assign[=] call[name[phantomC]][tuple[[<ast.Constant object at 0x7da1b1e93610>, <ast.Name object at 0x7da1b1e93d90>]]] variable[psi] assign[=] call[name[np].deg2rad, parameter[call[name[phantomC]][tuple[[<ast.Constant object at 0x7da1b1e93b80>, <ast.Name object at 0x7da1b1e922f0>]]]]] variable[equation2] assign[=] call[call[name[np].array, parameter[list[[<ast.Call object at 0x7da1b1e92a10>, <ast.Call object at 0x7da1b1e93550>]]]].dot, parameter[name[Vx0]]] <ast.AugAssign object at 0x7da1b1e93070> <ast.AugAssign object at 0x7da1b1e902b0> <ast.AugAssign object at 0x7da1b1e90400> if compare[name[value_type] equal[==] constant[materials]] begin[:] variable[materials] assign[=] call[name[np].zeros, parameter[name[space].size]] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.043]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.047]]]] assign[=] constant[1] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.047]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.048]]]] assign[=] constant[2] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.048]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.052]]]] assign[=] constant[3] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.052]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.053]]]] assign[=] constant[4] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.053]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.058]]]] assign[=] constant[5] call[name[materials]][binary_operation[compare[name[image] greater[>] constant[1.058]] <ast.BitAnd object at 0x7da2590d6b60> compare[name[image] less_or_equal[<=] constant[1.062]]]] assign[=] constant[6] call[name[materials]][compare[name[image] greater[>] constant[1.75]]] assign[=] constant[7] return[call[name[space].element, parameter[call[name[materials].reshape, parameter[name[space].shape]]]]]
keyword[def] identifier[forbild] ( identifier[space] , identifier[resolution] = keyword[False] , identifier[ear] = keyword[True] , identifier[value_type] = literal[string] , identifier[scale] = literal[string] ): literal[string] keyword[def] identifier[transposeravel] ( identifier[arr] ): literal[string] keyword[return] identifier[arr] . identifier[T] . identifier[ravel] () keyword[if] keyword[not] identifier[isinstance] ( identifier[space] , identifier[DiscreteLp] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[space] . identifier[ndim] != literal[int] : keyword[raise] identifier[TypeError] ( literal[string] ) identifier[scale] , identifier[scale_in] = identifier[str] ( identifier[scale] ). identifier[lower] (), identifier[scale] identifier[value_type] , identifier[value_type_in] = identifier[str] ( identifier[value_type] ). identifier[lower] (), identifier[value_type] identifier[phantomE] , identifier[phantomC] = identifier[_analytical_forbild_phantom] ( identifier[resolution] , identifier[ear] ) identifier[xcoord] , identifier[ycoord] = identifier[space] . identifier[points] (). identifier[T] keyword[if] identifier[scale] == literal[string] : identifier[xcoord] =(( identifier[xcoord] - identifier[space] . identifier[min_pt] [ literal[int] ])/ ( identifier[space] . identifier[max_pt] [ literal[int] ]- identifier[space] . identifier[min_pt] [ literal[int] ])) identifier[xcoord] = literal[int] * identifier[xcoord] - literal[int] identifier[ycoord] =(( identifier[ycoord] - identifier[space] . identifier[min_pt] [ literal[int] ])/ ( identifier[space] . identifier[max_pt] [ literal[int] ]- identifier[space] . identifier[min_pt] [ literal[int] ])) identifier[ycoord] = literal[int] * identifier[ycoord] - literal[int] keyword[elif] identifier[scale] == literal[string] : keyword[pass] keyword[elif] identifier[scale] == literal[string] : identifier[xcoord] *= literal[int] identifier[ycoord] *= literal[int] keyword[elif] identifier[scale] == literal[string] : identifier[xcoord] /= literal[int] identifier[ycoord] /= literal[int] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[scale_in] )) identifier[image] = identifier[np] . identifier[zeros] ( identifier[space] . identifier[size] ) identifier[nclipinfo] = literal[int] keyword[for] identifier[k] keyword[in] identifier[range] ( identifier[phantomE] . identifier[shape] [ literal[int] ]): identifier[Vx0] = identifier[np] . identifier[array] ([ identifier[transposeravel] ( identifier[xcoord] )- identifier[phantomE] [ identifier[k] , literal[int] ], identifier[transposeravel] ( identifier[ycoord] )- identifier[phantomE] [ identifier[k] , literal[int] ]]) identifier[D] = identifier[np] . identifier[array] ([[ literal[int] / identifier[phantomE] [ identifier[k] , literal[int] ], literal[int] ], [ literal[int] , literal[int] / identifier[phantomE] [ identifier[k] , literal[int] ]]]) identifier[phi] = identifier[np] . identifier[deg2rad] ( identifier[phantomE] [ identifier[k] , literal[int] ]) identifier[Q] = identifier[np] . identifier[array] ([[ identifier[np] . identifier[cos] ( identifier[phi] ), identifier[np] . identifier[sin] ( identifier[phi] )], [- identifier[np] . identifier[sin] ( identifier[phi] ), identifier[np] . identifier[cos] ( identifier[phi] )]]) identifier[f] = identifier[phantomE] [ identifier[k] , literal[int] ] identifier[nclip] = identifier[int] ( identifier[phantomE] [ identifier[k] , literal[int] ]) identifier[equation1] = identifier[np] . identifier[sum] ( identifier[D] . identifier[dot] ( identifier[Q] ). identifier[dot] ( identifier[Vx0] )** literal[int] , identifier[axis] = literal[int] ) identifier[i] =( identifier[equation1] <= literal[int] ) keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[nclip] ): identifier[d] = identifier[phantomC] [ literal[int] , identifier[nclipinfo] ] identifier[psi] = identifier[np] . identifier[deg2rad] ( identifier[phantomC] [ literal[int] , identifier[nclipinfo] ]) identifier[equation2] = identifier[np] . identifier[array] ([ identifier[np] . identifier[cos] ( identifier[psi] ), identifier[np] . identifier[sin] ( identifier[psi] )]). identifier[dot] ( identifier[Vx0] ) identifier[i] &=( identifier[equation2] < identifier[d] ) identifier[nclipinfo] += literal[int] identifier[image] [ identifier[i] ]+= identifier[f] keyword[if] identifier[value_type] == literal[string] : identifier[materials] = identifier[np] . identifier[zeros] ( identifier[space] . identifier[size] , identifier[dtype] = identifier[space] . identifier[dtype] ) identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [( identifier[image] > literal[int] )&( identifier[image] <= literal[int] )]= literal[int] identifier[materials] [ identifier[image] > literal[int] ]= literal[int] keyword[return] identifier[space] . identifier[element] ( identifier[materials] . identifier[reshape] ( identifier[space] . identifier[shape] )) keyword[elif] identifier[value_type] == literal[string] : keyword[return] identifier[space] . identifier[element] ( identifier[image] . identifier[reshape] ( identifier[space] . identifier[shape] )) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[value_type_in] ))
def forbild(space, resolution=False, ear=True, value_type='density', scale='auto'): """Standard FORBILD phantom in 2 dimensions. The FORBILD phantom is intended for testing CT algorithms and is intended to be similar to a human head. The phantom is defined using the following materials: ========================= ===== ================ Material Index Density (g/cm^3) ========================= ===== ================ Air 0 0.0000 Cerebrospinal fluid (CSF) 1 1.0450 Small less dense sphere 2 1.0475 Brain 3 1.0500 Small more dense sphere 4 1.0525 Blood 5 1.0550 Eyes 6 1.0600 Bone 7 1.8000 ========================= ===== ================ Parameters ---------- space : `DiscreteLp` The space in which the phantom should be corrected. Needs to be two- dimensional. resolution : bool, optional If ``True``, insert a small resolution test pattern to the left. ear : bool, optional If ``True``, insert an ear-like structure to the right. value_type : {'density', 'materials'}, optional The format the phantom should be given in. 'density' returns floats in the range [0, 1.8] (g/cm^3) 'materials' returns indices in the range [0, 7]. scale : {'auto', 'cm', 'meters', 'mm'}, optional Controls how ``space`` should be rescaled to fit the definition of the forbild phantom, which is defined on the square [-12.8, 12.8] x [-12.8, 12.8] cm. * ``'auto'`` means that space is rescaled to fit exactly. The space is also centered at [0, 0]. * ``'cm'`` means the dimensions of the space should be used as-is. * ``'m'`` means all dimensions of the space are multiplied by 100. * ``'mm'`` means all dimensions of the space are divided by 10. Returns ------- forbild : ``space``-element FORBILD phantom discretized by ``space``. See Also -------- shepp_logan : A simpler phantom for similar purposes, also working in 3d. References ---------- .. _FORBILD phantom: www.imp.uni-erlangen.de/phantoms/head/head.html .. _algorithm: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3426508/ """ def transposeravel(arr): """Implement MATLAB's ``transpose(arr(:))``.""" return arr.T.ravel() if not isinstance(space, DiscreteLp): raise TypeError('`space` must be a `DiscreteLp`') # depends on [control=['if'], data=[]] if space.ndim != 2: raise TypeError('`space` must be two-dimensional') # depends on [control=['if'], data=[]] (scale, scale_in) = (str(scale).lower(), scale) (value_type, value_type_in) = (str(value_type).lower(), value_type) # Create analytic description of phantom (phantomE, phantomC) = _analytical_forbild_phantom(resolution, ear) # Rescale points to the default grid. # The forbild phantom is defined on [-12.8, 12.8] x [-12.8, 12.8] (xcoord, ycoord) = space.points().T if scale == 'auto': xcoord = (xcoord - space.min_pt[0]) / (space.max_pt[0] - space.min_pt[0]) xcoord = 25.8 * xcoord - 12.8 ycoord = (ycoord - space.min_pt[1]) / (space.max_pt[1] - space.min_pt[1]) ycoord = 25.8 * ycoord - 12.8 # depends on [control=['if'], data=[]] elif scale == 'cm': pass # dimensions already correct. # depends on [control=['if'], data=[]] elif scale == 'm': xcoord *= 100.0 ycoord *= 100.0 # depends on [control=['if'], data=[]] elif scale == 'mm': xcoord /= 10.0 ycoord /= 10.0 # depends on [control=['if'], data=[]] else: raise ValueError('unknown `scale` {}'.format(scale_in)) # Compute the phantom values in each voxel image = np.zeros(space.size) nclipinfo = 0 for k in range(phantomE.shape[0]): # Handle elliptic bounds Vx0 = np.array([transposeravel(xcoord) - phantomE[k, 0], transposeravel(ycoord) - phantomE[k, 1]]) D = np.array([[1 / phantomE[k, 2], 0], [0, 1 / phantomE[k, 3]]]) phi = np.deg2rad(phantomE[k, 4]) Q = np.array([[np.cos(phi), np.sin(phi)], [-np.sin(phi), np.cos(phi)]]) f = phantomE[k, 5] nclip = int(phantomE[k, 6]) equation1 = np.sum(D.dot(Q).dot(Vx0) ** 2, axis=0) i = equation1 <= 1.0 # Handle clipping surfaces for _ in range(nclip): # note: nclib can be 0 d = phantomC[0, nclipinfo] psi = np.deg2rad(phantomC[1, nclipinfo]) equation2 = np.array([np.cos(psi), np.sin(psi)]).dot(Vx0) i &= equation2 < d nclipinfo += 1 # depends on [control=['for'], data=[]] image[i] += f # depends on [control=['for'], data=['k']] if value_type == 'materials': materials = np.zeros(space.size, dtype=space.dtype) # csf materials[(image > 1.043) & (image <= 1.047)] = 1 # less_dense_sphere materials[(image > 1.047) & (image <= 1.048)] = 2 # brain materials[(image > 1.048) & (image <= 1.052)] = 3 # denser_sphere materials[(image > 1.052) & (image <= 1.053)] = 4 # blood materials[(image > 1.053) & (image <= 1.058)] = 5 # eye materials[(image > 1.058) & (image <= 1.062)] = 6 # Bone materials[image > 1.75] = 7 return space.element(materials.reshape(space.shape)) # depends on [control=['if'], data=[]] elif value_type == 'density': return space.element(image.reshape(space.shape)) # depends on [control=['if'], data=[]] else: raise ValueError('unknown `value_type` {}'.format(value_type_in))
def nvmlDeviceSetPersistenceMode(handle, mode): r""" /** * Set the persistence mode for the device. * * For all products. * For Linux only. * Requires root/admin permissions. * * The persistence mode determines whether the GPU driver software is torn down after the last client * exits. * * This operation takes effect immediately. It is not persistent across reboots. After each reboot the * persistence mode is reset to "Disabled". * * See \ref nvmlEnableState_t for available modes. * * @param device The identifier of the target device * @param mode The target persistence mode * * @return * - \ref NVML_SUCCESS if the persistence mode was set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is invalid * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPersistenceMode() */ nvmlReturn_t DECLDIR nvmlDeviceSetPersistenceMode """ fn = _nvmlGetFunctionPointer("nvmlDeviceSetPersistenceMode") ret = fn(handle, _nvmlEnableState_t(mode)) _nvmlCheckReturn(ret) return None
def function[nvmlDeviceSetPersistenceMode, parameter[handle, mode]]: constant[ /** * Set the persistence mode for the device. * * For all products. * For Linux only. * Requires root/admin permissions. * * The persistence mode determines whether the GPU driver software is torn down after the last client * exits. * * This operation takes effect immediately. It is not persistent across reboots. After each reboot the * persistence mode is reset to "Disabled". * * See \ref nvmlEnableState_t for available modes. * * @param device The identifier of the target device * @param mode The target persistence mode * * @return * - \ref NVML_SUCCESS if the persistence mode was set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is invalid * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPersistenceMode() */ nvmlReturn_t DECLDIR nvmlDeviceSetPersistenceMode ] variable[fn] assign[=] call[name[_nvmlGetFunctionPointer], parameter[constant[nvmlDeviceSetPersistenceMode]]] variable[ret] assign[=] call[name[fn], parameter[name[handle], call[name[_nvmlEnableState_t], parameter[name[mode]]]]] call[name[_nvmlCheckReturn], parameter[name[ret]]] return[constant[None]]
keyword[def] identifier[nvmlDeviceSetPersistenceMode] ( identifier[handle] , identifier[mode] ): literal[string] identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] ) identifier[ret] = identifier[fn] ( identifier[handle] , identifier[_nvmlEnableState_t] ( identifier[mode] )) identifier[_nvmlCheckReturn] ( identifier[ret] ) keyword[return] keyword[None]
def nvmlDeviceSetPersistenceMode(handle, mode): """ /** * Set the persistence mode for the device. * * For all products. * For Linux only. * Requires root/admin permissions. * * The persistence mode determines whether the GPU driver software is torn down after the last client * exits. * * This operation takes effect immediately. It is not persistent across reboots. After each reboot the * persistence mode is reset to "Disabled". * * See \\ref nvmlEnableState_t for available modes. * * @param device The identifier of the target device * @param mode The target persistence mode * * @return * - \\ref NVML_SUCCESS if the persistence mode was set * - \\ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \\ref NVML_ERROR_INVALID_ARGUMENT if \\a device is invalid or \\a mode is invalid * - \\ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \\ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation * - \\ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \\ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPersistenceMode() */ nvmlReturn_t DECLDIR nvmlDeviceSetPersistenceMode """ fn = _nvmlGetFunctionPointer('nvmlDeviceSetPersistenceMode') ret = fn(handle, _nvmlEnableState_t(mode)) _nvmlCheckReturn(ret) return None
async def ask(self, body, quick_replies=None, options=None, user=None): """ simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return: """ await self.send_text_message_to_all_interfaces( recipient=user, text=body, quick_replies=quick_replies, options=options, ) return any.Any()
<ast.AsyncFunctionDef object at 0x7da1b27477f0>
keyword[async] keyword[def] identifier[ask] ( identifier[self] , identifier[body] , identifier[quick_replies] = keyword[None] , identifier[options] = keyword[None] , identifier[user] = keyword[None] ): literal[string] keyword[await] identifier[self] . identifier[send_text_message_to_all_interfaces] ( identifier[recipient] = identifier[user] , identifier[text] = identifier[body] , identifier[quick_replies] = identifier[quick_replies] , identifier[options] = identifier[options] , ) keyword[return] identifier[any] . identifier[Any] ()
async def ask(self, body, quick_replies=None, options=None, user=None): """ simple ask with predefined quick replies :param body: :param quick_replies: (optional) in form of {'title': <message>, 'payload': <any json>} :param options: :param user: :return: """ await self.send_text_message_to_all_interfaces(recipient=user, text=body, quick_replies=quick_replies, options=options) return any.Any()